Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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 <https://github.com/pytest-dev/pytest-django/issues/1156>`__).

v4.14.0 (2026-08-10)
--------------------

Expand Down
8 changes: 8 additions & 0 deletions docs/helpers.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
~~~~~~~~~~~~~~~~~~~~~~~

Expand Down
15 changes: 15 additions & 0 deletions pytest_django/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 ################


Expand Down
9 changes: 9 additions & 0 deletions tests/test_environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down