Fakeredis, mocking django cache function in DRF tests

44 Views Asked by At

I'm using fakeredis to mock my Django tests

settings.py

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6382",
        "TIMEOUT": env.int("CACHE_TIMEOUT", default=2 * 60 * 60),
        "OPTIONS": {
            "CONNECTION_POOL_KWARGS": {"connection_class": FakeConnection},
        },
    }
}

In views I use from django.core.cache import cache

views.py

class MyViewSet(GenericViewSet):
    
    @action(methods=["GET"], detail=False)
    def my_view(self, request):
        if my_data := cache.get("my_key"):
            # some logic
        else:
            # some logic with calculation
            cache.set("my_key", my_data)
        return Response(my_data)

Now, in DRF tests I want to check that cache is set and in the next call of this endpoint the value is received from cache and no calculation is performed

tests.py

class MyTestCase(APITestCase):
    def test_my_view(self):
        response = self.client.get(reverse("my_view"))
        self.assertEqual(status.HTTP_200_OK, response.status_code)
        self.assertEqual() # want to check that cache is set

Is there any way to mock django cache with fakeredis and check that value appears in cache?

1

There are 1 best solutions below

0
On BEST ANSWER

Import from django.core.cache import cache and check the cache value after the first call.