Skip to content

Commit 33fc064

Browse files
WillMatthewsDPJacques
authored andcommitted
add Until method on clocks
1 parent fc59783 commit 33fc064

2 files changed

Lines changed: 28 additions & 0 deletions

File tree

clockwork.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ type Clock interface {
1616
Sleep(d time.Duration)
1717
Now() time.Time
1818
Since(t time.Time) time.Duration
19+
Until(t time.Time) time.Duration
1920
NewTicker(d time.Duration) Ticker
2021
NewTimer(d time.Duration) Timer
2122
AfterFunc(d time.Duration, f func()) Timer
@@ -45,6 +46,10 @@ func (rc *realClock) Since(t time.Time) time.Duration {
4546
return rc.Now().Sub(t)
4647
}
4748

49+
func (rc *realClock) Until(t time.Time) time.Duration {
50+
return t.Sub(rc.Now())
51+
}
52+
4853
func (rc *realClock) NewTicker(d time.Duration) Ticker {
4954
return realTicker{time.NewTicker(d)}
5055
}
@@ -132,6 +137,12 @@ func (fc *FakeClock) Since(t time.Time) time.Duration {
132137
return fc.Now().Sub(t)
133138
}
134139

140+
// Until returns the duration that has to pass from the given time on the fakeClock
141+
// to reach the given time.
142+
func (fc *FakeClock) Until(t time.Time) time.Duration {
143+
return t.Sub(fc.Now())
144+
}
145+
135146
// NewTicker returns a Ticker that will expire only after calls to
136147
// FakeClock.Advance() have moved the clock past the given duration.
137148
//

clockwork_test.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,23 @@ func TestFakeClockSince(t *testing.T) {
124124
}
125125
}
126126

127+
func TestFakeClockUntil(t *testing.T) {
128+
t.Parallel()
129+
testTime := time.Now()
130+
fc := NewFakeClockAt(testTime)
131+
132+
testOffset := time.Minute
133+
probeTime := testTime.Add(testOffset)
134+
135+
elapsedTime := time.Second
136+
fc.Advance(elapsedTime)
137+
138+
expectedDuration := testOffset - elapsedTime
139+
if fc.Until(probeTime) != expectedDuration {
140+
t.Fatalf("fakeClock.Until() returned unexpected duration, got: %d, want: %d", fc.Until(probeTime), expectedDuration)
141+
}
142+
}
143+
127144
// This used to result in a deadlock.
128145
// https://github.com/jonboulle/clockwork/issues/35
129146
func TestTwoBlockersOneBlock(t *testing.T) {

0 commit comments

Comments
 (0)