Files
cms-server/internal/authcode/authcode_test.go
Asai Neko 210b8b08ce
All checks were successful
Server Check Build (NixCN CMS) TeamCity build finished
Add test for all components
Signed-off-by: Asai Neko <sugar@sne.moe>
2026-03-26 18:19:26 +08:00

82 lines
1.8 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package authcode
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"nixcn-cms/testutil"
)
func TestNewAuthCode(t *testing.T) {
mr := testutil.Setup(t)
_ = mr
ctx := context.Background()
code, err := NewAuthCode(ctx, "client-1", "user@example.com")
require.NoError(t, err)
assert.NotEmpty(t, code)
}
func TestVerifyAuthCodeValid(t *testing.T) {
testutil.Setup(t)
ctx := context.Background()
code, err := NewAuthCode(ctx, "client-1", "user@example.com")
require.NoError(t, err)
token, ok := VerifyAuthCode(ctx, code)
require.True(t, ok)
assert.Equal(t, "client-1", token.ClientId)
assert.Equal(t, "user@example.com", token.Email)
}
func TestVerifyAuthCodeOneTimeUse(t *testing.T) {
testutil.Setup(t)
ctx := context.Background()
code, err := NewAuthCode(ctx, "client-1", "user@example.com")
require.NoError(t, err)
// First use should succeed
_, ok := VerifyAuthCode(ctx, code)
require.True(t, ok)
// Second use must fail (one-time)
_, ok = VerifyAuthCode(ctx, code)
assert.False(t, ok)
}
func TestVerifyAuthCodeInvalidCode(t *testing.T) {
testutil.Setup(t)
ctx := context.Background()
_, ok := VerifyAuthCode(ctx, "completely-wrong-code")
assert.False(t, ok)
}
func TestVerifyAuthCodeExpired(t *testing.T) {
mr := testutil.Setup(t)
ctx := context.Background()
code, err := NewAuthCode(ctx, "client-1", "user@example.com")
require.NoError(t, err)
// Fast-forward time past the TTL (10 minutes from testutil)
mr.FastForward(11 * time.Minute)
_, ok := VerifyAuthCode(ctx, code)
assert.False(t, ok, "expired code should not be valid")
}
func TestNewAuthCodeUniqueness(t *testing.T) {
testutil.Setup(t)
ctx := context.Background()
c1, _ := NewAuthCode(ctx, "client", "a@example.com")
c2, _ := NewAuthCode(ctx, "client", "a@example.com")
assert.NotEqual(t, c1, c2)
}