-
Notifications
You must be signed in to change notification settings - Fork 81
/
stubber.go
105 lines (91 loc) · 2.58 KB
/
stubber.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
package prompt
import (
"fmt"
"reflect"
"github.com/AlecAivazis/survey/v2"
"github.com/AlecAivazis/survey/v2/core"
)
type AskStubber struct {
Asks [][]*survey.Question
AskOnes []*survey.Prompt
Count int
OneCount int
Stubs [][]*QuestionStub
StubOnes []*StubPrompt
}
func InitAskStubber() (*AskStubber, func()) {
origSurveyAsk := SurveyAsk
origSurveyAskOne := SurveyAskOne
as := AskStubber{}
SurveyAskOne = func(p survey.Prompt, response interface{}, opts ...survey.AskOpt) error {
as.AskOnes = append(as.AskOnes, &p)
count := as.OneCount
as.OneCount++
if count >= len(as.StubOnes) {
panic(fmt.Sprintf("more asks than stubs. most recent call: %v", p))
}
stubbedPrompt := as.StubOnes[count]
if stubbedPrompt.Default {
// TODO this is failing for basic AskOne invocations with a string result.
defaultValue := reflect.ValueOf(p).Elem().FieldByName("Default")
_ = core.WriteAnswer(response, "", defaultValue)
} else {
_ = core.WriteAnswer(response, "", stubbedPrompt.Value)
}
return nil
}
SurveyAsk = func(qs []*survey.Question, response interface{}, opts ...survey.AskOpt) error {
as.Asks = append(as.Asks, qs)
count := as.Count
as.Count++
if count >= len(as.Stubs) {
panic(fmt.Sprintf("more asks than stubs. most recent call: %#v", qs))
}
// actually set response
stubbedQuestions := as.Stubs[count]
if len(stubbedQuestions) != len(qs) {
panic(fmt.Sprintf("asked questions: %d; stubbed questions: %d", len(qs), len(stubbedQuestions)))
}
for i, sq := range stubbedQuestions {
q := qs[i]
if q.Name != sq.Name {
panic(fmt.Sprintf("stubbed question mismatch: %s != %s", q.Name, sq.Name))
}
if sq.Default {
defaultValue := reflect.ValueOf(q.Prompt).Elem().FieldByName("Default")
_ = core.WriteAnswer(response, q.Name, defaultValue)
} else {
_ = core.WriteAnswer(response, q.Name, sq.Value)
}
}
return nil
}
teardown := func() {
SurveyAsk = origSurveyAsk
SurveyAskOne = origSurveyAskOne
}
return &as, teardown
}
type StubPrompt struct {
Value interface{}
Default bool
}
type QuestionStub struct {
Name string
Value interface{}
Default bool
}
func (as *AskStubber) StubOne(value interface{}) {
as.StubOnes = append(as.StubOnes, &StubPrompt{
Value: value,
})
}
func (as *AskStubber) StubOneDefault() {
as.StubOnes = append(as.StubOnes, &StubPrompt{
Default: true,
})
}
func (as *AskStubber) Stub(stubbedQuestions []*QuestionStub) {
// A call to .Ask takes a list of questions; a stub is then a list of questions in the same order.
as.Stubs = append(as.Stubs, stubbedQuestions)
}