-
Notifications
You must be signed in to change notification settings - Fork 288
/
fixture.go
107 lines (90 loc) · 2.38 KB
/
fixture.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
package starkit
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.starlark.net/starlark"
"github.com/windmilleng/tilt/internal/testutils/tempdir"
)
// A fixture for test setup/teardown
type Fixture struct {
tb testing.TB
extensions []Extension
path string
temp *tempdir.TempDirFixture
fs map[string]string
out *bytes.Buffer
useRealFS bool // Use a real filesystem
loadInterceptors []LoadInterceptor
}
func NewFixture(tb testing.TB, extensions ...Extension) *Fixture {
temp := tempdir.NewTempDirFixture(tb)
temp.Chdir()
return &Fixture{
tb: tb,
extensions: extensions,
path: temp.Path(),
temp: temp,
fs: make(map[string]string),
out: bytes.NewBuffer(nil),
}
}
func (f *Fixture) OnStart(e *Environment) error {
if !f.useRealFS {
e.SetFakeFileSystem(f.fs)
}
e.SetPrint(func(t *starlark.Thread, msg string) {
_, _ = fmt.Fprintf(f.out, "%s\n", msg)
})
e.SetContext(context.Background())
return nil
}
func (f *Fixture) ExecFile(name string) (Model, error) {
extensions := append([]Extension{f}, f.extensions...)
env := newEnvironment(extensions...)
for _, i := range f.loadInterceptors {
env.AddLoadInterceptor(i)
}
return env.start(filepath.Join(f.path, name))
}
func (f *Fixture) SetLoadInterceptor(i LoadInterceptor) {
f.loadInterceptors = append(f.loadInterceptors, i)
}
func (f *Fixture) PrintOutput() string {
return f.out.String()
}
func (f *Fixture) Path() string {
return f.path
}
func (f *Fixture) JoinPath(elem ...string) string {
return filepath.Join(append([]string{f.path}, elem...)...)
}
func (f *Fixture) File(name, contents string) {
fullPath := filepath.Join(f.path, name)
if f.useRealFS {
dir := filepath.Dir(fullPath)
err := os.MkdirAll(dir, os.FileMode(0755))
assert.NoError(f.tb, err)
err = ioutil.WriteFile(fullPath, []byte(contents), os.FileMode(0644))
assert.NoError(f.tb, err)
return
}
f.fs[fullPath] = contents
}
func (f *Fixture) UseRealFS() {
// '/' is not allowed in filenames, so get that out of there
path, err := ioutil.TempDir("", strings.Replace(f.tb.Name(), "/", "_", -1))
require.NoError(f.tb, err)
f.path = path
f.useRealFS = true
}
func (f *Fixture) TearDown() {
f.temp.TearDown()
}