oauth2 icon indicating copy to clipboard operation
oauth2 copied to clipboard

Feature Request: use a local time.Now implementation through module to support testing

Open mattbnz opened this issue 2 years ago • 0 comments

After embedding go-ouath2 into a server writing test-cases to validate the integration is functioning as expected, particularly in terms of token expiry is very difficult as the library contains many direct calls to time.Now in the token creation and validation code paths that cannot be altered by any of the callbacks.

One example is refresh token expirty at https://github.com/go-oauth2/oauth2/blob/master/manage/manager.go#L496

A common pattern to enable this type of testing is to create a local instance of Now in each package (or perhaps in a common oauth2time package within the module...) and ensure that is used rather than time.Now everywhere throughout the codebase.

This then allows integrators of the library to set the local Now to a mocked value for testing purposes.

Would a PR of this type be accepted?

Example change proposed:

// in manage/time.go 
var ManageNow time.Now

// in manage/manager.go:496
ti.GetRefreshCreateAt().Add(ti.GetRefreshExpiresIn()).Before(ManageNow()) {

Which then enables:

// in some integratino's test code
func Test_Expiry(t *testing.T) {
   baseTime :=  time.Date(2023, 09, 01, 0, 0, 0, 0, time.Local)
   manage.ManageNow = func() time.Time { return baseTime }
   defer func() { manage.ManageNow = time.Now }()

  // test code that issues/generates tokens with 4-day refresh expiry

  // Advance clock 5 days
  manage.ManageNow = func() time.Time { return baseTime.AddDate(0, 0, 5) }

  // remaining test code that validates expiry, etc. 
}

mattbnz avatar Sep 28 '23 02:09 mattbnz