-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_clock_test.go
125 lines (92 loc) · 1.85 KB
/
example_clock_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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package clock_test
import (
"context"
"fmt"
"sync"
"time"
"github.com/transcelestial/clock"
)
func ExampleClock_Now() {
ck := clock.New()
// inject the Clock interface as dependency into some func
myFunc := func(ck clock.Clock) {
// use the clock the same way you'd use the "time" package
fmt.Println(ck.Now())
}
myFunc(ck)
}
func ExampleClock_Sleep() {
ck := clock.New()
now := time.Now()
ck.Sleep(time.Second)
d := time.Since(now)
if d >= time.Second {
fmt.Println("slept a second")
}
// Output:
// slept a second
}
func ExampleClock_NewTicker() {
ck := clock.New()
// create a new ticker that ticks every 100ms
ticker := ck.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
ctx, cancel := context.WithTimeout(context.Background(), 350*time.Millisecond)
defer cancel()
var i int
for {
select {
case <-ctx.Done():
return
// get notifications from the ticker (same way the "time" ticker.C chan works)
case <-ticker.C():
fmt.Println(i)
i++
}
}
// Output:
// 0
// 1
// 2
}
func ExampleClock_NewTimer() {
ck := clock.New()
// create a new timer that will trigger after 100ms
timer := ck.NewTimer(100 * time.Millisecond)
defer timer.Stop()
// wait for the timer to trigger
<-timer.C()
fmt.Println("done")
// Output:
// done
}
func ExampleClock_After() {
ck := clock.New()
// wait for the timer to trigger
<-ck.After(100 * time.Millisecond)
fmt.Println("done")
// Output:
// done
}
func ExampleClock_AfterFunc() {
ck := clock.New()
var wg sync.WaitGroup
wg.Add(1)
f := func() {
wg.Done()
}
_ = ck.AfterFunc(100*time.Millisecond, f)
// wait for the timer to trigger
wg.Wait()
fmt.Println("done")
// Output:
// done
}
func ExampleClock_Tick() {
ck := clock.New()
// wait for the timer to trigger
<-ck.Tick(100 * time.Millisecond)
fmt.Println("done")
// Output:
// done
}