|
| 1 | +package clock_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "testing" |
| 6 | + "time" |
| 7 | + |
| 8 | + "github.com/coder/coder/v2/clock" |
| 9 | +) |
| 10 | + |
| 11 | +func TestTimer_NegativeDuration(t *testing.T) { |
| 12 | + t.Parallel() |
| 13 | + // nolint:gocritic // trying to avoid Coder-specific stuff with an eye toward spinning this out |
| 14 | + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 15 | + defer cancel() |
| 16 | + |
| 17 | + mClock := clock.NewMock(t) |
| 18 | + start := mClock.Now() |
| 19 | + trap := mClock.Trap().NewTimer() |
| 20 | + defer trap.Close() |
| 21 | + |
| 22 | + timers := make(chan *clock.Timer, 1) |
| 23 | + go func() { |
| 24 | + timers <- mClock.NewTimer(-time.Second) |
| 25 | + }() |
| 26 | + c := trap.MustWait(ctx) |
| 27 | + c.Release() |
| 28 | + // trap returns the actual passed value |
| 29 | + if c.Duration != -time.Second { |
| 30 | + t.Fatalf("expected -time.Second, got: %v", c.Duration) |
| 31 | + } |
| 32 | + |
| 33 | + tmr := <-timers |
| 34 | + select { |
| 35 | + case <-ctx.Done(): |
| 36 | + t.Fatal("timeout waiting for timer") |
| 37 | + case tme := <-tmr.C: |
| 38 | + // the tick is the current time, not the past |
| 39 | + if !tme.Equal(start) { |
| 40 | + t.Fatalf("expected time %v, got %v", start, tme) |
| 41 | + } |
| 42 | + } |
| 43 | + if tmr.Stop() { |
| 44 | + t.Fatal("timer still running") |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +func TestAfterFunc_NegativeDuration(t *testing.T) { |
| 49 | + t.Parallel() |
| 50 | + // nolint:gocritic // trying to avoid Coder-specific stuff with an eye toward spinning this out |
| 51 | + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 52 | + defer cancel() |
| 53 | + |
| 54 | + mClock := clock.NewMock(t) |
| 55 | + trap := mClock.Trap().AfterFunc() |
| 56 | + defer trap.Close() |
| 57 | + |
| 58 | + timers := make(chan *clock.Timer, 1) |
| 59 | + done := make(chan struct{}) |
| 60 | + go func() { |
| 61 | + timers <- mClock.AfterFunc(-time.Second, func() { |
| 62 | + close(done) |
| 63 | + }) |
| 64 | + }() |
| 65 | + c := trap.MustWait(ctx) |
| 66 | + c.Release() |
| 67 | + // trap returns the actual passed value |
| 68 | + if c.Duration != -time.Second { |
| 69 | + t.Fatalf("expected -time.Second, got: %v", c.Duration) |
| 70 | + } |
| 71 | + |
| 72 | + tmr := <-timers |
| 73 | + select { |
| 74 | + case <-ctx.Done(): |
| 75 | + t.Fatal("timeout waiting for timer") |
| 76 | + case <-done: |
| 77 | + // OK! |
| 78 | + } |
| 79 | + if tmr.Stop() { |
| 80 | + t.Fatal("timer still running") |
| 81 | + } |
| 82 | +} |
0 commit comments