packageredisimport("context""fmt""github.com/testcontainers/testcontainers-go""github.com/testcontainers/testcontainers-go/wait")typeredisContainerstruct{testcontainers.ContainerURIstring}funcstartContainer(ctxcontext.Context)(*redisContainer,error){req:=testcontainers.ContainerRequest{Image:"redis:6",ExposedPorts:[]string{"6379/tcp"},WaitingFor:wait.ForLog("* Ready to accept connections"),}container,err:=testcontainers.GenericContainer(ctx,testcontainers.GenericContainerRequest{ContainerRequest:req,Started:true,})iferr!=nil{returnnil,err}mappedPort,err:=container.MappedPort(ctx,"6379")iferr!=nil{returnnil,err}hostIP,err:=container.Host(ctx)iferr!=nil{returnnil,err}uri:=fmt.Sprintf("redis://%s:%s",hostIP,mappedPort.Port())return&redisContainer{Container:container,URI:uri},nil}
packageredisimport("context""fmt""testing""time""github.com/go-redis/redis/v8""github.com/google/uuid""github.com/stretchr/testify/require")funcTestIntegrationSetGet(t*testing.T){iftesting.Short(){t.Skip("Skipping integration test")}ctx:=context.Background()redisContainer,err:=startContainer(ctx)iferr!=nil{t.Fatal(err)}t.Cleanup(func(){iferr:=redisContainer.Terminate(ctx);err!=nil{t.Fatalf("failed to terminate container: %s",err)}})// You will likely want to wrap your Redis package of choice in an// interface to aid in unit testing and limit lock-in throughtout your// codebase but that's out of scope for this exampleoptions,err:=redis.ParseURL(redisContainer.URI)iferr!=nil{t.Fatal(err)}client:=redis.NewClient(options)deferflushRedis(ctx,*client)t.Log("pinging redis")pong,err:=client.Ping(ctx).Result()require.NoError(t,err)t.Log("received response from redis")ifpong!="PONG"{t.Fatalf("received unexpected response from redis: %s",pong)}// Set datakey:=fmt.Sprintf("{user.%s}.favoritefood",uuid.NewString())value:="Cabbage Biscuits"ttl,_:=time.ParseDuration("2h")err=client.Set(ctx,key,value,ttl).Err()iferr!=nil{t.Fatal(err)}// Get datasavedValue,err:=client.Get(ctx,key).Result()iferr!=nil{t.Fatal(err)}ifsavedValue!=value{t.Fatalf("Expected value %s. Got %s.",savedValue,value)}}funcflushRedis(ctxcontext.Context,clientredis.Client)error{returnclient.FlushAll(ctx).Err()}