notify/tests/test_delivery.py

840 lines
35 KiB
Python

from datetime import timedelta
from unittest.mock import patch
import requests
from django.contrib.auth import get_user_model
from django.core import mail
from django.core.exceptions import ValidationError
from django.db import IntegrityError, transaction
from django.test import TestCase
from django.utils import timezone
from notify.delivery import get_provider, get_provider_or_raise, registered_channels
from notify.delivery.providers.exolve import EXOLVE_API_TIMEOUT, EXOLVE_SMS_URL
from notify.delivery.providers.max import MAX_API_TIMEOUT
from notify.delivery.providers.telegram import TELEGRAM_API_TIMEOUT
from notify.models import (
DeliveryChannel,
DeliveryEmailConfig,
DeliveryStatus,
DeliveryTokenConfig,
Notification,
NotificationGroup,
NotificationRecipient,
NotificationTemplate,
NotificationType,
)
from notify.rendering import render
from notify.services import create_notification
from notify.tasks import RETRY_BASE_DELAY, deliver_notification, retry_countdown
User = get_user_model()
class RetryCountdownTests(TestCase):
def test_delay_doubles_with_bounded_jitter(self):
for retries in range(5):
expected = RETRY_BASE_DELAY * 2 ** retries
for _ in range(20):
delay = retry_countdown(retries)
self.assertGreaterEqual(delay, expected)
self.assertLessEqual(delay, expected + expected // 10)
class DeliveryTests(TestCase):
def setUp(self):
self.user = User.objects.create_user("alice", "alice@example.com", "pass")
self.email_config = DeliveryEmailConfig.objects.create(
name="default-smtp",
channel=DeliveryChannel.EMAIL,
is_default=True,
host="smtp.example.com",
port=587,
from_email="noreply@example.com",
use_ssl=False,
use_tls=False,
)
def _email_recipient(self, **notification_kwargs):
notification = create_notification(
title=notification_kwargs.pop("title", "Hello"),
description=notification_kwargs.pop("description", "Body"),
recipients=[
{
"user": self.user,
"channels": [{"channel": DeliveryChannel.EMAIL, "target": {"email": "alice@example.com"}}],
}
],
**notification_kwargs,
)
return notification.recipients.get()
def _max_recipient(self, target=None):
DeliveryTokenConfig.objects.create(
name="max",
channel=DeliveryChannel.MAX,
is_default=True,
token="token",
)
notification = Notification.objects.create(title="Hello", description="Body")
return NotificationRecipient.objects.create(
notification=notification,
user=self.user,
channel=DeliveryChannel.MAX,
target={"chat_id": -10} if target is None else target,
)
def test_email_failure_is_not_marked_sent(self):
recipient = self._email_recipient()
with patch(
"notify.delivery.providers.email.EmailMessage.send",
side_effect=OSError("smtp down"),
):
result = deliver_notification.apply(args=[str(recipient.id)], throw=False)
self.assertEqual(result.state, "FAILURE")
recipient.refresh_from_db()
self.assertEqual(recipient.status, DeliveryStatus.FAILED)
self.assertEqual(recipient.attempts, 6)
self.assertIn("Email delivery failed", recipient.last_error)
self.assertIsNone(recipient.sent_at)
self.assertEqual(len(mail.outbox), 0)
def test_missing_email_config_fails_explicitly(self):
recipient = self._email_recipient()
self.email_config.delete()
result = deliver_notification.apply(args=[str(recipient.id)], throw=False)
self.assertEqual(result.state, "FAILURE")
recipient.refresh_from_db()
self.assertEqual(recipient.status, DeliveryStatus.FAILED)
def test_missing_address_is_permanent_failure(self):
notification = Notification.objects.create(title="Hello", description="Body")
recipient = NotificationRecipient.objects.create(
notification=notification,
user=self.user,
channel=DeliveryChannel.EMAIL,
target=None,
)
deliver_notification.apply(args=[str(recipient.id)], throw=True)
recipient.refresh_from_db()
self.assertEqual(recipient.status, DeliveryStatus.FAILED)
def test_successful_email_is_sent_once_and_escapes_html(self):
recipient = self._email_recipient(
title="Hello\r\nBcc: leak",
description="<script>alert(1)</script>",
)
deliver_notification.apply(args=[str(recipient.id)], throw=True)
deliver_notification.apply(args=[str(recipient.id)], throw=True)
recipient.refresh_from_db()
self.assertEqual(recipient.status, DeliveryStatus.SENT)
self.assertEqual(recipient.attempts, 1)
self.assertEqual(recipient.last_error, "")
self.assertIsNotNone(recipient.sent_at)
self.assertEqual(len(mail.outbox), 1)
self.assertNotIn("\n", mail.outbox[0].subject)
self.assertNotIn("<script>", mail.outbox[0].body)
self.assertIn("&lt;script&gt;", mail.outbox[0].body)
self.assertEqual(mail.outbox[0].from_email, "noreply@example.com")
self.assertEqual(mail.outbox[0].to, ["alice@example.com"])
def test_template_context_does_not_expose_the_user_model(self):
NotificationTemplate.objects.create(
channel=DeliveryChannel.EMAIL,
name="email-default",
is_default=True,
subject="{{ notification.title }}",
body="hash={{ user.password }} title={{ notification.title }}",
)
recipient = self._email_recipient(title="Approved", description="<b>x</b>")
deliver_notification.apply(args=[str(recipient.id)], throw=True)
body = mail.outbox[0].body
self.assertIn("title=Approved", body)
self.assertNotIn(self.user.password, body)
self.assertNotIn("<b>", body)
def test_disallowed_channel_does_not_create_notification(self):
group = NotificationGroup.objects.create(code="orders", name="Orders")
NotificationType.objects.create(
code="approved",
name="Approved",
group=group,
channels=[DeliveryChannel.EMAIL],
title="Approved",
)
with self.assertRaisesMessage(ValueError, "not allowed"):
create_notification(
notification_type="approved",
recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
],
)
self.assertEqual(Notification.objects.count(), 0)
def test_unknown_channel_does_not_create_recipient(self):
with self.assertRaisesMessage(ValueError, "No delivery provider"):
create_notification(
title="Ping",
recipients=[
{"user": self.user, "channels": [{"channel": "push"}]},
],
)
self.assertEqual(Notification.objects.count(), 0)
self.assertEqual(NotificationRecipient.objects.count(), 0)
def test_inactive_type_raises(self):
group = NotificationGroup.objects.create(code="orders", name="Orders")
NotificationType.objects.create(
code="approved",
name="Approved",
group=group,
channels=[DeliveryChannel.BROWSER],
title="Approved",
is_active=False,
)
with self.assertRaisesMessage(ValueError, "inactive"):
create_notification(
notification_type="approved",
recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
],
)
self.assertEqual(Notification.objects.count(), 0)
def test_duplicate_channel_rolls_back(self):
with self.assertRaisesMessage(ValueError, "Duplicate"):
create_notification(
title="Ping",
recipients=[
{
"user": self.user,
"channels": [
{"channel": DeliveryChannel.EMAIL, "target": {"email": "alice@example.com"}},
{"channel": DeliveryChannel.EMAIL, "target": {"email": "alice@example.com"}},
],
}
],
)
self.assertEqual(Notification.objects.count(), 0)
def test_recipient_channel_is_unique(self):
notification = Notification.objects.create(title="Hello")
NotificationRecipient.objects.create(
notification=notification,
user=self.user,
channel=DeliveryChannel.EMAIL,
target={"email": "alice@example.com"},
)
with self.assertRaises(IntegrityError):
with transaction.atomic():
NotificationRecipient.objects.create(
notification=notification,
user=self.user,
channel=DeliveryChannel.EMAIL,
target={"email": "other@example.com"},
)
def test_max_request_has_timeout_and_retries_server_errors(self):
DeliveryTokenConfig.objects.create(
name="max",
channel=DeliveryChannel.MAX,
is_default=True,
token="token",
)
notification = Notification.objects.create(title="Hello", description="Body")
recipient = NotificationRecipient.objects.create(
notification=notification,
user=self.user,
channel=DeliveryChannel.MAX,
target={"chat_id": -10},
)
response = requests.Response()
response.status_code = 503
error = requests.HTTPError("unavailable")
error.response = response
with patch("notify.delivery.providers.max.requests.post") as post:
post.return_value.raise_for_status.side_effect = error
result = deliver_notification.apply(args=[str(recipient.id)], throw=False)
self.assertEqual(result.state, "FAILURE")
self.assertGreater(post.call_count, 1)
self.assertEqual(post.call_args.kwargs["timeout"], MAX_API_TIMEOUT)
recipient.refresh_from_db()
self.assertEqual(recipient.status, DeliveryStatus.FAILED)
def test_max_client_error_is_not_retried(self):
DeliveryTokenConfig.objects.create(
name="max",
channel=DeliveryChannel.MAX,
is_default=True,
token="token",
)
notification = Notification.objects.create(title="Hello", description="Body")
recipient = NotificationRecipient.objects.create(
notification=notification,
user=self.user,
channel=DeliveryChannel.MAX,
target={"chat_id": -10},
)
response = requests.Response()
response.status_code = 400
error = requests.HTTPError("bad request")
error.response = response
with patch("notify.delivery.providers.max.requests.post") as post:
post.return_value.raise_for_status.side_effect = error
deliver_notification.apply(args=[str(recipient.id)], throw=True)
self.assertEqual(post.call_count, 1)
recipient.refresh_from_db()
self.assertEqual(recipient.status, DeliveryStatus.FAILED)
def test_second_default_config_replaces_the_first(self):
second = DeliveryEmailConfig.objects.create(
name="other-smtp",
channel=DeliveryChannel.EMAIL,
is_default=True,
host="smtp.other.example.com",
use_ssl=False,
use_tls=False,
)
self.email_config.refresh_from_db()
self.assertFalse(self.email_config.is_default)
self.assertEqual(DeliveryEmailConfig.get_default().pk, second.pk)
def test_ssl_and_tls_together_are_rejected(self):
config = DeliveryEmailConfig(
name="bad",
channel=DeliveryChannel.EMAIL,
host="smtp.example.com",
use_ssl=True,
use_tls=True,
)
with self.assertRaises(ValidationError):
config.full_clean()
with self.assertRaises(ValidationError):
config.save()
def test_new_email_config_defaults_to_starttls(self):
config = DeliveryEmailConfig(name="new", channel=DeliveryChannel.EMAIL, host="smtp.example.com")
self.assertFalse(config.use_ssl)
self.assertTrue(config.use_tls)
def test_markdown_filter_escapes_raw_html(self):
rendered = render("{{ text | markdown }}", {"text": "<script>alert(1)</script>"})
self.assertNotIn("<script>", rendered)
self.assertIn("&lt;script&gt;", rendered)
def test_expired_notifications_stay_until_the_cleanup_task(self):
old = Notification.objects.create(
title="old",
expires_at=timezone.now() - timedelta(minutes=1),
)
from notify.tasks import delete_expired_notifications
deleted = delete_expired_notifications()
self.assertEqual(deleted, 1)
self.assertFalse(Notification.objects.filter(pk=old.pk).exists())
def test_cleanup_keeps_notifications_that_have_not_expired(self):
fresh = Notification.objects.create(title="fresh")
from notify.tasks import delete_expired_notifications
self.assertEqual(delete_expired_notifications(), 0)
self.assertTrue(Notification.objects.filter(pk=fresh.pk).exists())
def test_expired_cleanup_is_scheduled_hourly(self):
from notify.tasks import BEAT_SCHEDULE
entry = BEAT_SCHEDULE["notify-delete-expired-notifications"]
self.assertEqual(entry["task"], "notify.tasks.delete_expired_notifications")
self.assertEqual(set(entry["schedule"].minute), {0})
def test_builtin_providers_are_registered(self):
self.assertIsNotNone(get_provider(DeliveryChannel.EMAIL))
self.assertIsNotNone(get_provider(DeliveryChannel.BROWSER))
self.assertIsNotNone(get_provider(DeliveryChannel.MAX))
self.assertIsNotNone(get_provider(DeliveryChannel.TELEGRAM))
self.assertIsNotNone(get_provider(DeliveryChannel.SMS))
self.assertIsNone(get_provider("push"))
with self.assertRaisesMessage(KeyError, "push"):
get_provider_or_raise("push")
self.assertCountEqual(
list(registered_channels()),
[
DeliveryChannel.EMAIL,
DeliveryChannel.BROWSER,
DeliveryChannel.MAX,
DeliveryChannel.TELEGRAM,
DeliveryChannel.SMS,
],
)
def test_missing_recipient_is_a_no_op(self):
result = deliver_notification.apply(args=["999999"], throw=True)
self.assertEqual(result.state, "SUCCESS")
def test_failed_recipient_is_not_sent_again(self):
recipient = self._email_recipient()
recipient.status = DeliveryStatus.FAILED
recipient.save(update_fields=["status"])
with patch("notify.delivery.providers.email.EmailMessage.send") as send:
deliver_notification.apply(args=[str(recipient.id)], throw=True)
send.assert_not_called()
self.assertEqual(len(mail.outbox), 0)
def test_unknown_channel_fails_without_retry(self):
notification = Notification.objects.create(title="Hello", description="Body")
recipient = NotificationRecipient.objects.create(
notification=notification,
user=self.user,
channel="push",
)
deliver_notification.apply(args=[str(recipient.id)], throw=True)
recipient.refresh_from_db()
self.assertEqual(recipient.status, DeliveryStatus.FAILED)
def test_invalid_email_message_is_not_retried(self):
recipient = self._email_recipient()
with patch(
"notify.delivery.providers.email.EmailMessage.send",
side_effect=ValueError("bad"),
) as send:
deliver_notification.apply(args=[str(recipient.id)], throw=True)
self.assertEqual(send.call_count, 1)
recipient.refresh_from_db()
self.assertEqual(recipient.status, DeliveryStatus.FAILED)
def test_unaccepted_email_is_retried(self):
recipient = self._email_recipient()
with patch("notify.delivery.providers.email.EmailMessage.send", return_value=0) as send:
result = deliver_notification.apply(args=[str(recipient.id)], throw=False)
self.assertEqual(result.state, "FAILURE")
self.assertEqual(send.call_count, 6)
recipient.refresh_from_db()
self.assertEqual(recipient.status, DeliveryStatus.FAILED)
def test_typed_template_wins_over_the_channel_default(self):
group = NotificationGroup.objects.create(code="orders", name="Orders")
kind = NotificationType.objects.create(
code="approved",
name="Approved",
group=group,
channels=[DeliveryChannel.EMAIL],
title="Approved",
)
NotificationTemplate.objects.create(
channel=DeliveryChannel.EMAIL,
name="email-default",
is_default=True,
subject="default {{ notification.title }}",
body="DEFAULT {{ notification.url }}",
)
NotificationTemplate.objects.create(
channel=DeliveryChannel.EMAIL,
notification_type=kind,
name="approved-email",
subject="typed {{ notification.title }}",
body="TYPED {{ notification.url }}",
)
recipient = self._email_recipient(
notification_type=kind,
title="Approved",
url="https://example.com/orders/9",
description="plain",
)
deliver_notification.apply(args=[str(recipient.id)], throw=True)
self.assertEqual(mail.outbox[0].subject, "typed Approved")
self.assertIn("TYPED https://example.com/orders/9", mail.outbox[0].body)
self.assertNotIn("DEFAULT", mail.outbox[0].body)
def test_email_ignores_another_channels_template(self):
NotificationTemplate.objects.create(
channel=DeliveryChannel.MAX,
name="max-only",
is_default=True,
body="MAX-ONLY {{ notification.title }}",
)
recipient = self._email_recipient(title="Approved", description="plain")
deliver_notification.apply(args=[str(recipient.id)], throw=True)
self.assertNotIn("MAX-ONLY", mail.outbox[0].body)
self.assertIn("plain", mail.outbox[0].body)
def test_max_message_is_sent_and_marked(self):
recipient = self._max_recipient({"chat_id": 15, "user_id": 4})
response = requests.Response()
response.status_code = 200
with patch("notify.delivery.providers.max.requests.post", return_value=response) as post:
deliver_notification.apply(args=[str(recipient.id)], throw=True)
self.assertEqual(post.call_count, 1)
self.assertEqual(post.call_args.kwargs["params"], {"user_id": 4})
self.assertEqual(post.call_args.kwargs["json"]["chat_id"], 15)
self.assertEqual(post.call_args.kwargs["headers"]["Authorization"], "token")
self.assertEqual(post.call_args.kwargs["timeout"], MAX_API_TIMEOUT)
self.assertIn("Body", post.call_args.kwargs["json"]["text"])
recipient.refresh_from_db()
self.assertEqual(recipient.status, DeliveryStatus.SENT)
def test_max_without_user_id_uses_chat_id(self):
recipient = self._max_recipient()
response = requests.Response()
response.status_code = 200
with patch("notify.delivery.providers.max.requests.post", return_value=response) as post:
deliver_notification.apply(args=[str(recipient.id)], throw=True)
self.assertEqual(post.call_args.kwargs["params"], {"chat_id": -10})
recipient.refresh_from_db()
self.assertEqual(recipient.status, DeliveryStatus.SENT)
def test_max_without_chat_id_is_permanent(self):
recipient = self._max_recipient({})
with patch("notify.delivery.providers.max.requests.post") as post:
deliver_notification.apply(args=[str(recipient.id)], throw=True)
post.assert_not_called()
recipient.refresh_from_db()
self.assertEqual(recipient.status, DeliveryStatus.FAILED)
def test_missing_max_config_is_retried(self):
notification = Notification.objects.create(title="Hello", description="Body")
recipient = NotificationRecipient.objects.create(
notification=notification,
user=self.user,
channel=DeliveryChannel.MAX,
target={"chat_id": -10},
)
result = deliver_notification.apply(args=[str(recipient.id)], throw=False)
self.assertEqual(result.state, "FAILURE")
recipient.refresh_from_db()
self.assertEqual(recipient.status, DeliveryStatus.FAILED)
def test_max_timeout_is_retried(self):
recipient = self._max_recipient()
with patch(
"notify.delivery.providers.max.requests.post",
side_effect=requests.Timeout(),
) as post:
result = deliver_notification.apply(args=[str(recipient.id)], throw=False)
self.assertEqual(result.state, "FAILURE")
self.assertEqual(post.call_count, 6)
recipient.refresh_from_db()
self.assertEqual(recipient.status, DeliveryStatus.FAILED)
def test_max_network_error_is_retried(self):
recipient = self._max_recipient()
with patch(
"notify.delivery.providers.max.requests.post",
side_effect=requests.ConnectionError("down"),
) as post:
result = deliver_notification.apply(args=[str(recipient.id)], throw=False)
self.assertEqual(result.state, "FAILURE")
self.assertEqual(post.call_count, 6)
recipient.refresh_from_db()
self.assertEqual(recipient.status, DeliveryStatus.FAILED)
def test_telegram_message_is_sent_and_marked(self):
DeliveryTokenConfig.objects.create(
name="telegram",
channel=DeliveryChannel.TELEGRAM,
is_default=True,
token="bot-token",
)
notification = create_notification(
title="Hello",
description="Body",
recipients=[
{
"user": self.user,
"channels": [{"channel": DeliveryChannel.TELEGRAM, "target": {"chat_id": 42}}],
}
],
)
recipient = notification.recipients.get()
response = requests.Response()
response.status_code = 200
with patch("notify.delivery.providers.telegram.requests.post", return_value=response) as post:
deliver_notification.apply(args=[str(recipient.id)], throw=True)
self.assertEqual(post.call_count, 1)
self.assertEqual(
post.call_args.args[0],
"https://api.telegram.org/botbot-token/sendMessage",
)
self.assertEqual(post.call_args.kwargs["json"]["chat_id"], 42)
self.assertIn("Body", post.call_args.kwargs["json"]["text"])
self.assertEqual(post.call_args.kwargs["timeout"], TELEGRAM_API_TIMEOUT)
recipient.refresh_from_db()
self.assertEqual(recipient.status, DeliveryStatus.SENT)
self.assertEqual(recipient.attempts, 1)
def test_telegram_requires_target(self):
with self.assertRaisesMessage(ValueError, "target is required"):
create_notification(
title="Hi",
recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.TELEGRAM}]},
],
)
self.assertEqual(Notification.objects.count(), 0)
def test_telegram_client_error_is_not_retried(self):
DeliveryTokenConfig.objects.create(
name="telegram",
channel=DeliveryChannel.TELEGRAM,
is_default=True,
token="bot-token",
)
notification = Notification.objects.create(title="Hello", description="Body")
recipient = NotificationRecipient.objects.create(
notification=notification,
user=self.user,
channel=DeliveryChannel.TELEGRAM,
target={"chat_id": 42},
)
response = requests.Response()
response.status_code = 400
error = requests.HTTPError("bad request")
error.response = response
with patch("notify.delivery.providers.telegram.requests.post") as post:
post.return_value.raise_for_status.side_effect = error
deliver_notification.apply(args=[str(recipient.id)], throw=True)
self.assertEqual(post.call_count, 1)
recipient.refresh_from_db()
self.assertEqual(recipient.status, DeliveryStatus.FAILED)
self.assertEqual(recipient.attempts, 1)
self.assertIn("400", recipient.last_error)
def test_telegram_timeout_is_retried(self):
DeliveryTokenConfig.objects.create(
name="telegram",
channel=DeliveryChannel.TELEGRAM,
is_default=True,
token="bot-token",
)
notification = Notification.objects.create(title="Hello", description="Body")
recipient = NotificationRecipient.objects.create(
notification=notification,
user=self.user,
channel=DeliveryChannel.TELEGRAM,
target={"chat_id": 42},
)
with patch(
"notify.delivery.providers.telegram.requests.post",
side_effect=requests.Timeout(),
) as post:
result = deliver_notification.apply(args=[str(recipient.id)], throw=False)
self.assertEqual(result.state, "FAILURE")
self.assertEqual(post.call_count, 6)
recipient.refresh_from_db()
self.assertEqual(recipient.status, DeliveryStatus.FAILED)
self.assertEqual(recipient.attempts, 6)
def test_email_without_user_is_sent(self):
patient = NotificationGroup.objects.create(code="patient", name="Patient")
NotificationTemplate.objects.create(
channel=DeliveryChannel.EMAIL,
name="external",
is_default=True,
subject="{{ recipient.content_type }}",
body="{% if user %}user{% else %}guest{% endif %} {{ recipient.object_id }}",
)
notification = create_notification(
title="Hello",
description="Body",
recipients=[
{
"content_object": patient,
"channels": [{"channel": DeliveryChannel.EMAIL, "target": {"email": "guest@example.com"}}],
}
],
)
recipient = notification.recipients.get()
self.assertIsNone(recipient.user_id)
deliver_notification.apply(args=[str(recipient.id)], throw=True)
self.assertEqual(mail.outbox[0].to, ["guest@example.com"])
self.assertEqual(mail.outbox[0].subject, "notify.notificationgroup")
self.assertIn("guest", mail.outbox[0].body)
self.assertIn(str(patient.pk), mail.outbox[0].body)
recipient.refresh_from_db()
self.assertEqual(recipient.status, DeliveryStatus.SENT)
def test_sms_without_user_is_sent(self):
DeliveryTokenConfig.objects.create(
name="sms",
channel=DeliveryChannel.SMS,
is_default=True,
token="sms-token",
sender="MTS",
)
notification = create_notification(
title="Hello",
description="Body",
recipients=[
{"channels": [{"channel": DeliveryChannel.SMS, "target": {"phone": "79991234567"}}]},
],
)
recipient = notification.recipients.get()
response = requests.Response()
response.status_code = 200
with patch("notify.delivery.providers.exolve.requests.post", return_value=response) as post:
deliver_notification.apply(args=[str(recipient.id)], throw=True)
self.assertEqual(post.call_args.kwargs["json"]["destination"], "79991234567")
self.assertEqual(post.call_args.kwargs["json"]["number"], "MTS")
recipient.refresh_from_db()
self.assertEqual(recipient.status, DeliveryStatus.SENT)
def test_max_without_user_is_sent(self):
DeliveryTokenConfig.objects.create(
name="max",
channel=DeliveryChannel.MAX,
is_default=True,
token="token",
)
notification = create_notification(
title="Hello",
description="Body",
recipients=[
{"channels": [{"channel": DeliveryChannel.MAX, "target": {"chat_id": -5}}]},
],
)
recipient = notification.recipients.get()
response = requests.Response()
response.status_code = 200
with patch("notify.delivery.providers.max.requests.post", return_value=response) as post:
deliver_notification.apply(args=[str(recipient.id)], throw=True)
self.assertEqual(post.call_args.kwargs["params"], {"chat_id": -5})
recipient.refresh_from_db()
self.assertEqual(recipient.status, DeliveryStatus.SENT)
def test_sms_message_is_sent_and_marked(self):
DeliveryTokenConfig.objects.create(
name="sms",
channel=DeliveryChannel.SMS,
is_default=True,
token="sms-token",
sender="MTS",
)
notification = create_notification(
title="Hello",
description="Body",
recipients=[
{
"user": self.user,
"channels": [{"channel": DeliveryChannel.SMS, "target": {"phone": "+7 (999) 123-45-67"}}],
}
],
)
recipient = notification.recipients.get()
self.assertEqual(recipient.target, {"phone": "79991234567"})
response = requests.Response()
response.status_code = 200
with patch("notify.delivery.providers.exolve.requests.post", return_value=response) as post:
deliver_notification.apply(args=[str(recipient.id)], throw=True)
self.assertEqual(post.call_count, 1)
self.assertEqual(post.call_args.args[0], EXOLVE_SMS_URL)
self.assertEqual(post.call_args.kwargs["headers"]["Authorization"], "Bearer sms-token")
self.assertEqual(post.call_args.kwargs["timeout"], EXOLVE_API_TIMEOUT)
self.assertEqual(
post.call_args.kwargs["json"],
{"number": "MTS", "destination": "79991234567", "text": "Hello\nBody"},
)
recipient.refresh_from_db()
self.assertEqual(recipient.status, DeliveryStatus.SENT)
self.assertEqual(recipient.attempts, 1)
def test_sms_requires_target(self):
with self.assertRaisesMessage(ValueError, "target is required"):
create_notification(
title="Hi",
recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.SMS}]},
],
)
self.assertEqual(Notification.objects.count(), 0)
def test_sms_rejects_a_short_phone(self):
with self.assertRaisesMessage(ValueError, "10 to 15 digits"):
create_notification(
title="Hi",
recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.SMS, "target": {"phone": "123"}}]},
],
)
self.assertEqual(Notification.objects.count(), 0)
def test_sms_client_error_is_not_retried(self):
DeliveryTokenConfig.objects.create(
name="sms",
channel=DeliveryChannel.SMS,
is_default=True,
token="sms-token",
sender="MTS",
)
notification = Notification.objects.create(title="Hello", description="Body")
recipient = NotificationRecipient.objects.create(
notification=notification,
user=self.user,
channel=DeliveryChannel.SMS,
target={"phone": "79991234567"},
)
response = requests.Response()
response.status_code = 400
error = requests.HTTPError("bad request")
error.response = response
with patch("notify.delivery.providers.exolve.requests.post") as post:
post.return_value.raise_for_status.side_effect = error
deliver_notification.apply(args=[str(recipient.id)], throw=True)
self.assertEqual(post.call_count, 1)
recipient.refresh_from_db()
self.assertEqual(recipient.status, DeliveryStatus.FAILED)
self.assertEqual(recipient.attempts, 1)
self.assertIn("400", recipient.last_error)
def test_sms_timeout_is_retried(self):
DeliveryTokenConfig.objects.create(
name="sms",
channel=DeliveryChannel.SMS,
is_default=True,
token="sms-token",
sender="MTS",
)
notification = Notification.objects.create(title="Hello", description="Body")
recipient = NotificationRecipient.objects.create(
notification=notification,
user=self.user,
channel=DeliveryChannel.SMS,
target={"phone": "79991234567"},
)
with patch(
"notify.delivery.providers.exolve.requests.post",
side_effect=requests.Timeout(),
) as post:
result = deliver_notification.apply(args=[str(recipient.id)], throw=False)
self.assertEqual(result.state, "FAILURE")
self.assertEqual(post.call_count, 6)
recipient.refresh_from_db()
self.assertEqual(recipient.status, DeliveryStatus.FAILED)
self.assertEqual(recipient.attempts, 6)
def test_sms_without_sender_is_retried(self):
DeliveryTokenConfig.objects.create(
name="sms",
channel=DeliveryChannel.SMS,
is_default=True,
token="sms-token",
)
notification = Notification.objects.create(title="Hello", description="Body")
recipient = NotificationRecipient.objects.create(
notification=notification,
user=self.user,
channel=DeliveryChannel.SMS,
target={"phone": "79991234567"},
)
with patch("notify.delivery.providers.exolve.requests.post") as post:
result = deliver_notification.apply(args=[str(recipient.id)], throw=False)
post.assert_not_called()
self.assertEqual(result.state, "FAILURE")
recipient.refresh_from_db()
self.assertEqual(recipient.status, DeliveryStatus.FAILED)
self.assertEqual(recipient.attempts, 6)
self.assertIn("sender", recipient.last_error)
def test_markdown_filter_renders_fenced_code(self):
rendered = render("{{ text | markdown }}", {"text": "```\nprint(1)\n```"})
self.assertIn("<code>", rendered)
self.assertIn("print(1)", rendered)