From 9ad3423513e0dea989f442786aafa8e85363475d Mon Sep 17 00:00:00 2001 From: Sami Hiltunen Date: Thu, 15 Dec 2016 14:12:55 +0100 Subject: [PATCH] since function * Adds support for time.Time Since function. --- clock.go | 10 +++++++++- clock_test.go | 10 ++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/clock.go b/clock.go index 518178d..c4c5230 100644 --- a/clock.go +++ b/clock.go @@ -15,6 +15,7 @@ type Clock interface { After(d time.Duration) <-chan time.Time AfterFunc(d time.Duration, f func()) *Timer Now() time.Time + Since(t time.Time) time.Duration Sleep(d time.Duration) Tick(d time.Duration) <-chan time.Time Ticker(d time.Duration) *Ticker @@ -37,6 +38,8 @@ func (c *clock) AfterFunc(d time.Duration, f func()) *Timer { func (c *clock) Now() time.Time { return time.Now() } +func (c *clock) Since(t time.Time) time.Duration { return time.Since(t) } + func (c *clock) Sleep(d time.Duration) { time.Sleep(d) } func (c *clock) Tick(d time.Duration) <-chan time.Time { return time.Tick(d) } @@ -87,7 +90,7 @@ func (m *Mock) Add(d time.Duration) { gosched() } -// Sets the current time of the mock clock to a specific one. +// Set sets the current time of the mock clock to a specific one. // This should only be called from a single goroutine at a time. func (m *Mock) Set(t time.Time) { // Continue to execute timers until there are no more before the new time. @@ -158,6 +161,11 @@ func (m *Mock) Now() time.Time { return m.now } +// Since returns time since the mock clocks wall time. +func (m *Mock) Since(t time.Time) time.Duration { + return m.Now().Sub(t) +} + // Sleep pauses the goroutine for the given duration on the mock clock. // The clock must be moved forward in a separate goroutine. func (m *Mock) Sleep(d time.Duration) { diff --git a/clock_test.go b/clock_test.go index 9c090d5..322b742 100644 --- a/clock_test.go +++ b/clock_test.go @@ -306,6 +306,16 @@ func TestMock_Now(t *testing.T) { } } +func TestMock_Since(t *testing.T) { + clock := NewMock() + + beginning := clock.Now() + clock.Add(500 * time.Second) + if since := clock.Since(beginning); since.Seconds() != 500 { + t.Fatalf("expected 500 since beginning, actually: %v", since.Seconds()) + } +} + // Ensure that the mock can sleep for the correct time. func TestMock_Sleep(t *testing.T) { var ok int32