1package clockwork
2
3import (
4	"testing"
5	"time"
6)
7
8func TestFakeTickerStop(t *testing.T) {
9	fc := &fakeClock{}
10
11	ft := fc.NewTicker(1)
12	ft.Stop()
13	select {
14	case <-ft.Chan():
15		t.Errorf("received unexpected tick!")
16	default:
17	}
18}
19
20func TestFakeTickerTick(t *testing.T) {
21	fc := &fakeClock{}
22	now := fc.Now()
23
24	// The tick at now.Add(2) should not get through since we advance time by
25	// two units below and the channel can hold at most one tick until it's
26	// consumed.
27	first := now.Add(1)
28	second := now.Add(3)
29
30	// We wrap the Advance() calls with blockers to make sure that the ticker
31	// can go to sleep and produce ticks without time passing in parallel.
32	ft := fc.NewTicker(1)
33	fc.BlockUntil(1)
34	fc.Advance(2)
35	fc.BlockUntil(1)
36
37	select {
38	case tick := <-ft.Chan():
39		if tick != first {
40			t.Errorf("wrong tick time, got: %v, want: %v", tick, first)
41		}
42	case <-time.After(time.Millisecond):
43		t.Errorf("expected tick!")
44	}
45
46	// Advance by one more unit, we should get another tick now.
47	fc.Advance(1)
48	fc.BlockUntil(1)
49
50	select {
51	case tick := <-ft.Chan():
52		if tick != second {
53			t.Errorf("wrong tick time, got: %v, want: %v", tick, second)
54		}
55	case <-time.After(time.Millisecond):
56		t.Errorf("expected tick!")
57	}
58	ft.Stop()
59}
60
61func TestFakeTicker_Race(t *testing.T) {
62	fc := NewFakeClock()
63
64	tickTime := 1 * time.Millisecond
65	ticker := fc.NewTicker(tickTime)
66	defer ticker.Stop()
67
68	fc.Advance(tickTime)
69
70	timeout := time.NewTimer(500 * time.Millisecond)
71	defer timeout.Stop()
72
73	select {
74	case <-ticker.Chan():
75		// Pass
76	case <-timeout.C:
77		t.Fatalf("Ticker didn't detect the clock advance!")
78	}
79}
80
81func TestFakeTicker_Race2(t *testing.T) {
82	fc := NewFakeClock()
83	ft := fc.NewTicker(5 * time.Second)
84	for i := 0; i < 100; i++ {
85		fc.Advance(5 * time.Second)
86		<-ft.Chan()
87	}
88	ft.Stop()
89}
90