627 lines
26 KiB
Python
627 lines
26 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.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(
|
|
verb=notification_kwargs.pop("verb", "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, delivery_target=None):
|
|
DeliveryTokenConfig.objects.create(
|
|
name="max",
|
|
channel=DeliveryChannel.MAX,
|
|
is_default=True,
|
|
token="token",
|
|
)
|
|
notification = Notification.objects.create(verb="Hello", description="Body")
|
|
return NotificationRecipient.objects.create(
|
|
notification=notification,
|
|
user=self.user,
|
|
delivery_channel=DeliveryChannel.MAX,
|
|
delivery_target={"chat_id": -10} if delivery_target is None else delivery_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.delivery_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.delivery_status, DeliveryStatus.FAILED)
|
|
|
|
def test_missing_address_is_permanent_failure(self):
|
|
notification = Notification.objects.create(verb="Hello", description="Body")
|
|
recipient = NotificationRecipient.objects.create(
|
|
notification=notification,
|
|
user=self.user,
|
|
delivery_channel=DeliveryChannel.EMAIL,
|
|
delivery_target=None,
|
|
)
|
|
deliver_notification.apply(args=[str(recipient.id)], throw=True)
|
|
recipient.refresh_from_db()
|
|
self.assertEqual(recipient.delivery_status, DeliveryStatus.FAILED)
|
|
|
|
def test_successful_email_is_sent_once_and_escapes_html(self):
|
|
recipient = self._email_recipient(
|
|
verb="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.delivery_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("<script>", 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_template="{{ notification.verb }}",
|
|
body_template="hash={{ user.password }} verb={{ notification.verb }}",
|
|
)
|
|
recipient = self._email_recipient(verb="Approved", description="<b>x</b>")
|
|
deliver_notification.apply(args=[str(recipient.id)], throw=True)
|
|
body = mail.outbox[0].body
|
|
self.assertIn("verb=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],
|
|
verb="Approved",
|
|
)
|
|
with self.assertRaisesMessage(ValueError, "not allowed"):
|
|
create_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(
|
|
verb="Ping",
|
|
recipients=[
|
|
{"user": self.user, "channels": [{"channel": "sms"}]},
|
|
],
|
|
)
|
|
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],
|
|
verb="Approved",
|
|
is_active=False,
|
|
)
|
|
with self.assertRaisesMessage(ValueError, "inactive"):
|
|
create_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(
|
|
verb="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(verb="Hello")
|
|
NotificationRecipient.objects.create(
|
|
notification=notification,
|
|
user=self.user,
|
|
delivery_channel=DeliveryChannel.EMAIL,
|
|
delivery_target={"email": "alice@example.com"},
|
|
)
|
|
with self.assertRaises(IntegrityError):
|
|
with transaction.atomic():
|
|
NotificationRecipient.objects.create(
|
|
notification=notification,
|
|
user=self.user,
|
|
delivery_channel=DeliveryChannel.EMAIL,
|
|
delivery_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(verb="Hello", description="Body")
|
|
recipient = NotificationRecipient.objects.create(
|
|
notification=notification,
|
|
user=self.user,
|
|
delivery_channel=DeliveryChannel.MAX,
|
|
delivery_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.delivery_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(verb="Hello", description="Body")
|
|
recipient = NotificationRecipient.objects.create(
|
|
notification=notification,
|
|
user=self.user,
|
|
delivery_channel=DeliveryChannel.MAX,
|
|
delivery_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.delivery_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("<script>", rendered)
|
|
|
|
def test_expired_notifications_stay_until_the_cleanup_task(self):
|
|
old = Notification.objects.create(
|
|
verb="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(verb="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.assertIsNone(get_provider("sms"))
|
|
with self.assertRaisesMessage(KeyError, "sms"):
|
|
get_provider_or_raise("sms")
|
|
self.assertCountEqual(
|
|
list(registered_channels()),
|
|
[
|
|
DeliveryChannel.EMAIL,
|
|
DeliveryChannel.BROWSER,
|
|
DeliveryChannel.MAX,
|
|
DeliveryChannel.TELEGRAM,
|
|
],
|
|
)
|
|
|
|
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.delivery_status = DeliveryStatus.FAILED
|
|
recipient.save(update_fields=["delivery_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(verb="Hello", description="Body")
|
|
recipient = NotificationRecipient.objects.create(
|
|
notification=notification,
|
|
user=self.user,
|
|
delivery_channel="sms",
|
|
)
|
|
deliver_notification.apply(args=[str(recipient.id)], throw=True)
|
|
recipient.refresh_from_db()
|
|
self.assertEqual(recipient.delivery_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.delivery_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.delivery_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],
|
|
verb="Approved",
|
|
)
|
|
NotificationTemplate.objects.create(
|
|
channel=DeliveryChannel.EMAIL,
|
|
name="email-default",
|
|
is_default=True,
|
|
subject_template="default {{ notification.verb }}",
|
|
body_template="DEFAULT {{ notification.url }}",
|
|
)
|
|
NotificationTemplate.objects.create(
|
|
channel=DeliveryChannel.EMAIL,
|
|
type=kind,
|
|
name="approved-email",
|
|
subject_template="typed {{ notification.verb }}",
|
|
body_template="TYPED {{ notification.url }}",
|
|
)
|
|
recipient = self._email_recipient(
|
|
type=kind,
|
|
verb="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_template="MAX-ONLY {{ notification.verb }}",
|
|
)
|
|
recipient = self._email_recipient(verb="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.delivery_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.delivery_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.delivery_status, DeliveryStatus.FAILED)
|
|
|
|
def test_missing_max_config_is_retried(self):
|
|
notification = Notification.objects.create(verb="Hello", description="Body")
|
|
recipient = NotificationRecipient.objects.create(
|
|
notification=notification,
|
|
user=self.user,
|
|
delivery_channel=DeliveryChannel.MAX,
|
|
delivery_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.delivery_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.delivery_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.delivery_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(
|
|
verb="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.delivery_status, DeliveryStatus.SENT)
|
|
self.assertEqual(recipient.attempts, 1)
|
|
|
|
def test_telegram_requires_target(self):
|
|
with self.assertRaisesMessage(ValueError, "target is required"):
|
|
create_notification(
|
|
verb="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(verb="Hello", description="Body")
|
|
recipient = NotificationRecipient.objects.create(
|
|
notification=notification,
|
|
user=self.user,
|
|
delivery_channel=DeliveryChannel.TELEGRAM,
|
|
delivery_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.delivery_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(verb="Hello", description="Body")
|
|
recipient = NotificationRecipient.objects.create(
|
|
notification=notification,
|
|
user=self.user,
|
|
delivery_channel=DeliveryChannel.TELEGRAM,
|
|
delivery_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.delivery_status, DeliveryStatus.FAILED)
|
|
self.assertEqual(recipient.attempts, 6)
|
|
|
|
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)
|