-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtesting.go
More file actions
49 lines (42 loc) · 964 Bytes
/
testing.go
File metadata and controls
49 lines (42 loc) · 964 Bytes
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
package cachex
import (
"sync"
"time"
)
// MockClock provides a controllable time source for testing
type MockClock struct {
mu sync.RWMutex
current time.Time
}
// NewMockClock creates a new mock clock starting at the given time
func NewMockClock(start time.Time) *MockClock {
return &MockClock{
current: start,
}
}
// Now returns the current mocked time
func (m *MockClock) Now() time.Time {
m.mu.RLock()
defer m.mu.RUnlock()
return m.current
}
// Advance moves the clock forward by the given duration
func (m *MockClock) Advance(d time.Duration) {
m.mu.Lock()
defer m.mu.Unlock()
m.current = m.current.Add(d)
}
// Set sets the clock to a specific time
func (m *MockClock) Set(t time.Time) {
m.mu.Lock()
defer m.mu.Unlock()
m.current = t
}
// Install replaces the global NowFunc with this mock clock
func (m *MockClock) Install() func() {
originalNowFunc := NowFunc
NowFunc = m.Now
return func() {
NowFunc = originalNowFunc
}
}