-
Notifications
You must be signed in to change notification settings - Fork 0
/
completion_source_test.go
102 lines (80 loc) · 2.33 KB
/
completion_source_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
package ticker_autocomplete
import (
"errors"
"math"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestNewCompletionSource(t *testing.T) {
expected := &MockCompleter{}
factory := func() (Completer, error) {
time.Sleep(1 * time.Millisecond)
return expected, nil
}
cs := NewCompletionSource(factory)
assert.NotNil(t, cs)
c := cs.GetCompleter()
assert.Nil(t, c, "GetCompleter should return nil before the first refresh is complete")
time.Sleep(10 * time.Millisecond)
c = cs.GetCompleter()
assert.Same(t, expected, c, "GetCompleter should return the completer after the first refresh is complete")
}
func TestRefresh(t *testing.T) {
expected := &MockCompleter{}
count := 0
factory := func() (Completer, error) {
count++
time.Sleep(1 * time.Millisecond)
return expected, nil
}
cs := NewCompletionSource(factory)
assert.Equal(t, 0, count, "Factory should not be called until the first refresh completes")
time.Sleep(10 * time.Millisecond)
assert.Equal(t, 1, count, "Factory should have been called once during initialization")
err := cs.Refresh()
assert.Nil(t, err, "Refresh should not return an error")
assert.Equal(t, 2, count, "Refresh invokes the factory")
}
func TestAutoRefresh(t *testing.T) {
expected := &MockCompleter{}
count := 0
factory := func() (Completer, error) {
count++
return expected, nil
}
cs := newCompletionSource(factory, 1*time.Millisecond, 1*time.Millisecond)
time.Sleep(10 * time.Millisecond)
assert.Greater(t, count, 1, "Factory be refreshed many times in 10ms")
c := cs.GetCompleter()
assert.Same(t, expected, c)
assert.Nil(t, cs.LastError)
}
func TestRefresh_Retry(t *testing.T) {
expected := &MockCompleter{}
count := 0
err := errors.New("expected error")
factory := func() (Completer, error) {
count++
return expected, err
}
cs := newCompletionSource(factory, 1*time.Minute, 1*time.Nanosecond)
time.Sleep(100 * time.Millisecond)
assert.Greater(t, count, 1, "Factory be retried many times")
c := cs.GetCompleter()
assert.Same(t, err, cs.LastError)
assert.Nil(t, c)
}
type MockCompleter struct {
Results []Completion
}
func (c *MockCompleter) GetCompletions(prompt string, limit int) []Completion {
var results []Completion
if limit < 0 {
limit = math.MaxInt32
}
return results[:limit]
}
func (c *MockCompleter) GetAll() []Completion {
return c.Results
}