ui / django-post_office

A Django app that allows you to send email asynchronously in Django. Supports HTML email, database backed templates and logging.
MIT License
1.01k stars 268 forks source link

Mocking email template for tests #444

Open MariaMozgunova opened 1 year ago

MariaMozgunova commented 1 year ago

Hi,

When writing unit tests for our application, we use the following setup to prevent emails from being sent:

POST_OFFICE = {
    ...
    "BACKENDS": {"default": "django.core.mail.backends.dummy.EmailBackend"},
}

However, when I run tests I get an error that the email template does not exist:

post_office.models.EmailTemplate.DoesNotExist: EmailTemplate matching query does not exist.

So the question is, is there some recommended way to mock email templates for tests? As an alternative, we can use the fixture to mock mail.send function altogether:

@pytest.fixture(scope="session", autouse=True)
def send_email_mock():
    with mock.patch("post_office.mail.send", return_value=None) as _fixture:
        yield _fixture

What is the recommended approach here?