Redis
Установка
Если вы используете Codeception, установленный с помощью composer, установите этот модуль с помощью следующей команды:
composer require --dev codeception/module-redis
В качестве альтернативы, вы можете включить Redis модуль в файле конфигурации набора и запустить
codecept init upgrade4
Этот модуль был включён в Codeception 2 и 3, но начиная с версии 4 его необходимо устанавливать отдельно. Некоторые модули поставляются с файлами PHAR.
Предупреждение. Использование файла PHAR и composer в одном проекте может привести к непредвиденным ошибкам.
Описание
Этот модуль использует библиотеку Predis для взаимодействия с сервером Redis.
Статус
- Устойчивость: бета
Конфигурация
-
host(string, значение по умолчанию'127.0.0.1') - Хост Redis -
port(int, значение по умолчанию6379) - Порт Redis -
database(int, значение по умолчанию отсутствует) - База данных Redis. Необходимо указать. -
username(string, значение по умолчанию отсутствует) - При включении ACL на Redis >= 6.0, для аутентификации пользователя требуются как имя пользователя, так и пароль. -
password(string, значение по умолчанию отсутствует) - Пароль/секрет Redis. -
cleanupBefore: (string, значение по умолчанию'never') - Очистка базы данных:-
suite: в начале каждого набора -
test: в начале каждого теста - Любое другое значение: никогда
-
Примечание: Полный список конфигурации можно найти на github Predis.
Пример (unit.suite.yml)
modules:
- Redis:
host: '127.0.0.1'
port: 6379
database: 0
cleanupBefore: 'never' Общедоступные свойства
- driver - Содержит клиент/драйвер Predis
@author Marc Verney marc@marcverney.net
Действия
cleanup
Удалить все ключи в базе данных Redis
@throws ModuleException
dontSeeInRedis
Проверяет, что ключ не существует или, необязательно, что он не имеет заданного значения $value.
Примеры:
<?php
// With only one argument, only checks the key does not exist
$I->dontSeeInRedis('example:string');
// Checks a String does not exist or its value is not the one provided
$I->dontSeeInRedis('example:string', 'life');
// Checks a List does not exist or its value is not the one provided (order of elements is compared).
$I->dontSeeInRedis('example:list', ['riri', 'fifi', 'loulou']);
// Checks a Set does not exist or its value is not the one provided (order of members is ignored).
$I->dontSeeInRedis('example:set', ['riri', 'fifi', 'loulou']);
// Checks a ZSet does not exist or its value is not the one provided (scores are required, order of members is compared)
$I->dontSeeInRedis('example:zset', ['riri' => 1, 'fifi' => 2, 'loulou' => 3]);
// Checks a Hash does not exist or its value is not the one provided (order of members is ignored).
$I->dontSeeInRedis('example:hash', ['riri' => true, 'fifi' => 'Dewey', 'loulou' => 2]); -
param string$key Имя ключа -
param mixed$value Необязательно. Если указано, также проверяет, что ключ имеет это значение. Булевы значения будут преобразованы в 1 и 0 (даже внутри массивов)
dontSeeRedisKeyContains
Проверяет, что заданный ключ не содержит заданный элемент.
Примеры:
<?php
// Strings: performs a substring search
$I->dontSeeRedisKeyContains('string', 'bar');
// Lists
$I->dontSeeRedisKeyContains('example:list', 'poney');
// Sets
$I->dontSeeRedisKeyContains('example:set', 'cat');
// ZSets: check whether the zset has this member
$I->dontSeeRedisKeyContains('example:zset', 'jordan');
// ZSets: check whether the zset has this member with this score
$I->dontSeeRedisKeyContains('example:zset', 'jordan', 23);
// Hashes: check whether the hash has this field
$I->dontSeeRedisKeyContains('example:hash', 'magic');
// Hashes: check whether the hash has this field with this value
$I->dontSeeRedisKeyContains('example:hash', 'magic', 32); -
param string$key Ключ -
param mixed$item Элемент -
param null$itemValue Необязательно и используется только для zsets и хешей. Если указано, метод также проверит, что элемент $item имеет это значение/счёт
grabFromRedis
Возвращает значение заданного ключа
Примеры:
<?php
// Strings
$I->grabFromRedis('string');
// Lists: get all members
$I->grabFromRedis('example:list');
// Lists: get a specific member
$I->grabFromRedis('example:list', 2);
// Lists: get a range of elements
$I->grabFromRedis('example:list', 2, 4);
// Sets: get all members
$I->grabFromRedis('example:set');
// ZSets: get all members
$I->grabFromRedis('example:zset');
// ZSets: get a range of members
$I->grabFromRedis('example:zset', 3, 12);
// Hashes: get all fields of a key
$I->grabFromRedis('example:hash');
// Hashes: get a specific field of a key
$I->grabFromRedis('example:hash', 'foo'); -
param string$key Имя ключа -
return array|string|null
@throws ModuleException если ключ не существует
haveInRedis
Создаёт или изменяет ключи
Если $key уже существует:
- Строки: его значение будет перезаписано значением $value
- Другие типы: элементы $value будут добавлены к его значению
Примеры:
<?php
// Strings: $value must be a scalar
$I->haveInRedis('string', 'Obladi Oblada');
// Lists: $value can be a scalar or an array
$I->haveInRedis('list', ['riri', 'fifi', 'loulou']);
// Sets: $value can be a scalar or an array
$I->haveInRedis('set', ['riri', 'fifi', 'loulou']);
// ZSets: $value must be an associative array with scores
$I->haveInRedis('zset', ['riri' => 1, 'fifi' => 2, 'loulou' => 3]);
// Hashes: $value must be an associative array
$I->haveInRedis('hash', ['obladi' => 'oblada']); -
param string$type Тип ключа -
param string$key Имя ключа -
param mixed$value Значение
@throws ModuleException
seeInRedis
Проверяет, что ключ существует, и необязательно, что он имеет заданное значение $value.
Примеры:
<?php
// With only one argument, only checks the key exists
$I->seeInRedis('example:string');
// Checks a String exists and has the value "life"
$I->seeInRedis('example:string', 'life');
// Checks the value of a List. Order of elements is compared.
$I->seeInRedis('example:list', ['riri', 'fifi', 'loulou']);
// Checks the value of a Set. Order of members is ignored.
$I->seeInRedis('example:set', ['riri', 'fifi', 'loulou']);
// Checks the value of a ZSet. Scores are required. Order of members is compared.
$I->seeInRedis('example:zset', ['riri' => 1, 'fifi' => 2, 'loulou' => 3]);
// Checks the value of a Hash. Order of members is ignored.
$I->seeInRedis('example:hash', ['riri' => true, 'fifi' => 'Dewey', 'loulou' => 2]); -
param string$key Имя ключа -
param mixed$value Необязательно. Если указано, также проверяет, что ключ имеет это значение. Булевы значения будут преобразованы в 1 и 0 (даже внутри массивов)
seeRedisKeyContains
Проверяет, что заданный ключ содержит заданный элемент.
Примеры:
<?php
// Strings: performs a substring search
$I->seeRedisKeyContains('example:string', 'bar');
// Lists
$I->seeRedisKeyContains('example:list', 'poney');
// Sets
$I->seeRedisKeyContains('example:set', 'cat');
// ZSets: check whether the zset has this member
$I->seeRedisKeyContains('example:zset', 'jordan');
// ZSets: check whether the zset has this member with this score
$I->seeRedisKeyContains('example:zset', 'jordan', 23);
// Hashes: check whether the hash has this field
$I->seeRedisKeyContains('example:hash', 'magic');
// Hashes: check whether the hash has this field with this value
$I->seeRedisKeyContains('example:hash', 'magic', 32); -
param string$key Ключ -
param mixed$item Элемент -
param null$itemValue Необязательно и используется только для zsets и хешей. Если указано, метод также проверит, что элемент $item имеет это значение/счёт
sendCommandToRedis
Отправляет команду непосредственно в драйвер Redis. См. документацию по адресу https://github.com/nrk/predis Каждый аргумент, следующий за именем $command, будет передан ему.
Примеры:
<?php
$I->sendCommandToRedis('incr', 'example:string');
$I->sendCommandToRedis('strLen', 'example:string');
$I->sendCommandToRedis('lPop', 'example:list');
$I->sendCommandToRedis('zRangeByScore', 'example:set', '-inf', '+inf', ['withscores' => true, 'limit' => [1, 2]]);
$I->sendCommandToRedis('flushdb'); -
param string$command Имя команды
© 2011 Michael Bodnarchuk and contributors
Licensed under the MIT License.
https://codeception.com/docs/modules/Redis