-
Notifications
You must be signed in to change notification settings - Fork 293
/
fixture.go
78 lines (66 loc) · 1.6 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
package starkit
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"go.starlark.net/starlark"
)
// A fixture for test setup/teardown
type Fixture struct {
tb testing.TB
extensions []Extension
path string
fs map[string]string
out *bytes.Buffer
useRealFS bool // Use a real filesystem
}
func NewFixture(tb testing.TB, extensions ...Extension) *Fixture {
return &Fixture{
tb: tb,
extensions: extensions,
path: "/fake/path/to/dir",
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)
})
return nil
}
func (f *Fixture) ExecFile(name string) (Model, error) {
extensions := append([]Extension{f}, f.extensions...)
return ExecFile(filepath.Join(f.path, name), extensions...)
}
func (f *Fixture) PrintOutput() string {
return f.out.String()
}
func (f *Fixture) Path() string {
return f.path
}
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() {
path, err := ioutil.TempDir("", f.tb.Name())
assert.NoError(f.tb, err)
f.path = path
f.useRealFS = true
}