-
Notifications
You must be signed in to change notification settings - Fork 0
/
mock.go
97 lines (84 loc) · 2.31 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 nosqlorm
import (
"github.com/stretchr/testify/assert"
"sync"
"testing"
)
type MockSession struct {
Test *testing.T
Expectations []interface{}
idx int
lock sync.Mutex
}
type expect[T interface{}] struct {
ExpectInput []T
returnObj []T // For Select only
errorObj error
}
type MockTable[T interface{}] struct {
sess *MockSession
t *testing.T
}
func NewMockSession(t *testing.T) *MockSession {
return &MockSession{Test: t, Expectations: make([]interface{}, 0), idx: 0}
}
func (m *MockSession) AddIdx() {
m.lock.Lock()
defer m.lock.Unlock()
m.idx++
}
func NewMockTable[T interface{}](sess *MockSession) *MockTable[T] {
return &MockTable[T]{sess: sess, t: sess.Test}
}
func (m *MockTable[T]) Select(obj T) ([]T, error) {
idx := m.sess.idx
defer m.sess.AddIdx()
if idx >= len(m.sess.Expectations) {
m.t.Error("Unexpected query")
}
assert.Equal(m.t, obj, m.sess.Expectations[idx].(expect[T]).ExpectInput[0])
return m.sess.Expectations[idx].(expect[T]).returnObj, nil
}
func (m *MockTable[T]) Insert(obj T) error {
idx := m.sess.idx
defer m.sess.AddIdx()
if idx >= len(m.sess.Expectations) {
m.t.Error("Unexpected query")
}
assert.Equal(m.t, obj, m.sess.Expectations[idx].(expect[T]).ExpectInput[0])
return m.sess.Expectations[idx].(expect[T]).errorObj
}
func (m *MockTable[T]) Update(obj T) error {
idx := m.sess.idx
defer m.sess.AddIdx()
if idx >= len(m.sess.Expectations) {
m.t.Error("Unexpected query")
}
assert.Equal(m.t, obj, m.sess.Expectations[idx].(expect[T]).ExpectInput[0])
return m.sess.Expectations[idx].(expect[T]).errorObj
}
func (m *MockTable[T]) Delete(obj T) error {
idx := m.sess.idx
defer m.sess.AddIdx()
if idx >= len(m.sess.Expectations) {
m.t.Error("Unexpected query")
}
assert.Equal(m.t, obj, m.sess.Expectations[idx].(expect[T]).ExpectInput[0])
return m.sess.Expectations[idx].(expect[T]).errorObj
}
func (m *MockTable[T]) AddSelectExpectation(input T, objs []T) {
newExpect := expect[T]{
ExpectInput: []T{input},
returnObj: objs,
errorObj: nil,
}
m.sess.Expectations = append(m.sess.Expectations, newExpect)
}
func (m *MockTable[T]) AddOtherExpectation(input T, err error) {
newExpect := expect[T]{
ExpectInput: []T{input},
returnObj: nil,
errorObj: err,
}
m.sess.Expectations = append(m.sess.Expectations, newExpect)
}