library-go/jwt/define_test.go

83 lines
2.4 KiB
Go
Raw Permalink Normal View History

2024-08-27 05:46:58 +00:00
package jwt
import (
"testing"
"time"
2024-08-27 05:49:17 +00:00
"github.com/stretchr/testify/require"
2024-08-27 05:46:58 +00:00
)
func TestAccessTokenExpires(t *testing.T) {
token := &Token{
ExpiresIn: 3600, // 1小時
}
expectedDuration := time.Hour
actualDuration := token.AccessTokenExpires()
require.Equal(t, expectedDuration, actualDuration, "Access token expiration duration should be 1 hour")
}
func TestRefreshTokenExpires(t *testing.T) {
token := &Token{
RefreshExpiresIn: 7200, // 2小時
}
expectedDuration := 2 * time.Hour
actualDuration := token.RefreshTokenExpires()
require.Equal(t, expectedDuration, actualDuration, "Refresh token expiration duration should be 2 hours")
}
func TestRefreshTokenExpiresUnix(t *testing.T) {
token := &Token{
RefreshExpiresIn: 3600, // 1小時
}
expectedUnix := time.Now().Add(1 * time.Hour).Unix()
actualUnix := token.RefreshTokenExpiresUnix()
// 設定允許範圍確保結果在1秒的範圍內
require.InEpsilon(t, expectedUnix, actualUnix, 1, "Refresh token expires Unix time should match the expected time")
}
func TestIsExpires(t *testing.T) {
// 測試過期情況
tokenExpired := &Token{
ExpiresIn: 3600, // 1小時
AccessCreateAt: time.Now().Add(-2 * time.Hour), // 2小時前生成的 token應該過期
}
require.True(t, tokenExpired.IsExpires(), "Token should be expired")
// 測試未過期情況
tokenNotExpired := &Token{
ExpiresIn: 3600, // 1小時
AccessCreateAt: time.Now().Add(-30 * time.Minute), // 30分鐘前生成的 token應該未過期
}
require.False(t, tokenNotExpired.IsExpires(), "Token should not be expired")
}
func TestRedisExpiredSec(t *testing.T) {
token := &Token{
ExpiresIn: int(time.Now().Add(1 * time.Hour).Unix()), // 1小時後過期
}
expectedSec := int64(3600) // 1小時
actualSec := token.RedisExpiredSec()
// 確保時間在合理範圍內
require.InDelta(t, expectedSec, actualSec, 1, "Redis expired seconds should be close to 3600 seconds")
}
func TestRedisRefreshExpiredSec(t *testing.T) {
token := &Token{
RefreshExpiresIn: int(time.Now().Add(2 * time.Hour).Unix()), // 2小時後過期
}
expectedSec := int64(7200) // 2小時
actualSec := token.RedisRefreshExpiredSec()
// 確保時間在合理範圍內
require.InDelta(t, expectedSec, actualSec, 1, "Redis refresh expired seconds should be close to 7200 seconds")
}