-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmock.go
137 lines (109 loc) · 2.12 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
package clock
import (
"sync"
"time"
)
type mock struct {
base time.Time
setAt time.Time
frozen bool
timeMutex sync.Mutex
sleep time.Duration
sleepMutex sync.Mutex
}
// NewMock returns a new manipulable Clock.
func NewMock() Mock {
return &mock{
base: time.Now(),
setAt: time.Now(),
sleep: -1,
}
}
func (c *mock) Now() time.Time {
defer c.timeMutex.Unlock()
c.timeMutex.Lock()
if c.frozen {
return c.setAt
}
return c.base.Add(c.elapsed())
}
func (c *mock) Set(t time.Time) Mock {
defer c.timeMutex.Unlock()
c.timeMutex.Lock()
c.base = t
c.setAt = time.Now()
return c
}
func (c *mock) Add(d time.Duration) Mock {
defer c.timeMutex.Unlock()
c.timeMutex.Lock()
c.base = c.base.Add(d)
if c.frozen {
c.setAt = c.setAt.Add(d)
} else {
c.setAt = time.Now()
}
return c
}
func (c *mock) Freeze() Mock {
return c.FreezeAt(c.Now())
}
func (c *mock) IsFrozen() bool {
defer c.timeMutex.Unlock()
c.timeMutex.Lock()
return c.frozen
}
func (c *mock) FreezeAt(t time.Time) Mock {
defer c.timeMutex.Unlock()
c.timeMutex.Lock()
c.frozen = true
c.setAt = t
return c
}
func (c *mock) Unfreeze() Mock {
defer c.timeMutex.Unlock()
c.timeMutex.Lock()
c.setAt = c.setAt.Add(c.elapsed())
c.frozen = false
return c
}
func (c *mock) SetSleep(d time.Duration) Mock {
defer c.sleepMutex.Unlock()
c.sleepMutex.Lock()
c.sleep = d
return c
}
func (c *mock) NoSleep() Mock {
c.SetSleep(0)
return c
}
func (c *mock) ResetSleep() Mock {
c.SetSleep(-1)
return c
}
func (c *mock) Sleep(d time.Duration) {
c.sleepMutex.Lock()
override := c.sleep
c.sleepMutex.Unlock()
if override == -1 {
time.Sleep(d)
} else {
time.Sleep(override)
}
}
// elapsed returns the Duration between the date the time was set and now.
func (c *mock) elapsed() time.Duration {
return time.Now().Sub(c.setAt)
}
func (*mock) Tick(d time.Duration) <-chan time.Time {
// TODO: make mockable
return time.Tick(d)
}
func (*mock) Ticker(d time.Duration) *time.Ticker {
// TODO: make mockable
return time.NewTicker(d)
}
func (c *mock) After(d time.Duration) <-chan time.Time {
// TODO: make mockable
return time.After(d)
}