pytest-redis

4.0.0 · active · verified Thu Apr 16

pytest-redis is a pytest plugin that provides Redis fixtures and fixture factories, enabling developers to test code that relies on a running Redis database. It simplifies the setup and teardown of Redis instances for testing, offering fixtures for Redis processes and clients. The current version is 4.0.0 and it maintains an active release cadence, primarily updating to support newer Python and pytest versions.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use the built-in `redisdb` fixture for basic Redis operations within a test. It also illustrates how to create and use custom, named Redis process and client fixtures using `pytest_redis.factories` to allow for specific configurations (like a custom port) or different scopes. Run with `pytest` after installing `pytest-redis` and `redis` client.

import pytest
from redis import Redis
from pytest_redis import factories
import os

# Basic test using the default function-scoped redisdb fixture
def test_can_connect(redisdb: Redis):
    # Ensure environment variables for Redis connection (if needed by redis-py)
    # are not hardcoded in actual tests, though pytest-redis manages the server.
    # For direct Redis client instantiation, you might do:
    # client = Redis(host=os.environ.get('REDIS_HOST', 'localhost'), 
    #                port=int(os.environ.get('REDIS_PORT', '6379')))

    redisdb.set("ping", "pong")
    assert redisdb.get("ping") == b"pong"
    print(f"Redis DB size: {redisdb.dbsize()}")

# Creating custom fixtures using factories
# Example: A session-scoped Redis process with a specific port or configuration
custom_redis_proc = factories.redis_proc(port=6380)

# A client fixture that uses the custom process
# Note: The string 'custom_redis_proc' matches the variable name of the proc fixture
custom_redis_client = factories.redisdb('custom_redis_proc')

# Test using the custom client fixture
def test_custom_redis_instance(custom_redis_client: Redis):
    custom_redis_client.set("mykey", "myvalue")
    assert custom_redis_client.get("mykey") == b"myvalue"
    assert custom_redis_client.info()['tcp_port'] == 6380

view raw JSON →