Andy Andy - 8 months ago 68
Python Question

Use LocMemCache for selective Django pytest

I have a custom Throttling classes based on Django REST framework's SimpleRateThrottle and I would like to test my custom class with pytest. Since my default test settings uses DummyCache, I would like to switch to LocMemCache for just this particular test module(SimpleRateThrottle uses cache backend to track counts). Is there a way to switch the cache backend for just selective tests? Setting settings.CACHE in a fixture doesn't seem to work. I also tried mocking the default_cache inside the SimpleRateThrottle, but I couldn't get it right.

from rest_framework.throttling import SimpleRateThrottle

class NaiveThrottler(SimpleRateThrottle):


from django.core.cache import cache as default_cache # Or how can I patch this?

class SimpleRateThrottle(BaseThrottle):


Django provides override_settings and modify_settings decorators for this. If you want to change the CACHES settings just for one test you can do this:

from django.test import TestCase, override_settings

class MyTestCase(TestCase):

    @override_settings(CACHES = {
                           'default': {
                              'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
    def test_chache(self):
        # your test code