-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathmock.go
78 lines (66 loc) · 1.73 KB
/
mock.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
package mock
import "sync"
type (
// Mock implementation of a service client.
Mock struct {
funcs map[string]interface{}
seqs map[string][]interface{}
indices []*index
pos int
lock sync.Mutex
}
// index identifies a mock in a sequence.
index struct {
name string
pos int
}
)
// New returns a new mock client.
func New() *Mock {
return &Mock{
funcs: make(map[string]interface{}),
seqs: make(map[string][]interface{}),
}
}
// If there is no mock left in the sequence then Next returns the permanent mock
// for name if any, nil otherwise. If there are mocks left in the sequence then
// Next returns the next mock if its name is name, nil otherwise.
func (m *Mock) Next(name string) interface{} {
m.lock.Lock()
defer m.lock.Unlock()
if m.pos < len(m.indices) && len(m.seqs[name]) > 0 {
idx := m.indices[m.pos]
if idx.name != name || idx.pos >= len(m.seqs[name]) {
// There is a sequence but the wrong method is being called
return nil
}
f := m.seqs[name][idx.pos]
idx.pos++
m.pos++
return f
}
// No sequence or sequence fully consumed - look for permanent mock
if f, ok := m.funcs[name]; ok {
return f
}
return nil
}
// Add adds f to the mock sequence.
func (m *Mock) Add(name string, f interface{}) {
m.lock.Lock()
defer m.lock.Unlock()
m.indices = append(m.indices, &index{name, len(m.seqs[name])})
m.seqs[name] = append(m.seqs[name], f)
}
// Set a permanent mock for the function with the given name.
func (m *Mock) Set(name string, f interface{}) {
m.lock.Lock()
defer m.lock.Unlock()
m.funcs[name] = f
}
// HasMore returns true if the mock sequence isn't fully consumed.
func (m *Mock) HasMore() bool {
m.lock.Lock()
defer m.lock.Unlock()
return m.pos < len(m.indices)
}