| 1 |
package redigostore_test |
| 2 |
|
| 3 |
import ( |
| 4 |
"testing" |
| 5 |
"time" |
| 6 |
|
| 7 |
"github.com/gomodule/redigo/redis" |
| 8 |
|
| 9 |
"github.com/throttled/throttled/store/redigostore" |
| 10 |
"github.com/throttled/throttled/store/storetest" |
| 11 |
) |
| 12 |
|
| 13 |
const ( |
| 14 |
redisTestDB = 1 |
| 15 |
redisTestPrefix = "throttled:" |
| 16 |
) |
| 17 |
|
| 18 |
func getPool() *redis.Pool { |
| 19 |
pool := &redis.Pool{ |
| 20 |
MaxIdle: 3, |
| 21 |
IdleTimeout: 30 * time.Second, |
| 22 |
Dial: func() (redis.Conn, error) { |
| 23 |
return redis.Dial("tcp", ":6379") |
| 24 |
}, |
| 25 |
TestOnBorrow: func(c redis.Conn, t time.Time) error { |
| 26 |
_, err := c.Do("PING") |
| 27 |
return err |
| 28 |
}, |
| 29 |
} |
| 30 |
return pool |
| 31 |
} |
| 32 |
|
| 33 |
func TestRedisStore(t *testing.T) { |
| 34 |
c, st := setupRedis(t, 0) |
| 35 |
defer c.Close() |
| 36 |
defer clearRedis(c) |
| 37 |
|
| 38 |
clearRedis(c) |
| 39 |
storetest.TestGCRAStore(t, st) |
| 40 |
storetest.TestGCRAStoreTTL(t, st) |
| 41 |
} |
| 42 |
|
| 43 |
func BenchmarkRedisStore(b *testing.B) { |
| 44 |
c, st := setupRedis(b, 0) |
| 45 |
defer c.Close() |
| 46 |
defer clearRedis(c) |
| 47 |
|
| 48 |
storetest.BenchmarkGCRAStore(b, st) |
| 49 |
} |
| 50 |
|
| 51 |
func clearRedis(c redis.Conn) error { |
| 52 |
keys, err := redis.Values(c.Do("KEYS", redisTestPrefix+"*")) |
| 53 |
if err != nil { |
| 54 |
return err |
| 55 |
} |
| 56 |
|
| 57 |
if _, err := redis.Int(c.Do("DEL", keys...)); err != nil { |
| 58 |
return err |
| 59 |
} |
| 60 |
|
| 61 |
return nil |
| 62 |
} |
| 63 |
|
| 64 |
func setupRedis(tb testing.TB, ttl time.Duration) (redis.Conn, *redigostore.RedigoStore) { |
| 65 |
pool := getPool() |
| 66 |
c := pool.Get() |
| 67 |
|
| 68 |
if _, err := redis.String(c.Do("PING")); err != nil { |
| 69 |
c.Close() |
| 70 |
tb.Skip("redis server not available on localhost port 6379") |
| 71 |
} |
| 72 |
|
| 73 |
if _, err := redis.String(c.Do("SELECT", redisTestDB)); err != nil { |
| 74 |
c.Close() |
| 75 |
tb.Fatal(err) |
| 76 |
} |
| 77 |
|
| 78 |
st, err := redigostore.New(pool, redisTestPrefix, redisTestDB) |
| 79 |
if err != nil { |
| 80 |
c.Close() |
| 81 |
tb.Fatal(err) |
| 82 |
} |
| 83 |
|
| 84 |
return c, st |
| 85 |
} |