-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_test.go
124 lines (105 loc) · 2.63 KB
/
main_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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package main_test
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
var coverDir string
func init() {
for i := len(os.Args) - 1; i > -1; i-- {
_, dir, ok := strings.Cut(os.Args[i], "-test.gocoverdir=")
if !ok {
continue
}
coverDir = Must2(filepath.Abs(dir))
Must(os.RemoveAll(coverDir))
Must(os.MkdirAll(coverDir, 0o755))
return
}
}
func TestMain(t *testing.T) {
file, err := os.CreateTemp("", "")
require.NoError(t, err)
require.NoError(t, file.Close())
args := []string{"build", "-o", file.Name()}
if coverDir != "" {
args = append(args, "-cover", "-coverpkg=github.com/davidmdm/gostall")
}
args = append(args, ".")
build := exec.Command("go", args...)
build.Stdout, build.Stderr = os.Stdout, os.Stderr
require.NoError(t, build.Run())
gobin, err := filepath.Abs(outputGobin)
require.NoError(t, err)
gostall := func(path, name string) *exec.Cmd {
cmd := exec.Command(file.Name(), path, name)
cmd.Dir = outputDir
cmd.Env = append(os.Environ(), "GOBIN="+gobin, "GOCOVERDIR="+coverDir)
return cmd
}
cases := []struct {
Name string
Path string
Out string
ExpectedOut string
}{
{
Name: "local path with name",
Path: "..",
Out: "test",
ExpectedOut: filepath.Join(gobin, "test"),
},
{
Name: "local path with local out",
Path: "..",
Out: "./test",
ExpectedOut: filepath.Join(outputDir, "test"),
},
{
Name: "remote path with name",
Path: "github.com/matryer/moq@latest",
Out: "test",
ExpectedOut: filepath.Join(gobin, "test"),
},
{
Name: "remote path with local out",
Path: "github.com/matryer/moq@latest",
Out: "./test",
ExpectedOut: filepath.Join(outputDir, "test"),
},
}
for _, tc := range cases {
t.Run(tc.Name, func(t *testing.T) {
ResetTestOutput(t)
require.NoError(t, gostall(tc.Path, tc.Out).Run())
_, err := os.Stat(tc.ExpectedOut)
require.NoError(t, err)
})
}
t.Run("no args passed", func(t *testing.T) {
output, err := exec.Command(file.Name()).CombinedOutput()
require.EqualError(t, err, "exit status 1")
require.Contains(t, string(output), "need two positional arguments: [path] [name]\n")
})
}
var (
outputDir = "./test_output"
outputGobin = filepath.Join(outputDir, "bin")
)
func ResetTestOutput(t *testing.T) {
t.Helper()
require.NoError(t, os.RemoveAll(outputDir))
require.NoError(t, os.MkdirAll(outputGobin, 0o755))
}
func Must(err error) {
if err != nil {
panic(err)
}
}
func Must2[T any](value T, err error) T {
Must(err)
return value
}