Skip to content

Commit

Permalink
tstime: add Since method (#8622)
Browse files Browse the repository at this point in the history
Updates #8463

Signed-off-by: Claire Wang <claire@tailscale.com>
  • Loading branch information
clairew authored Jul 14, 2023
1 parent 60e5761 commit 0573f6e
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
5 changes: 5 additions & 0 deletions tstest/clock.go
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,11 @@ func (c *Clock) AfterFunc(d time.Duration, f func()) tstime.TimerController {
return t
}

// Since subtracts specified duration from Now().
func (c *Clock) Since(t time.Time) time.Duration {
return c.Now().Sub(t)
}

// eventHandler offers a common interface for Timer and Ticker events to avoid
// code duplication in eventManager.
type eventHandler interface {
Expand Down
44 changes: 44 additions & 0 deletions tstest/clock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2437,3 +2437,47 @@ func TestAfterFunc(t *testing.T) {
})
}
}

func TestSince(t *testing.T) {
t.Parallel()

tests := []struct {
name string
start time.Time
since time.Time
want time.Duration
}{
{
name: "positive",
start: time.Unix(12345, 1000),
since: time.Unix(11111, 1000),
want: 1234 * time.Second,
},
{
name: "negative",
start: time.Unix(12345, 1000),
since: time.Unix(15436, 1000),
want: -3091 * time.Second,
},
{
name: "zero",
start: time.Unix(12345, 1000),
since: time.Unix(12345, 1000),
want: 0,
},
}

for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
clock := NewClock(ClockOpts{
Start: tt.start,
})
got := clock.Since(tt.since)
if got != tt.want {
t.Errorf("Since duration %v, want %v", got, tt.want)
}
})
}
}
8 changes: 8 additions & 0 deletions tstime/tstime.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,9 @@ type Clock interface {
// by this Clock. When the ticker expires, it will call the provided func.
// It follows the semantics of time.AfterFunc.
AfterFunc(d time.Duration, f func()) TimerController
// Since returns the time elapsed since t.
// It follows the semantics of time.Since.
Since(t time.Time) time.Duration
}

// TickerController offers the receivers of a time.Ticker to ensure
Expand Down Expand Up @@ -135,3 +138,8 @@ func (StdClock) NewTicker(d time.Duration) (TickerController, <-chan time.Time)
func (StdClock) AfterFunc(d time.Duration, f func()) TimerController {
return time.AfterFunc(d, f)
}

// Since calls time.Since.
func (StdClock) Since(t time.Time) time.Duration {
return time.Since(t)
}

0 comments on commit 0573f6e

Please sign in to comment.