...
1 package poll
2
3 import (
4 "fmt"
5 "testing"
6 "time"
7
8 "gotest.tools/v3/assert"
9 "gotest.tools/v3/assert/cmp"
10 )
11
12 type fakeT struct {
13 failed string
14 }
15
16 func (t *fakeT) Fatalf(format string, args ...interface{}) {
17 t.failed = fmt.Sprintf(format, args...)
18 panic("exit wait on")
19 }
20
21 func (t *fakeT) Log(...interface{}) {}
22
23 func (t *fakeT) Logf(string, ...interface{}) {}
24
25 func TestContinueMessage(t *testing.T) {
26 tests := []struct {
27 msg string
28 args []interface{}
29 expected string
30 }{
31 {
32 msg: "literal message",
33 expected: "literal message",
34 },
35 {
36 msg: "templated %s",
37 args: []interface{}{"message"},
38 expected: "templated message",
39 },
40 {
41 msg: "literal message with percentage symbols (%USERPROFILE%)",
42 expected: "literal message with percentage symbols (%USERPROFILE%)",
43 },
44 }
45
46 for _, tc := range tests {
47 actual := Continue(tc.msg, tc.args...).Message()
48 assert.Check(t, cmp.Equal(tc.expected, actual))
49 }
50 }
51
52 func TestWaitOn(t *testing.T) {
53 counter := 0
54 end := 4
55 check := func(LogT) Result {
56 if counter == end {
57 return Success()
58 }
59 counter++
60 return Continue("counter is at %d not yet %d", counter-1, end)
61 }
62
63 WaitOn(t, check, WithDelay(0))
64 assert.Equal(t, end, counter)
65 }
66
67 func TestWaitOnWithTimeout(t *testing.T) {
68 fakeT := &fakeT{}
69
70 check := func(LogT) Result {
71 return Continue("not done")
72 }
73
74 assert.Assert(t, cmp.Panics(func() {
75 WaitOn(fakeT, check, WithTimeout(time.Millisecond))
76 }))
77 assert.Equal(t, "timeout hit after 1ms: not done", fakeT.failed)
78 }
79
80 func TestWaitOnWithCheckTimeout(t *testing.T) {
81 fakeT := &fakeT{}
82
83 check := func(LogT) Result {
84 time.Sleep(1 * time.Second)
85 return Continue("not done")
86 }
87
88 assert.Assert(t, cmp.Panics(func() { WaitOn(fakeT, check, WithTimeout(time.Millisecond)) }))
89 assert.Equal(t, "timeout hit after 1ms: first check never completed", fakeT.failed)
90 }
91
92 func TestWaitOnWithCheckError(t *testing.T) {
93 fakeT := &fakeT{}
94
95 check := func(LogT) Result {
96 return Error(fmt.Errorf("broke"))
97 }
98
99 assert.Assert(t, cmp.Panics(func() { WaitOn(fakeT, check) }))
100 assert.Equal(t, "polling check failed: broke", fakeT.failed)
101 }
102
103 func TestWaitOn_WithCompare(t *testing.T) {
104 fakeT := &fakeT{}
105
106 check := func(LogT) Result {
107 return Compare(cmp.Equal(3, 4))
108 }
109
110 assert.Assert(t, cmp.Panics(func() {
111 WaitOn(fakeT, check, WithDelay(0), WithTimeout(10*time.Millisecond))
112 }))
113 assert.Assert(t, cmp.Contains(fakeT.failed, "assertion failed: 3 (int) != 4 (int)"))
114 }
115
View as plain text