README
¶
Miniredis
Pure Go Redis test server, used in Go unittests. This is a fork of the dlsteuer/miniredis project, converting to use the type safe go-redis library instead of gomodule/redigo
Sometimes you want to test code which uses Redis, without making it a full-blown
integration test.
Miniredis implements (parts of) the Redis server, to be used in unittests. It
enables a simple, cheap, in-memory, Redis replacement, with a real TCP interface. Think of it as the Redis version of net/http/httptest
.
It saves you from using mock code, and since the redis server lives in the test process you can query for values directly, without going through the server stack.
There are no dependencies on external binaries, so you can easily integrate it in automated build processes.
Changelog
2.4.3
Fixed using Lua with authenticated redis.
2.4.2
Changed redigo import path.
2.4
Minor cleanups. Miniredis now requires Go >= 1.9 (only for the tests. If you don't run the tests you can use an older Go version).
2.3.1
Lua changes: added cjson
library, and redis.sha1hex()
.
2.3
Added the EVAL
, EVALSHA
, and SCRIPT
commands. Uses a pure Go Lua interpreter. Please open an issue if there are problems with any Lua code.
2.2
Introduced StartAddr()
.
2.1
Internal cleanups. No changes in functionality.
2.0
2.0.0 improves TTLs to be time.Duration
values. .Expire()
is removed and
replaced by .TTL()
, which returns the TTL as a time.Duration
.
This should be the change needed to upgrade:
1.0:
m.Expire() == 4
2.0:
m.TTL() == 4 * time.Second
Furthermore, .SetTime()
is added to help with EXPIREAT
commands, and .FastForward()
is introduced to test keys expiration.
Commands
Implemented commands:
- Connection (complete)
- AUTH -- see RequireAuth()
- ECHO
- PING
- SELECT
- QUIT
- Key
- DEL
- EXISTS
- EXPIRE
- EXPIREAT
- KEYS
- MOVE
- PERSIST
- PEXPIRE
- PEXPIREAT
- PTTL
- RENAME
- RENAMENX
- RANDOMKEY -- call math.rand.Seed(...) once before using.
- TTL
- TYPE
- SCAN
- Transactions (complete)
- DISCARD
- EXEC
- MULTI
- UNWATCH
- WATCH
- Server
- DBSIZE
- FLUSHALL
- FLUSHDB
- String keys (complete)
- APPEND
- BITCOUNT
- BITOP
- BITPOS
- DECR
- DECRBY
- GET
- GETBIT
- GETRANGE
- GETSET
- INCR
- INCRBY
- INCRBYFLOAT
- MGET
- MSET
- MSETNX
- PSETEX
- SET
- SETBIT
- SETEX
- SETNX
- SETRANGE
- STRLEN
- Hash keys (complete)
- HDEL
- HEXISTS
- HGET
- HGETALL
- HINCRBY
- HINCRBYFLOAT
- HKEYS
- HLEN
- HMGET
- HMSET
- HSET
- HSETNX
- HVALS
- HSCAN
- List keys (complete)
- BLPOP
- BRPOP
- BRPOPLPUSH
- LINDEX
- LINSERT
- LLEN
- LPOP
- LPUSH
- LPUSHX
- LRANGE
- LREM
- LSET
- LTRIM
- RPOP
- RPOPLPUSH
- RPUSH
- RPUSHX
- Set keys (complete)
- SADD
- SCARD
- SDIFF
- SDIFFSTORE
- SINTER
- SINTERSTORE
- SISMEMBER
- SMEMBERS
- SMOVE
- SPOP -- call math.rand.Seed(...) once before using.
- SRANDMEMBER -- call math.rand.Seed(...) once before using.
- SREM
- SUNION
- SUNIONSTORE
- SSCAN
- Sorted Set keys (complete)
- ZADD
- ZCARD
- ZCOUNT
- ZINCRBY
- ZINTERSTORE
- ZLEXCOUNT
- ZRANGE
- ZRANGEBYLEX
- ZRANGEBYSCORE
- ZRANK
- ZREM
- ZREMRANGEBYLEX
- ZREMRANGEBYRANK
- ZREMRANGEBYSCORE
- ZREVRANGE
- ZREVRANGEBYSCORE
- ZREVRANK
- ZSCORE
- ZUNIONSTORE
- ZSCAN
- Scripting
- EVAL
- EVALSHA
- SCRIPT LOAD
- SCRIPT EXISTS
- SCRIPT FLUSH
Since miniredis is intended to be used in unittests TTLs don't decrease
automatically. You can use TTL()
to get the TTL (as a time.Duration) of a
key. It will return 0 when no TTL is set. EXPIREAT and PEXPIREAT values will be
converted to a duration. For that you can either set m.SetTime(t) to use that
time as the base for the (P)EXPIREAT conversion, or don't call SetTime(), in
which case time.Now() will be used.
m.FastForward(d)
can be used to decrement all TTLs. All TTLs which become <=
0 will be removed.
Example
func TestSomething(t *testing.T) {
s, err := miniredis.Run()
if err != nil {
panic(err)
}
defer s.Close()
// Optionally set some keys your code expects:
s.Set("foo", "bar")
s.HSet("some", "other", "key")
// Run your code and see if it behaves.
// An example using the redigo library from "github.com/gomodule/redigo/redis":
c, err := redis.Dial("tcp", s.Addr())
_, err = c.Do("SET", "foo", "bar")
// Optionally check values in redis...
if got, err := s.Get("foo"); err != nil || got != "bar" {
t.Error("'foo' has the wrong value")
}
// ... or use a helper for that:
s.CheckGet(t, "foo", "bar")
// TTL and expiration:
s.Set("foo", "bar")
s.SetTTL("foo", 10*time.Second)
s.FastForward(11 * time.Second)
if s.Exists("foo") {
t.Fatal("'foo' should not have existed anymore")
}
}
Not supported
Commands which will probably not be implemented:
- CLUSTER (all)
CLUSTER *READONLYREADWRITE
- GEO (all) -- unless someone needs these
GEOADDGEODISTGEOHASHGEOPOSGEORADIUSGEORADIUSBYMEMBER
- HyperLogLog (all) -- unless someone needs these
PFADDPFCOUNTPFMERGE
- Key
DUMPMIGRATEOBJECTRESTOREWAIT
- Pub/Sub (all)
PSUBSCRIBEPUBLISHPUBSUBPUNSUBSCRIBESUBSCRIBEUNSUBSCRIBE
- Scripting
SCRIPT DEBUGSCRIPT KILL
- Server
BGSAVEBGWRITEAOFCLIENT *COMMAND *CONFIG *DEBUG *INFOLASTSAVEMONITORROLESAVESHUTDOWNSLAVEOFSLOWLOGSYNCTIME
&c.
See https://github.com/dlsteuer/miniredis_vs_redis for tests comparing miniredis against the real thing. Tests are run against Redis 4.0.6 (Debian).
Documentation
¶
Overview ¶
Package miniredis is a pure Go Redis test server, for use in Go unittests. There are no dependencies on system binaries, and every server you start will be empty.
Start a server with `s, err := miniredis.Run()`. Stop it with `defer s.Close()`.
Point your Redis client to `s.Addr()` or `s.Host(), s.Port()`.
Set keys directly via s.Set(...) and similar commands, or use a Redis client.
For direct use you can select a Redis database with either `s.Select(12); s.Get("foo")` or `s.DB(12).Get("foo")`.
Index ¶
- Variables
- type Miniredis
- func (m *Miniredis) Addr() string
- func (m *Miniredis) CheckGet(t T, key, expected string)
- func (m *Miniredis) CheckList(t T, key string, expected ...string)
- func (m *Miniredis) CheckSet(t T, key string, expected ...string)
- func (m *Miniredis) Close()
- func (m *Miniredis) CommandCount() int
- func (m *Miniredis) CurrentConnectionCount() int
- func (m *Miniredis) DB(i int) *RedisDB
- func (m *Miniredis) Del(k string) bool
- func (m *Miniredis) Dump() string
- func (m *Miniredis) Exists(k string) bool
- func (m *Miniredis) FastForward(duration time.Duration)
- func (m *Miniredis) FlushAll()
- func (m *Miniredis) FlushDB()
- func (m *Miniredis) Get(k string) (string, error)
- func (m *Miniredis) HDel(k, f string)
- func (m *Miniredis) HGet(k, f string) string
- func (m *Miniredis) HIncr(k, f string, delta int) (int, error)
- func (m *Miniredis) HIncrfloat(k, f string, delta float64) (float64, error)
- func (m *Miniredis) HKeys(k string) ([]string, error)
- func (m *Miniredis) HSet(k, f, v string)
- func (m *Miniredis) Host() string
- func (m *Miniredis) Incr(k string, delta int) (int, error)
- func (m *Miniredis) Incrfloat(k string, delta float64) (float64, error)
- func (m *Miniredis) IsMember(k, v string) (bool, error)
- func (m *Miniredis) Keys() []string
- func (m *Miniredis) List(k string) ([]string, error)
- func (m *Miniredis) Lpop(k string) (string, error)
- func (m *Miniredis) Lpush(k, v string) (int, error)
- func (m *Miniredis) Members(k string) ([]string, error)
- func (m *Miniredis) Pop(k string) (string, error)
- func (m *Miniredis) Port() string
- func (m *Miniredis) Push(k string, v ...string) (int, error)
- func (m *Miniredis) RequireAuth(pw string)
- func (m *Miniredis) Restart() error
- func (m *Miniredis) SRem(k string, fields ...string) (int, error)
- func (m *Miniredis) Select(i int)
- func (m *Miniredis) Set(k, v string) error
- func (m *Miniredis) SetAdd(k string, elems ...string) (int, error)
- func (m *Miniredis) SetTTL(k string, ttl time.Duration)
- func (m *Miniredis) SetTime(t time.Time)
- func (m *Miniredis) SortedSet(k string) (map[string]float64, error)
- func (m *Miniredis) Start() error
- func (m *Miniredis) StartAddr(addr string) error
- func (m *Miniredis) TTL(k string) time.Duration
- func (m *Miniredis) TotalConnectionCount() int
- func (m *Miniredis) Type(k string) string
- func (m *Miniredis) ZAdd(k string, score float64, member string) (bool, error)
- func (m *Miniredis) ZMembers(k string) ([]string, error)
- func (m *Miniredis) ZRem(k, member string) (bool, error)
- func (m *Miniredis) ZScore(k, member string) (float64, error)
- type RedisDB
- func (db *RedisDB) Del(k string) bool
- func (db *RedisDB) Exists(k string) bool
- func (db *RedisDB) FlushDB()
- func (db *RedisDB) Get(k string) (string, error)
- func (db *RedisDB) HDel(k, f string)
- func (db *RedisDB) HGet(k, f string) string
- func (db *RedisDB) HIncr(k, f string, delta int) (int, error)
- func (db *RedisDB) HIncrfloat(k, f string, delta float64) (float64, error)
- func (db *RedisDB) HKeys(key string) ([]string, error)
- func (db *RedisDB) HSet(k, f, v string)
- func (db *RedisDB) Incr(k string, delta int) (int, error)
- func (db *RedisDB) Incrfloat(k string, delta float64) (float64, error)
- func (db *RedisDB) IsMember(k, v string) (bool, error)
- func (db *RedisDB) Keys() []string
- func (db *RedisDB) List(k string) ([]string, error)
- func (db *RedisDB) Lpop(k string) (string, error)
- func (db *RedisDB) Lpush(k, v string) (int, error)
- func (db *RedisDB) Members(k string) ([]string, error)
- func (db *RedisDB) Pop(k string) (string, error)
- func (db *RedisDB) Push(k string, v ...string) (int, error)
- func (db *RedisDB) SRem(k string, fields ...string) (int, error)
- func (db *RedisDB) Set(k, v string) error
- func (db *RedisDB) SetAdd(k string, elems ...string) (int, error)
- func (db *RedisDB) SetTTL(k string, ttl time.Duration)
- func (db *RedisDB) SortedSet(k string) (map[string]float64, error)
- func (db *RedisDB) TTL(k string) time.Duration
- func (db *RedisDB) Type(k string) string
- func (db *RedisDB) ZAdd(k string, score float64, member string) (bool, error)
- func (db *RedisDB) ZMembers(k string) ([]string, error)
- func (db *RedisDB) ZRem(k, member string) (bool, error)
- func (db *RedisDB) ZScore(k, member string) (float64, error)
- type T
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrKeyNotFound is returned when a key doesn't exist. ErrKeyNotFound = errors.New(msgKeyNotFound) // ErrWrongType when a key is not the right type. ErrWrongType = errors.New(msgWrongType) // ErrIntValueError can returned by INCRBY ErrIntValueError = errors.New(msgInvalidInt) // ErrFloatValueError can returned by INCRBYFLOAT ErrFloatValueError = errors.New(msgInvalidFloat) )
Functions ¶
This section is empty.
Types ¶
type Miniredis ¶
Miniredis is a Redis server implementation.
func NewMiniRedis ¶
func NewMiniRedis() *Miniredis
NewMiniRedis makes a new, non-started, Miniredis object.
func (*Miniredis) Addr ¶
Addr returns '127.0.0.1:12345'. Can be given to a Dial(). See also Host() and Port(), which return the same things.
func (*Miniredis) CheckGet ¶
CheckGet does not call Errorf() iff there is a string key with the expected value. Normal use case is `m.CheckGet(t, "username", "theking")`.
func (*Miniredis) CheckList ¶
CheckList does not call Errorf() iff there is a list key with the expected values. Normal use case is `m.CheckGet(t, "favorite_colors", "red", "green", "infrared")`.
func (*Miniredis) CheckSet ¶
CheckSet does not call Errorf() iff there is a set key with the expected values. Normal use case is `m.CheckSet(t, "visited", "Rome", "Stockholm", "Dublin")`.
func (*Miniredis) CommandCount ¶
CommandCount returns the number of processed commands.
func (*Miniredis) CurrentConnectionCount ¶
CurrentConnectionCount returns the number of currently connected clients.
func (*Miniredis) Del ¶
Del deletes a key and any expiration value. Returns whether there was a key.
func (*Miniredis) FastForward ¶
FastForward decreases all TTLs by the given duration. All TTLs <= 0 will be expired.
func (*Miniredis) FlushAll ¶
func (m *Miniredis) FlushAll()
FlushAll removes all keys from all databases.
func (*Miniredis) FlushDB ¶
func (m *Miniredis) FlushDB()
FlushDB removes all keys from the selected database.
func (*Miniredis) HGet ¶
HGet returns hash keys added with HSET. This will return an empty string if the key is not set. Redis would return a nil. Returns empty string when the key is of a different type.
func (*Miniredis) HIncrfloat ¶
HIncrfloat increases a key/field by delta (float).
func (*Miniredis) HSet ¶
HSet sets a hash key. If there is another key by the same name it will be gone.
func (*Miniredis) List ¶
List returns the list k, or an error if it's not there or something else. This is the same as the Redis command `LRANGE 0 -1`, but you can do your own range-ing.
func (*Miniredis) Push ¶
Push add element at the end. Is called RPUSH in redis. Returns the new length.
func (*Miniredis) RequireAuth ¶
RequireAuth makes every connection need to AUTH first. Disable again by setting an empty string.
func (*Miniredis) Restart ¶
Restart restarts a Close()d server on the same port. Values will be preserved.
func (*Miniredis) SetTime ¶
SetTime sets the time against which EXPIREAT values are compared. EXPIREAT will use time.Now() if this is not set.
func (*Miniredis) Start ¶
Start starts a server. It listens on a random port on localhost. See also Addr().
func (*Miniredis) StartAddr ¶
StartAddr runs miniredis with a given addr. Examples: "127.0.0.1:6379", ":6379", or "127.0.0.1:0"
func (*Miniredis) TTL ¶
TTL is the left over time to live. As set via EXPIRE, PEXPIRE, EXPIREAT, PEXPIREAT. 0 if not set.
func (*Miniredis) TotalConnectionCount ¶
TotalConnectionCount returns the number of client connections since server start.
type RedisDB ¶
type RedisDB struct {
// contains filtered or unexported fields
}
RedisDB holds a single (numbered) Redis database.
func (*RedisDB) HGet ¶
HGet returns hash keys added with HSET. Returns empty string when the key is of a different type.
func (*RedisDB) HIncrfloat ¶
HIncrfloat increases a key/field by delta (float).
func (*RedisDB) HSet ¶
HSet sets a hash key. If there is another key by the same name it will be gone.
func (*RedisDB) List ¶
List returns the list k, or an error if it's not there or something else. This is the same as the Redis command `LRANGE 0 -1`, but you can do your own range-ing.
func (*RedisDB) Push ¶
Push add element at the end. Is called RPUSH in redis. Returns the new length.
func (*RedisDB) Set ¶
Set sets a string key. Removes expire. Unlike redis the key can't be an existing non-string key.
func (*RedisDB) TTL ¶
TTL is the left over time to live. As set via EXPIRE, PEXPIRE, EXPIREAT, PEXPIREAT. 0 if not set.