mirror of
https://gitlab.com/allianceauth/allianceauth.git
synced 2026-02-08 08:06:20 +01:00
Ensure backwards compatibility when fetching a redis client
This commit is contained in:
0
allianceauth/utils/__init__.py
Normal file
0
allianceauth/utils/__init__.py
Normal file
21
allianceauth/utils/cache.py
Normal file
21
allianceauth/utils/cache.py
Normal file
@@ -0,0 +1,21 @@
|
||||
from redis import Redis
|
||||
|
||||
from django.core.cache import caches
|
||||
|
||||
try:
|
||||
import django_redis
|
||||
except ImportError:
|
||||
django_redis = None
|
||||
|
||||
|
||||
def get_redis_client() -> Redis:
|
||||
"""Get the configured redis client used by Django for caching.
|
||||
|
||||
This function is a wrapper designed to work for both AA2 and AA3
|
||||
and should always be used to ensure backwards compatibility.
|
||||
"""
|
||||
try:
|
||||
return django_redis.get_redis_connection("default")
|
||||
except AttributeError:
|
||||
default_cache = caches["default"]
|
||||
return default_cache.get_master_client()
|
||||
0
allianceauth/utils/tests/__init__.py
Normal file
0
allianceauth/utils/tests/__init__.py
Normal file
39
allianceauth/utils/tests/test_cache.py
Normal file
39
allianceauth/utils/tests/test_cache.py
Normal file
@@ -0,0 +1,39 @@
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from django.test import TestCase
|
||||
|
||||
from allianceauth.utils.cache import get_redis_client
|
||||
|
||||
MODULE_PATH = "allianceauth.utils.cache"
|
||||
|
||||
|
||||
class RedisClientStub:
|
||||
"""Substitute for a Redis client."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class TestGetRedisClient(TestCase):
|
||||
def test_should_work_with_aa2_api(self):
|
||||
# given
|
||||
mock_django_cache = MagicMock()
|
||||
mock_django_cache.get_master_client.return_value = RedisClientStub()
|
||||
# when
|
||||
with patch(MODULE_PATH + ".django_redis", None), patch.dict(
|
||||
MODULE_PATH + ".caches", {"default": mock_django_cache}
|
||||
):
|
||||
client = get_redis_client()
|
||||
# then
|
||||
self.assertIsInstance(client, RedisClientStub)
|
||||
|
||||
def test_should_work_with_aa3_api(self):
|
||||
# given
|
||||
mock_django_redis = MagicMock()
|
||||
mock_django_redis.get_redis_connection.return_value = RedisClientStub()
|
||||
# when
|
||||
with patch(MODULE_PATH + ".django_redis", mock_django_redis), patch.dict(
|
||||
MODULE_PATH + ".caches", {"default": None}
|
||||
):
|
||||
client = get_redis_client()
|
||||
# then
|
||||
self.assertIsInstance(client, RedisClientStub)
|
||||
Reference in New Issue
Block a user