github.com/xushiwei/go@v0.0.0-20130601165731-2b9d83f45bc9/src/pkg/time/tick_test.go (about)

     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.
     4  
     5  package time_test
     6  
     7  import (
     8  	"testing"
     9  	. "time"
    10  )
    11  
    12  func TestTicker(t *testing.T) {
    13  	const Count = 10
    14  	Delta := 100 * Millisecond
    15  	ticker := NewTicker(Delta)
    16  	t0 := Now()
    17  	for i := 0; i < Count; i++ {
    18  		<-ticker.C
    19  	}
    20  	ticker.Stop()
    21  	t1 := Now()
    22  	dt := t1.Sub(t0)
    23  	target := Delta * Count
    24  	slop := target * 2 / 10
    25  	if dt < target-slop || (!testing.Short() && dt > target+slop) {
    26  		t.Fatalf("%d %s ticks took %s, expected [%s,%s]", Count, Delta, dt, target-slop, target+slop)
    27  	}
    28  	// Now test that the ticker stopped
    29  	Sleep(2 * Delta)
    30  	select {
    31  	case <-ticker.C:
    32  		t.Fatal("Ticker did not shut down")
    33  	default:
    34  		// ok
    35  	}
    36  }
    37  
    38  // Test that a bug tearing down a ticker has been fixed.  This routine should not deadlock.
    39  func TestTeardown(t *testing.T) {
    40  	Delta := 100 * Millisecond
    41  	if testing.Short() {
    42  		Delta = 20 * Millisecond
    43  	}
    44  	for i := 0; i < 3; i++ {
    45  		ticker := NewTicker(Delta)
    46  		<-ticker.C
    47  		ticker.Stop()
    48  	}
    49  }
    50  
    51  func BenchmarkTicker(b *testing.B) {
    52  	ticker := NewTicker(1)
    53  	b.ResetTimer()
    54  	b.StartTimer()
    55  	for i := 0; i < b.N; i++ {
    56  		<-ticker.C
    57  	}
    58  	b.StopTimer()
    59  	ticker.Stop()
    60  }