From 36a7019397c4c86cf59eeab3bc0d188bac444277 Mon Sep 17 00:00:00 2001 From: Brad Fitzpatrick Date: Fri, 11 Jan 2019 18:04:42 +0000 Subject: [PATCH] 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 TryBot-Result: Gobot Gobot Reviewed-by: Dmitri Shuralyov --- token.go | 5 ++++- token_test.go | 6 +++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/token.go b/token.go index 9be1ae5..ee4be54 100644 --- a/token.go +++ b/token.go @@ -118,13 +118,16 @@ func (t *Token) Extra(key string) interface{} { 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. // t must be non-nil. func (t *Token) expired() bool { if t.Expiry.IsZero() { 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. diff --git a/token_test.go b/token_test.go index 80db83c..ee97b4f 100644 --- a/token_test.go +++ b/token_test.go @@ -34,13 +34,17 @@ func TestTokenExtra(t *testing.T) { func TestTokenExpiry(t *testing.T) { now := time.Now() + timeNow = func() time.Time { return now } + defer func() { timeNow = time.Now }() + cases := []struct { name string tok *Token want bool }{ {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}, } for _, tc := range cases {