package cache import ( "context" "encoding/json" "fmt" "os" "testing" "time" "tercul/internal/domain" platform_cache "tercul/internal/platform/cache" "github.com/redis/go-redis/v9" "github.com/stretchr/testify/require" "github.com/testcontainers/testcontainers-go" "github.com/testcontainers/testcontainers-go/wait" ) func TestRedisIntegration_CachedWorkRepository(t *testing.T) { if os.Getenv("INTEGRATION_TESTS") != "true" { t.Skip("skipping integration test; set INTEGRATION_TESTS=true to run") } ctx := context.Background() req := testcontainers.ContainerRequest{ Image: "redis:7.0", ExposedPorts: []string{"6379/tcp"}, WaitingFor: wait.ForListeningPort("6379/tcp").WithStartupTimeout(30 * time.Second), } redisC, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{ContainerRequest: req, Started: true}) require.NoError(t, err) defer redisC.Terminate(ctx) host, err := redisC.Host(ctx) require.NoError(t, err) port, err := redisC.MappedPort(ctx, "6379") require.NoError(t, err) addr := fmt.Sprintf("%s:%s", host, port.Port()) rcClient := redis.NewClient(&redis.Options{Addr: addr}) defer rcClient.Close() require.NoError(t, rcClient.Ping(ctx).Err()) // create platform redis cache using key prefix that caches expect keyGen := platform_cache.NewDefaultKeyGenerator("tercul:repo:") rc := platform_cache.NewRedisCache(rcClient, keyGen, 0) // create dummy repo and wrap d := newDummyWorkRepo() d.store[1] = &domain.Work{Title: "intwork", TranslatableModel: domain.TranslatableModel{BaseModel: domain.BaseModel{ID: 1}, Language: "en"}} cw := NewCachedWorkRepository(d, rc, nil) // call and assert Redis stored entity w, err := cw.GetByID(ctx, 1) require.NoError(t, err) require.Equal(t, "intwork", w.Title) key := keyGen.EntityKey("work", 1) val, err := rcClient.Get(ctx, key).Bytes() require.NoError(t, err) var stored domain.Work require.NoError(t, json.Unmarshal(val, &stored)) require.Equal(t, "intwork", stored.Title) // list caching test d.store[2] = &domain.Work{Title: "intwork2", TranslatableModel: domain.TranslatableModel{BaseModel: domain.BaseModel{ID: 2}, Language: "en"}} // call list _, err = cw.List(ctx, 1, 10) require.NoError(t, err) listKey := keyGen.ListKey("work", 1, 10) _, err = rcClient.Get(ctx, listKey).Bytes() require.NoError(t, err) }