oauth2: deflake test relying on time.Now values

It was particularly flaky on Windows where time.Now doesn't advance as
fast as elsewhere.

Change-Id: Ic0b7c3e4c69389009d1e28750be0cd203fa770aa
Reviewed-on: https://go-review.googlesource.com/c/157578
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
This commit is contained in:
Brad Fitzpatrick 2019-01-11 18:04:42 +00:00
parent fd3eaa146c
commit 36a7019397
2 changed files with 9 additions and 2 deletions

View File

@ -118,13 +118,16 @@ func (t *Token) Extra(key string) interface{} {
return v return v
} }
// timeNow is time.Now but pulled out as a variable for tests.
var timeNow = time.Now
// expired reports whether the token is expired. // expired reports whether the token is expired.
// t must be non-nil. // t must be non-nil.
func (t *Token) expired() bool { func (t *Token) expired() bool {
if t.Expiry.IsZero() { if t.Expiry.IsZero() {
return false return false
} }
return t.Expiry.Round(0).Add(-expiryDelta).Before(time.Now()) return t.Expiry.Round(0).Add(-expiryDelta).Before(timeNow())
} }
// Valid reports whether t is non-nil, has an AccessToken, and is not expired. // Valid reports whether t is non-nil, has an AccessToken, and is not expired.

View File

@ -34,13 +34,17 @@ func TestTokenExtra(t *testing.T) {
func TestTokenExpiry(t *testing.T) { func TestTokenExpiry(t *testing.T) {
now := time.Now() now := time.Now()
timeNow = func() time.Time { return now }
defer func() { timeNow = time.Now }()
cases := []struct { cases := []struct {
name string name string
tok *Token tok *Token
want bool want bool
}{ }{
{name: "12 seconds", tok: &Token{Expiry: now.Add(12 * time.Second)}, want: false}, {name: "12 seconds", tok: &Token{Expiry: now.Add(12 * time.Second)}, want: false},
{name: "10 seconds", tok: &Token{Expiry: now.Add(expiryDelta)}, want: true}, {name: "10 seconds", tok: &Token{Expiry: now.Add(expiryDelta)}, want: false},
{name: "10 seconds-1ns", tok: &Token{Expiry: now.Add(expiryDelta - 1*time.Nanosecond)}, want: true},
{name: "-1 hour", tok: &Token{Expiry: now.Add(-1 * time.Hour)}, want: true}, {name: "-1 hour", tok: &Token{Expiry: now.Add(-1 * time.Hour)}, want: true},
} }
for _, tc := range cases { for _, tc := range cases {