2022-03-26 17:59:19 +03:00
|
|
|
package jitter
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestNewTickerContext(t *testing.T) {
|
|
|
|
t.Parallel()
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
ticker := NewTickerContext(ctx, 600*time.Millisecond, 1000*time.Millisecond)
|
|
|
|
defer ticker.Stop()
|
|
|
|
loop:
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
ticker.Stop()
|
|
|
|
break loop
|
|
|
|
case v, ok := <-ticker.C:
|
|
|
|
if ok {
|
|
|
|
t.Fatalf("context must be closed %s", v)
|
|
|
|
}
|
|
|
|
break loop
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestTicker(t *testing.T) {
|
|
|
|
t.Parallel()
|
|
|
|
|
2024-12-09 16:23:25 +03:00
|
|
|
minTime := time.Duration(10)
|
|
|
|
maxTime := time.Duration(20)
|
2022-03-26 17:59:19 +03:00
|
|
|
|
|
|
|
// tick can take a little longer since we're not adjusting it to account for
|
|
|
|
// processing.
|
|
|
|
precision := time.Duration(4)
|
|
|
|
|
2024-12-09 16:23:25 +03:00
|
|
|
rt := NewTicker(minTime*time.Millisecond, maxTime*time.Millisecond)
|
2022-03-26 17:59:19 +03:00
|
|
|
for i := 0; i < 5; i++ {
|
|
|
|
t0 := time.Now()
|
|
|
|
t1 := <-rt.C
|
|
|
|
td := t1.Sub(t0)
|
2024-12-09 16:23:25 +03:00
|
|
|
if td < minTime*time.Millisecond {
|
2022-03-26 17:59:19 +03:00
|
|
|
t.Fatalf("tick was shorter than expected: %s", td)
|
2024-12-09 16:23:25 +03:00
|
|
|
} else if td > (maxTime+precision)*time.Millisecond {
|
2022-03-26 17:59:19 +03:00
|
|
|
t.Fatalf("tick was longer than expected: %s", td)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
rt.Stop()
|
2024-12-09 16:23:25 +03:00
|
|
|
time.Sleep((maxTime + precision) * time.Millisecond)
|
2022-03-26 17:59:19 +03:00
|
|
|
select {
|
|
|
|
case v, ok := <-rt.C:
|
|
|
|
if ok || !v.IsZero() {
|
|
|
|
t.Fatal("ticker did not shut down")
|
|
|
|
}
|
|
|
|
default:
|
|
|
|
t.Fatal("expected to receive close channel signal")
|
|
|
|
}
|
|
|
|
}
|