Last active
September 2, 2022 11:56
-
-
Save atuchak/1fa3b915b776299ef0476f703ccd4f44 to your computer and use it in GitHub Desktop.
pytest xdist django cache prefix per process
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@pytest.fixture(autouse=True, scope='session') | |
def django_cache_add_xdist_key_prefix(request): | |
skip_if_no_django() | |
# prefix like gw0_, gw1_ etc on xdist processes | |
xdist_prefix = getattr(request.config, 'slaveinput', {}).get('slaveid') | |
if not xdist_prefix: | |
return | |
from django.conf import settings | |
from django.core.cache import caches, _create_cache | |
for cache_alias, cache_settings in settings.CACHES.items(): | |
new_prefix = xdist_prefix + '_' + cache_settings.get('KEY_PREFIX', '') | |
cache_settings['KEY_PREFIX'] = new_prefix | |
new_cache = copy(settings.CACHES[cache_alias]) | |
new_cache['KEY_PREFIX'] = new_prefix | |
settings.CACHES[cache_alias] = new_cache | |
if getattr(caches._caches, 'caches', None) is None: | |
continue | |
caches._caches.caches[cache_alias] = _create_cache(cache_alias) | |
@pytest.fixture(scope='function', autouse=True) | |
def clear_cache_befor_and_after_test(settings): | |
from django.core.cache import cache | |
key_prefix = settings.CACHES['default'].get('KEY_PREFIX', '') | |
key_prefix = f'{key_prefix}:*' | |
for key in cache.keys(key_prefix): | |
cache.delete(key) | |
yield | |
for key in cache.keys(key_prefix): | |
cache.delete(key) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment