Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add Until method on clock interface #85

Merged
merged 1 commit into from
Aug 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading