Inicial
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
goredis "github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
type Redis struct {
|
||||
Client *goredis.Client
|
||||
}
|
||||
|
||||
func New(redisURL string) (*Redis, error) {
|
||||
opts, err := goredis.ParseURL(redisURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("redis: invalid URL: %w", err)
|
||||
}
|
||||
|
||||
client := goredis.NewClient(opts)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := client.Ping(ctx).Err(); err != nil {
|
||||
client.Close()
|
||||
return nil, fmt.Errorf("redis: failed to connect: %w", err)
|
||||
}
|
||||
|
||||
return &Redis{Client: client}, nil
|
||||
}
|
||||
|
||||
func (r *Redis) Close() error {
|
||||
return r.Client.Close()
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package redis_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
redispkg "github.com/techxcar/backend/pkg/redis"
|
||||
)
|
||||
|
||||
func TestNew_invalidURL(t *testing.T) {
|
||||
_, err := redispkg.New("not-a-valid-url")
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
func TestNew_valid(t *testing.T) {
|
||||
url := os.Getenv("TEST_REDIS_URL")
|
||||
if url == "" {
|
||||
t.Skip("TEST_REDIS_URL not set, skipping integration test")
|
||||
}
|
||||
|
||||
rdb, err := redispkg.New(url)
|
||||
require.NoError(t, err)
|
||||
defer rdb.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
err = rdb.Client.Set(ctx, "test_key", "test_value", time.Second).Err()
|
||||
assert.NoError(t, err)
|
||||
|
||||
val, err := rdb.Client.Get(ctx, "test_key").Result()
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "test_value", val)
|
||||
}
|
||||
Reference in New Issue
Block a user