-
Notifications
You must be signed in to change notification settings - Fork 2
/
ttime_test.go
106 lines (100 loc) · 2.4 KB
/
ttime_test.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
package ttime
import (
// "github.com/stretchr/testify/assert"
"testing"
"time"
)
func TestFreezingTime(t *testing.T) {
// freeze time at a specific date/time (eg, test leap-year support!):
now, err := time.Parse(time.RFC3339, "2012-02-29T00:00:00Z")
if err != nil {
panic("date time parse failed")
}
Freeze(now)
if !IsFrozen() {
t.Error("Time should be frozen here, and was not.")
}
if Now().UTC() != now {
t.Error("Time should still be set to frozen time")
}
t.Logf("It is now %v (frozen)", Now().UTC())
Unfreeze()
if Now().UTC() == now || IsFrozen() {
t.Error("Time should no longer be frozen")
}
t.Logf("It is now %v (not frozen)", Now().UTC())
}
func TestAfter(t *testing.T) {
// test frozen functionality.
start := Now()
Freeze(Now())
<-After(10 * time.Millisecond)
Unfreeze()
elapsed := Now().Sub(start)
t.Logf("Took %v", elapsed)
if elapsed >= 1*time.Millisecond {
t.Error("Took too long")
}
// test original functionality is restored
start = Now()
<-After(1 * time.Millisecond)
elapsed = Now().Sub(start)
t.Logf("Took %v", elapsed)
if elapsed > 2*time.Millisecond {
t.Error("Took too long")
}
if elapsed < 1*time.Millisecond {
t.Error("Went too fast")
}
}
func TestTick(t *testing.T) {
// test frozen functionality.
start := Now()
Freeze(start)
c := Tick(10 * time.Millisecond)
<-c
<-c
<-c
if !start.Add(40 * time.Millisecond).Equal(Now()) {
t.Errorf("Expected Tick to advance clock, did not. %v != %v", start.Add(40*time.Millisecond), Now())
}
Unfreeze()
elapsed := Now().Sub(start)
t.Logf("Took %v", elapsed)
if elapsed >= 1*time.Millisecond {
t.Error("Took too long")
}
// test original functionality is restored
start = Now()
c = Tick(1 * time.Millisecond)
<-c
<-c
<-c
elapsed = Now().Sub(start)
t.Logf("Took %v", elapsed)
if elapsed > 4*time.Millisecond {
t.Error("Took too long")
}
if elapsed < 3*time.Millisecond {
t.Error("Went too fast")
}
}
func TestSleep(t *testing.T) {
start := time.Now()
Freeze(start)
Sleep(1 * time.Second)
Unfreeze()
elapsed := time.Now().Sub(start)
if elapsed > 1*time.Millisecond {
t.Error("Took too long")
}
start = Now()
Sleep(1 * time.Millisecond)
elapsed = Now().Sub(start)
if elapsed > 2*time.Millisecond {
t.Error("Took too long")
}
if elapsed < 1*time.Millisecond {
t.Error("Went too fast")
}
}