tests/e2e: fix email backend

Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org>
This commit is contained in:
Jens Langhammer 2021-11-23 13:04:14 +01:00
parent 8f5af464a2
commit 355b832cc3
5 changed files with 30 additions and 14 deletions

View File

@ -4,8 +4,8 @@ from pathlib import Path
from typing import Type from typing import Type
from django.conf import settings from django.conf import settings
from django.core.mail import get_connection
from django.core.mail.backends.base import BaseEmailBackend from django.core.mail.backends.base import BaseEmailBackend
from django.core.mail.backends.smtp import EmailBackend
from django.db import models from django.db import models
from django.utils.translation import gettext as _ from django.utils.translation import gettext as _
from django.views import View from django.views import View
@ -97,12 +97,17 @@ class EmailStage(Stage):
def component(self) -> str: def component(self) -> str:
return "ak-stage-email-form" return "ak-stage-email-form"
@property
def backend_class(self) -> Type[BaseEmailBackend]:
"""Get the email backend class to use"""
return EmailBackend
@property @property
def backend(self) -> BaseEmailBackend: def backend(self) -> BaseEmailBackend:
"""Get fully configured Email Backend instance""" """Get fully configured Email Backend instance"""
if self.use_global_settings: if self.use_global_settings:
return get_connection() return self.backend_class()
return get_connection( return self.backend_class(
host=self.host, host=self.host,
port=self.port, port=self.port,
username=self.username, username=self.username,

View File

@ -83,7 +83,7 @@ def send_mail(self: MonitoredTask, message: dict[Any, Any], email_stage_pk: Opti
message_object.extra_headers["Message-ID"] = message_id message_object.extra_headers["Message-ID"] = message_id
LOGGER.debug("Sending mail", to=message_object.to) LOGGER.debug("Sending mail", to=message_object.to)
stage.backend.send_messages([message_object]) backend.send_messages([message_object])
Event.new( Event.new(
EventAction.EMAIL_SENT, EventAction.EMAIL_SENT,
message=(f"Email to {', '.join(message_object.to)} sent"), message=(f"Email to {', '.join(message_object.to)} sent"),

View File

@ -1,6 +1,6 @@
"""email tests""" """email tests"""
from smtplib import SMTPException from smtplib import SMTPException
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, PropertyMock, patch
from django.core import mail from django.core import mail
from django.core.mail.backends.locmem import EmailBackend from django.core.mail.backends.locmem import EmailBackend
@ -42,7 +42,10 @@ class TestEmailStageSending(APITestCase):
session.save() session.save()
url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}) url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
with self.settings(EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend"): with patch(
"authentik.stages.email.models.EmailStage.backend_class",
PropertyMock(return_value=EmailBackend),
):
response = self.client.post(url) response = self.client.post(url)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(len(mail.outbox), 1) self.assertEqual(len(mail.outbox), 1)
@ -64,7 +67,10 @@ class TestEmailStageSending(APITestCase):
session.save() session.save()
url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}) url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
with self.settings(EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend"): with patch(
"authentik.stages.email.models.EmailStage.backend_class",
PropertyMock(return_value=EmailBackend),
):
with patch( with patch(
"django.core.mail.backends.locmem.EmailBackend.send_messages", "django.core.mail.backends.locmem.EmailBackend.send_messages",
MagicMock(side_effect=[SMTPException, EmailBackend.send_messages]), MagicMock(side_effect=[SMTPException, EmailBackend.send_messages]),

View File

@ -1,7 +1,9 @@
"""email tests""" """email tests"""
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, PropertyMock, patch
from django.core import mail from django.core import mail
from django.core.mail.backends.locmem import EmailBackend
from django.core.mail.backends.smtp import EmailBackend as SMTPEmailBackend
from django.urls import reverse from django.urls import reverse
from django.utils.encoding import force_str from django.utils.encoding import force_str
from django.utils.http import urlencode from django.utils.http import urlencode
@ -67,7 +69,10 @@ class TestEmailStage(APITestCase):
session.save() session.save()
url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}) url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
with self.settings(EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend"): with patch(
"authentik.stages.email.models.EmailStage.backend_class",
PropertyMock(return_value=EmailBackend),
):
response = self.client.post(url) response = self.client.post(url)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(len(mail.outbox), 1) self.assertEqual(len(mail.outbox), 1)
@ -76,9 +81,11 @@ class TestEmailStage(APITestCase):
def test_use_global_settings(self): def test_use_global_settings(self):
"""Test use_global_settings""" """Test use_global_settings"""
host = "some-unique-string" host = "some-unique-string"
with self.settings( with patch(
EMAIL_HOST=host, EMAIL_BACKEND="django.core.mail.backends.smtp.EmailBackend" "authentik.stages.email.models.EmailStage.backend_class",
PropertyMock(return_value=SMTPEmailBackend),
): ):
with self.settings(EMAIL_HOST=host):
self.assertEqual(EmailStage(use_global_settings=True).backend.host, host) self.assertEqual(EmailStage(use_global_settings=True).backend.host, host)
def test_token(self): def test_token(self):

View File

@ -4,7 +4,6 @@ from time import sleep
from typing import Any, Optional from typing import Any, Optional
from unittest.case import skipUnless from unittest.case import skipUnless
from django.test import override_settings
from docker.types import Healthcheck from docker.types import Healthcheck
from selenium.webdriver.common.by import By from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec from selenium.webdriver.support import expected_conditions as ec
@ -111,7 +110,6 @@ class TestFlowsEnroll(SeleniumTestCase):
@apply_migration("authentik_core", "0002_auto_20200523_1133_squashed_0011_provider_name_temp") @apply_migration("authentik_core", "0002_auto_20200523_1133_squashed_0011_provider_name_temp")
@apply_migration("authentik_flows", "0008_default_flows") @apply_migration("authentik_flows", "0008_default_flows")
@apply_migration("authentik_flows", "0011_flow_title") @apply_migration("authentik_flows", "0011_flow_title")
@override_settings(EMAIL_BACKEND="django.core.mail.backends.smtp.EmailBackend")
def test_enroll_email(self): def test_enroll_email(self):
"""Test enroll with Email verification""" """Test enroll with Email verification"""
# First stage fields # First stage fields