first commit
This commit is contained in:
67
internal/pkg/utils/jwt_test.go
Normal file
67
internal/pkg/utils/jwt_test.go
Normal file
@@ -0,0 +1,67 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"cardverse/config"
|
||||
)
|
||||
|
||||
func setupTestConfig() {
|
||||
config.Cfg = &config.Config{
|
||||
JWTSecret: "test-secret-key",
|
||||
JWTExpiresHours: 1,
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateToken_AndValidateToken(t *testing.T) {
|
||||
setupTestConfig()
|
||||
|
||||
token, err := GenerateToken(42, "user@example.com", "admin")
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateToken expected no error, got: %v", err)
|
||||
}
|
||||
if token == "" {
|
||||
t.Fatal("token should not be empty")
|
||||
}
|
||||
|
||||
claims, err := ValidateToken(token)
|
||||
if err != nil {
|
||||
t.Fatalf("ValidateToken expected no error for valid token, got: %v", err)
|
||||
}
|
||||
|
||||
if claims.UserID != 42 {
|
||||
t.Errorf("UserID expected 42, got %d", claims.UserID)
|
||||
}
|
||||
if claims.Email != "user@example.com" {
|
||||
t.Errorf("Email expected user@example.com, got %s", claims.Email)
|
||||
}
|
||||
if claims.Role != "admin" {
|
||||
t.Errorf("Role expected admin, got %s", claims.Role)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateToken_InvalidToken(t *testing.T) {
|
||||
setupTestConfig()
|
||||
|
||||
_, err := ValidateToken("invalid.random.token")
|
||||
if err == nil {
|
||||
t.Fatal("ValidateToken should fail for invalid token")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateToken_ExpiredToken(t *testing.T) {
|
||||
config.Cfg = &config.Config{
|
||||
JWTSecret: "test-secret-key",
|
||||
JWTExpiresHours: 0,
|
||||
}
|
||||
|
||||
token, _ := GenerateToken(1, "expired@example.com", "user")
|
||||
|
||||
time.Sleep(1100 * time.Millisecond)
|
||||
|
||||
_, err := ValidateToken(token)
|
||||
if err == nil {
|
||||
t.Fatal("ValidateToken should fail for expired token")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user