### Install redismock Source: https://github.com/go-redis/redismock/blob/master/README.md Use `go get` to install the redismock library for version 9 of go-redis. ```go go get github.com/go-redis/redismock/v9 ``` -------------------------------- ### Mock String Commands: Get/Set Source: https://github.com/go-redis/redismock/blob/master/_autodocs/quick-reference.md Examples for mocking common Redis string commands like GET, SET, and their variants. ```go // Get/Set mock.ExpectGet(key).SetVal(value) ``` ```go mock.ExpectSet(key, value, duration).SetVal("OK") ``` ```go mock.ExpectSetArgs(key, value, args).SetVal("OK") ``` ```go mock.ExpectSetEx(key, value, duration).SetVal("OK") ``` ```go mock.ExpectSetNX(key, value, duration).SetVal(true) ``` ```go mock.ExpectSetXX(key, value, duration).SetVal(true) ``` ```go mock.ExpectGetSet(key, value).SetVal(oldValue) ``` ```go mock.ExpectGetDel(key).SetVal(value) ``` ```go mock.ExpectGetEx(key, duration).SetVal(value) ``` -------------------------------- ### Install go-redis/redismock Source: https://github.com/go-redis/redismock/blob/master/_autodocs/README.md Import the redismock library. Requires go-redis/v9 v9.2.0 or later. ```go import "github.com/go-redis/redismock/v9" ``` -------------------------------- ### Import Redismock Module Source: https://github.com/go-redis/redismock/blob/master/_autodocs/quick-reference.md Import the redismock package to start mocking Redis clients. ```go import "github.com/go-redis/redismock/v9" ``` -------------------------------- ### Mock RedisClient Get and Set Source: https://github.com/go-redis/redismock/blob/master/README.md Demonstrates mocking `Get` and `Set` commands for a RedisClient. The `Get` command is mocked to return `redis.Nil`, and the `Set` command is mocked to return an error using a regular expression for the key. ```go var ctx = context.TODO() func NewsInfoForCache(redisDB *redis.Client, newsID int) (info string, err error) { cacheKey := fmt.Sprintf("news_redis_cache_%d", newsID) info, err = redisDB.Get(ctx, cacheKey).Result() if err == redis.Nil { // info, err = call api() info = "test" err = redisDB.Set(ctx, cacheKey, info, 30 * time.Minute).Err() } return } func TestNewsInfoForCache(t *testing.T) { db, mock := redismock.NewClientMock() newsID := 123456789 key := fmt.Sprintf("news_redis_cache_%d", newsID) // mock ignoring `call api()` mock.ExpectGet(key).RedisNil() mock.Regexp().ExpectSet(key, `[a-z]+`, 30 * time.Minute).SetErr(errors.New("FAIL")) _, err := NewsInfoForCache(db, newsID) if err == nil || err.Error() != "FAIL" { t.Error("wrong error") } if err := mock.ExpectationsWereMet(); err != nil { t.Error(err) } } ``` -------------------------------- ### Basic Usage of go-redis/redismock Source: https://github.com/go-redis/redismock/blob/master/_autodocs/README.md Demonstrates creating a mock client, queuing expectations for a GET command, executing the command using the mock, and verifying expectations. ```go package main import ( "context" "fmt" "github.com/go-redis/redismock/v9" ) func main() { ctx := context.Background() // Create mock db, mock := redismock.NewClientMock() // Queue expectations mock.ExpectGet("mykey").SetVal("myvalue") // Use mock client like a real client result, _ := db.Get(ctx, "mykey").Result() fmt.Println(result) // Output: myvalue // Verify all expectations were met if err := mock.ExpectationsWereMet(); err != nil { panic(err) } } ``` -------------------------------- ### Test Cache Layer with Set and Get Source: https://github.com/go-redis/redismock/blob/master/_autodocs/README.md Demonstrates how to mock Set and Get operations for a cache layer. Use this to test your cache logic in isolation. ```go mock.ExpectSet("cache:123", jsonData, 1*time.Hour).SetVal("OK") mock.ExpectGet("cache:123").SetVal(jsonData) // Test cache get/set logic ``` -------------------------------- ### String Commands Source: https://github.com/go-redis/redismock/blob/master/_autodocs/quick-reference.md Provides examples for mocking various Redis string commands, including Get, Set, Append, Increment, and more. ```APIDOC ## String Commands ### Description This section provides examples for mocking common Redis string commands. Each example shows how to set up an expectation and configure its return value. ### Mocked Commands - **Get/Set** - `ExpectGet(key string) *Expected` - `ExpectSet(key string, value string, expiration time.Duration) *Expected` - `ExpectSetArgs(key string, value string, args ...interface{}) *Expected` - `ExpectSetEx(key string, value string, expiration time.Duration) *Expected` - `ExpectSetNX(key string, value string, expiration time.Duration) *Expected` - `ExpectSetXX(key string, value string, expiration time.Duration) *Expected` - `ExpectGetSet(key string, value string) *Expected` - `ExpectGetDel(key string) *Expected` - `ExpectGetEx(key string, expiration time.Duration) *Expected` - **Numeric** - `ExpectAppend(key string, value string) *Expected` - `ExpectIncr(key string) *Expected` - `ExpectIncrBy(key string, increment int64) *Expected` - `ExpectIncrByFloat(key string, increment float64) *Expected` - `ExpectDecr(key string) *Expected` - `ExpectDecrBy(key string, decrement int64) *Expected` - **Range/Len** - `ExpectGetRange(key string, start, end int64) *Expected` - `ExpectSetRange(key string, offset int64, value string) *Expected` - `ExpectStrLen(key string) *Expected` - **Multiple** - `ExpectMGet(keys ...string) *Expected` - `ExpectMSet(pairs ...string) *Expected` - `ExpectMSetNX(pairs ...string) *Expected` ### Usage Example ```APIDOC // Example for ExpectSet mock.ExpectSet("mykey", "myvalue", 0).SetVal("OK") ``` ``` -------------------------------- ### Mock String Commands: Multiple Source: https://github.com/go-redis/redismock/blob/master/_autodocs/quick-reference.md Examples for mocking Redis commands that operate on multiple string keys, such as MGET, MSET, and MSETNX. ```go // Multiple mock.ExpectMGet(keys...).SetVal([]interface{}{val1, val2, ...}) ``` ```go mock.ExpectMSet(key1, val1, key2, val2, ...).SetVal("OK") ``` ```go mock.ExpectMSetNX(key1, val1, key2, val2, ...).SetVal(true) ``` -------------------------------- ### ExpectMSet Example Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-string-commands.md Mocks the MSET command, which sets multiple key-value pairs atomically. Use this when you need to simulate the MSET command's behavior. ```go mock.ExpectMSet("key1", "value1", "key2", "value2").SetVal("OK") err := db.MSet(ctx, "key1", "value1", "key2", "value2").Err() // err == nil ``` -------------------------------- ### ExpectMGet Go Example Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-string-commands.md Mocks the MGET command. This is useful for simulating the retrieval of multiple string values from different keys simultaneously and checking the returned slice. ```go mock.ExpectMGet("key1", "key2", "key3").SetVal([]interface{}{"value1", nil, "value3"}) values, _ := db.MGet(ctx, "key1", "key2", "key3").Result() // values == []interface{}{"value1", nil, "value3"} ``` -------------------------------- ### Set Return Values for Mocked Commands Source: https://github.com/go-redis/redismock/blob/master/_autodocs/README.md Examples of setting different return values for mocked commands, including success, error, and key not found scenarios. ```go mock.ExpectGet("key").SetVal("value") // Success case ``` ```go mock.ExpectGet("key").SetErr(errors.New("error")) // Error case ``` ```go mock.ExpectGet("key").RedisNil() // Key not found ``` -------------------------------- ### Mock Redis GET Command Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-string-commands.md Queue an expectation for the GET command. Use SetVal for a successful retrieval, RedisNil for a key not found scenario, or SetErr to simulate an error. ```go // Successful get mock.ExpectGet("username").SetVal("john_doe") result, _ := db.Get(ctx, "username").Result() // result == "john_doe" // Key not found mock.ExpectGet("missing").RedisNil() _, err := db.Get(ctx, "missing").Result() // err == redis.Nil // Error case mock.ExpectGet("locked").SetErr(errors.New("connection refused")) _, err := db.Get(ctx, "locked").Result() // err.Error() == "connection refused" ``` -------------------------------- ### ExpectTxPipeline Mock - Go Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-transaction-commands.md Mocks the MULTI command, which starts a transaction. Use this at the beginning of a transaction sequence. ```go func (m *mock) ExpectTxPipeline() ``` -------------------------------- ### ExpectConfigGet Mock Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-transaction-commands.md Queue an expectation for the CONFIG GET command. Use this to mock retrieving a specific configuration parameter. ```go mock.ExpectConfigGet("maxmemory").SetVal(map[string]string{"maxmemory": "1gb"}) result, _ := db.ConfigGet(ctx, "maxmemory").Result() // result == map[string]string{"maxmemory": "1gb"} ``` -------------------------------- ### Basic Redis GET Expectation Source: https://github.com/go-redis/redismock/blob/master/_autodocs/overview.md Set up an expectation for a GET command and retrieve its value. Always verify expectations were met after executing commands. ```go mock.ExpectGet("key").SetVal("value") result := db.Get(ctx, "key").Val() if err := mock.ExpectationsWereMet(); err != nil { t.Fatal(err) } ``` -------------------------------- ### ExpectIncrByFloat Go Example Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-string-commands.md Mocks the INCRBYFLOAT command. Use this to simulate incrementing a floating-point value associated with a key and verifying the outcome. ```go mock.ExpectIncrByFloat("temperature", 0.5).SetVal(98.6) newTemp, _ := db.IncrByFloat(ctx, "temperature", 0.5).Result() // newTemp == 98.6 ``` -------------------------------- ### Regex Pattern Examples for Redismock Source: https://github.com/go-redis/redismock/blob/master/_autodocs/advanced-usage.md Demonstrates various regular expression patterns for different data formats like UUIDs, ISO timestamps, and JSON objects. It also shows how to match keys with dynamic parts using regex. Remember that only string arguments are matched as regex; other types use exact matching. ```go // UUID pattern mock.Regexp().ExpectSet("uuid", `^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`, 0).SetVal("OK") // ISO timestamp mock.Regexp().ExpectSet("timestamp", `^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$`, 0).SetVal("OK") // JSON object (loose validation) mock.Regexp().ExpectSet("json_key", `^\{.*\}$`, 0).SetVal("OK") // Any positive integer mock.Regexp().ExpectGet(`counter:\d+`).SetVal("100") ``` -------------------------------- ### ExpectTxPipeline Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-transaction-commands.md Mocks the MULTI command, which starts a transaction. Use this at the beginning of a transaction sequence. ```APIDOC ## ExpectTxPipeline ### Description Mocks the MULTI command, which starts a transaction. Use this at the beginning of a transaction sequence. ### Signature ```go func (m *mock) ExpectTxPipeline() ``` ### Example ```go db, mock := redismock.NewClientMock() ctx := context.Background() // Queue transaction expectations mock.ExpectTxPipeline() mock.ExpectSet("key1", "value1", 0).SetVal("OK") mock.ExpectSet("key2", "value2", 0).SetVal("OK") mock.ExpectTxPipelineExec() // Execute transaction pipe := db.TxPipeline() pipe.Set(ctx, "key1", "value1", 0) pipe.Set(ctx, "key2", "value2", 0) pipe.Exec(ctx) if err := mock.ExpectationsWereMet(); err != nil { t.Fatal(err) } ``` ``` -------------------------------- ### Mock Redis Transaction Execution - Go Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-transaction-commands.md Sets up expectations for a transaction pipeline, including MULTI, a GET command, and EXEC, then executes the pipeline and retrieves results. ```go mock.ExpectTxPipeline() mock.ExpectGet("key1").SetVal("value1") mock.ExpectTxPipelineExec().SetVal([]interface{}{"value1"}) pipe := db.TxPipeline() pipe.Get(ctx, "key1") results, err := pipe.Exec(ctx) // results contains the responses from each command ``` -------------------------------- ### Mocking Redis Transaction Commands Source: https://github.com/go-redis/redismock/blob/master/_autodocs/quick-reference.md Examples for mocking Redis transaction commands, including pipelines and watch operations. ```go // Transaction pipeline mock.ExpectTxPipeline() mock.ExpectSet("key", "value", 0).SetVal("OK") mock.ExpectTxPipelineExec().SetVal([]interface{}{"OK"}) // Watch mock.ExpectWatch("key").SetVal("OK") ``` -------------------------------- ### Mock Redis Transaction Pipeline - Go Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-transaction-commands.md Queues expectations for a Redis transaction. This example demonstrates setting up expectations for MULTI, two SET commands, and EXEC, then executing the pipeline. ```go db, mock := redismock.NewClientMock() ctx := context.Background() // Queue transaction expectations mock.ExpectTxPipeline() mock.ExpectSet("key1", "value1", 0).SetVal("OK") mock.ExpectSet("key2", "value2", 0).SetVal("OK") mock.ExpectTxPipelineExec() // Execute transaction pipe := db.TxPipeline() pipe.Set(ctx, "key1", "value1", 0) pipe.Set(ctx, "key2", "value2", 0) pipe.Exec(ctx) if err := mock.ExpectationsWereMet(); err != nil { t.Fatal(err) } ``` -------------------------------- ### Simulate Redis Watch (Optimistic Locking) - Success Source: https://github.com/go-redis/redismock/blob/master/_autodocs/advanced-usage.md Simulate Redis WATCH command for optimistic locking. This example shows a successful WATCH operation where the key is not modified concurrently. Queue expectations for WATCH, GET, SET, and TxPipelineExec. ```go db, mock := redismock.NewClientMock() ctx := context.Background() // Watch returns success mock.ExpectWatch("mykey").SetVal("OK") mock.ExpectGet("mykey").SetVal("current_value") mock.ExpectSet("mykey", "new_value", 0).SetVal("OK") mock.ExpectTxPipelineExec().SetVal([]interface{}{"OK"}) // Use with Watch err := db.Watch(ctx, func(tx *redis.Tx) error { val, _ := tx.Get(ctx, "mykey").Result() if val == "current_value" { tx.Set(ctx, "mykey", "new_value", 0) } return nil }, "mykey") ``` -------------------------------- ### Basic Test Pattern Source: https://github.com/go-redis/redismock/blob/master/_autodocs/quick-reference.md Demonstrates a basic test case using redismock to mock a GET command and verify the result. ```APIDOC ## Testing Patterns ### Basic Test This example shows a basic test for a GET command. ```go func TestGet(t *testing.T) { db, mock := redismock.NewClientMock() ctx := context.Background() mock.ExpectGet("key").SetVal("value") result, _ := db.Get(ctx, "key").Result() if result != "value" { t.Errorf("expected value, got %s", result) } if err := mock.ExpectationsWereMet(); err != nil { t.Fatal(err) } } ``` ``` -------------------------------- ### Mocking Redis Stream Commands Source: https://github.com/go-redis/redismock/blob/master/_autodocs/quick-reference.md Examples for mocking various Redis stream commands including basic operations, reading, consumer groups, acknowledgments, claiming, trimming, and info retrieval. ```go // Basic mock.ExpectXAdd(args).SetVal(id) mock.ExpectXDel(stream, ids...).SetVal(count) mock.ExpectXLen(stream).SetVal(length) // Reading mock.ExpectXRange(stream, start, end).SetVal([]redis.XMessage{...}) mock.ExpectXRevRange(stream, start, end).SetVal([]redis.XMessage{...}) mock.ExpectXRead(args).SetVal([]redis.XStream{...}) mock.ExpectXReadStreams(streams...).SetVal([]redis.XStream{...}) // Consumer Groups mock.ExpectXGroupCreate(stream, group, start).SetVal("OK") mock.ExpectXGroupCreateMkStream(stream, group, start).SetVal("OK") mock.ExpectXGroupDestroy(stream, group).SetVal(1) mock.ExpectXGroupSetID(stream, group, id).SetVal("OK") mock.ExpectXGroupCreateConsumer(stream, group, consumer).SetVal(1) mock.ExpectXGroupDelConsumer(stream, group, consumer).SetVal(count) // Reading from Groups mock.ExpectXReadGroup(args).SetVal([]redis.XStream{...}) // Acknowledgment mock.ExpectXAck(stream, group, ids...).SetVal(count) mock.ExpectXPending(stream, group).SetVal(&redis.XPending{...}) // Claiming mock.ExpectXClaim(args).SetVal([]redis.XMessage{...}) mock.ExpectXAutoClaim(args).SetVal(&redis.XAutoClaimResult{...}) // Trimming mock.ExpectXTrimMaxLen(stream, maxLen).SetVal(count) mock.ExpectXTrimMinID(stream, minID).SetVal(count) // Info mock.ExpectXInfoStream(stream).SetVal(&redis.XInfoStream{...}) mock.ExpectXInfoGroups(stream).SetVal([]redis.XInfoGroup{...}) mock.ExpectXInfoConsumers(stream, group).SetVal([]redis.XInfoConsumer{...}) ``` -------------------------------- ### Mock String Commands: Range/Len Source: https://github.com/go-redis/redismock/blob/master/_autodocs/quick-reference.md Examples for mocking Redis string commands related to ranges and lengths, such as GETRANGE, SETRANGE, and STRLEN. ```go // Range/Len mock.ExpectGetRange(key, start, end).SetVal(substring) ``` ```go mock.ExpectSetRange(key, offset, value).SetVal(newLength) ``` ```go mock.ExpectStrLen(key).SetVal(length) ``` -------------------------------- ### Mock Config Commands Source: https://github.com/go-redis/redismock/blob/master/_autodocs/quick-reference.md Mocks for Redis Config commands including Get, Set, ResetStat, and Rewrite. ```go mock.ExpectConfigGet(parameter).SetVal(map[string]string{...}) ``` ```go mock.ExpectConfigSet(parameter, value).SetVal("OK") ``` ```go mock.ExpectConfigResetStat().SetVal("OK") ``` ```go mock.ExpectConfigRewrite().SetVal("OK") ``` -------------------------------- ### ExpectIncrBy Go Example Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-string-commands.md Mocks the INCRBY command. Use this when you need to simulate incrementing an integer value associated with a key and then asserting the expected result. ```go mock.ExpectIncrBy("score", 10).SetVal(110) newScore, _ := db.IncrBy(ctx, "score", 10).Result() // newScore == 110 ``` -------------------------------- ### Mock String Commands: Numeric Source: https://github.com/go-redis/redismock/blob/master/_autodocs/quick-reference.md Examples for mocking Redis numeric string commands like APPEND, INCR, DECR, and their variants. ```go // Numeric mock.ExpectAppend(key, value).SetVal(newLength) ``` ```go mock.ExpectIncr(key).SetVal(newValue) ``` ```go mock.ExpectIncrBy(key, increment).SetVal(newValue) ``` ```go mock.ExpectIncrByFloat(key, increment).SetVal(newValue) ``` ```go mock.ExpectDecr(key).SetVal(newValue) ``` ```go mock.ExpectDecrBy(key, decrement).SetVal(newValue) ``` -------------------------------- ### Mock Hash Get Commands Source: https://github.com/go-redis/redismock/blob/master/_autodocs/quick-reference.md Mock commands for retrieving data from Redis hashes, including single fields (HGET), all fields (HGETALL), and multiple fields (HMGET). ```go mock.ExpectHGet(key, field).SetVal(value) mock.ExpectHGetAll(key).SetVal(map[string]string{...}) mock.ExpectHMGet(key, fields...).SetVal([]interface{}{...}) ``` -------------------------------- ### Mock Hash Length and Key/Value Retrieval Commands Source: https://github.com/go-redis/redismock/blob/master/_autodocs/quick-reference.md Mock commands to get the number of fields in a hash (HLEN), retrieve all field names (HKEYS), and retrieve all field values (HVALS). ```go mock.ExpectHLen(key).SetVal(count) mock.ExpectHKeys(key).SetVal([]string{...}) mock.ExpectHVals(key).SetVal([]string{...}) ``` -------------------------------- ### Mock Redis EXPIRE Command (Key Exists) Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-key-commands.md Mocks the EXPIRE command to set a key's time-to-live. This example demonstrates setting the expectation for when the key exists and the expiration is successfully set. ```go mock.ExpectExpire("mykey", 60*time.Second).SetVal(true) ok, _ := db.Expire(ctx, "mykey", 60*time.Second).Result() // ok == true ``` -------------------------------- ### Mock Redis EXPIRE Command (Key Missing) Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-key-commands.md Mocks the EXPIRE command to set a key's time-to-live. This example demonstrates setting the expectation for when the key does not exist and the expiration is not set. ```go // Key doesn't exist mock.ExpectExpire("missing", 60*time.Second).SetVal(false) ok, _ := db.Expire(ctx, "missing", 60*time.Second).Result() // ok == false ``` -------------------------------- ### Creating Mocks Source: https://github.com/go-redis/redismock/blob/master/_autodocs/quick-reference.md Demonstrates how to create mock clients for both single Redis instances and Redis clusters. ```APIDOC ## Creating Mocks ### Description This section shows how to initialize mock Redis clients for testing purposes. You can create mocks for a single Redis instance or a Redis cluster. ### Methods - **NewClientMock()** - Initializes a mock client for a single Redis instance. - Returns a `redis.Client` and a `redismock.ClientMock`. - **NewClusterMock()** - Initializes a mock client for a Redis cluster. - Returns a `redis.Cluster` and a `redismock.ClusterMock`. ``` -------------------------------- ### ExpectXGroupSetID Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-stream-commands.md Mocks the XGROUP SETID command to update a consumer group's starting ID. ```APIDOC ## ExpectXGroupSetID ### Description Queue expectation for XGROUP SETID command. Mocks XGROUP SETID, which updates the group's ID position. ### Method ```go func (m *mock) ExpectXGroupSetID(stream, group, start string) *ExpectedStatus ``` ### Parameters #### Path Parameters - **stream** (string) - Required - Stream key - **group** (string) - Required - Consumer group name - **start** (string) - Required - New starting ID ### Return Type `*ExpectedStatus` ### Example ```go mock.ExpectXGroupSetID("mystream", "mygroup", "1234567890-0").SetVal("OK") err := db.XGroupSetID(ctx, "mystream", "mygroup", "1234567890-0").Err() ``` ``` -------------------------------- ### Create Mock Redis Clients Source: https://github.com/go-redis/redismock/blob/master/_autodocs/quick-reference.md Instantiate mock clients for both single Redis instances and Redis clusters. ```go // Redis single instance db, mock := redismock.NewClientMock() ``` ```go // Redis cluster clusterDb, clusterMock := redismock.NewClusterMock() ``` -------------------------------- ### Mock Server Commands Source: https://github.com/go-redis/redismock/blob/master/_autodocs/quick-reference.md Mocks for server administration commands such as INFO, TIME, DBSize, FLUSHDB, FLUSHALL, SAVE, BGsave, and LASTsave. ```go mock.ExpectInfo(section).SetVal(infoString) ``` ```go mock.ExpectTime().SetVal([]time.Time{...}) ``` ```go mock.ExpectDBSize().SetVal(count) ``` ```go mock.ExpectFlushDB().SetVal("OK") ``` ```go mock.ExpectFlushAll().SetVal("OK") ``` ```go mock.ExpectSave().SetVal("OK") ``` ```go mock.ExpectBgSave().SetVal(status) ``` ```go mock.ExpectLastSave().SetVal(unixTimestamp) ``` -------------------------------- ### Mock Key Dump and Restore Commands Source: https://github.com/go-redis/redismock/blob/master/_autodocs/quick-reference.md Simulate the DUMP and RESTORE commands for serializing and deserializing Redis keys. ```go mock.ExpectDump(key).SetVal(serialized) mock.ExpectRestore(key, ttl, value).SetVal("OK") ``` -------------------------------- ### ExpectConfigGet Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-transaction-commands.md Queue expectation for the CONFIG GET command. This function mocks the behavior of retrieving configuration parameters from Redis. ```APIDOC ## ExpectConfigGet ### Description Queue expectation for CONFIG GET command. ### Method Signature ```go func (m *mock) ExpectConfigGet(parameter string) *ExpectedMapStringString ``` ### Parameters #### Path Parameters - **parameter** (string) - Required - Config parameter name or pattern ### Return Type `*ExpectedMapStringString` ### Example ```go mock.ExpectConfigGet("maxmemory").SetVal(map[string]string{"maxmemory": "1gb"}) result, _ := db.ConfigGet(ctx, "maxmemory").Result() // result == map[string]string{"maxmemory": "1gb"} ``` ``` -------------------------------- ### Handle Missing Mock Configuration Source: https://github.com/go-redis/redismock/blob/master/_autodocs/expected-types.md Illustrates the error returned when a mock command is not configured with SetVal or SetErr. ```go mock.ExpectGet("key") // Missing SetVal or SetErr result, err := db.Get(ctx, "key").Result() // err will be: "cmd(get key), return value is required" ``` -------------------------------- ### Transaction, Connection, Database, Server, and Config Commands Source: https://github.com/go-redis/redismock/blob/master/_autodocs/README.md Mocking methods for transaction, connection, database, server, and configuration commands. ```APIDOC ## Transaction Commands ### ExpectTxPipeline Expects a transaction pipeline to be started. ### ExpectTxPipelineExec Expects the execution of a transaction pipeline. ### ExpectWatch Expects a WATCH command to monitor keys. ## Connection Commands ### ExpectPing Expects a PING command. ### ExpectEcho Expects an ECHO command. ### ExpectQuit Expects a QUIT command. ### ExpectClientID Expects a CLIENT ID command. ## Database Commands ### ExpectDBSize Expects a DBSIZE command. ### ExpectFlushDB Expects a FLUSHDB command. ### ExpectFlushAll Expects a FLUSHALL command. ## Server Commands ### ExpectInfo Expects an INFO command. ### ExpectTime Expects a TIME command. ### ExpectSave Expects a SAVE command. ### ExpectBgSave Expects a BG SAVE command. ## Config Commands ### ExpectConfigGet Expects a CONFIG GET command. ### ExpectConfigSet Expects a CONFIG SET command. ### ExpectConfigResetStat Expects a CONFIG RESETSTAT command. ``` -------------------------------- ### Expect ClientList Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-transaction-commands.md Mocks the CLIENT LIST command, which returns information about all connected clients. Use this to simulate the output of the CLIENT LIST command. ```go clientList := "id=1 addr=127.0.0.1:1234 fd=8 name= age=0" mock.ExpectClientList().SetVal(clientList) result, _ := db.ClientList(ctx).Result() ``` -------------------------------- ### Initialize RedisCluster Mock Source: https://github.com/go-redis/redismock/blob/master/README.md Quickly initialize a mock for RedisCluster using `redismock.NewClusterMock()`. ```go clusterClient, clusterMock := redismock.NewClusterMock() ``` -------------------------------- ### Mock XGROUP SETID Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-stream-commands.md Mocks the XGROUP SETID command. Use this to simulate updating the position of a consumer group to a new starting ID. ```go mock.ExpectXGroupSetID("mystream", "mygroup", "1234567890-0").SetVal("OK") err := db.XGroupSetID(ctx, "mystream", "mygroup", "1234567890-0").Err() ``` -------------------------------- ### Create Redis Client Mock Source: https://github.com/go-redis/redismock/blob/master/_autodocs/overview.md Instantiate a mock client for single Redis instances or a cluster. Use these mocks in your tests to simulate Redis behavior. ```go // Client mock db, mock := redismock.NewClientMock() ``` ```go // Cluster mock clusterDb, clusterMock := redismock.NewClusterMock() ``` -------------------------------- ### ExpectGetRange Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-string-commands.md Mocks the GETRANGE command, which returns a substring of the value stored at a key. It takes the key, start index, and end index as parameters. ```APIDOC ## ExpectGetRange Queue expectation for GETRANGE command. ```go func (m *mock) ExpectGetRange(key string, start, end int64) *ExpectedString ``` ### Parameters | Parameter | Type | Description | |-----------|------|-------------| | key | `string` | Key to read from | | start | `int64` | Start index (inclusive) | | end | `int64` | End index (inclusive) | ### Return Type `*ExpectedString` ### Description Mocks the GETRANGE command, which returns a substring of the value stored at a key. ### Example ```go mock.ExpectGetRange("mystring", 0, 4).SetVal("Hello") substring, _ := db.GetRange(ctx, "mystring", 0, 4).Result() // substring == "Hello" ``` ``` -------------------------------- ### Mock Connection Commands Source: https://github.com/go-redis/redismock/blob/master/_autodocs/quick-reference.md Use these mocks for connection-related commands like PING, ECHO, QUIT, and CLIENT GETNAME. ```go mock.ExpectPing().SetVal("PONG") ``` ```go mock.ExpectEcho(message).SetVal(message) ``` ```go mock.ExpectQuit().SetVal("OK") ``` ```go mock.ExpectClientGetName().SetVal(name) ``` -------------------------------- ### Mock XLEN Command Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-stream-commands.md Mocks the XLEN command to get the number of entries in a stream. Use this to simulate retrieving the length of a stream and verify the count. ```go mock.ExpectXLen("mystream").SetVal(3) length, _ := db.XLen(ctx, "mystream").Result() // length == 3 ``` -------------------------------- ### Mock Key Rename and Copy Commands Source: https://github.com/go-redis/redismock/blob/master/_autodocs/quick-reference.md Mock commands for renaming keys (RENAME, RENAME NX) and copying keys between databases. ```go mock.ExpectRename(oldKey, newKey).SetVal("OK") mock.ExpectRenameNX(oldKey, newKey).SetVal(true) mock.ExpectCopy(source, dest, db, replace).SetVal(1) ``` -------------------------------- ### Mock Pub/Sub Commands Source: https://github.com/go-redis/redismock/blob/master/_autodocs/quick-reference.md Mocks for Publish/Subscribe commands: PUBLISH, PUBSUB CHANNELS, and PUBSUB NUMSUB. ```go mock.ExpectPublish(channel, message).SetVal(subscribers) ``` ```go mock.ExpectPubSubChannels(pattern).SetVal([]string{...}) ``` ```go mock.ExpectPubSubNumSub(channels...).SetVal(map[string]int64{...}) ``` -------------------------------- ### Mock XGROUP CREATE Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-stream-commands.md Mocks the XGROUP CREATE command. Use this to simulate creating a new consumer group for a stream. The stream is not created if it doesn't exist. ```go mock.ExpectXGroupCreate("mystream", "mygroup", "$").SetVal("OK") err := db.XGroupCreate(ctx, "mystream", "mygroup", "$").Err() // err == nil ``` -------------------------------- ### ExpectZUnionStore Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-sorted-set-commands.md Queue expectation for ZUNIONSTORE command. This mock setup is for ZUNIONSTORE, specifying the destination key, store configuration, and the expected integer count of members. ```APIDOC ## ExpectZUnionStore ### Description Queue expectation for ZUNIONSTORE command. ### Method Signature ```go func (m *mock) ExpectZUnionStore(dest string, store *redis.ZStore) *ExpectedInt ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **dest** (`string`) - Required - Destination key - **store** (`*redis.ZStore`) - Required - Store configuration ### Return Type - `*ExpectedInt` ### Example ```go store := &redis.ZStore{Keys: []string{"zset1", "zset2"}} mock.ExpectZUnionStore("out", store).SetVal(3) count, _ := db.ZUnionStore(ctx, "out", store).Result() ``` ``` -------------------------------- ### ExpectGet Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-string-commands.md Mocks the Redis GET command, which retrieves the string value of a key. You can set the expected value, simulate a key not found (RedisNil), or return an error. ```APIDOC ## ExpectGet Queue expectation for GET command. ```go func (m *mock) ExpectGet(key string) *ExpectedString ``` ### Parameters | Parameter | Type | Description | |-----------|------|-------------| | key | `string` | Key to retrieve | ### Return Type `*ExpectedString` ### Description Mocks the GET command, which retrieves the string value of a key. ### Example ```go // Successful get mock.ExpectGet("username").SetVal("john_doe") result, _ := db.Get(ctx, "username").Result() // result == "john_doe" // Key not found mock.ExpectGet("missing").RedisNil() _, err := db.Get(ctx, "missing").Result() // err == redis.Nil // Error case mock.ExpectGet("locked").SetErr(errors.New("connection refused")) _, err := db.Get(ctx, "locked").Result() // err.Error() == "connection refused" ``` ``` -------------------------------- ### Test Error Handling with Mocked Connection Timeout Source: https://github.com/go-redis/redismock/blob/master/_autodocs/README.md Simulates a connection timeout error for a Get operation. Use this to test retry or fallback logic in your application. ```go mock.ExpectGet("key").SetErr(errors.New("connection timeout")) // Test retry/fallback logic ``` -------------------------------- ### Mock Redis Pub/Sub Commands Source: https://github.com/go-redis/redismock/blob/master/_autodocs/advanced-usage.md While full Pub/Sub subscriptions are not supported, you can mock PUBLISH, PUBSUB CHANNELS, and PUBSUB NUMSUB commands. This allows testing the logic that interacts with these specific commands. ```go db, mock := redismock.NewClientMock() ctx := context.Background() // Mock PUBLISH (returns number of subscribers) mock.ExpectPublish("mychannel", "message").SetVal(5) subs, _ := db.Publish(ctx, "mychannel", "message").Result() // subs == 5 // Mock PUBSUB CHANNELS mock.ExpectPubSubChannels("pattern").SetVal([]string{"ch1", "ch2"}) channels, _ := db.PubSubChannels(ctx, "pattern").Result() // Mock PUBSUB NUMSUB mock.ExpectPubSubNumSub("ch1", "ch2").SetVal(map[string]int64{ "ch1": 5, "ch2": 3, }) result, _ := db.PubSubNumSub(ctx, "ch1", "ch2").Result() ``` -------------------------------- ### Regex Matching Pattern Source: https://github.com/go-redis/redismock/blob/master/_autodocs/quick-reference.md Illustrates how to use regular expressions to match expected values for commands like SET. ```APIDOC ### Regex Matching Use regular expressions for flexible matching. ```go mock.Regexp().ExpectSet("key", `^\d{5}$`, 0).SetVal("OK") ``` ``` -------------------------------- ### Mock XPending Command (Summary) Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-stream-commands.md Queue an expectation for the XPENDING command to mock the summary of pending messages. Use SetVal to provide a redis.XPending struct with summary details. ```go pending := &redis.XPending{ Count: 2, Lower: "1234567890-0", Higher: "1234567891-0", Consumers: map[string]int64{"consumer1": 2}, } mock.ExpectXPending("mystream", "mygroup").SetVal(pending) result, _ := db.XPending(ctx, "mystream", "mygroup").Result() ``` -------------------------------- ### Expect GetRange Command Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-string-commands.md Mocks the GETRANGE command. Use this when you need to simulate retrieving a substring of a value stored at a specific key. The start and end indices are inclusive. ```go mock.ExpectGetRange("mystring", 0, 4).SetVal("Hello") substring, _ := db.GetRange(ctx, "mystring", 0, 4).Result() // substring == "Hello" ``` -------------------------------- ### Mock XGROUP CREATE MKSTREAM Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-stream-commands.md Mocks the XGROUP CREATE MKSTREAM command. This is similar to XGROUP CREATE but ensures the stream is created if it does not already exist. ```go mock.ExpectXGroupCreateMkStream("newstream", "newgroup", "0").SetVal("OK") err := db.XGroupCreateMkStream(ctx, "newstream", "newgroup", "0").Err() ``` -------------------------------- ### Mock XPending Command (Extended Details) Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-stream-commands.md Queue an expectation for the XPENDING command with extended arguments to mock detailed pending message information. Use SetVal to provide a slice of redis.XPendingExtData. ```go args := &redis.XPendingExtArgs{ Stream: "mystream", Group: "mygroup", Start: "-", End: "+", Count: 10, } details := []redis.XPendingExtData{ {ID: "1234567890-0", Consumer: "consumer1", Idle: 100000, RetryCount: 1}, } mock.ExpectXPendingExt(args).SetVal(details) result, _ := db.XPendingExt(ctx, args).Result() ``` -------------------------------- ### CustomMatch Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/base-mock-interface.md Registers a custom matching function for subsequent Expect* calls. Returns a cloned mock instance with the custom matcher installed, enabling complex command matching logic. ```APIDOC ## CustomMatch ### Description Register a custom matching function for subsequent Expect* calls. ### Method ```go func CustomMatch(fn CustomMatch) *mock ``` ### Parameters #### Path Parameters - **fn** (CustomMatch) - Required - Custom matching function: `func(expected, actual []interface{}) error` ### Return Type Returns a cloned mock instance with the custom matcher installed. ### Detailed Description `CustomMatch()` enables complex command matching logic beyond regex patterns. It returns a new mock instance with the custom matcher active. The function receives both expected and actual command arguments as slices and should return an error if they don't match. The expected arguments are those from the Expect* call; the actual arguments are from the executed command. ### Example ```go db, mock := redismock.NewClientMock() ctx := context.Background() // Custom matcher that checks JSON structure mock.CustomMatch(func(expected, actual []interface{}) error { if len(actual) < 2 { return fmt.Errorf("expected at least 2 args") } // Verify first arg (command) matches if expected[0] != actual[0] { return fmt.Errorf("command mismatch") } // Parse JSON from actual[2] and validate it var jsonData map[string]interface{} if err := json.Unmarshal([]byte(actual[2].(string)), &jsonData); err != nil { return fmt.Errorf("invalid JSON: %v", err) } // Custom validation if _, ok := jsonData["id"]; !ok { return fmt.Errorf("missing 'id' field") } return nil }).ExpectSet("user:data", "ignored", 0).SetVal("OK") // This will pass custom validation db.Set(ctx, "user:data", `{"id":123,"name":"test"}`, 0) ``` ``` -------------------------------- ### Chain Mock Methods Source: https://github.com/go-redis/redismock/blob/master/_autodocs/expected-types.md Demonstrates chaining multiple mock methods for setting values and expectations. ```go mock.ExpectGet("key").SetVal("value") // Or chain with other mock methods: mock.ExpectGet("key1").SetVal("value1") mock.ExpectSet("key2", "value2", 0).SetVal("OK") mock.ExpectDel("key1").SetVal(1) if err := mock.ExpectationsWereMet(); err != nil { t.Fatal(err) } ``` -------------------------------- ### Mock Redis PExpireTime Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-key-commands.md Mocks the PEXPIRETIME command. Use this to set an expected absolute Unix timestamp in milliseconds for a given key. The example shows setting the value and then retrieving it. ```go mock.ExpectPExpireTime("mykey").SetVal(1704067200000 * time.Millisecond) ttl, _ := db.PExpireTime(ctx, "mykey").Result() ``` -------------------------------- ### Mock Key Scanning Commands Source: https://github.com/go-redis/redismock/blob/master/_autodocs/quick-reference.md Mock commands for scanning keys using patterns (KEYS, SCAN). ```go mock.ExpectKeys(pattern).SetVal([]string{...}) mock.ExpectScan(cursor, pattern, count).SetVal(keys, nextCursor) ``` -------------------------------- ### Mock Redis MIGRATE Command Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-key-commands.md Mocks the MIGRATE command for atomically transferring a key between Redis instances. Use this when testing distributed Redis setups or key migration logic. ```go mock.ExpectMigrate("127.0.0.1", "6380", "mykey", 0, 5*time.Second).SetVal("OK") err := db.Migrate(ctx, "127.0.0.1", "6380", "mykey", 0, 5*time.Second).Err() // err == nil ``` -------------------------------- ### Mock SETNX Command Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-string-commands.md Mocks the SETNX command, which sets a key only if it doesn't exist. Use this to test scenarios where a key is set only if it's new. ```go mock.ExpectSetNX("newkey", "value", 0).SetVal(true) ok, _ := db.SetNX(ctx, "newkey", "value", 0).Result() // ok == true // Key already exists mock.ExpectSetNX("existing", "value", 0).SetVal(false) ok, _ := db.SetNX(ctx, "existing", "value", 0).Result() // ok == false ``` -------------------------------- ### Simulate Redis Transaction (MULTI/EXEC) Source: https://github.com/go-redis/redismock/blob/master/_autodocs/advanced-usage.md Simulate a Redis transaction using MULTI/EXEC commands. Queue transaction commands using ExpectTxPipeline and ExpectTxPipelineExec, then execute them using TxPipeline and Exec. ```go db, mock := redismock.NewClientMock() ctx := context.Background() // Queue transaction commands mock.ExpectTxPipeline() // MULTI mock.ExpectSet("key1", "value1", 0).SetVal("OK") mock.ExpectIncr("counter").SetVal(1) mock.ExpectGet("key1").SetVal("value1") mock.ExpectTxPipelineExec().SetVal([]interface{}{"OK", int64(1), "value1"}) // Execute transaction pipe := db.TxPipeline() pipe.Set(ctx, "key1", "value1", 0) pipe.Incr(ctx, "counter") pipe.Get(ctx, "key1") results, err := pipe.Exec(ctx) // results[0] = "OK" // results[1] = 1 // results[2] = "value1" ``` -------------------------------- ### Mocking DBSize Command Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-transaction-commands.md Queue expectation for the DBSIZE command, which returns the number of keys in the current database. Use this when you need to mock the retrieval of the database size. ```go mock.ExpectDBSize().SetVal(1000) size, _ := db.DBSize(ctx).Result() // size == 1000 ``` -------------------------------- ### Simulate Redis Watch (Optimistic Locking) - Error Source: https://github.com/go-redis/redismock/blob/master/_autodocs/advanced-usage.md Simulate a failed Redis WATCH operation due to concurrent modification. This example sets an error for the WATCH expectation, causing the transaction block to not execute. ```go db, mock := redismock.NewClientMock() ctx := context.Background() // Watch with error (concurrent modification) mock.ExpectWatch("mykey").SetErr(errors.New("WATCHED_KEY_CHANGED")) err = db.Watch(ctx, func(tx *redis.Tx) error { // This won't execute if Watch fails return nil }, "mykey") // err will contain the watch error ``` -------------------------------- ### Mock Redis SORT Command Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-key-commands.md Mocks the SORT command for lists, sets, or sorted sets. Use this to simulate sorting elements based on provided parameters like BY, GET, LIMIT, and order (ASC/DESC, ALPHA). ```go sort := &redis.Sort{Limit: redis.Limit{Offset: 0, Count: 10}} mock.ExpectSort("mylist", sort).SetVal([]string{"a", "b", "c"}) result, _ := db.Sort(ctx, "mylist", sort).Result() // result == []string{"a", "b", "c"} ``` -------------------------------- ### JSON Validation with Custom Matcher in Redismock Source: https://github.com/go-redis/redismock/blob/master/_autodocs/advanced-usage.md Use a custom matcher function with `.CustomMatch()` to validate JSON payloads sent to Redis. This example demonstrates unmarshalling the value and checking for the presence of specific fields within the JSON structure. ```go jsonMatcher := func(expected, actual []interface{}) error { if len(actual) < 3 { return fmt.Errorf("invalid args") } jsonStr := actual[2].(string) var data map[string]interface{} if err := json.Unmarshal([]byte(jsonStr), &data); err != nil { return fmt.Errorf("invalid JSON: %v", err) } // Validate specific fields if _, ok := data["id"]; !ok { return fmt.Errorf("missing 'id' field") } if _, ok := data["timestamp"]; !ok { return fmt.Errorf("missing 'timestamp' field") } return nil } mock.CustomMatch(jsonMatcher).ExpectSet("user", "ignored", 0).SetVal("OK") db.Set(ctx, "user", `{"id": 123, "timestamp": "2024-01-01"}`, 0) ``` -------------------------------- ### Manage Mock Expectations Source: https://github.com/go-redis/redismock/blob/master/_autodocs/quick-reference.md Control and verify mock expectations, including resetting, enabling regex/custom matching, and checking for unmet expectations. Use `MatchExpectationsInOrder(false)` to allow commands in any order. ```go // Reset all expectations mock.ClearExpect() ``` ```go // Enable regex matching for next Expect call mock.Regexp().ExpectGet("key") ``` ```go // Enable custom matching for next Expect call mock.CustomMatch(func(exp, act []interface{}) error { // Custom logic return nil }).ExpectSet("key", "value", 0) ``` ```go // Verify all expectations were met if err := mock.ExpectationsWereMet(); err != nil { t.Fatal(err) } ``` ```go // Check for unexpected calls hasUnexpected, cmds := mock.UnexpectedCallsWereMade() ``` ```go // Allow commands in any order (not strict sequential) mock.MatchExpectationsInOrder(false) ``` -------------------------------- ### Mock XREAD Command with Args Source: https://github.com/go-redis/redismock/blob/master/_autodocs/api-reference/expect-stream-commands.md Queue an expectation for the XREAD command using XReadArgs. This allows mocking reads from one or multiple streams with options for count and block time. The Streams field in XReadArgs specifies the streams and their starting IDs. ```go args := &redis.XReadArgs{ Streams: []string{"mystream", "0"}, Count: 2, } result := []redis.XStream{ {Stream: "mystream", Messages: []redis.XMessage{ {ID: "1234567890-0", Values: map[string]interface{}{"field": "value1"}}, }}, } mock.ExpectXRead(args).SetVal(result) streams, _ := db.XRead(ctx, args).Result() ```