A community-supported supercharged document management system: scan, index and archive all your documents
Python aiangulararchivingdjangodmsdocument-managementdocument-management-systemllmmachine-learningocroptical-character-recognitionpdf
Fix: Clear ContentType/guardian caches at import and test cases (#12758)
Trenton H5202dc074857
diff --git a/src/documents/management/commands/document_importer.py b/src/documents/management/commands/document_importer.pyindex 6cb495777..90986858b 100644--- a/src/documents/management/commands/document_importer.py+++ b/src/documents/management/commands/document_importer.py@@ -30,6 +30,7 @@ from django.db.models import Modelfrom django.db.models.signals import m2m_changedfrom django.db.models.signals import post_savefrom filelock import FileLock+from guardian.shortcuts import clear_ct_cachefrom documents.file_handling import create_source_path_directoryfrom documents.management.commands.base import PaperlessCommand@@ -429,6 +430,12 @@ class Command(CryptMixin, PaperlessCommand):self.stdout.write(self.style.ERROR(self._import_error_context_message()))raise+ # ContentType/Permission rows were deleted and reinserted above; stale+ # in-process caches must be invalidated so permission checks use the+ # new IDs rather than pre-import PKs.+ ContentType.objects.clear_cache()+ clear_ct_cache()+def handle(self, *args, **options) -> None:logging.getLogger().handlers[0].level = logging.ERRORdiff --git a/src/documents/tests/conftest.py b/src/documents/tests/conftest.pyindex 88f0e9d76..07c20c944 100644--- a/src/documents/tests/conftest.py+++ b/src/documents/tests/conftest.py@@ -8,6 +8,8 @@ from typing import TYPE_CHECKINGimport filelockimport pytestfrom django.contrib.auth import get_user_model+from django.contrib.contenttypes.models import ContentType+from guardian.shortcuts import clear_ct_cachefrom pytest_django.fixtures import SettingsWrapperfrom rest_framework.test import APIClient@@ -158,6 +160,19 @@ def user_client(rest_api_client: APIClient, regular_user: UserModelT) -> APICliereturn rest_api_client[email protected](autouse=True)+def _clear_content_type_caches() -> None:+ """Clear Django's ContentType cache and guardian's lru_cache before each test.++ Tests that delete and reinsert ContentType/Permission rows (e.g. the+ importer) corrupt both caches. Without this fixture a subsequent test on+ the same xdist worker sees stale ContentType objects and guardian raises+ MixedContentTypeError.+ """+ ContentType.objects.clear_cache()+ clear_ct_cache()++@pytest.fixture(scope="session", autouse=True)def faker_session_locale():"""Set Faker locale for reproducibility."""