Redis client Mock Provide mock test for redis query

Related tags

mock go-redis redis-mock
Overview

Redis client Mock Build Status

Provide mock test for redis query, Compatible with github.com/go-redis/redis/v8

Install

Confirm that you are using redis.Client the version is github.com/go-redis/redis/v8

go get github.com/go-redis/redismock/v8

Example

More examples: https://github.com/go-redis/redismock/blob/v8/example/example.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)
	}
}
Issues
  • Possible to use as in-memory mock storage

    Possible to use as in-memory mock storage

    I notice this package is a great substitution for *redis.Client. However all calls to it must be prepared with mock.ExpectGet(..).SetVal(..).

    I am hoping to use this as a mock redis implementation in my main application code (where I use redis as a "cache") that just accepts the commands, and ignores them.

    So I'm almost looking for an in-memory implementation of *redis.Client (because I don't want to run redis-server to have my app run locally). It does not have to actually store/serve the data.

    Does this exist –or is there a way I can use redismock in this way, say something like mock.ExpectAnything().

    opened by ahmetb 5
  • Checking a hash set created with map is failing

    Checking a hash set created with map is failing

    In one of our applications, we are using HSet to create a Redis hash map. We've been using the map syntax:

    cmd, err := redisCli.HSet("key", map[string]interface{}{"1": "one", "2": "two"})
    

    The request is later unpacked into a slice of arguments (which is native for Redis). But as it was passed as a map, the order every time is different. Then in the mock.match function we iterate over the list of expected args and comparing it to the list of cmd args. This function accesses the elements by index, so chances of getting a match decrease with each new item added into the hash :smile:

    Workaround: Use the slice syntax instead:

    cmd, err := redisCli.HSet("key", []string{"1", "one", "2", "two"})
    

    It is more confusing but works :slightly_smiling_face:

    I'm not really sure what could be a good approach to handle this :confused: Possible solutions on my mind:

    • Give the option to ignore an order of the argument pairs in tests. The same way as it is done with the mock.MatchExpectationsInOrder(true) option
    • Add a check in the match function to ignore an order of the pairs if the called operation supports map syntax
    opened by 8tomat8 2
  • Problems On `CustomMatch` and `Regexp`

    Problems On `CustomMatch` and `Regexp`

    Sorry to take your precious time to help me.

    1. problem codes
    import "github.com/go-redis/redis/v8" //@v8.11.0
    import "github.com/go-redis/redismock/v8"  // @8.0.6
    // ...
    db, mock := redismock.NewClientMock()
    mock.Regexp().ExpectHSet("somekey", `.*`).SetErr(nil)
    mock.CustomMatch(func(expected, actual []interface{}) error {return nil}).ExpectHSet("somekey", "").SetErr(nil)
    
    1. What I expect I want the two mock can fulfill all Hsets. No matter what I give them, they should return normally nil.

    2. What I got

    parameters do not match expectation '[somekey .*]', but call to cmd '[somekey field1 value1 field2 value2]'

    1. comment

    I searched the Internet but found nothing about this two functions, I am not sure whether it is valid to use dot and star in the regexp. So help me please! Feel Free to comment.

    opened by Littledarren 2
  • Configure Renovate

    Configure Renovate

    WhiteSource Renovate

    Welcome to Renovate! This is an onboarding PR to help you understand and configure settings before regular Pull Requests begin.

    :vertical_traffic_light: To activate Renovate, merge this Pull Request. To disable Renovate, simply close this Pull Request unmerged.


    Detected Package Files

    • go.mod (gomod)

    Configuration Summary

    Based on the default config's presets, Renovate will:

    • Start dependency updates only once this onboarding PR is merged
    • Separate major versions of dependencies into individual branches/PRs
    • Do not separate patch and minor upgrades into separate PRs for the same dependency
    • Upgrade to unstable versions only if the existing version is unstable
    • Raise PRs immediately (after branch is created)
    • If semantic commits detected, use semantic commit type fix for dependencies and chore for all others
    • Keep existing branches updated even when not scheduled
    • Disable automerging feature - wait for humans to merge all PRs
    • Ignore node_modules, bower_components, vendor and various test/tests directories
    • Autodetect whether to pin dependencies or maintain ranges
    • Rate limit PR creation to a maximum of two per hour
    • Limit to maximum 20 open PRs at any time
    • Group known monorepo packages together
    • Use curated list of recommended non-monorepo package groupings
    • Ignore wrongly tagged actions/setup-node v2 releases
    • Ignore spring cloud 1.x releases

    :abcd: Would you like to change the way Renovate is upgrading your dependencies? Simply edit the renovate.json in this branch with your custom config and the list of Pull Requests in the "What to Expect" section below will be updated the next time Renovate runs.


    What to Expect

    It looks like your repository dependencies are already up-to-date and no Pull Requests will be necessary right away.


    :question: Got questions? Check out Renovate's Docs, particularly the Getting Started section. If you need any further assistance then you can also request help here.


    This PR has been generated by WhiteSource Renovate. View repository job log here.

    opened by renovate[bot] 1
  • Support for TxPipeline

    Support for TxPipeline

    What is the best way of mocking client.TxPipeline? When expectations are define for the following: HSet, ZAddNX

    pipe := client.TxPipeline()
    pipe.HSet
    pipe.ZAddNX
    pipe.Exec()
    

    the following error is returned: call to cmd '[multi]' was not expected

    opened by zedar 1
  • Do not expose mutex methods

    Do not expose mutex methods

    Screen Shot 2020-12-18 at 11 07 36 am

    expectedBase embeds a mutex and its methods are exposed. Confusing UX :)

    opened by ash2k 1
  • Can't be displayed on pkg.go.dev

    Can't be displayed on pkg.go.dev

    Hiya, I just wanted to add a feature request to be able to find this library on pkg.go.dev, and maybe a link to it in README. Currently it is not displayed due to licence restrictions. Thank you.

    opened by AtakanColak 1
  • Fix #5: add support for WATCH

    Fix #5: add support for WATCH

    This adds support for client.Watch().

    opened by bstpierre 1
  • gomod不支持v8版本

    gomod不支持v8版本

    require github.com/go-redis/redismoc: version "v8.0.6" invalid: should be v0 or v1, not v8 go get可以获取,但是go mod无法获取

    opened by Allen-ZhangM 1
  • 过期时间如何进行通配

    过期时间如何进行通配

    比如ExpectSet这种,一定要设置一个过期时间,但是代码中有些过期时间是随机的导致匹配不上。 报错如下 args not DeepEqual, expectation: '0', but gave: '48308' expire是否可以像value一样用regexp通配? 或者用什么方式不用DeepEqual?

    opened by Allen-ZhangM 1
  • Why mock with no expectations not failing

    Why mock with no expectations not failing

    This package looks awesome, but i would have expected these tests to fail:

    package frontpage_test
    
    import (
    	"context"
    	"testing"
    
    	"github.com/go-redis/redismock/v8"
    	. "github.com/onsi/ginkgo"
    
    	. "github.com/onsi/gomega"
    )
    
    func TestFrontpage(t *testing.T) {
    	RegisterFailHandler(Fail)
    	RunSpecs(t, "Frontpage Suite")
    }
    
    var _ = FDescribe("Reader", func() {
    	It("should fail", func() {
    		redisCli, redisMock := redismock.NewClientMock()
                     // No expectations set, so this should fail right?
    		_ = redisCli.Set(context.TODO(), "key", "value", 0).Err()
    
    		Expect(redisMock.ExpectationsWereMet()).To(BeNil())
    	})
    
    	It("should fail", func() {
    		redisCli, redisMock := redismock.NewClientMock()
                     // just setting an expectation that is fullfilled, to see if that helps...
    		redisMock.ExpectPing()
    		redisCli.Ping(context.TODO())
    		_ = redisCli.Set(context.TODO(), "key", "value", 0).Err()
    
    		Expect(redisMock.ExpectationsWereMet()).To(BeNil())
    	})
    })
    
    

    Im calling a Set that is not expected, why is that not failing?

    opened by henrikrudstrom 4
Type-safe Redis client for Golang

Redis client for Golang ❤️ Uptrace.dev - distributed traces, logs, and errors in one place Join Discord to ask questions. Documentation Reference Exam

null 12k Jul 20, 2021
Go Redis Client

xredis Built on top of github.com/garyburd/redigo with the idea to simplify creating a Redis client, provide type safe calls and encapsulate the low l

Raed Shomali 15 Jun 2, 2021
Distributed WebSocket broker

dSock dSock is a distributed WebSocket broker (in Go, using Redis). Clients can authenticate & connect, and you can send text/binary message as an API

Charles Crete 200 Jul 22, 2021
Redis client Mock Provide mock test for redis query

Redis client Mock Provide mock test for redis query, Compatible with github.com/go-redis/redis/v8 Install Confirm that you are using redis.Client the

null 50 Jul 21, 2021
Redis Sorted Sets Benchmark

redis-zbench-go Redis Sorted Sets Benchmark Overview This repo contains code to trigger load ( ZADD ) or query (ZRANGEBYLEX key min max) benchmarks, w

filipe oliveira 3 May 18, 2021
Go language driver for RethinkDB

RethinkDB-go - RethinkDB Driver for Go Go driver for RethinkDB Current version: v6.2.1 (RethinkDB v2.4) Please note that this version of the driver on

RethinkDB 1.6k Jul 15, 2021
RethinkDB-go - RethinkDB Driver for Go

Go language driver for RethinkDB

RethinkDB 1.6k Jul 15, 2021
Simple key-value store abstraction and implementations for Go (Redis, Consul, etcd, bbolt, BadgerDB, LevelDB, Memcached, DynamoDB, S3, PostgreSQL, MongoDB, CockroachDB and many more)

gokv Simple key-value store abstraction and implementations for Go Contents Features Simple interface Implementations Value types Marshal formats Road

Philipp Gillé 347 Jul 10, 2021
Golang client for redislabs' ReJSON module with support for multilple redis clients (redigo, go-redis)

Go-ReJSON - a golang client for ReJSON (a JSON data type for Redis) Go-ReJSON is a Go client for ReJSON Redis Module. ReJSON is a Redis module that im

Nitish Malhotra 172 Jul 24, 2021
redis client implement by golang, inspired by jedis.

godis redis client implement by golang, refers to jedis. this library implements most of redis command, include normal redis command, cluster command,

piaohao 93 Jul 19, 2021
Google Go Client and Connectors for Redis

Go-Redis Go Clients and Connectors for Redis. The initial release provides the interface and implementation supporting the (~) full set of current Red

Joubin Houshyar 436 Jul 22, 2021
GoBigdis is a persistent database that implements the Redis server protocol. Any Redis client can interface with it and start to use it right away.

GoBigdis GoBigdis is a persistent database that implements the Redis server protocol. Any Redis client can interface with it and start to use it right

Riccardo 4 Jul 10, 2021
Go client for Redis

Redigo Redigo is a Go client for the Redis database. Features A Print-like API with support for all Redis commands. Pipelining, including pipelined tr

null 8.5k Jul 21, 2021
Redis client library for Go

go-redis go-redis is a Redis client library for the Go programming language. It's built on the skeleton of gomemcache. It is safe to use by multiple g

Alexandre Fiori 45 Jul 14, 2020