diff --git a/redis/go.mod b/redis/go.mod index 6d2adecd..87f7f5bb 100644 --- a/redis/go.mod +++ b/redis/go.mod @@ -2,4 +2,7 @@ module github.com/gofiber/storage/redis go 1.15 -require github.com/gomodule/redigo v1.8.2 +require ( + github.com/gofiber/utils v0.0.10 + github.com/gomodule/redigo v1.8.2 +) diff --git a/redis/go.sum b/redis/go.sum index ebba3589..13c3040f 100644 --- a/redis/go.sum +++ b/redis/go.sum @@ -1,4 +1,6 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gofiber/utils v0.0.10 h1:3Mr7X7JdCUo7CWf/i5sajSaDmArEDtti8bM1JUVso2U= +github.com/gofiber/utils v0.0.10/go.mod h1:9J5aHFUIjq0XfknT4+hdSMG6/jzfaAgCu4HEbWDeBlo= github.com/gomodule/redigo v1.8.2 h1:H5XSIre1MB5NbPYFp+i1NBbb5qN1W8Y8YAQoAYbkm8k= github.com/gomodule/redigo v1.8.2/go.mod h1:P9dn9mFrCBvWhGE1wpxx6fgq7BAeLBk+UUUzlpkBYO0= github.com/gomodule/redigo/redis v0.0.0-do-not-use h1:J7XIp6Kau0WoyT4JtXHT3Ei0gA1KkSc6bc87j9v9WIo= diff --git a/redis/redis_test.go b/redis/redis_test.go new file mode 100644 index 00000000..41de1b27 --- /dev/null +++ b/redis/redis_test.go @@ -0,0 +1,190 @@ +package redisStore + +import ( + "fmt" + "testing" + "time" + + "github.com/gofiber/utils" + "github.com/gomodule/redigo/redis" +) + +// The tests here assume that you have a local Redis sever running on the default port. +// The Redis address can be changed using the redisLocation variable. + +var ( + redisLocation = "127.0.0.1:6379" + getConn = func() (redis.Conn, error) { + return redis.Dial("tcp", redisLocation) + } +) + +func Test_Set(t *testing.T) { + + topLevelKey := "store" + store := NewRedisStore(getConn, topLevelKey) + + key := "aaaa" + val := []byte("This is a value") + + err := store.Set(key, val, 0) + utils.AssertEqual(t, nil, err) + + key = fmt.Sprintf("%s:%s", topLevelKey, key) + + redisConn, err := getConn() + defer redisConn.Close() + utils.AssertEqual(t, nil, err) + + exists, err := redis.Bool(redisConn.Do("EXISTS", key)) + utils.AssertEqual(t, nil, err) + utils.AssertEqual(t, true, exists) + + output, err := redis.Bytes(redisConn.Do("GET", key)) + utils.AssertEqual(t, nil, err) + utils.AssertEqual(t, val, output) + +} + +func Test_SetExpiry(t *testing.T) { + + topLevelKey := "store" + store := NewRedisStore(getConn, topLevelKey) + + key := "aaaa" + val := []byte("This is a value") + + expiry := time.Second * 60 + + err := store.Set(key, val, expiry) + utils.AssertEqual(t, nil, err) + + key = fmt.Sprintf("%s:%s", topLevelKey, key) + + redisConn, err := getConn() + defer redisConn.Close() + utils.AssertEqual(t, nil, err) + + exists, err := redis.Bool(redisConn.Do("EXISTS", key)) + utils.AssertEqual(t, nil, err) + utils.AssertEqual(t, true, exists) + + ttl, err := redis.Int(redisConn.Do("TTL", key)) + utils.AssertEqual(t, nil, err) + if !(float64(ttl) <= expiry.Seconds() && float64(ttl) > expiry.Seconds()-5) { + t.Fatalf("Test_SetExpiry: expiry out of bounds (is %d, must be %d