Pkg.go.dev is a new destination for Go discovery & docs. Check it out at pkg.go.dev/github.com/EverythingMe/disposable-redis and share your feedback.

package disposable_redis

import "github.com/EverythingMe/disposable-redis"

A utility to create disposable instances of redis server on random ports.

This can be used for testing redis dependent code without having to make assumptions on if and where redis server is running, or fear of corrupting data. You create a redis server instance, run your code against it as if it were a mock, and then remove it without a trace.

disposable_redis.go

❖ const ( MaxRetries = 10 //this is the amount of time we give the server to start itself up and start listening (or fail) LaunchWaitTimeout = 100 * time.Millisecond )

❖ var RedisCommand = "redis-server"

The redis executable. This allows you to set it if you're using a custom one. Can be an absolute path, or an executable in your $PATH

❖ type Server struct { // contains filtered or unexported fields }

A wrapper reperesenting a running disposable redis server

Example Code: // create a new server on a random port r, err := NewServerRandomPort() if err != nil { panic("Could not create random server") } // we must remember to kill it at the end, or we'll have zombie redises defer r.Stop() // wait for our server to be ready for serving, for at least 50 ms. // This gives redis time to initialize itself and listen if err = r.WaitReady(50 * time.Millisecond); err != nil { panic("Couldn't connect to instance") } //now we can just connect and talk to it conn, err := redigo.Dial("tcp", fmt.Sprintf("localhost:%d", r.Port())) if err != nil { panic(err) } fmt.Println(redigo.String(conn.Do("SET", "foo", "bar"))) Output: OK <nil>

Create and run a new server on a given port. Return an error if the server cannot be started

Create a new server on a random port. If the port is taken we retry (10 times). If we still couldn't start the process, we return an error

Addr returns the address of the server as a host:port string

Info returns the value of the server's INFO command parsed into a map of strings

NewSlaveOf creates a new server with a random port and makes it a slave of the current server.

Get the port of this server

Stop the running redis server

Wait for the server to be ready, or until a timeout has elapsed. This just blocks and waits using sleep intervals of 5ms if it can't connect