This repository was archived by the owner on Mar 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmock.go
278 lines (236 loc) · 6.09 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
package tock
import (
"runtime"
"sort"
"sync"
"time"
)
// MockClock is a Clock where time only advances under your control
type MockClock interface {
Clock
Advance(duration time.Duration)
BlockUntil(n int)
}
type mockClock struct {
advanceMutex sync.Mutex // Mutexes Advance()
mutex sync.Mutex // Protects all internal data
now time.Time
sleepersChanged []chan int
opts MockOptions
// Sleepers are an empty interface because we want to preserve the struct
// with a channel C for the Ticker or Timer we return to users.
// These are sorted by time.
sleepers []interface{}
}
var _ MockClock = &mockClock{}
type MockOptions struct {
// Yield to other goroutines after firing a Timer or Ticker.
Yield bool
}
// NewMock creates a new mock Clock, starting at zero time
func NewMock(opts MockOptions) *mockClock {
return &mockClock{
now: time.Time{},
}
}
// Now is the current time, starting at zero time and controlled by Advance
func (c *mockClock) Now() time.Time {
c.mutex.Lock()
defer c.mutex.Unlock()
return c.now
}
func sleeperWhen(sleeper interface{}) time.Time {
switch s := sleeper.(type) {
case *Timer:
return s.when
case *Ticker:
return s.when
default:
return time.Time{}
}
}
func notifySleeper(sleeper interface{}, now time.Time, yield bool) {
switch s := sleeper.(type) {
case *Timer:
s.outC <- now
case *Ticker:
s.outC <- now
}
// Give timers an opportunity to run - helpful if we're in the middle of a
// long Advance. Very well-written tests shouldn't rely on timers running
// immediately at the time they are scheduled and don't need this.
if yield {
runtime.Gosched()
time.Sleep(100 * time.Microsecond)
}
}
// must be holding mutex when calling
func (c *mockClock) insertSleeper(s interface{}) {
t := sleeperWhen(s)
i := sort.Search(len(c.sleepers), func(i int) bool {
return t.Before(sleeperWhen(c.sleepers[i]))
})
c.sleepers = append(c.sleepers, &Timer{})
copy(c.sleepers[i+1:], c.sleepers[i:])
c.sleepers[i] = s
for _, sc := range c.sleepersChanged {
sc <- len(c.sleepers)
}
}
// must be holding mutex when calling
func (c *mockClock) removeSleeper(s interface{}) bool {
i := 0
for ; i < len(c.sleepers); i++ {
if s == c.sleepers[i] {
break
}
}
if i == len(c.sleepers) {
// Couldn't find the timer in this list. This happens if the timer or
// ticker fired via Advance(), and is calling Stop()
return false
}
c.sleepers = append(c.sleepers[:i], c.sleepers[i+1:]...)
for _, sc := range c.sleepersChanged {
sc <- len(c.sleepers)
}
return true
}
// NewTimer creates a new Timer that will send to C after duration
func (c *mockClock) NewTimer(duration time.Duration) *Timer {
c.mutex.Lock()
defer c.mutex.Unlock()
outC := make(chan time.Time)
t := &Timer{
C: outC, // user sees receive-channel
outC: outC, // we use it as a send-channel
mock: c,
when: c.now.Add(duration),
}
c.insertSleeper(t)
return t
}
// NewTicker creates a new Ticker that will send to C every duration interval
func (c *mockClock) NewTicker(duration time.Duration) *Ticker {
c.mutex.Lock()
defer c.mutex.Unlock()
outC := make(chan time.Time)
t := &Ticker{
C: outC, // user sees receive-channel
outC: outC, // we use it as a send-channel
mock: c,
when: c.now.Add(duration),
period: duration,
}
c.insertSleeper(t)
return t
}
// Advance simulated time by duration, firing any registerd Timers, etc.
func (c *mockClock) Advance(duration time.Duration) {
// Take advanceMutex and then mutex. We will drop/retake mutex
// as we fire each timer, since some timers may register new timers
c.advanceMutex.Lock()
defer c.advanceMutex.Unlock()
c.mutex.Lock()
defer c.mutex.Unlock()
until := c.now.Add(duration)
for {
if len(c.sleepers) == 0 {
c.now = until
return
}
headWhen := sleeperWhen(c.sleepers[0])
if headWhen.After(until) {
c.now = until
return
}
// Arrange for all our internal data to be correct before dropping the
// lock to send - the timer may want to register new timers.
head, remaining := c.sleepers[0], c.sleepers[1:]
c.sleepers = remaining
c.now = headWhen
// Drop the mutex temporarily and notify
c.mutex.Unlock()
notifySleeper(head, c.now, c.opts.Yield)
c.mutex.Lock()
switch s := head.(type) {
case *Ticker:
// Requeue ticker
if !s.stopped {
s.when = c.now.Add(s.period)
c.insertSleeper(s)
}
case *Timer:
// Discard timer, and notify that sleepers changed
s.stopped = true
for _, sc := range c.sleepersChanged {
sc <- len(c.sleepers)
}
}
}
}
func stopMockTimer(t *Timer) bool {
c := t.mock
c.mutex.Lock()
defer c.mutex.Unlock()
if t.stopped {
return false
}
t.stopped = true
return c.removeSleeper(t)
}
func stopMockTicker(t *Ticker) {
c := t.mock
c.mutex.Lock()
defer c.mutex.Unlock()
if t.stopped {
return
}
t.stopped = true
c.removeSleeper(t)
}
// BlockUntil will not return until the number of pending Timers etc. is exactly n
func (c *mockClock) BlockUntil(n int) {
changed := make(chan int)
c.mutex.Lock()
defer c.mutex.Unlock()
if len(c.sleepers) == n {
return
}
c.sleepersChanged = append(c.sleepersChanged, changed)
c.mutex.Unlock()
for {
nowSleepers := <-changed
if nowSleepers == n {
c.mutex.Lock()
for i, x := range c.sleepersChanged {
if x == changed {
c.sleepersChanged = append(c.sleepersChanged[:i], c.sleepersChanged[i+1:]...)
break
}
}
return
}
}
}
// A channel that receives after duration
// Equivalent to `c.NewTimer(duration).C`
func (c *mockClock) After(duration time.Duration) <-chan time.Time {
return c.NewTimer(duration).C
}
// Blocks until duration has elapsed, returns immediately if duration <= 0
// Equivalent to `<-c.NewTimer(duration).C`
func (c *mockClock) Sleep(duration time.Duration) {
if duration <= 0 {
return
}
<-c.After(duration)
}
// Elasped since t relative to mock time, equivalent to `c.Now().Sub(t)`
func (c *mockClock) Since(t time.Time) time.Duration {
return c.now.Sub(t)
}
// Time until t relative to mock time, equivalent to `t.Sub(c.Now())`
func (c *mockClock) Until(t time.Time) time.Duration {
return t.Sub(c.now)
}