|
| 1 | +package timer |
| 2 | + |
| 3 | +import ( |
| 4 | + "testing" |
| 5 | + "time" |
| 6 | +) |
| 7 | + |
| 8 | +func TestStopAndDrainTimer_NilTimer(t *testing.T) { |
| 9 | + // Should not panic on nil timer. |
| 10 | + StopAndDrainTimer(nil) |
| 11 | +} |
| 12 | + |
| 13 | +func TestStopAndDrainTimer_UnfiredTimer(t *testing.T) { |
| 14 | + timer := time.NewTimer(time.Hour) |
| 15 | + StopAndDrainTimer(timer) |
| 16 | + |
| 17 | + // Channel should be empty after stop+drain. |
| 18 | + select { |
| 19 | + case <-timer.C: |
| 20 | + t.Fatal("expected timer channel to be drained") |
| 21 | + default: |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +func TestStopAndDrainTimer_FiredTimer(t *testing.T) { |
| 26 | + timer := time.NewTimer(time.Nanosecond) |
| 27 | + // Wait for it to fire. |
| 28 | + time.Sleep(time.Millisecond) |
| 29 | + |
| 30 | + StopAndDrainTimer(timer) |
| 31 | + |
| 32 | + // Channel should be empty after stop+drain. |
| 33 | + select { |
| 34 | + case <-timer.C: |
| 35 | + t.Fatal("expected timer channel to be drained") |
| 36 | + default: |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +func TestResetTimer(t *testing.T) { |
| 41 | + timer := time.NewTimer(time.Hour) |
| 42 | + |
| 43 | + // Reset to a very short duration. |
| 44 | + ResetTimer(timer, time.Nanosecond) |
| 45 | + |
| 46 | + select { |
| 47 | + case <-timer.C: |
| 48 | + // Expected. |
| 49 | + case <-time.After(100 * time.Millisecond): |
| 50 | + t.Fatal("expected timer to fire after reset") |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +func TestResetTimer_AfterFired(t *testing.T) { |
| 55 | + timer := time.NewTimer(time.Nanosecond) |
| 56 | + // Wait for it to fire. |
| 57 | + time.Sleep(time.Millisecond) |
| 58 | + <-timer.C |
| 59 | + |
| 60 | + // Reset after consuming the fired event. |
| 61 | + ResetTimer(timer, time.Nanosecond) |
| 62 | + |
| 63 | + select { |
| 64 | + case <-timer.C: |
| 65 | + // Expected. |
| 66 | + case <-time.After(100 * time.Millisecond): |
| 67 | + t.Fatal("expected timer to fire after reset") |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +func TestResetTimer_MultipleTimes(t *testing.T) { |
| 72 | + timer := time.NewTimer(time.Hour) |
| 73 | + defer timer.Stop() |
| 74 | + |
| 75 | + for i := 0; i < 10; i++ { |
| 76 | + ResetTimer(timer, time.Nanosecond) |
| 77 | + |
| 78 | + select { |
| 79 | + case <-timer.C: |
| 80 | + // Expected. |
| 81 | + case <-time.After(100 * time.Millisecond): |
| 82 | + t.Fatalf("iteration %d: expected timer to fire after reset", i) |
| 83 | + } |
| 84 | + } |
| 85 | +} |
0 commit comments