forked from rethinkdb/rethinkdb-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mock.go
394 lines (326 loc) · 10.3 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
package gorethink
import (
"encoding/json"
"fmt"
"reflect"
"sync"
"time"
p "gopkg.in/dancannon/gorethink.v2/ql2"
)
// Mocking is based on the amazing package github.com/stretchr/testify
// testingT is an interface wrapper around *testing.T
type testingT interface {
Logf(format string, args ...interface{})
Errorf(format string, args ...interface{})
FailNow()
}
// MockAnything can be used in place of any term, this is useful when you want
// mock similar queries or queries that you don't quite know the exact structure
// of.
func MockAnything() Term {
t := constructRootTerm("MockAnything", p.Term_DATUM, nil, nil)
t.isMockAnything = true
return t
}
func (t Term) MockAnything() Term {
t = constructMethodTerm(t, "MockAnything", p.Term_DATUM, nil, nil)
t.isMockAnything = true
return t
}
// MockQuery represents a mocked query and is used for setting expectations,
// as well as recording activity.
type MockQuery struct {
parent *Mock
// Holds the query and term
Query Query
// Holds the JSON representation of query
BuiltQuery []byte
// Holds the response that should be returned when this method is executed.
Response interface{}
// Holds the error that should be returned when this method is executed.
Error error
// The number of times to return the return arguments when setting
// expectations. 0 means to always return the value.
Repeatability int
// Holds a channel that will be used to block the Return until it either
// recieves a message or is closed. nil means it returns immediately.
WaitFor <-chan time.Time
// Amount of times this query has been executed
executed int
}
func newMockQuery(parent *Mock, q Query) *MockQuery {
// Build and marshal term
builtQuery, err := json.Marshal(q.Build())
if err != nil {
panic(fmt.Sprintf("Failed to build query: %s", err))
}
return &MockQuery{
parent: parent,
Query: q,
BuiltQuery: builtQuery,
Response: make([]interface{}, 0),
Repeatability: 0,
WaitFor: nil,
}
}
func newMockQueryFromTerm(parent *Mock, t Term, opts map[string]interface{}) *MockQuery {
q, err := parent.newQuery(t, opts)
if err != nil {
panic(fmt.Sprintf("Failed to build query: %s", err))
}
return newMockQuery(parent, q)
}
func (mq *MockQuery) lock() {
mq.parent.mu.Lock()
}
func (mq *MockQuery) unlock() {
mq.parent.mu.Unlock()
}
// Return specifies the return arguments for the expectation.
//
// mock.On(r.Table("test")).Return(nil, errors.New("failed"))
func (mq *MockQuery) Return(response interface{}, err error) *MockQuery {
mq.lock()
defer mq.unlock()
mq.Response = response
mq.Error = err
return mq
}
// Once indicates that that the mock should only return the value once.
//
// mock.On(r.Table("test")).Return(result, nil).Once()
func (mq *MockQuery) Once() *MockQuery {
return mq.Times(1)
}
// Twice indicates that that the mock should only return the value twice.
//
// mock.On(r.Table("test")).Return(result, nil).Twice()
func (mq *MockQuery) Twice() *MockQuery {
return mq.Times(2)
}
// Times indicates that that the mock should only return the indicated number
// of times.
//
// mock.On(r.Table("test")).Return(result, nil).Times(5)
func (mq *MockQuery) Times(i int) *MockQuery {
mq.lock()
defer mq.unlock()
mq.Repeatability = i
return mq
}
// WaitUntil sets the channel that will block the mock's return until its closed
// or a message is received.
//
// mock.On(r.Table("test")).WaitUntil(time.After(time.Second))
func (mq *MockQuery) WaitUntil(w <-chan time.Time) *MockQuery {
mq.lock()
defer mq.unlock()
mq.WaitFor = w
return mq
}
// After sets how long to block until the query returns
//
// mock.On(r.Table("test")).After(time.Second)
func (mq *MockQuery) After(d time.Duration) *MockQuery {
return mq.WaitUntil(time.After(d))
}
// On chains a new expectation description onto the mocked interface. This
// allows syntax like.
//
// Mock.
// On(r.Table("test")).Return(result, nil).
// On(r.Table("test2")).Return(nil, errors.New("Some Error"))
func (mq *MockQuery) On(t Term) *MockQuery {
return mq.parent.On(t)
}
// Mock is used to mock query execution and verify that the expected queries are
// being executed. Mocks are used by creating an instance using NewMock and then
// passing this when running your queries instead of a session. For example:
//
// mock := r.NewMock()
// mock.On(r.Table("test")).Return([]interface{}{data}, nil)
//
// cursor, err := r.Table("test").Run(mock)
//
// mock.AssertExpectations(t)
type Mock struct {
mu sync.Mutex
opts ConnectOpts
ExpectedQueries []*MockQuery
Queries []MockQuery
}
// NewMock creates an instance of Mock, you can optionally pass ConnectOpts to
// the function, if passed any mocked query will be generated using those
// options.
func NewMock(opts ...ConnectOpts) *Mock {
m := &Mock{
ExpectedQueries: make([]*MockQuery, 0),
Queries: make([]MockQuery, 0),
}
if len(opts) > 0 {
m.opts = opts[0]
}
return m
}
// On starts a description of an expectation of the specified query
// being executed.
//
// mock.On(r.Table("test"))
func (m *Mock) On(t Term, opts ...map[string]interface{}) *MockQuery {
var qopts map[string]interface{}
if len(opts) > 0 {
qopts = opts[0]
}
m.mu.Lock()
defer m.mu.Unlock()
mq := newMockQueryFromTerm(m, t, qopts)
m.ExpectedQueries = append(m.ExpectedQueries, mq)
return mq
}
// AssertExpectations asserts that everything specified with On and Return was
// in fact executed as expected. Queries may have been executed in any order.
func (m *Mock) AssertExpectations(t testingT) bool {
var somethingMissing bool
var failedExpectations int
// iterate through each expectation
expectedQueries := m.expectedQueries()
for _, expectedQuery := range expectedQueries {
if !m.queryWasExecuted(expectedQuery) && expectedQuery.executed == 0 {
somethingMissing = true
failedExpectations++
t.Logf("❌\t%s", expectedQuery.Query.Term.String())
} else {
m.mu.Lock()
if expectedQuery.Repeatability > 0 {
somethingMissing = true
failedExpectations++
} else {
t.Logf("✅\t%s", expectedQuery.Query.Term.String())
}
m.mu.Unlock()
}
}
if somethingMissing {
t.Errorf("FAIL: %d out of %d expectation(s) were met.\n\tThe query you are testing needs to be executed %d more times(s).", len(expectedQueries)-failedExpectations, len(expectedQueries), failedExpectations)
}
return !somethingMissing
}
// AssertNumberOfExecutions asserts that the query was executed expectedExecutions times.
func (m *Mock) AssertNumberOfExecutions(t testingT, expectedQuery *MockQuery, expectedExecutions int) bool {
var actualExecutions int
for _, query := range m.queries() {
if query.Query.Term.compare(*expectedQuery.Query.Term, map[int64]int64{}) && query.Repeatability > -1 {
// if bytes.Equal(query.BuiltQuery, expectedQuery.BuiltQuery) {
actualExecutions++
}
}
if expectedExecutions != actualExecutions {
t.Errorf("Expected number of executions (%d) does not match the actual number of executions (%d).", expectedExecutions, actualExecutions)
return false
}
return true
}
// AssertExecuted asserts that the method was executed.
// It can produce a false result when an argument is a pointer type and the underlying value changed after executing the mocked method.
func (m *Mock) AssertExecuted(t testingT, expectedQuery *MockQuery) bool {
if !m.queryWasExecuted(expectedQuery) {
t.Errorf("The query \"%s\" should have been executed, but was not.", expectedQuery.Query.Term.String())
return false
}
return true
}
// AssertNotExecuted asserts that the method was not executed.
// It can produce a false result when an argument is a pointer type and the underlying value changed after executing the mocked method.
func (m *Mock) AssertNotExecuted(t testingT, expectedQuery *MockQuery) bool {
if m.queryWasExecuted(expectedQuery) {
t.Errorf("The query \"%s\" was executed, but should NOT have been.", expectedQuery.Query.Term.String())
return false
}
return true
}
func (m *Mock) IsConnected() bool {
return true
}
func (m *Mock) Query(q Query) (*Cursor, error) {
found, query := m.findExpectedQuery(q)
if found < 0 {
panic(fmt.Sprintf("gorethink: mock: This query was unexpected:\n\t\t%s", q.Term.String()))
} else {
m.mu.Lock()
switch {
case query.Repeatability == 1:
query.Repeatability = -1
query.executed++
case query.Repeatability > 1:
query.Repeatability--
query.executed++
case query.Repeatability == 0:
query.executed++
}
m.mu.Unlock()
}
// add the query
m.mu.Lock()
m.Queries = append(m.Queries, *newMockQuery(m, q))
m.mu.Unlock()
// block if specified
if query.WaitFor != nil {
<-query.WaitFor
}
// Return error without building cursor if non-nil
if query.Error != nil {
return nil, query.Error
}
// Build cursor and return
c := newCursor(nil, "", query.Query.Token, query.Query.Term, query.Query.Opts)
c.finished = true
c.fetching = false
c.isAtom = true
responseVal := reflect.ValueOf(query.Response)
if responseVal.Kind() == reflect.Slice || responseVal.Kind() == reflect.Array {
for i := 0; i < responseVal.Len(); i++ {
c.buffer = append(c.buffer, responseVal.Index(i).Interface())
}
} else {
c.buffer = append(c.buffer, query.Response)
}
return c, nil
}
func (m *Mock) Exec(q Query) error {
_, err := m.Query(q)
return err
}
func (m *Mock) newQuery(t Term, opts map[string]interface{}) (Query, error) {
return newQuery(t, opts, &m.opts)
}
func (m *Mock) findExpectedQuery(q Query) (int, *MockQuery) {
m.mu.Lock()
defer m.mu.Unlock()
for i, query := range m.ExpectedQueries {
// if bytes.Equal(query.BuiltQuery, builtQuery) && query.Repeatability > -1 {
if query.Query.Term.compare(*q.Term, map[int64]int64{}) && query.Repeatability > -1 {
return i, query
}
}
return -1, nil
}
func (m *Mock) queryWasExecuted(expectedQuery *MockQuery) bool {
for _, query := range m.queries() {
if query.Query.Term.compare(*expectedQuery.Query.Term, map[int64]int64{}) {
// if bytes.Equal(query.BuiltQuery, expectedQuery.BuiltQuery) {
return true
}
}
// we didn't find the expected query
return false
}
func (m *Mock) expectedQueries() []*MockQuery {
m.mu.Lock()
defer m.mu.Unlock()
return append([]*MockQuery{}, m.ExpectedQueries...)
}
func (m *Mock) queries() []MockQuery {
m.mu.Lock()
defer m.mu.Unlock()
return append([]MockQuery{}, m.Queries...)
}