@@ -44,7 +44,7 @@ func TestExampleTickerFunc(t *testing.T) {
44
44
ctx , cancel := context .WithTimeout (context .Background (), 10 * time .Second )
45
45
defer cancel ()
46
46
47
- mClock := clock .NewMock ()
47
+ mClock := clock .NewMock (t )
48
48
49
49
// Because the ticker is started on a goroutine, we can't immediately start
50
50
// advancing the clock, or we will race with the start of the ticker. If we
@@ -76,9 +76,74 @@ func TestExampleTickerFunc(t *testing.T) {
76
76
}
77
77
78
78
// Now that we know the ticker is started, we can advance the time.
79
- mClock .Advance (time .Hour ).MustWait (ctx , t )
79
+ mClock .Advance (time .Hour ).MustWait (ctx )
80
80
81
81
if tks := tc .Ticks (); tks != 1 {
82
82
t .Fatalf ("expected 1 got %d ticks" , tks )
83
83
}
84
84
}
85
+
86
+ type exampleLatencyMeasurer struct {
87
+ mu sync.Mutex
88
+ lastLatency time.Duration
89
+ }
90
+
91
+ func newExampleLatencyMeasurer (ctx context.Context , clk clock.Clock ) * exampleLatencyMeasurer {
92
+ m := & exampleLatencyMeasurer {}
93
+ clk .TickerFunc (ctx , 10 * time .Second , func () error {
94
+ start := clk .Now ()
95
+ // m.doSomething()
96
+ latency := clk .Since (start )
97
+ m .mu .Lock ()
98
+ defer m .mu .Unlock ()
99
+ m .lastLatency = latency
100
+ return nil
101
+ })
102
+ return m
103
+ }
104
+
105
+ func (m * exampleLatencyMeasurer ) LastLatency () time.Duration {
106
+ m .mu .Lock ()
107
+ defer m .mu .Unlock ()
108
+ return m .lastLatency
109
+ }
110
+
111
+ func TestExampleLatencyMeasurer (t * testing.T ) {
112
+ t .Parallel ()
113
+
114
+ // nolint:gocritic // trying to avoid Coder-specific stuff with an eye toward spinning this out
115
+ ctx , cancel := context .WithTimeout (context .Background (), 10 * time .Second )
116
+ defer cancel ()
117
+
118
+ mClock := clock .NewMock (t )
119
+ trap := mClock .Trap ().Since ()
120
+ defer trap .Close ()
121
+
122
+ lm := newExampleLatencyMeasurer (ctx , mClock )
123
+
124
+ w := mClock .Advance (10 * time .Second ) // triggers first tick
125
+ c := trap .MustWait (ctx ) // call to Since()
126
+ mClock .Advance (33 * time .Millisecond )
127
+ c .Release ()
128
+ w .MustWait (ctx )
129
+
130
+ if l := lm .LastLatency (); l != 33 * time .Millisecond {
131
+ t .Fatalf ("expected 33ms got %s" , l .String ())
132
+ }
133
+
134
+ // Next tick is in 10s - 33ms, but if we don't want to calculate, we can use:
135
+ d , w2 := mClock .AdvanceNext ()
136
+ c = trap .MustWait (ctx )
137
+ mClock .Advance (17 * time .Millisecond )
138
+ c .Release ()
139
+ w2 .MustWait (ctx )
140
+
141
+ expectedD := 10 * time .Second - 33 * time .Millisecond
142
+ if d != expectedD {
143
+ t .Fatalf ("expected %s got %s" , expectedD .String (), d .String ())
144
+ }
145
+
146
+ if l := lm .LastLatency (); l != 17 * time .Millisecond {
147
+ t .Fatalf ("expected 17ms got %s" , l .String ())
148
+ }
149
+ }
0 commit comments