/
monitormock.go
76 lines (57 loc) · 1.4 KB
/
monitormock.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
package monitor
import (
"sync"
"testing"
)
type mockedMethods struct {
startMock func() error
stopMock func() error
}
// TestMonitor us
type TestMonitor interface {
Monitor
MockStart(t *testing.T, impl func() error)
MockStop(t *testing.T, impl func() error)
}
// A testManipulator is an empty TransactionalManipulator that can be easily mocked.
type testMonitor struct {
mocks map[*testing.T]*mockedMethods
lock *sync.Mutex
currentTest *testing.T
}
// NewTestMonitor returns a new TestManipulator.
func NewTestMonitor() TestMonitor {
return &testMonitor{
lock: &sync.Mutex{},
mocks: map[*testing.T]*mockedMethods{},
}
}
func (m *testMonitor) MockStart(t *testing.T, impl func() error) {
m.currentMocks(t).startMock = impl
}
func (m *testMonitor) MockStop(t *testing.T, impl func() error) {
m.currentMocks(t).stopMock = impl
}
func (m *testMonitor) Start() error {
if mock := m.currentMocks(m.currentTest); mock != nil && mock.startMock != nil {
return mock.startMock()
}
return nil
}
func (m *testMonitor) Stop() error {
if mock := m.currentMocks(m.currentTest); mock != nil && mock.stopMock != nil {
return mock.stopMock()
}
return nil
}
func (m *testMonitor) currentMocks(t *testing.T) *mockedMethods {
m.lock.Lock()
defer m.lock.Unlock()
mocks := m.mocks[t]
if mocks == nil {
mocks = &mockedMethods{}
m.mocks[t] = mocks
}
m.currentTest = t
return mocks
}