grok_token_refresher_test.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. //go:build unit
  2. package service
  3. import (
  4. "testing"
  5. "time"
  6. "github.com/stretchr/testify/require"
  7. )
  8. func TestGrokTokenRefreshWindowWithJitter_StableAndBounded(t *testing.T) {
  9. base := grokTokenRefreshSkew
  10. w1 := grokTokenRefreshWindowWithJitter(42, base)
  11. w2 := grokTokenRefreshWindowWithJitter(42, base)
  12. require.Equal(t, w1, w2, "same account id must yield stable window")
  13. require.GreaterOrEqual(t, w1, grokTokenRefreshSkewMin)
  14. require.LessOrEqual(t, w1, base)
  15. // Different accounts should usually differ (not a hard guarantee for all pairs,
  16. // but for sequential ids the hash spread is good enough to assert inequality
  17. // across a small sample).
  18. seen := map[time.Duration]bool{}
  19. for id := int64(1); id <= 50; id++ {
  20. seen[grokTokenRefreshWindowWithJitter(id, base)] = true
  21. }
  22. require.Greater(t, len(seen), 1, "jitter should spread windows across accounts")
  23. }
  24. func TestGrokTokenRefresher_NeedsRefresh_UsesSkewFloor(t *testing.T) {
  25. refresher := NewGrokTokenRefresher(nil)
  26. // Expires in 50 minutes — within 1h skew, should need refresh.
  27. expires := time.Now().Add(50 * time.Minute).UTC().Format(time.RFC3339)
  28. account := &Account{
  29. ID: 7,
  30. Platform: PlatformGrok,
  31. Type: AccountTypeOAuth,
  32. Credentials: map[string]any{
  33. "access_token": "at",
  34. "refresh_token": "rt",
  35. "expires_at": expires,
  36. },
  37. }
  38. // Pass a tiny window; NeedsRefresh raises it to grokTokenRefreshSkew then jitter.
  39. require.True(t, refresher.NeedsRefresh(account, time.Minute))
  40. // Far future — no refresh.
  41. account.Credentials["expires_at"] = time.Now().Add(3 * time.Hour).UTC().Format(time.RFC3339)
  42. require.False(t, refresher.NeedsRefresh(account, time.Minute))
  43. }