m6web/redis-mock

Library providing a PHP mock for Redis

v5.6.0 2023-05-02 19:20 UTC

README

PHP 7.1 library providing a Redis PHP mock for your tests.

Work for now only with predis

Installation

$ composer require --dev m6web/redis-mock

Functions

It currently mocks these Redis commands :

It mocks MULTI, DISCARD and EXEC commands but without any transaction behaviors, they just make the interface fluent and return each command results. PIPELINE and EXECUTE pseudo commands (client pipelining) are also mocked. EVAL, EVALSHA, WATCH and UNWATCH are just stubs—they won't execute anything

Usage

RedisMock library provides a factory able to build a mocked class of your Redis library that can be directly injected in your application :

$factory          = new \M6Web\Component\RedisMock\RedisMockFactory();
$myRedisMockClass = $factory->getAdapterClass('My\Redis\Library');
$myRedisMock      = new $myRedisMockClass($myParameters);

In a simpler way, if you don't need to instanciate the mocked class with custom parameters (e.g. to easier inject the mock using Symfony config file), you can use getAdapter instead of getAdapterClass to directly create the adapter :

$factory     = new \M6Web\Component\RedisMock\RedisMockFactory();
$myRedisMock = $factory->getAdapter('My\Redis\Library');

WARNING !

  • RedisMock doesn't implement all Redis features and commands. The mock can have undesired behavior if your parent class uses unsupported features.
  • Storage is static and therefore shared by all instances.

Note : the factory will throw an exception by default if your parent class implements unsupported commands. If you want even so partially use the mock, you can specify the second parameter when you build it $factory->getAdapter('My\Redis\Library', true). The exception will then thrown only when the command is called.

Static storage & Multiple servers

The storage in the RedisMock class is organized by named areas. The default area's name is the empty string '' but you can specify an alternate area name when calling the factory's getAdapter method.

getAdapter($classToExtend, $failOnlyAtRuntime = false, $ignoreConstructor = true, $storage = '')

This enables the mocking of several remote Redis servers, each one with its own storage area.

However, one same area remains statically shared across all the instances bound to it.

Tests

The development environment is provided by Vagrant and the Xotelia box.

$ cp Vagrantfile.dist Vagrantfile
$ vagrant up
$ vagrant ssh
$ cd /vagrant
$ composer install
$ ./vendor/bin/atoum

Credits

Developped by the Cytron Team of M6 Web.
Tested with atoum.

License

RedisMock is licensed under the MIT license.