forked from profclems/glab
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.go
104 lines (88 loc) · 2.11 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
package test
import (
"bytes"
"fmt"
"os/exec"
"regexp"
"github.com/profclems/glab/internal/run"
"github.com/pkg/errors"
)
// TODO copypasta from command package
type CmdOut struct {
OutBuf, ErrBuf *bytes.Buffer
}
func (c CmdOut) String() string {
return c.OutBuf.String()
}
func (c CmdOut) Stderr() string {
return c.ErrBuf.String()
}
// OutputStub implements a simple utils.Runnable
type OutputStub struct {
Out []byte
Error error
}
func (s OutputStub) Output() ([]byte, error) {
if s.Error != nil {
return s.Out, s.Error
}
return s.Out, nil
}
func (s OutputStub) Run() error {
if s.Error != nil {
return s.Error
}
return nil
}
type CmdStubber struct {
Stubs []*OutputStub
Count int
Calls []*exec.Cmd
}
func InitCmdStubber() (*CmdStubber, func()) {
cs := CmdStubber{}
teardown := run.SetPrepareCmd(createStubbedPrepareCmd(&cs))
return &cs, teardown
}
func (cs *CmdStubber) Stub(desiredOutput string) {
// TODO maybe have some kind of command mapping but going simple for now
cs.Stubs = append(cs.Stubs, &OutputStub{[]byte(desiredOutput), nil})
}
func (cs *CmdStubber) StubError(errText string) {
// TODO support error types beyond CmdError
stderrBuff := bytes.NewBufferString(errText)
args := []string{"stub"} // TODO make more real?
err := errors.New(errText)
cs.Stubs = append(cs.Stubs, &OutputStub{Error: &run.CmdError{
Stderr: stderrBuff,
Args: args,
Err: err,
}})
}
func createStubbedPrepareCmd(cs *CmdStubber) func(*exec.Cmd) run.Runnable {
return func(cmd *exec.Cmd) run.Runnable {
cs.Calls = append(cs.Calls, cmd)
call := cs.Count
cs.Count += 1
if call >= len(cs.Stubs) {
panic(fmt.Sprintf("more execs than stubs. most recent call: %v", cmd))
}
// fmt.Printf("Called stub for `%v`\n", cmd) // Helpful for debugging
return cs.Stubs[call]
}
}
type T interface {
Helper()
Errorf(string, ...interface{})
}
func ExpectLines(t T, output string, lines ...string) {
t.Helper()
var r *regexp.Regexp
for _, l := range lines {
r = regexp.MustCompile(l)
if !r.MatchString(output) {
t.Errorf("output did not match regexp /%s/\n> output\n%s\n", r, output)
return
}
}
}