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

Commit

Permalink
Merge pull request #38 from djmitche/issue29
Browse files Browse the repository at this point in the history
add Until
  • Loading branch information
djmitche authored Oct 29, 2021
2 parents 4378ee0 + eb95674 commit 0a12ec5
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
10 changes: 9 additions & 1 deletion clock.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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) }
Expand Down Expand Up @@ -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) {
Expand Down
13 changes: 13 additions & 0 deletions clock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 0a12ec5

Please sign in to comment.