This repository has been archived by the owner on Aug 29, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
survey.go
89 lines (70 loc) · 1.58 KB
/
survey.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
package surveydog
import (
"errors"
"sync"
"github.com/nhatthm/surveyexpect"
"github.com/stretchr/testify/assert"
)
// Survey is a wrapper around *surveyexpect.Survey to make it run with cucumber/godog.
type Survey struct {
*surveyexpect.Survey
test surveyexpect.TestingT
mu sync.Mutex
doneChan chan struct{}
}
func (s *Survey) getDoneChan() <-chan struct{} {
s.mu.Lock()
defer s.mu.Unlock()
return s.getDoneChanLocked()
}
func (s *Survey) getDoneChanLocked() chan struct{} {
if s.doneChan == nil {
s.doneChan = make(chan struct{})
}
return s.doneChan
}
func (s *Survey) closeDoneChan() {
s.mu.Lock()
defer s.mu.Unlock()
ch := s.getDoneChanLocked()
select {
case <-ch:
// Already closed. Don't close again.
default:
// Safe to close here. We're the only closer, guarded
// by s.mu.
close(ch)
}
}
// Expect runs an expectation against a given console.
func (s *Survey) Expect(c surveyexpect.Console) error {
for {
select {
case <-s.getDoneChan():
return nil
default:
err := s.Survey.Expect(c)
if err != nil && !errors.Is(err, surveyexpect.ErrNothingToDo) {
return err
}
}
}
}
// Start starts a new survey.
func (s *Survey) Start(console surveyexpect.Console) *Survey {
go func() {
assert.NoError(s.test, s.Expect(console))
}()
return s
}
// Close notifies other parties and close the survey.
func (s *Survey) Close() {
s.closeDoneChan()
}
// NewSurvey creates a new survey.
func NewSurvey(t surveyexpect.TestingT, options ...surveyexpect.ExpectOption) *Survey {
return &Survey{
Survey: surveyexpect.New(t, options...),
test: t,
}
}