2010-12-03 05:34:57 +01:00
|
|
|
// Copyright 2009 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package time_test
|
|
|
|
|
|
|
|
import (
|
|
|
|
"testing"
|
|
|
|
. "time"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestTicker(t *testing.T) {
|
2012-03-02 17:38:43 +01:00
|
|
|
const Count = 10
|
|
|
|
Delta := 100 * Millisecond
|
2010-12-03 05:34:57 +01:00
|
|
|
ticker := NewTicker(Delta)
|
2011-12-13 20:16:27 +01:00
|
|
|
t0 := Now()
|
2010-12-03 05:34:57 +01:00
|
|
|
for i := 0; i < Count; i++ {
|
|
|
|
<-ticker.C
|
|
|
|
}
|
|
|
|
ticker.Stop()
|
2011-12-13 20:16:27 +01:00
|
|
|
t1 := Now()
|
|
|
|
dt := t1.Sub(t0)
|
|
|
|
target := Delta * Count
|
2010-12-03 05:34:57 +01:00
|
|
|
slop := target * 2 / 10
|
2012-03-30 23:27:11 +02:00
|
|
|
if dt < target-slop || (!testing.Short() && dt > target+slop) {
|
2011-12-13 20:16:27 +01:00
|
|
|
t.Fatalf("%d %s ticks took %s, expected [%s,%s]", Count, Delta, dt, target-slop, target+slop)
|
2010-12-03 05:34:57 +01:00
|
|
|
}
|
|
|
|
// Now test that the ticker stopped
|
|
|
|
Sleep(2 * Delta)
|
2011-03-17 00:05:44 +01:00
|
|
|
select {
|
|
|
|
case <-ticker.C:
|
2011-01-21 19:19:03 +01:00
|
|
|
t.Fatal("Ticker did not shut down")
|
2011-03-17 00:05:44 +01:00
|
|
|
default:
|
|
|
|
// ok
|
2010-12-03 05:34:57 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-07-22 20:15:38 +02:00
|
|
|
// Test that a bug tearing down a ticker has been fixed. This routine should not deadlock.
|
2010-12-03 05:34:57 +01:00
|
|
|
func TestTeardown(t *testing.T) {
|
2012-03-02 17:38:43 +01:00
|
|
|
Delta := 100 * Millisecond
|
|
|
|
if testing.Short() {
|
|
|
|
Delta = 20 * Millisecond
|
|
|
|
}
|
2010-12-03 05:34:57 +01:00
|
|
|
for i := 0; i < 3; i++ {
|
2012-03-02 17:38:43 +01:00
|
|
|
ticker := NewTicker(Delta)
|
2010-12-03 05:34:57 +01:00
|
|
|
<-ticker.C
|
|
|
|
ticker.Stop()
|
|
|
|
}
|
|
|
|
}
|
2011-03-17 00:05:44 +01:00
|
|
|
|
2014-06-05 01:15:33 +02:00
|
|
|
// Test the Tick convenience wrapper.
|
|
|
|
func TestTick(t *testing.T) {
|
|
|
|
// Test that giving a negative duration returns nil.
|
|
|
|
if got := Tick(-1); got != nil {
|
|
|
|
t.Errorf("Tick(-1) = %v; want nil", got)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Test that NewTicker panics when given a duration less than zero.
|
|
|
|
func TestNewTickerLtZeroDuration(t *testing.T) {
|
|
|
|
defer func() {
|
|
|
|
if err := recover(); err == nil {
|
|
|
|
t.Errorf("NewTicker(-1) should have panicked")
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
NewTicker(-1)
|
|
|
|
}
|
|
|
|
|
2011-03-17 00:05:44 +01:00
|
|
|
func BenchmarkTicker(b *testing.B) {
|
|
|
|
ticker := NewTicker(1)
|
|
|
|
b.ResetTimer()
|
|
|
|
b.StartTimer()
|
|
|
|
for i := 0; i < b.N; i++ {
|
|
|
|
<-ticker.C
|
|
|
|
}
|
|
|
|
b.StopTimer()
|
|
|
|
ticker.Stop()
|
|
|
|
}
|