redigomock

package module
v0.0.0-...-9fe6b7b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 27, 2016 License: GPL-2.0 Imports: 9 Imported by: 0

README

redigomock

Build Status

GoDoc

Easy way to unit test projects using redigo library (Redis client in go).

install

go get -u github.com/gmlexx/redigomock

usage

Here is an example of using redigomock, for more information please check the API documentation.

package main

import (
	"fmt"
	"github.com/garyburd/redigo/redis"
	"github.com/gmlexx/redigomock"
)

type Person struct {
	Name string `redis:"name"`
	Age  int    `redis:"age"`
}

func RetrievePerson(conn redis.Conn, id string) (Person, error) {
	var person Person

	values, err := redis.Values(conn.Do("HGETALL", fmt.Sprintf("person:%s", id)))
	if err != nil {
		return person, err
	}

	err = redis.ScanStruct(values, &person)
	return person, err
}

func main() {
	// Simulate command result

	conn := redigomock.NewConn()
	cmd := conn.Command("HGETALL", "person:1").ExpectMap(map[string]string{
		"name": "Mr. Johson",
		"age":  "42",
	})

	person, err := RetrievePerson(conn, "1")
	if err != nil {
		fmt.Println(err)
		return
	}

	if conn.Stats(cmd) != 1 {
		fmt.Println("Command was not used")
		return
	}

	if person.Name != "Mr. Johson" {
		fmt.Printf("Invalid name. Expected 'Mr. Johson' and got '%s'\n", person.Name)
		return
	}

	if person.Age != 42 {
		fmt.Printf("Invalid age. Expected '42' and got '%d'\n", person.Age)
		return
	}

	// Simulate command error

	conn.Clear()
	cmd = conn.Command("HGETALL", "person:1").ExpectError(fmt.Errorf("Simulate error!"))

	person, err = RetrievePerson(conn, "1")
	if err == nil {
		fmt.Println("Should return an error!")
		return
	}

	if conn.Stats(cmd) != 1 {
		fmt.Println("Command was not used")
		return
	}

	fmt.Println("Success!")
}

fakeredis

Inspired by python fakeredis, this library can mock redis connection to act as real redis. This work is at the beginning and only the following commands are supported:

  • GET
  • SET
  • MULTI, EXEC
  • KEYS
  • FLUSHDB
  • SADD
  • SMEMBERS
  • SREM
  • SUNION
  • ZADD
  • ZRANGE
  • ZCOUNT
  • ZREMRANGEBYSCORE
  • ZRANGEBYSCORE
  • HGET
  • HSET
  • HLEN
  • HGETALL

Note: commands implementations are not optimized for performance.

Fakeredis example

	import (
		"github.com/gmlexx/redigomock"
		"github.com/garyburd/redigo/redis"
	)

	// Fake connection is thread-safe
	c := redigomock.NewFakeRedis()
	pool := &redis.Pool{
		MaxIdle:     3,
		IdleTimeout: 240 * time.Second,
		Dial: func() (redis.Conn, error) {
			return c, nil
		},
	}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cmd

type Cmd struct {
	Name      string        // Name of the command
	Args      []interface{} // Arguments of the command
	Responses []Response    // Slice of returned responses
	Callback  callback      // Callback will always be called, Responses ignored
	// contains filtered or unexported fields
}

Cmd stores the registered information about a command to return it later when request by a command execution

func (*Cmd) Expect

func (c *Cmd) Expect(response interface{}) *Cmd

Expect sets a response for this command. Everytime a Do or Receive methods are executed for a registered command this response or error will be returned. Expect call returns a pointer to Cmd struct, so you can chain Expect calls. Chained responses will be returned on subsequent calls matching this commands arguments in FIFO order

func (*Cmd) ExpectCallback

func (c *Cmd) ExpectCallback(cb callback) *Cmd

ExpectCallback register callback function to return response result

func (*Cmd) ExpectError

func (c *Cmd) ExpectError(err error) *Cmd

ExpectError allows you to force an error when executing a command/arguments

func (*Cmd) ExpectMap

func (c *Cmd) ExpectMap(response map[string]string) *Cmd

ExpectMap works in the same way of the Expect command, but has a key/value input to make it easier to build test environments

type Conn

type Conn struct {
	ReceiveWait bool         // When set to true, Receive method will wait for a value in ReceiveNow channel to proceed, this is useful in a PubSub scenario
	ReceiveNow  chan bool    // Used to lock Receive method to simulate a PubSub scenario
	CloseMock   func() error // Mock the redigo Close method
	ErrMock     func() error // Mock the redigo Err method
	FlushMock   func() error // Mock the redigo Flush method
	// contains filtered or unexported fields
}

Conn is the struct that can be used where you inject the redigo.Conn on your project

func NewConn

func NewConn() *Conn

NewConn returns a new mocked connection. Obviously as we are mocking we don't need any Redis connection parameter

func NewFakeRedis

func NewFakeRedis() *Conn

NewFakeRedis returns a connection, that acts as real redis

func (*Conn) Clear

func (c *Conn) Clear()

Clear removes all registered commands. Useful for connection reuse in test scenarios

func (*Conn) Close

func (c *Conn) Close() error

Close can be mocked using the Conn struct attributes

func (*Conn) Command

func (c *Conn) Command(commandName string, args ...interface{}) *Cmd

Command register a command in the mock system using the same arguments of a Do or Send commands. It will return a registered command object where you can set the response or error

func (*Conn) Do

func (c *Conn) Do(commandName string, args ...interface{}) (reply interface{}, err error)

Do looks in the registered commands (via Command function) if someone matches with the given command name and arguments, if so the corresponding response or error is returned. If no registered command is found an error is returned

func (*Conn) Err

func (c *Conn) Err() error

Err can be mocked using the Conn struct attributes

func (*Conn) Flush

func (c *Conn) Flush() error

Flush can be mocked using the Conn struct attributes

func (*Conn) GenericCommand

func (c *Conn) GenericCommand(commandName string) *Cmd

GenericCommand register a command without arguments. If a command with arguments doesn't match with any registered command, it will look for generic commands before throwing an error

func (*Conn) Receive

func (c *Conn) Receive() (reply interface{}, err error)

Receive will process the queue created by the Send method, only one item of the queue is processed by Receive call. It will work as the Do method

func (*Conn) Script

func (c *Conn) Script(scriptData []byte, keyCount int, args ...interface{}) *Cmd

Script registers a command in the mock system just like Command method would do. The first argument is a byte array with the script text, next ones are the ones you would pass to redis Script.Do() method

func (*Conn) Send

func (c *Conn) Send(commandName string, args ...interface{}) error

Send stores the command and arguments to be executed later (by the Receive function) in a first-come first-served order

func (Conn) Stats

func (c Conn) Stats(cmd *Cmd) int

Stats returns the number of times that a command was called in the current connection

type FuzzyMatcher

type FuzzyMatcher interface {

	// Match takes an argument passed to mock connection Do call and check if
	// it fulfills constraints set in concrete implementation of this interface
	Match(interface{}) bool
}

FuzzyMatcher is an interface that exports exports one function. It can be passed to the Command as a argument. When the command is evaluated agains data provided in mock connection Do call, FuzzyMatcher will call Match on the argument and returns true if argument fulfils constraints set in concrete implementation

func NewAnyData

func NewAnyData() FuzzyMatcher

NewAnyData returns a FuzzyMatcher instance matching every data passed as an arguments (returns true by default)

func NewAnyDataArray

func NewAnyDataArray() FuzzyMatcher

NewAnyDataArray returns a FuzzyMatcher instance matching every data passed as an arguments (returns true by default) and ignore arguments length

func NewAnyDouble

func NewAnyDouble() FuzzyMatcher

NewAnyDouble returns a FuzzyMatcher instance mathing any double passed as an argument

func NewAnyInt

func NewAnyInt() FuzzyMatcher

NewAnyInt returns a FuzzyMatcher instance matching any integer passed as an argument

type Response

type Response struct {
	Response interface{} // Response to send back when this command/arguments are called
	Error    error       // Error to send back when this command/arguments are called
}

Response struct that represents single response from `Do` call

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL