From 3b49124c9f463821bdcd25989a827f6660bacb22 Mon Sep 17 00:00:00 2001 From: Adam Luzsi Date: Tue, 5 Mar 2024 20:48:20 +0100 Subject: [PATCH] clock pkg optimisation --- clock/Clock.go | 6 +++++- clock/Clock_test.go | 8 ++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/clock/Clock.go b/clock/Clock.go index 4c9ed54..e122ff5 100644 --- a/clock/Clock.go +++ b/clock/Clock.go @@ -15,8 +15,12 @@ func Sleep(d time.Duration) { } func After(d time.Duration) <-chan time.Time { - startedAt := internal.GetTime() ch := make(chan time.Time) + if d == 0 { + close(ch) + return ch + } + startedAt := internal.GetTime() go func() { wait: for { diff --git a/clock/Clock_test.go b/clock/Clock_test.go index 74541a1..ca8542d 100644 --- a/clock/Clock_test.go +++ b/clock/Clock_test.go @@ -220,6 +220,14 @@ func TestAfter(t *testing.T) { t.Fatal("clock.After should have finished already its work after travel that went more forward as the duration") } }) //Ω, testcase.Flaky(5*time.Second)) + + s.Test("no matter what, when the wait time is zero, clock.After returns instantly", func(t *testcase.T) { + timecop.SetSpeed(t, 0.001) + timecop.Travel(t, time.Second, timecop.Freeze()) + assert.Within(t, time.Millisecond, func(ctx context.Context) { + <-clock.After(0) + }, "expected to finish instantly") + }) } func Test_testTimeWithMinusDuration(t *testing.T) {