-
Notifications
You must be signed in to change notification settings - Fork 6
/
watch_test.go
86 lines (66 loc) · 1.43 KB
/
watch_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
package stopwatch
import (
"fmt"
"regexp"
"testing"
"time"
)
const (
expectedMilliseconds = (86400 * 1000)
)
func withNow(fn func() time.Time, callback func()) {
oldNow := now
defer func() {
now = oldNow
}()
now = fn
callback()
}
func withNowOffset(t time.Duration, callback func()) {
fn := func() time.Time {
return time.Now().Add(t)
}
withNow(fn, callback)
}
func TestStopWatchString(t *testing.T) {
exp := `^30\.(\d+)ms$`
rexp := regexp.MustCompile(exp)
var watch Watch
withNowOffset(-30*time.Millisecond, func() {
watch = Start()
})
watch.Stop()
// We're not millisecond accurate above, so...
if !rexp.MatchString(watch.String()) {
t.Fatalf("expected `%s` to match `%s`", watch, exp)
}
}
func TestDeferring(t *testing.T) {
exp := `^30m0\.\d+s$`
rexp := regexp.MustCompile(exp)
var called bool
defer func() {
if !called {
t.Fatalf("failed to call defered function")
}
}()
var watch Watch
// Rewind the clock by 30 minutes so we have a realistic value to check this
// against.
withNowOffset(-30*time.Minute, func() {
watch = Start()
})
defer watch.Timer(func(w Watch) {
called = true
if !rexp.MatchString(w.String()) {
t.Fatalf("expected `%s` to match `%s`", watch, exp)
}
})
}
func ExampleWatch_Timer() {
defer StartAt(time.Now().Add(-30 * time.Minute)).Timer(func(w Watch) {
fmt.Printf("elapsed time: %d minutes", w.Minutes())
})
// Output:
// elapsed time: 30 minutes
}