Files
mtusi2026lab2/internal/storage/redis/session_repository_test.go
T
Vladislav Kunetskiy 1e38dbdf35
Application / Lint (pull_request) Canceled after 0s
Application / Unit tests (pull_request) Canceled after 0s
Application / Docker build (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
lab2
2026-10-06 18:58:40 +03:00

242 lines
6.2 KiB
Go

//go:build integration
package redis_test
import (
"context"
"encoding/hex"
"os"
"strconv"
"testing"
"time"
"github.com/google/uuid"
goredis "github.com/redis/go-redis/v9"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/suite"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/platform/cache"
storageredis "mtusi-messenger/internal/storage/redis"
"mtusi-messenger/internal/storage/redis/mocks"
)
const testRedisDB = 1
func redisEnv(key, fallback string) string {
if value := os.Getenv(key); value != "" {
return value
}
return fallback
}
func redisEnvInt(key string, fallback int) int {
value := os.Getenv(key)
if value == "" {
return fallback
}
parsed, err := strconv.Atoi(value)
if err != nil {
return fallback
}
return parsed
}
func testRedisConfig() cache.RedisConfig {
return cache.RedisConfig{
Host: redisEnv("TEST_REDIS_HOST", "localhost"),
Port: redisEnvInt("TEST_REDIS_PORT", 6379),
Password: os.Getenv("TEST_REDIS_PASSWORD"),
DB: redisEnvInt("TEST_REDIS_DB", testRedisDB),
MaxRetries: 3,
DialTimeout: 5 * time.Second,
ReadTimeout: 3 * time.Second,
WriteTimeout: 3 * time.Second,
PoolSize: 5,
}
}
type SessionRepositorySuite struct {
suite.Suite
cache *cache.RedisCache
client *goredis.Client
}
func TestSessionRepositorySuite(t *testing.T) {
suite.Run(t, new(SessionRepositorySuite))
}
func (s *SessionRepositorySuite) SetupSuite() {
cfg := testRedisConfig()
var err error
s.cache, err = cache.NewRedis(cfg)
s.Require().NoError(err)
s.client = goredis.NewClient(&goredis.Options{
Addr: cfg.Host + ":" + strconv.Itoa(cfg.Port),
Password: cfg.Password,
DB: cfg.DB,
})
s.Require().NoError(s.client.Ping(s.T().Context()).Err())
}
func (s *SessionRepositorySuite) TearDownSuite() {
if s.client != nil {
s.Require().NoError(s.client.Close())
}
if s.cache != nil {
s.Require().NoError(s.cache.Close())
}
}
func (s *SessionRepositorySuite) SetupTest() {
s.Require().NoError(s.client.FlushDB(s.T().Context()).Err())
}
func (s *SessionRepositorySuite) newRepo(source storageredis.SessionSource) *storageredis.SessionRepository {
s.T().Helper()
return storageredis.NewSessionRepository(source, s.cache, 5*time.Minute, nil)
}
func testSession(userID uuid.UUID, expiresAt time.Time) domain.Session {
return domain.Session{
ExpiresAt: expiresAt,
User: domain.User{
ID: userID,
Username: "alice",
DisplayName: "Алиса",
CreatedAt: time.Now().UTC(),
},
}
}
func (s *SessionRepositorySuite) TestCacheTTLCapAndSessionExpiry() {
ctx := s.T().Context()
for _, remaining := range []time.Duration{time.Hour, time.Minute} {
hash := []byte(uuid.NewString())
session := testSession(uuid.New(), time.Now().UTC().Add(remaining))
source := mocks.NewMockSessionSource(s.T())
source.EXPECT().Resolve(mock.Anything, hash).Return(session, nil).Once()
_, err := s.newRepo(source).Resolve(ctx, hash)
s.Require().NoError(err)
ttl, err := s.client.PTTL(ctx, sessionCacheKey(hash)).Result()
s.Require().NoError(err)
s.Positive(ttl)
s.LessOrEqual(ttl, min(remaining, 5*time.Minute))
}
}
func (s *SessionRepositorySuite) TestResolvePopulatesCacheAndServesFromIt() {
ctx := s.T().Context()
tokenHash := []byte("hash-populate")
session := testSession(uuid.New(), time.Now().UTC().Add(time.Hour))
source := mocks.NewMockSessionSource(s.T())
source.EXPECT().Resolve(mock.Anything, tokenHash).Return(session, nil).Once()
repo := s.newRepo(source)
first, err := repo.Resolve(ctx, tokenHash)
s.Require().NoError(err)
s.Equal(session.User.ID, first.User.ID)
second, err := repo.Resolve(ctx, tokenHash)
s.Require().NoError(err)
s.Equal(session.User.ID, second.User.ID)
}
func (s *SessionRepositorySuite) TestResolveFallsBackToSourceOnMiss() {
ctx := s.T().Context()
tokenHash := []byte("unknown")
source := mocks.NewMockSessionSource(s.T())
source.EXPECT().Resolve(mock.Anything, tokenHash).Return(domain.Session{}, domain.ErrUnauthenticated).Once()
_, err := s.newRepo(source).Resolve(ctx, tokenHash)
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
}
func (s *SessionRepositorySuite) TestRevokeEvictsCacheAndSource() {
ctx := s.T().Context()
userID := uuid.New()
tokenHash := []byte("hash-revoke")
session := testSession(userID, time.Now().UTC().Add(time.Hour))
source := mocks.NewMockSessionSource(s.T())
source.EXPECT().Resolve(mock.Anything, tokenHash).Return(session, nil).Once()
source.EXPECT().Revoke(mock.Anything, userID, tokenHash).Return(nil).Once()
source.EXPECT().Resolve(mock.Anything, tokenHash).Return(domain.Session{}, domain.ErrUnauthenticated).Once()
repo := s.newRepo(source)
_, err := repo.Resolve(ctx, tokenHash)
s.Require().NoError(err)
s.Require().NoError(repo.Revoke(ctx, userID, tokenHash))
_, err = repo.Resolve(ctx, tokenHash)
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
}
func (s *SessionRepositorySuite) TestEvictedCacheEntryReloadsFromSource() {
ctx := s.T().Context()
tokenHash := []byte("hash-evicted")
session := testSession(uuid.New(), time.Now().UTC().Add(time.Hour))
source := mocks.NewMockSessionSource(s.T())
source.EXPECT().Resolve(mock.Anything, tokenHash).Return(session, nil).Twice()
repo := s.newRepo(source)
_, err := repo.Resolve(ctx, tokenHash)
s.Require().NoError(err)
// Simulate a Redis flush/restart by dropping the cache entry.
s.Require().NoError(s.client.Del(ctx, sessionCacheKey(tokenHash)).Err())
_, err = repo.Resolve(ctx, tokenHash)
s.Require().NoError(err)
}
func (s *SessionRepositorySuite) TestExpiredSessionIsRejected() {
ctx := s.T().Context()
tokenHash := []byte("hash-expired")
source := mocks.NewMockSessionSource(s.T())
source.EXPECT().Resolve(mock.Anything, tokenHash).Return(domain.Session{}, domain.ErrUnauthenticated).Once()
_, err := s.newRepo(source).Resolve(ctx, tokenHash)
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
}
func sessionCacheKey(tokenHash []byte) string {
return "session:" + hex.EncodeToString(tokenHash)
}
func flushRedisDB(ctx context.Context) error {
cfg := testRedisConfig()
client := goredis.NewClient(&goredis.Options{
Addr: cfg.Host + ":" + strconv.Itoa(cfg.Port),
Password: cfg.Password,
DB: cfg.DB,
})
defer func() { _ = client.Close() }()
return client.FlushDB(ctx).Err()
}