Skip to content

Commit

Permalink
add Until method on clocks
Browse files Browse the repository at this point in the history
  • Loading branch information
WillMatthews authored and DPJacques committed Aug 23, 2024
1 parent fc59783 commit 33fc064
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
11 changes: 11 additions & 0 deletions clockwork.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)}
}
Expand Down Expand Up @@ -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.
//
Expand Down
17 changes: 17 additions & 0 deletions clockwork_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 33fc064

Please sign in to comment.