-
Notifications
You must be signed in to change notification settings - Fork 152
/
test.go
54 lines (44 loc) · 1.16 KB
/
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
package interactive
import (
"context"
"fmt"
"io"
)
//
// Code in this file is useful if you are trying to test code that use interactive package
//
type contextKeyType struct{}
var contextKey = contextKeyType{}
func InjectMockResponseToContext(ctx context.Context, mockValues []string) context.Context {
return context.WithValue(ctx, contextKey, &mockValues)
}
func popMockResponseFromContext(ctx context.Context) (string, bool) {
contextValue := ctx.Value(contextKey)
if contextValue == nil {
return "", false
}
mockValues := contextValue.(*[]string)
if mockValues == nil || len(*mockValues) == 0 {
return "", false
}
str := (*mockValues)[0]
*mockValues = (*mockValues)[1:]
return str, true
}
type mockResponseReader struct {
ctx context.Context
defaultReader io.ReadCloser
}
func (m *mockResponseReader) Read(p []byte) (n int, err error) {
if m.ctx != nil {
if mockResponse, exist := popMockResponseFromContext(m.ctx); exist {
buff := []byte(fmt.Sprintf("%s\n", mockResponse))
copy(p, buff)
return len(buff), nil
}
}
return m.defaultReader.Read(p)
}
func (m *mockResponseReader) Close() error {
return m.defaultReader.Close()
}