Skip to content

Fix mailoutbox fixture initialization with database-dependent fixtures - #1309

Open
gh640 wants to merge 1 commit into
pytest-dev:mainfrom
gh640:fix/mailoutbox-fixture-initialization
Open

Fix mailoutbox fixture initialization with database-dependent fixtures#1309
gh640 wants to merge 1 commit into
pytest-dev:mainfrom
gh640:fix/mailoutbox-fixture-initialization

Conversation

@gh640

@gh640 gh640 commented Aug 16, 2026

Copy link
Copy Markdown

Fixes #589

Ensure database setup completes before mailoutbox captures Django's mail.outbox to prevent mailoutbox from retaining a stale list when Django's TestCase._pre_setup() (that is invoked in _django_db_helper fixture) replaces mail.outbox.


This PR intentionally covers only database dependencies that are visible in pytest's fixture graph. It does not cover fixtures that dynamically request database access after mailoutbox has been initialized, for example:

@pytest.fixture
def dynamically_requests_db(request):
    request.getfixturevalue("db")

Supporting that case would require a more invasive approach, such as preserving and synchronizing the existing outbox around _django_db_helper and Django's _pre_setup(). I am happy to change to the broader approach if maintainers prefer it.

Comment thread pytest_django/plugin.py
# 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")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Darn you're right, i'm tempted to not do this and set the mail.outbox = [] myself here, to not instantiate the db.

@bluetech thoughts?

Comment thread tests/test_fixtures.py
test_mail(mailoutbox)


def test_mailoutbox_with_db(mailoutbox, db: None) -> None: # noqa: ARG001

@kingbuzzman kingbuzzman Aug 28, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
def test_mailoutbox_with_db(mailoutbox, db: None) -> None: # noqa: ARG001
def test_mailoutbox_without_db(mailoutbox) -> None: # noqa: ARG001

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should have this test to make sure we don't regress yet again 😇

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

mail.outbox not being set?

2 participants