-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmock.go
97 lines (79 loc) · 1.93 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package gosmock
import (
"fmt"
"reflect"
"runtime"
"sync"
)
var mutex sync.Mutex
type MockTool struct {
responses map[string][]Call
calls map[string][]Call
}
func (f *MockTool) init() {
if f.responses == nil {
f.responses = make(map[string][]Call)
f.calls = make(map[string][]Call)
}
}
func (f *MockTool) ClearMocks() {
f.responses = nil
f.calls = nil
}
func (f *MockTool) Mock(fn interface{}) *Call {
mutex.Lock()
defer mutex.Unlock()
f.init()
fnType := reflect.TypeOf(fn)
if fnType.Kind() != reflect.Func {
panic("fn is not a function")
}
c := &Call{
mTool: f,
fn: fn,
fnType: fnType,
fnName: runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name(),
ParamUpdate: make(map[int]interface{}, 0),
}
return c
}
func (f *MockTool) GetMockedResponse(fn interface{}, params ...interface{}) *Call {
c := f.Mock(fn).WithParams(params...)
mutex.Lock()
defer mutex.Unlock()
c.Count = len(f.calls[c.fnName]) + 1
responses := f.responses[c.fnName]
// Find response with params
for i := 0; i < len(responses); i++ {
if responses[i].hasParams && responses[i].paramsHash == c.paramsHash {
f.extractResponse(c, i)
return c
}
}
// Find generic response (without params)
for i := 0; i < len(responses); i++ {
if !responses[i].hasParams {
f.extractResponse(c, i)
return c
}
}
panic(fmt.Sprintf("no mocked response available for fn %s", c.fnName))
}
func (f *MockTool) extractResponse(c *Call, i int) {
c.Response = f.responses[c.fnName][i].Response
c.ParamUpdate = f.responses[c.fnName][i].ParamUpdate
f.calls[c.fnName] = append(f.calls[c.fnName], *c)
f.responses[c.fnName] = append(f.responses[c.fnName][:i], f.responses[c.fnName][i+1:]...)
}
func (f *MockTool) GetMockedCalls(fn interface{}) []Call {
c := f.Mock(fn)
return f.calls[c.fnName]
}
func (f *MockTool) AllMocksUsed() bool {
for _, r := range f.responses {
if len(r) != 0 {
return false
}
}
return true
}