Skip to content
This repository has been archived by the owner on May 18, 2023. It is now read-only.

Commit

Permalink
since function
Browse files Browse the repository at this point in the history
* Adds support for time.Time Since function.
  • Loading branch information
SamiHiltunen committed Dec 15, 2016
1 parent a620c1c commit 9ad3423
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
10 changes: 9 additions & 1 deletion clock.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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) }
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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) {
Expand Down
10 changes: 10 additions & 0 deletions clock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 9ad3423

Please sign in to comment.