-
Notifications
You must be signed in to change notification settings - Fork 0
/
gosh_suite_test.go
365 lines (321 loc) · 8.21 KB
/
gosh_suite_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
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
package gosh_test
import (
"context"
stdlog "log"
"sync"
"testing"
"github.com/go-logr/logr"
"github.com/go-logr/stdr"
. "github.com/meln5674/gosh/pkg/gomega"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"bytes"
"fmt"
"io"
"os"
"strings"
"github.com/meln5674/gosh"
)
var log logr.Logger
func TestGosh(t *testing.T) {
RegisterFailHandler(Fail)
stdr.SetVerbosity(20)
log = stdr.New(stdlog.New(GinkgoWriter, "", 0))
gosh.GlobalLog = log.WithName("GoSH")
RunSpecs(t, "Gosh Suite")
}
type testError struct {
msg string
}
func (e *testError) Error() string {
return e.msg
}
var _ = error(&testError{})
var _ = Describe("MultiProcessError)", func() {
When("multiple errors present", func() {
err := gosh.MultiProcessError{Errors: []error{
&testError{"foo"},
&testError{"bar"},
&testError{"baz"},
}}
It("should contain each errors' Error() as a substring", func() {
msg := err.Error()
Expect(msg).To(ContainSubstring(err.Errors[0].Error()))
Expect(msg).To(ContainSubstring(err.Errors[1].Error()))
Expect(msg).To(ContainSubstring(err.Errors[2].Error()))
})
})
})
func saveStd() (stdin, stdout, stderr *os.File) {
stdin = os.Stdin
stdout = os.Stdout
stderr = os.Stderr
return
}
func waitBeforeStart(f func() gosh.Commander) {
When("waiting before starting", func() {
It("should return ErrorNotStarted", func() {
c := f()
Expect(c.Wait()).To(Equal(gosh.ErrNotStarted))
})
})
}
func killBeforeStart(f func() gosh.Commander) {
When("waiting before starting", func() {
It("should return ErrorNotStarted", func() {
c := f()
Expect(c.Kill()).To(Equal(gosh.ErrNotStarted))
})
})
}
func doubleKill(f func() gosh.Commander) {
When("kill is called twice", func() {
It("should return ErrorNotStarted", func() {
c := f()
Expect(c.Start()).To(Succeed())
Expect(c.Kill()).To(Succeed())
Expect(c.Kill()).To(Equal(gosh.ErrNotStarted))
})
})
}
var (
stdin, stdout, stderr *os.File
mockStdin, mockStdout, mockStderr *bytes.Buffer
mockStdinLock sync.Mutex
startMocks, stopMockIn, stopMockOutErr func()
ginkgoWriter GinkgoWriterInterface
mockLock = make(chan struct{}, 1)
)
func mockStd() (stdin, stdout, stderr *bytes.Buffer, start, closeIn, closeOutErr func()) {
stdinRead, stdinWrite, err := os.Pipe()
if err != nil {
panic(err)
}
stdoutRead, stdoutWrite, err := os.Pipe()
if err != nil {
panic(err)
}
stderrRead, stderrWrite, err := os.Pipe()
if err != nil {
panic(err)
}
stdin = bytes.NewBufferString("")
stdout = bytes.NewBufferString("")
stderr = bytes.NewBufferString("")
stdinDone := make(chan struct{})
stdinDoneACK := make(chan struct{})
stdoutDoneACK := make(chan struct{})
stderrDoneACK := make(chan struct{})
inClosed := false
outErrClosed := false
start = func() {
go func() {
defer GinkgoRecover()
loop:
for {
select {
case _ = <-stdinDone:
break loop
default:
func() {
mockStdinLock.Lock()
defer mockStdinLock.Unlock()
io.Copy(stdinWrite, stdin)
}()
}
}
func() {
mockStdinLock.Lock()
defer mockStdinLock.Unlock()
io.Copy(stdinWrite, stdin)
}()
stdinDoneACK <- struct{}{}
}()
go func() {
defer GinkgoRecover()
io.Copy(stdout, stdoutRead)
stdoutDoneACK <- struct{}{}
}()
go func() {
defer GinkgoRecover()
io.Copy(stderr, stderrRead)
stderrDoneACK <- struct{}{}
}()
}
closeIn = func() {
if inClosed {
return
}
inClosed = true
stdinDone <- struct{}{}
_ = <-stdinDoneACK
stdinWrite.Close()
}
closeOutErr = func() {
if outErrClosed {
return
}
outErrClosed = true
stdoutWrite.Close()
stderrWrite.Close()
for ix := 0; ix < 2; ix++ {
select {
case _ = <-stdoutDoneACK:
break
case _ = <-stderrDoneACK:
break
}
}
}
os.Stdin = stdinRead
os.Stdout = stdoutWrite
os.Stderr = stderrWrite
return
}
func restoreStd(stdin, stdout, stderr *os.File) {
os.Stdin = stdin
os.Stdout = stdout
os.Stderr = stderr
}
func pushMock() {
mockLock <- struct{}{}
stdin, stdout, stderr = saveStd()
mockStdin, mockStdout, mockStderr, startMocks, stopMockIn, stopMockOutErr = mockStd()
//ginkgoWriter = GinkgoWriter
//GinkgoWriter = &MockGinkgoWriter{Writer: stdout}
Expect(os.Stdin.Fd()).ToNot(Equal(uintptr(0)))
}
func popMock() {
_ = <-mockLock
restoreStd(stdin, stdout, stderr)
stdin = nil
stdout = nil
stderr = nil
mockStdin = nil
mockStdout = nil
mockStderr = nil
startMocks = nil
stopMockIn = nil
stopMockOutErr = nil
GinkgoWriter = ginkgoWriter
}
type MockGinkgoWriter struct {
io.Writer
}
var _ = GinkgoWriterInterface(&MockGinkgoWriter{})
func (m *MockGinkgoWriter) Print(a ...interface{}) {
fmt.Fprint(m, a...)
}
func (m *MockGinkgoWriter) Printf(format string, a ...interface{}) {
fmt.Fprintf(m, format, a...)
}
func (m *MockGinkgoWriter) Println(a ...interface{}) {
fmt.Fprintln(m, a...)
}
func (m *MockGinkgoWriter) TeeTo(writer io.Writer) {
// TODO: Needed?
}
func (m *MockGinkgoWriter) ClearTeeWriters() {
// TODO: Needed?
}
func useMocks() {
BeforeEach(pushMock)
AfterEach(popMock)
}
type genericTestArgs struct {
cmd gosh.Commander
stdin string
stdout string
stderr string
ignoreStdin bool
ignoreStdout bool
ignoreStderr bool
err error
errOnStart bool
async bool
}
func genericTest(args genericTestArgs) {
func() {
startMocks()
defer stopMockOutErr()
if !args.ignoreStdin {
func() {
mockStdinLock.Lock()
defer mockStdinLock.Unlock()
_, err := mockStdin.WriteString(args.stdin)
Expect(err).ToNot(HaveOccurred(), "Failed to write mock standard input")
}()
}
stopMockIn()
if args.async {
if args.err == nil {
Expect(args.cmd.Start()).To(Succeed(), "Command did not start")
Expect(args.cmd.Wait()).To(Succeed(), "Command did not succeed")
} else if args.errOnStart {
Expect(args.cmd.Start()).To(MatchMultiProcessErrorType(args.err), "Did not fail in expected way")
} else {
Expect(args.cmd.Start()).To(Succeed(), "Command did not start")
Expect(args.cmd.Wait()).To(MatchMultiProcessErrorType(args.err), "Did not fail in expected way")
}
} else if args.err == nil {
Expect(args.cmd.Run()).To(Succeed(), "Command did not succeed")
} else {
Expect(args.cmd.Run()).To(MatchMultiProcessErrorType(args.err), "Did not fail in expected way")
}
}()
if !args.ignoreStdin {
Expect(mockStdin.String()).To(HaveLen(0), "Standard input was not consumed")
}
if !args.ignoreStdout {
Expect(mockStdout.String()).To(Equal(args.stdout), "Standard output did not match")
}
if !args.ignoreStderr {
Expect(mockStderr.String()).To(Equal(args.stderr), "Standard error did not match")
}
}
func quoteShell(s string) string {
return fmt.Sprintf("'%s'", strings.ReplaceAll(s, "'", `'\''`))
}
func makeSentinel(dir, name string) string {
return fmt.Sprintf(`touch '%s/%s'`, dir, name)
}
func waitForSentinels(dir string, names ...string) string {
builder := strings.Builder{}
builder.WriteString("while ")
builder.WriteString(fmt.Sprintf(`! [ -f %s ]`, quoteShell(fmt.Sprintf(`%s/%s`, dir, names[0]))))
for _, name := range names[1:] {
builder.WriteString(" || ")
builder.WriteString(fmt.Sprintf(`! [ -f %s ]`, quoteShell(fmt.Sprintf(`%s/%s`, dir, name))))
}
builder.WriteString("; do sleep 1; done")
return builder.String()
}
func checkStdin(s string) string {
return fmt.Sprintf(`[ "$(cat)" == %s ]`, quoteShell(s))
}
func checkStdinLine(s string) string {
return fmt.Sprintf(`read && [ "${REPLY}" == %s ]`, quoteShell(s))
}
func checkStdinChar(c rune) string {
return fmt.Sprintf(`[ "$(go run util/readchar/main.go)" == %s ]`, quoteShell(string(c)))
}
func printStdout(s string) string {
return fmt.Sprintf(`echo -n %s`, quoteShell(s))
}
func printStderr(s string) string {
return fmt.Sprintf(`echo -n %s >&2`, quoteShell(s))
}
func inOutPassthrough() string {
return "cat"
}
func fail() string {
return "exit 1"
}
func failToStart(ctx context.Context) gosh.Commander {
return gosh.FromFunc(ctx, func(ctx context.Context, stdin io.Reader, stdout, stderr io.Writer, done chan error) error {
return fmt.Errorf("This command fails to start")
})
}
func allOf(s ...string) string {
return strings.Join(s, " && ")
}