-
Notifications
You must be signed in to change notification settings - Fork 199
/
helpers.go
271 lines (229 loc) · 6.43 KB
/
helpers.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
package context
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"get.porter.sh/porter/pkg/test"
"github.com/carolynvs/aferox"
"github.com/pkg/errors"
"github.com/spf13/afero"
"github.com/stretchr/testify/require"
)
type TestContext struct {
*Context
cleanupDirs []string
capturedErr *bytes.Buffer
capturedOut *bytes.Buffer
T *testing.T
}
// NewTestContext initializes a configuration suitable for testing, with the
// output buffered, and an in-memory file system, using the specified
// environment variables.
func NewTestContext(t *testing.T) *TestContext {
// Provide a way for tests to provide and capture stdin and stdout
// Copy output to the test log simultaneously, use go test -v to see the output
err := &bytes.Buffer{}
aggErr := io.MultiWriter(err, test.Logger{T: t})
out := &bytes.Buffer{}
aggOut := io.MultiWriter(out, test.Logger{T: t})
c := &TestContext{
Context: &Context{
Debug: true,
environ: getEnviron(),
FileSystem: aferox.NewAferox("/", afero.NewMemMapFs()),
In: &bytes.Buffer{},
Out: aggOut,
Err: aggErr,
PlugInDebugContext: &PluginDebugContext{
DebuggerPort: "2735",
RunPlugInInDebugger: "",
PlugInWorkingDirectory: "",
},
},
capturedOut: out,
capturedErr: err,
T: t,
}
c.NewCommand = NewTestCommand(c.Context)
return c
}
func NewTestCommand(c *Context) CommandBuilder {
return func(command string, args ...string) *exec.Cmd {
testArgs := append([]string{command}, args...)
cmd := exec.Command(os.Args[0], testArgs...)
cmd.Dir = c.Getwd()
cmd.Env = []string{
fmt.Sprintf("%s=true", test.MockedCommandEnv),
fmt.Sprintf("%s=%s", test.ExpectedCommandEnv, c.Getenv(test.ExpectedCommandEnv)),
}
return cmd
}
}
func (c *TestContext) GetTestDefinitionDirectory() string {
for i := 0; true; i++ {
_, filename, _, ok := runtime.Caller(i)
if !ok {
c.T.Fatal("could not determine calling test directory")
}
filename = strings.ToLower(filename)
if strings.HasSuffix(filename, "_test.go") {
return filepath.Dir(filename)
}
}
return ""
}
// UseFilesystem has porter's context use the OS filesystem instead of an in-memory filesystem
// Returns the test directory, and the temp porter home directory.
func (c *TestContext) UseFilesystem() (testDir string, homeDir string) {
homeDir, err := ioutil.TempDir("", "porter-test")
require.NoError(c.T, err)
c.cleanupDirs = append(c.cleanupDirs, homeDir)
testDir = c.GetTestDefinitionDirectory()
c.FileSystem = aferox.NewAferox(testDir, afero.NewOsFs())
c.defaultNewCommand()
return testDir, homeDir
}
func (c *TestContext) AddCleanupDir(dir string) {
c.cleanupDirs = append(c.cleanupDirs, dir)
}
func (c *TestContext) Cleanup() {
for _, dir := range c.cleanupDirs {
c.FileSystem.RemoveAll(dir)
}
}
// mode is optional and only the first one passed is used.
func (c *TestContext) AddTestFile(src, dest string, mode ...os.FileMode) []byte {
data, err := ioutil.ReadFile(src)
if err != nil {
c.T.Fatal(errors.Wrapf(err, "error reading file %s from host filesystem", src))
}
var perms os.FileMode
if len(mode) == 0 {
ext := filepath.Ext(dest)
if ext == ".sh" || ext == "" {
perms = 0700
} else {
perms = 0600
}
} else {
perms = mode[0]
}
err = c.FileSystem.WriteFile(dest, data, perms)
if err != nil {
c.T.Fatal(errors.Wrapf(err, "error writing file %s to test filesystem", dest))
}
return data
}
func (c *TestContext) AddTestFileContents(file []byte, dest string) error {
return c.FileSystem.WriteFile(dest, file, 0600)
}
// mode is optional and should only be specified once
func (c *TestContext) AddTestDirectory(srcDir, destDir string, mode ...os.FileMode) {
err := filepath.Walk(srcDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// Skip the root src directory
if path == srcDir {
return nil
}
// Translate the path from the src to the final destination
dest := filepath.Join(destDir, strings.TrimPrefix(path, srcDir))
if info.IsDir() {
return c.FileSystem.MkdirAll(dest, 0700)
}
c.AddTestFile(path, dest, mode...)
return nil
})
if err != nil {
c.T.Fatal(err)
}
}
func (c *TestContext) AddTestDriver(src, name string) string {
data, err := ioutil.ReadFile(src)
if err != nil {
c.T.Fatal(err)
}
dirname, err := c.FileSystem.TempDir("", "porter")
if err != nil {
c.T.Fatal(err)
}
// filename in accordance with cnab-go's command driver expectations
filename := fmt.Sprintf("%s/cnab-%s", dirname, name)
newfile, err := c.FileSystem.Create(filename)
if err != nil {
c.T.Fatal(err)
}
if len(data) > 0 {
_, err := newfile.Write(data)
if err != nil {
c.T.Fatal(err)
}
}
err = c.FileSystem.Chmod(newfile.Name(), 0700)
if err != nil {
c.T.Fatal(err)
}
err = newfile.Close()
if err != nil {
c.T.Fatal(err)
}
path := c.Getenv("PATH")
pathlist := []string{dirname, path}
newpath := strings.Join(pathlist, string(os.PathListSeparator))
c.Setenv("PATH", newpath)
return dirname
}
// GetOutput returns all text printed to stdout.
func (c *TestContext) GetOutput() string {
return string(c.capturedOut.Bytes())
}
// GetError returns all text printed to stderr.
func (c *TestContext) GetError() string {
return string(c.capturedErr.Bytes())
}
func (c *TestContext) ClearOutputs() {
c.capturedOut.Truncate(0)
c.capturedErr.Truncate(0)
}
// FindRepoRoot returns the path to the porter repository where the test is currently running
func (c *TestContext) FindRepoRoot() string {
goMod := c.findRepoFile("go.mod")
return filepath.Dir(goMod)
}
// FindBinDir returns the path to the bin directory of the repository where the test is currently running
func (c *TestContext) FindBinDir() string {
return c.findRepoFile("bin")
}
// Finds a file in the porter repository, does not use the mock filesystem
func (c *TestContext) findRepoFile(wantFile string) string {
d := c.GetTestDefinitionDirectory()
for {
if foundFile, ok := c.hasChild(d, wantFile); ok {
return foundFile
}
d = filepath.Dir(d)
if d == "." || d == "" || d == filepath.Dir(d) {
c.T.Fatalf("could not find %s", wantFile)
}
}
}
func (c *TestContext) hasChild(dir string, childName string) (string, bool) {
children, err := ioutil.ReadDir(dir)
if err != nil {
c.T.Fatal(err)
}
for _, child := range children {
if child.Name() == childName {
return filepath.Join(dir, child.Name()), true
}
}
return "", false
}