diff --git a/pytest_django/plugin.py b/pytest_django/plugin.py index aa45ff38..7897de56 100644 --- a/pytest_django/plugin.py +++ b/pytest_django/plugin.py @@ -646,12 +646,18 @@ def _dj_autoclear_mailbox() -> None: @pytest.fixture def mailoutbox( + request: pytest.FixtureRequest, django_mail_patch_dns: None, # noqa: ARG001 _dj_autoclear_mailbox: None, ) -> list[django.core.mail.EmailMessage] | None: """A clean email outbox to which Django-generated emails are sent.""" skip_if_no_django() + # Django's TestCase._pre_setup() replaces mail.outbox. Run the database + # helper first so mailoutbox returns the replacement list. + if "_django_db_helper" in request.fixturenames: + request.getfixturevalue("_django_db_helper") + from django.core import mail if hasattr(mail, "outbox"): diff --git a/tests/test_fixtures.py b/tests/test_fixtures.py index 5626de01..7654c392 100644 --- a/tests/test_fixtures.py +++ b/tests/test_fixtures.py @@ -804,6 +804,23 @@ def test_mail_again(mailoutbox) -> None: test_mail(mailoutbox) +def test_mailoutbox_with_db(mailoutbox, db: None) -> None: # noqa: ARG001 + assert mailoutbox is mail.outbox + + +@pytest.fixture +def mail_sending_db_fixture(db: None) -> None: # noqa: ARG001 + mail.send_mail("subject", "body", "from@example.com", ["to@example.com"]) + + +def test_mailoutbox_with_db_dependent_fixture( + mailoutbox, + mail_sending_db_fixture: None, # noqa: ARG001 +) -> None: + assert mailoutbox is mail.outbox + assert len(mailoutbox) == 1 + + def test_mail_message_uses_mocked_DNS_NAME(mailoutbox) -> None: mail.send_mail("subject", "body", "from@example.com", ["to@example.com"]) m = mailoutbox[0]