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_redis和 https://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/