From a1b64043c0799e160fc16dd3d4176efd0d2e8ff4 Mon Sep 17 00:00:00 2001 From: Andy Venet Date: Sat, 29 Aug 2026 19:35:19 -0300 Subject: [PATCH] Clear ContentType cache between tests --- docs/changelog.rst | 6 ++++++ docs/helpers.rst | 8 ++++++++ pytest_django/plugin.py | 15 +++++++++++++++ tests/test_environment.py | 9 +++++++++ 4 files changed, 38 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index e1c8a982..b456c059 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -9,6 +9,12 @@ Compatibility * Official Django 6.1 support. +Bugfixes +^^^^^^^^ + +* Clear Django's ContentType cache between tests so query counts do not depend + on test ordering (`#1156 `__). + v4.14.0 (2026-08-10) -------------------- diff --git a/docs/helpers.rst b/docs/helpers.rst index 688458fb..0e5c597e 100644 --- a/docs/helpers.rst +++ b/docs/helpers.rst @@ -619,6 +619,14 @@ be cleared for each test to avoid hitting the cache and causing the wrong Site object to be returned by ``Site.objects.get_current()``. +Clearing of ContentType cache +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If ``django.contrib.contenttypes`` is in your INSTALLED_APPS, the ContentType +cache will be cleared for each test to avoid test ordering affecting query +counts. + + Clearing of mail.outbox ~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/pytest_django/plugin.py b/pytest_django/plugin.py index aa45ff38..511b0dba 100644 --- a/pytest_django/plugin.py +++ b/pytest_django/plugin.py @@ -854,6 +854,21 @@ def _django_clear_site_cache() -> None: Site.objects.clear_cache() +@pytest.fixture(autouse=True) +def _django_clear_contenttypes_cache() -> None: + """Clears ``ContentType`` cache to avoid unexpected behavior with cached + content types. + """ + + if django_settings_is_configured(): + from django.conf import settings as dj_settings + + if "django.contrib.contenttypes" in dj_settings.INSTALLED_APPS: + from django.contrib.contenttypes.models import ContentType + + ContentType.objects.clear_cache() + + # ############### Helper Functions ################ diff --git a/tests/test_environment.py b/tests/test_environment.py index 0c4ef024..8e6f272e 100644 --- a/tests/test_environment.py +++ b/tests/test_environment.py @@ -2,6 +2,7 @@ import sys import pytest +from django.contrib.contenttypes.models import ContentType from django.contrib.sites import models as site_models from django.contrib.sites.models import Site from django.core import mail @@ -381,6 +382,14 @@ def test_clear_site_cache_check_site_cache_size(site_name: str, settings) -> Non assert len(site_models.SITE_CACHE) == 1 +@pytest.mark.django_db +@pytest.mark.parametrize("model", [Item, Site]) +def test_clear_contenttypes_cache(model: type[Item] | type[Site]) -> None: + assert ContentType.objects._cache == {} + ContentType.objects.get_for_model(model) + assert ContentType.objects._cache + + @pytest.mark.django_project( project_root="django_project_root", create_manage_py=True,