Chloe Parkes
Chloe Parkes

Reputation: 25

Force ConnectionError with Django cache in Tests

I have code which handles a ConnectionError when Django cannot connect to the Cache, which I'd like to test.

I've hit an issue that without actually disabling the real cache, I can't simulate it within the tests.

I have tried using the Django settings override:

with self.settings(CACHES={'default': {'BACKEND': 'django.core.cache.backends.dummy.DummyCache'}}):

However the above only simulates a cache, and not that it isn't available.

Is there a way to do this?

Thanks in advance.

Upvotes: 2

Views: 103

Answers (1)

Alasdair
Alasdair

Reputation: 309099

You could write your own cache backend that raises ConnectionError.

from django.core.cache.backends.base import BaseCache


class UnavailableCache(BaseCache):
    ...

    def get(self, *args, **kwargs)
        raise ConnectionError()
    ...

Then use this backend in self.settings:

with self.settings(CACHES={'default': {'BACKEND': 'path.to.UnavailableCache'}}):

Upvotes: 1

Related Questions