-
Notifications
You must be signed in to change notification settings - Fork 5
/
vagrant_client_test.go
91 lines (81 loc) · 2.2 KB
/
vagrant_client_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package vagrant
import (
"fmt"
"os"
"testing"
)
var successfulOutput = make(map[string]string)
const EnvTestOutputKey = "GO_VAGRANT_TEST_OUTPUT_KEY"
func newMockVagrantClient() *VagrantClient {
return &VagrantClient{
VagrantfileDir: ".",
executable: os.Args[0],
preArguments: []string{"-test.run=TestVagrantClient_Helper", "--", "HELPER"},
}
}
func assertErr(t *testing.T, err error) {
if err == nil {
t.Fail()
}
}
func assertNoErr(t *testing.T, err error) {
if err != nil {
t.Fail()
}
}
func assertArguments(t *testing.T, args []string, expected ...string) {
if len(args) != len(expected) {
t.Fatalf("Expected %v args; got %v", len(expected), len(args))
}
for i, arg := range args {
if arg != expected[i] {
t.Errorf("Expected arg %v to be '%v'; got %v", i, expected[i], arg)
}
}
}
// newEnvTestOutputKey creates an environment with a test output key,
// used by the TestVagrantClient_Helper for output selection.
func newEnvTestOutputKey(key string) []string {
return []string{fmt.Sprintf("%s=%s", EnvTestOutputKey, key)}
}
// This function is used during testing. It is called by the mock vagrant
// client instead of the actual vagrant binary.
func TestVagrantClient_Helper(t *testing.T) {
// Find where "-- HELPER" exists in the os.Args. If not found, exit.
args := os.Args
for idx, arg := range args {
if arg == "--" {
args = os.Args[idx+1:]
break
}
}
if len(args) == 0 || args[0] != "HELPER" {
return
}
args = args[1:]
// If we got here, we were called as part of a test that executed an exec.Cmd
// object. We output some information about the arguments passed to us.
if len(args) > 0 {
var output string
var ok bool
// if custom test output key is set, use it to retrieve test output data
outputKey := os.Getenv(EnvTestOutputKey)
if outputKey != "" {
output, ok = successfulOutput[outputKey]
} else { // otherwise, use the subcommand name
output, ok = successfulOutput[args[0]]
}
if ok {
fmt.Print(output)
} else {
fmt.Printf("123,,subcommand,%v\n", args[0])
for _, arg := range args[1:] {
if arg == "--machine-readable" {
fmt.Println("123,,machine-readable,true")
} else {
fmt.Printf("123,,arg,%v\n", arg)
}
}
}
}
}