1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
14 func TestTicker(t
*testing
.T
) {
15 // We want to test that a ticker takes as much time as expected.
16 // Since we don't want the test to run for too long, we don't
17 // want to use lengthy times. This makes the test inherently flaky.
18 // So only report an error if it fails five times in a row.
21 delta
:= 20 * Millisecond
23 // On Darwin ARM64 the tick frequency seems limited. Issue 35692.
24 if runtime
.GOOS
== "darwin" && runtime
.GOARCH
== "arm64" {
26 delta
= 100 * Millisecond
31 for _
, e
:= range errs
{
36 for i
:= 0; i
< 5; i
++ {
37 ticker
:= NewTicker(delta
)
39 for i
:= 0; i
< count
; i
++ {
45 target
:= delta
* Duration(count
)
46 slop
:= target
* 2 / 10
47 if dt
< target
-slop || dt
> target
+slop
{
48 errs
= append(errs
, fmt
.Sprintf("%d %s ticks took %s, expected [%s,%s]", count
, delta
, dt
, target
-slop
, target
+slop
))
51 // Now test that the ticker stopped.
55 errs
= append(errs
, "Ticker did not shut down")
61 // Test passed, so all done.
63 t
.Logf("saw %d errors, ignoring to avoid flakiness", len(errs
))
70 t
.Errorf("saw %d errors", len(errs
))
75 func TestTickerStopWithDirectInitialization(t
*testing
.T
) {
81 // Test that a bug tearing down a ticker has been fixed. This routine should not deadlock.
82 func TestTeardown(t
*testing
.T
) {
83 Delta
:= 100 * Millisecond
85 Delta
= 20 * Millisecond
87 for i
:= 0; i
< 3; i
++ {
88 ticker
:= NewTicker(Delta
)
94 // Test the Tick convenience wrapper.
95 func TestTick(t
*testing
.T
) {
96 // Test that giving a negative duration returns nil.
97 if got
:= Tick(-1); got
!= nil {
98 t
.Errorf("Tick(-1) = %v; want nil", got
)
102 // Test that NewTicker panics when given a duration less than zero.
103 func TestNewTickerLtZeroDuration(t
*testing
.T
) {
105 if err
:= recover(); err
== nil {
106 t
.Errorf("NewTicker(-1) should have panicked")
112 func BenchmarkTicker(b
*testing
.B
) {
113 benchmark(b
, func(n
int) {
114 ticker
:= NewTicker(Nanosecond
)
115 for i
:= 0; i
< n
; i
++ {