diff --git a/docs/changelog.rst b/docs/changelog.rst index 4683eeba..b75ddeb6 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -8,6 +8,7 @@ Bugfixes ^^^^^^^^ * Fixed type hints of assert methods to match actual signature (`PR #1271 `__) +* Fix Pytest `--help`/`--version` options when a `conftest.py` file imports Django models (`PR #1275 `__). v4.12.0 (2026-02-14) -------------------- diff --git a/pytest_django/plugin.py b/pytest_django/plugin.py index 2866eca8..b5817877 100644 --- a/pytest_django/plugin.py +++ b/pytest_django/plugin.py @@ -307,8 +307,7 @@ def pytest_load_initial_conftests( options = parser.parse_known_args(args) - if options.version or options.help: - return + is_help_or_version = bool(options.version or options.help) django_find_project = _get_boolean_value( early_config.getini("django_find_project"), "django_find_project" @@ -363,11 +362,21 @@ def _get_option_with_source( from django.conf import settings as dj_settings with _handle_import_error(_django_project_scan_outcome): - dj_settings.DATABASES # noqa: B018 + try: + dj_settings.DATABASES # noqa: B018 + except ImportError: + # Don't allow invalid settings to prevent printing these + if not is_help_or_version: + raise early_config.stash[blocking_manager_key] = DjangoDbBlocker(_ispytest=True) - _setup_django(early_config) + try: + _setup_django(early_config) + except Exception: + # Don't allow invalid settings to prevent printing these + if not is_help_or_version: + raise @pytest.hookimpl(trylast=True) diff --git a/tests/test_initialization.py b/tests/test_initialization.py index 631a41ed..3c444531 100644 --- a/tests/test_initialization.py +++ b/tests/test_initialization.py @@ -1,5 +1,7 @@ from textwrap import dedent +import pytest + from .helpers import DjangoPytester @@ -60,3 +62,38 @@ def test_ds(): ] ) assert result.ret == 0 + + +@pytest.mark.parametrize("flag", ["--help", "--version"]) +def test_django_setup_for_help_and_version_with_model_import( + django_pytester: DjangoPytester, + flag: str, +) -> None: + """Django should be set up before conftest files are loaded, even with + --help/--version, so that top-level model imports in conftest files + don't fail with AppRegistryNotReady. + + Regression test for https://github.com/pytest-dev/pytest-django/issues/1152 + """ + django_pytester.makeconftest( + """ + from tpkg.app.models import Item + """ + ) + + django_pytester.makepyfile( + """ + def test_placeholder(): + pass + """ + ) + + args = [flag] + if flag == "--version": + # pytest requires -V passed twice to actually print version info + args.append(flag) + + result = django_pytester.runpytest_subprocess(*args) + assert result.ret == 0 + result.stderr.no_fnmatch_line("*AppRegistryNotReady*") + result.stderr.no_fnmatch_line("*could not load initial conftests*")