/
command_test.go
108 lines (88 loc) · 2.46 KB
/
command_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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package conflict
import (
"fmt"
"os"
"os/exec"
"strconv"
"testing"
"github.com/mkchoi212/fac/testhelper"
)
var mockValidDirectory = "/"
var mockInvalidDirectory = "/hello/world"
var commands = []struct {
command string
ok bool
}{
{"time", true},
{"ls", true},
{"foobar", false},
}
func TestHelperProcess(t *testing.T) {
if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {
return
}
args := os.Getenv(argsEnvFlag)
// Purposely fail test
if args == "false" {
fmt.Fprintf(os.Stderr, "Mock exec: Command tragically failed")
os.Exit(1)
}
// TopLevelPath arguments
if args == "rev-parse,--show-toplevel" {
fmt.Fprintf(os.Stdout, "testdata")
os.Exit(0)
}
if args == "--no-pager,diff,--name-only,--diff-filter=U" {
fmt.Fprintf(os.Stdout, "lorem_ipsum\nassets/README.md\n")
os.Exit(0)
}
fmt.Fprintf(os.Stdout, "Mock exec: Command succeeded")
os.Exit(0)
}
// Allows us to mock exec.Command, thanks to
// https://npf.io/2015/06/testing-exec-command/
func mockExecCommand(command string, args ...string) *exec.Cmd {
cs := []string{"-test.run=TestHelperProcess", "--", command}
cs = append(cs, args...)
cmd := exec.Command(os.Args[0], cs...)
cmd.Env = append(cmd.Env, "GO_WANT_HELPER_PROCESS=1")
return cmd
}
func TestRun(t *testing.T) {
execCommand = mockExecCommand
defer func() { execCommand = exec.Command }()
for _, test := range commands {
stdout, stderr, exitCode := run(test.command, ".", strconv.FormatBool(test.ok))
if test.ok {
testhelper.Assert(t, exitCode == 0, "expected no errors but got %s", stderr)
} else {
testhelper.Assert(t, exitCode != 0, "expected errors but got %s", stdout)
}
}
}
func TestConflictedFiles(t *testing.T) {
execCommand = mockExecCommand
defer func() { execCommand = exec.Command }()
tests := []string{mockValidDirectory, mockInvalidDirectory}
for _, test := range tests {
out, err := conflictedFiles(test)
if test == mockValidDirectory {
testhelper.Ok(t, err)
} else if test == mockInvalidDirectory {
testhelper.Assert(t, err != nil, "expected errors but got %s", out)
}
}
}
func TestTopLevelPath(t *testing.T) {
execCommand = mockExecCommand
defer func() { execCommand = exec.Command }()
tests := []string{mockValidDirectory, mockInvalidDirectory}
for _, test := range tests {
out, err := topLevelPath(test)
if test == mockValidDirectory {
testhelper.Ok(t, err)
} else if test == mockInvalidDirectory {
testhelper.Assert(t, err != nil, "expected errors but got %s", out)
}
}
}