diff --git a/clock.go b/clock.go index 1ec40bc..7783201 100644 --- a/clock.go +++ b/clock.go @@ -19,6 +19,7 @@ type Clock interface { AfterFunc(d time.Duration, f func()) *Timer Now() time.Time Since(t time.Time) time.Duration + Until(t time.Time) time.Duration Sleep(d time.Duration) Tick(d time.Duration) <-chan time.Time Ticker(d time.Duration) *Ticker @@ -43,6 +44,8 @@ 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) Until(t time.Time) time.Duration { return time.Until(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) } @@ -164,11 +167,16 @@ func (m *Mock) Now() time.Time { return m.now } -// Since returns time since the mock clock's wall time. +// Since returns time since `t` using the mock clock's wall time. func (m *Mock) Since(t time.Time) time.Duration { return m.Now().Sub(t) } +// Until returns time until `t` using the mock clock's wall time. +func (m *Mock) Until(t time.Time) time.Duration { + return t.Sub(m.Now()) +} + // 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 f072b25..b587af7 100644 --- a/clock_test.go +++ b/clock_test.go @@ -295,6 +295,19 @@ func TestMock_Since(t *testing.T) { } } +func TestMock_Until(t *testing.T) { + clock := NewMock() + + end := clock.Now().Add(500 * time.Second) + if dur := clock.Until(end); dur.Seconds() != 500 { + t.Fatalf("expected 500s duration between `clock` and `end`, actually: %v", dur.Seconds()) + } + clock.Add(100 * time.Second) + if dur := clock.Until(end); dur.Seconds() != 400 { + t.Fatalf("expected 400s duration between `clock` and `end`, actually: %v", dur.Seconds()) + } +} + // Ensure that the mock can sleep for the correct time. func TestMock_Sleep(t *testing.T) { var ok int32