From 08a979e2f5e1e4ee4dcc04d09cc08005773fe48f Mon Sep 17 00:00:00 2001 From: William Matthews Date: Tue, 20 Aug 2024 16:21:13 +0000 Subject: [PATCH] add Until method on clocks --- clockwork.go | 11 +++++++++++ clockwork_test.go | 17 +++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/clockwork.go b/clockwork.go index df02ba9..b3a3e5f 100644 --- a/clockwork.go +++ b/clockwork.go @@ -16,6 +16,7 @@ type Clock interface { Sleep(d time.Duration) Now() time.Time Since(t time.Time) time.Duration + Until(t time.Time) time.Duration NewTicker(d time.Duration) Ticker NewTimer(d time.Duration) Timer AfterFunc(d time.Duration, f func()) Timer @@ -45,6 +46,10 @@ func (rc *realClock) Since(t time.Time) time.Duration { return rc.Now().Sub(t) } +func (rc *realClock) Until(t time.Time) time.Duration { + return t.Sub(rc.Now()) +} + func (rc *realClock) NewTicker(d time.Duration) Ticker { return realTicker{time.NewTicker(d)} } @@ -132,6 +137,12 @@ func (fc *FakeClock) Since(t time.Time) time.Duration { return fc.Now().Sub(t) } +// Until returns the duration that has to pass from the given time on the fakeClock +// to reach the given time. +func (fc *FakeClock) Until(t time.Time) time.Duration { + return t.Sub(fc.Now()) +} + // NewTicker returns a Ticker that will expire only after calls to // FakeClock.Advance() have moved the clock past the given duration. // diff --git a/clockwork_test.go b/clockwork_test.go index e94be1b..78c5f28 100644 --- a/clockwork_test.go +++ b/clockwork_test.go @@ -124,6 +124,23 @@ func TestFakeClockSince(t *testing.T) { } } +func TestFakeClockUntil(t *testing.T) { + t.Parallel() + testTime := time.Now() + fc := NewFakeClockAt(testTime) + + testOffset := time.Minute + probeTime := testTime.Add(testOffset) + + elapsedTime := time.Second + fc.Advance(elapsedTime) + + expectedDuration := testOffset - elapsedTime + if fc.Until(probeTime) != expectedDuration { + t.Fatalf("fakeClock.Until() returned unexpected duration, got: %d, want: %d", fc.Until(probeTime), expectedDuration) + } +} + // This used to result in a deadlock. // https://github.com/jonboulle/clockwork/issues/35 func TestTwoBlockersOneBlock(t *testing.T) {