python - 如何使用django-redis和mockredis在django中模拟redis

标签 python django redis django-rest-framework mocking

Redis 在 django 设置中配置如下:

CACHES = {
    'default': {
        'BACKEND': 'django_redis.cache.RedisCache',
        'LOCATION': 'redis://127.0.0.1:6379/',
        'OPTIONS': {
            'CLIENT_CLASS': 'django_redis.client.DefaultClient',
        }
    }
}

CACHE_TTL = 3600

我有以下使用 redis 缓存的 View :

from django.core.cache import cache

class TestView(APIView):
    def post(self, request):
        serializer = TestSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            data = serializer.data
            # save new data to cache
            cache.set(data['title'], data, timeout=CACHE_TTL)
            return Response(data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

我有一个使用上面的 View 并使用缓存的测试:

class MyTest(APITestCase):
    @patch('redis.StrictRedis', mock_strict_redis_client)
    def test_create(self):
        url = reverse('test-list')
        data = {'title': '77test'}
        response = self.client.post(url, data)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(IP.objects.count(), 1)
        self.assertEqual(IP.objects.get().title, '77test')

问题在于它使用真正的 Redis 缓存而不是使用模拟的缓存。 我正在查看http://niwinz.github.io/django-redis/latest/#_testing_with_django_redishttps://github.com/locationlabs/mockredis并且无法理解我做错了什么。

最佳答案

您可以使用django-fakeredis在 django 中轻松模拟 djagno-redis。

就您而言:

from django_fakeredis.fakeredis import FakeRedis
....
@FakeRedis("yourview.cache"):
def test_create(self)
    ....

如果您使用 get_redis_connection,您可以:

from django_fakeredis.fakeredis import FakeRedis
@FakeRedis("yourpath.get_redis_connection")
def test_foo():
    ...

关于python - 如何使用django-redis和mockredis在django中模拟redis,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54849998/

相关文章:

python - 子弹不与敌方 Pygame 碰撞(Python 3)

python - 在 AWS Cloudformation 上调用 ListStacks 时出现验证错误

django - 在本地运行结构脚本

database - 在 Redis 中对一组的所有项目进行排名

python - py.test : error: unrecognized arguments: --cov=ner_brands --cov-report=term-missing --cov-config

python - 如何使用 Selenium Webdriver 和 Python 单击悬停菜单中的链接?

django - 如何在 Django 中预取聚合的@property?

python - Django 报告选项

redis - 使用 REDIS 的集群启用选项启动 YCSB 负载

python - 了解 celery 工作节点