-
Notifications
You must be signed in to change notification settings - Fork 10
/
test_expectations.go
98 lines (88 loc) · 2.55 KB
/
test_expectations.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
package xray
import (
"fmt"
"os"
"strings"
"sync"
pkgerrors "github.com/pkg/errors"
)
type (
// TestClientExpectation is a generic mock.
TestClientExpectation struct {
mu sync.Mutex
expected expectations
unexpected []string
}
// expectations is the data structure used to record expected function
// calls and the corresponding behavior.
expectations map[string][]interface{}
)
// NewTestClientExpectation creates a new *TestClientExpectation
func NewTestClientExpectation() *TestClientExpectation {
return &TestClientExpectation{
mu: sync.Mutex{},
expected: make(expectations),
}
}
// Expect records the request handler in the list of expected request calls.
func (c *TestClientExpectation) Expect(fn string, e interface{}) {
c.mu.Lock()
defer c.mu.Unlock()
c.expected[fn] = append(c.expected[fn], e)
}
// ExpectNTimes records the request handler n times in the list of expected request calls.
func (c *TestClientExpectation) ExpectNTimes(n int, fn string, e interface{}) {
c.mu.Lock()
defer c.mu.Unlock()
for i := 0; i < n; i++ {
c.expected[fn] = append(c.expected[fn], e)
}
}
// Expectation removes the expectation for the function with the given name from the expected calls
// if there is one and returns it. If there is no (more) expectations for the function,
// it prints a warning to stderr and returns nil.
func (c *TestClientExpectation) Expectation(fn string) interface{} {
c.mu.Lock()
defer c.mu.Unlock()
es, ok := c.expected[fn]
if !ok {
err := pkgerrors.New("!!! Expectation not found for: " + fn)
fmt.Fprintf(os.Stderr, "\n%+v\n", err)
c.unexpected = append(c.unexpected, fn)
return nil
}
e := es[0]
if len(es) == 1 {
delete(c.expected, fn)
} else {
c.expected[fn] = c.expected[fn][1:]
}
return e
}
// MetExpectations returns nil if there no expectation left to be called and if there is no call
// that was made that did not match an expectation. It returns an error describing what is left to
// be called or what was called with no expectation otherwise.
func (c *TestClientExpectation) MetExpectations() error {
c.mu.Lock()
defer c.mu.Unlock()
var msg string
if len(c.unexpected) > 0 {
msg = fmt.Sprintf("%s was called but wasn't expected.", strings.Join(c.unexpected, ", "))
}
if len(c.expected) > 0 {
if len(msg) > 0 {
msg += "\n"
}
i := 0
keys := make([]string, len(c.expected))
for e := range c.expected {
keys[i] = e
i++
}
msg += fmt.Sprintf("%s was expected to be called but wasn't.", strings.Join(keys, ", "))
}
if msg == "" {
return nil
}
return fmt.Errorf(msg)
}