[英]How to mock redis in django using django-redis and mockredis
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缓存的视图:
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)
我有使用上面的视图并使用缓存的测试:
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_redis和https://github.com/locationlabs/mockredis ,无法理解我在做什么错。
您可以在django中使用django-fakeredis轻松模拟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():
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.