From b9ae427899a19967470f39bc0e2e880778cdb108 Mon Sep 17 00:00:00 2001 From: Marten Seemann Date: Sun, 26 Feb 2023 10:09:53 +1300 Subject: [PATCH] immediately fire a timer set to a negative duration --- clock.go | 3 ++- clock_test.go | 10 ++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/clock.go b/clock.go index 40555b3..3b684f0 100644 --- a/clock.go +++ b/clock.go @@ -219,7 +219,6 @@ func (m *Mock) Ticker(d time.Duration) *Ticker { // Timer creates a new instance of Timer. func (m *Mock) Timer(d time.Duration) *Timer { m.mu.Lock() - defer m.mu.Unlock() ch := make(chan time.Time, 1) t := &Timer{ C: ch, @@ -229,6 +228,8 @@ func (m *Mock) Timer(d time.Duration) *Timer { stopped: false, } m.timers = append(m.timers, (*internalTimer)(t)) + m.mu.Unlock() + m.runNextTimer(m.now) return t } diff --git a/clock_test.go b/clock_test.go index 63be66c..bc3a0b4 100644 --- a/clock_test.go +++ b/clock_test.go @@ -175,6 +175,16 @@ func TestClock_Timer_Reset(t *testing.T) { } } +func TestClock_NegativeDuration(t *testing.T) { + clock := NewMock() + timer := clock.Timer(-time.Second) + select { + case <-timer.C: + default: + t.Fatal("timer should have fired immediately") + } +} + // Ensure reset can be called immediately after reading channel func TestClock_Timer_Reset_Unlock(t *testing.T) { clock := NewMock()