You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django 1.11.9中用Pytest测试Redis缓存存储?

解决Django 1.11.9 + pytest + Redis测试缓存的预置与清理问题

嘿,针对你用Django 1.11.9搭配pytest和Redis做缓存测试的需求,我整理了一套类似Django数据库测试流程的方案——既能预置测试数据,又能在测试后自动清理,完全不用担心污染生产缓存。

第一步:配置测试专用的Redis缓存

首先要和生产缓存严格隔离,避免测试数据搞乱正式环境。你可以在项目的测试配置文件(比如test_settings.py)里单独配置测试用的Redis数据库:

# test_settings.py
from .settings import *  # 继承项目基础配置

CACHES = {
    'default': {
        'BACKEND': 'django_redis.cache.RedisCache',
        'LOCATION': 'redis://127.0.0.1:6379/1',  # 用db 1作为测试库,和生产的db 0区分开
        'OPTIONS': {
            'CLIENT_CLASS': 'django_redis.client.DefaultClient',
        }
    }
}

如果没有单独的测试配置,也可以在主settings.py里通过环境变量判断切换:

# settings.py
import os

if os.environ.get('TESTING') == 'True':
    CACHES = {
        'default': {
            'BACKEND': 'django_redis.cache.RedisCache',
            'LOCATION': 'redis://127.0.0.1:6379/1',
            'OPTIONS': {
                'CLIENT_CLASS': 'django_redis.client.DefaultClient',
            }
        }
    }
else:
    # 生产环境的缓存配置
    CACHES = { ... }

第二步:用pytest Fixtures实现数据预置与自动清理

pytest的fixtures是处理测试前后操作的绝佳工具,我们可以创建两个核心fixture:一个负责获取Redis连接并清理数据,另一个负责预置测试数据。

1. 基础Redis客户端fixture

在项目根目录的conftest.py里添加:

# conftest.py
import pytest
from django_redis import get_redis_connection

@pytest.fixture(scope='function')
def redis_client():
    # 获取测试缓存的Redis连接
    client = get_redis_connection('default')
    yield client
    # 测试结束后清空当前数据库的所有数据
    client.flushdb()

这里scope='function'表示每个测试函数执行完都会清空缓存,如果你想让数据在整个测试模块或会话中复用,可以改成scope='module'或scope='session',但记得手动清理避免数据污染。

2. 预置测试数据的fixture

基于上面的redis_client,我们再封装一个带预置数据的fixture:

@pytest.fixture(scope='function')
def populated_redis(redis_client):
    # 预置你需要的测试key-value对
    test_data = {
        'user:1:name': 'Alice',
        'user:2:name': 'Bob',
        'product:100:price': '99.99'
    }
    for key, value in test_data.items():
        redis_client.set(key, value)
    # 可选:给某些key设置过期时间
    # redis_client.expire('user:1:name', 3600)
    yield redis_client
    # 无需额外清理,因为redis_client fixture已经会调用flushdb()

如果你更习惯用Django的缓存API而非直接操作Redis客户端,也可以这样写:

from django.core.cache import cache

@pytest.fixture(scope='function')
def populated_cache():
    # 用Django cache API设置数据
    cache.set('user:1:name', 'Alice')
    cache.set('user:2:name', 'Bob')
    yield cache
    # 清空所有缓存数据
    cache.clear()

第三步:编写测试用例

现在你可以在测试函数里直接使用这些fixture了,举个例子:

# tests/test_cache_operations.py
def test_cache_data_retrieval(populated_redis):
    # 验证预置的数据存在(注意Redis返回的是字节串,所以用b''包裹)
    assert populated_redis.get('user:1:name') == b'Alice'
    assert populated_redis.get('product:100:price') == b'99.99'

def test_cache_update(populated_cache):
    # 用Django cache API测试修改操作
    assert populated_cache.get('user:2:name') == 'Bob'
    populated_cache.set('user:2:name', 'Bob Smith')
    assert populated_cache.get('user:2:name') == 'Bob Smith'

额外注意事项

  • 确保加载测试配置:运行pytest时,要指定使用测试配置。可以在pytest.ini里添加:
    [pytest]
    DJANGO_SETTINGS_MODULE = your_project.test_settings
    
    或者运行时加参数:pytest --ds=your_project.test_settings
  • 版本兼容:Django 1.11.9需要搭配兼容的django-redis版本,推荐使用4.8.x或4.9.x版本,避免出现兼容性问题。

内容的提问来源于stack exchange,提问作者koddr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:32:57