Skip to content

Instantly share code, notes, and snippets.

@atuchak
Last active September 2, 2022 11:56
Show Gist options
  • Save atuchak/1fa3b915b776299ef0476f703ccd4f44 to your computer and use it in GitHub Desktop.
Save atuchak/1fa3b915b776299ef0476f703ccd4f44 to your computer and use it in GitHub Desktop.
pytest xdist django cache prefix per process
@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