notify/tests/test_services.py

784 lines
31 KiB
Python

from datetime import timedelta
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.core import mail
from django.test import TestCase
from django.utils import timezone
from notify.models import (
DeliveryChannel,
DeliveryStatus,
Notification,
NotificationChannelPreference,
NotificationGroup,
NotificationLevel,
NotificationRecipient,
NotificationType,
)
from notify.services import channel_preferences, create_notification, save_channel_preferences
User = get_user_model()
class CreateNotificationTests(TestCase):
def setUp(self):
self.user = User.objects.create_user("alice", "alice@example.com", "pass")
self.other = User.objects.create_user("bob", "bob@example.com", "pass")
self.group = NotificationGroup.objects.create(code="orders", name="Orders")
self.kind = NotificationType.objects.create(
code="approved",
name="Approved",
group=self.group,
channels=[DeliveryChannel.EMAIL, DeliveryChannel.BROWSER, DeliveryChannel.MAX],
title="Approved",
)
def test_type_supplies_the_verb_and_links_the_row(self):
notification = create_notification(
notification_type=self.kind,
recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
],
)
self.assertEqual(notification.title, "Approved")
self.assertEqual(notification.notification_type, self.kind)
self.assertEqual(notification.level, NotificationLevel.INFO)
self.assertEqual(notification.data, {})
self.assertIsNone(notification.content_type)
self.assertEqual(notification.object_id, "")
self.assertIsNone(notification.content_object)
recipient = notification.recipients.get()
self.assertEqual(recipient.status, DeliveryStatus.SENT)
self.assertTrue(recipient.unread)
def test_code_resolves_to_the_same_type(self):
notification = create_notification(
notification_type="approved",
recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
],
)
self.assertEqual(notification.notification_type, self.kind)
self.assertEqual(notification.title, "Approved")
def test_explicit_fields_override_the_type(self):
when = timezone.now() + timedelta(days=2)
notification = create_notification(
notification_type="approved",
title="Custom",
url="https://example.com/orders/9?x=1",
level=NotificationLevel.ERROR,
content_object=self.other,
description="Done",
data={"n": 1},
expires_at=when,
recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
],
)
self.assertEqual(notification.title, "Custom")
self.assertEqual(notification.url, "https://example.com/orders/9?x=1")
self.assertEqual(notification.relative_url, "/orders/9")
self.assertEqual(notification.level, NotificationLevel.ERROR)
self.assertEqual(notification.content_object, self.other)
self.assertEqual(notification.object_id, str(self.other.pk))
self.assertEqual(notification.description, "Done")
self.assertEqual(notification.data, {"n": 1})
self.assertEqual(notification.expires_at, when)
def test_title_is_required(self):
self.kind.title = ""
self.kind.save(update_fields=["title"])
with self.assertRaisesMessage(ValueError, "title is required"):
create_notification(
notification_type="approved",
recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
],
)
self.assertEqual(Notification.objects.count(), 0)
def test_unknown_type_creates_nothing(self):
with self.assertRaises(NotificationType.DoesNotExist):
create_notification(
notification_type="missing",
title="Hi",
recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
],
)
self.assertEqual(Notification.objects.count(), 0)
def test_empty_recipient_list_is_rejected(self):
with self.assertRaisesMessage(ValueError, "At least one recipient"):
create_notification(title="Hi", recipients=[])
self.assertEqual(Notification.objects.count(), 0)
def test_recipient_without_channels_rolls_back(self):
with self.assertRaisesMessage(ValueError, "no channels"):
create_notification(
title="Hi",
recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
{"user": self.other, "channels": []},
],
)
self.assertEqual(Notification.objects.count(), 0)
self.assertEqual(NotificationRecipient.objects.count(), 0)
def test_same_user_and_channel_twice_rolls_back(self):
with self.assertRaisesMessage(ValueError, "Duplicate"):
create_notification(
title="Hi",
recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
],
)
self.assertEqual(Notification.objects.count(), 0)
def test_each_user_gets_a_recipient(self):
notification = create_notification(
title="Hi",
recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
{"user": self.other, "channels": [{"channel": DeliveryChannel.BROWSER}]},
],
)
self.assertEqual(
set(notification.recipients.values_list("user_id", flat=True)),
{self.user.pk, self.other.pk},
)
def test_invalid_email_rolls_back(self):
with self.assertRaisesMessage(ValueError, "valid email"):
create_notification(
title="Hi",
recipients=[
{
"user": self.user,
"channels": [
{"channel": DeliveryChannel.BROWSER},
{"channel": DeliveryChannel.EMAIL, "target": {"email": "not-an-email"}},
],
}
],
)
self.assertEqual(Notification.objects.count(), 0)
self.assertEqual(NotificationRecipient.objects.count(), 0)
def test_blank_email_is_rejected(self):
with self.assertRaisesMessage(ValueError, "valid email"):
create_notification(
title="Hi",
recipients=[
{
"user": self.user,
"channels": [{"channel": DeliveryChannel.EMAIL, "target": {"email": " "}}],
}
],
)
self.assertEqual(Notification.objects.count(), 0)
def test_email_requires_target(self):
with self.assertRaisesMessage(ValueError, "target is required"):
create_notification(
title="Hi",
recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.EMAIL}]},
],
)
self.assertEqual(Notification.objects.count(), 0)
def test_email_target_is_stored(self):
notification = create_notification(
title="Hi",
recipients=[
{
"user": self.user,
"channels": [{"channel": DeliveryChannel.EMAIL, "target": {"email": "alice@example.com"}}],
}
],
)
recipient = notification.recipients.get()
self.assertEqual(recipient.target, {"email": "alice@example.com"})
def test_browser_rejects_target(self):
with self.assertRaisesMessage(ValueError, "target is not supported"):
create_notification(
title="Hi",
recipients=[
{
"user": self.user,
"channels": [{"channel": DeliveryChannel.BROWSER, "target": {"chat_id": 1}}],
}
],
)
self.assertEqual(Notification.objects.count(), 0)
def test_max_chat_is_stored(self):
notification = create_notification(
title="Hi",
recipients=[
{
"user": self.user,
"channels": [{"channel": DeliveryChannel.MAX, "target": {"chat_id": -5}}],
}
],
)
self.assertEqual(
notification.recipients.get().target,
{"chat_id": -5, "user_id": None},
)
self.assertEqual(notification.recipients.get().status, DeliveryStatus.UNSENT)
def test_max_user_and_chat_are_stored(self):
notification = create_notification(
title="Hi",
recipients=[
{
"user": self.other,
"channels": [
{
"channel": DeliveryChannel.MAX,
"target": {"chat_id": 3, "user_id": 8},
}
],
}
],
)
self.assertEqual(
notification.recipients.get().target,
{"chat_id": 3, "user_id": 8},
)
def test_max_requires_target(self):
with self.assertRaisesMessage(ValueError, "target is required"):
create_notification(
title="Hi",
recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.MAX}]},
],
)
self.assertEqual(Notification.objects.count(), 0)
def test_max_rejects_a_positive_chat_without_user(self):
with self.assertRaisesMessage(ValueError, "negative"):
create_notification(
title="Hi",
recipients=[
{
"user": self.user,
"channels": [{"channel": DeliveryChannel.MAX, "target": {"chat_id": 5}}],
}
],
)
self.assertEqual(Notification.objects.count(), 0)
def test_max_rejects_a_non_positive_pair(self):
with self.assertRaisesMessage(ValueError, "positive"):
create_notification(
title="Hi",
recipients=[
{
"user": self.user,
"channels": [
{
"channel": DeliveryChannel.MAX,
"target": {"chat_id": -1, "user_id": 2},
}
],
}
],
)
self.assertEqual(Notification.objects.count(), 0)
class ExternalRecipientTests(TestCase):
def test_address_only_recipient_has_no_user(self):
notification = create_notification(
title="Код",
recipients=[
{"channels": [{"channel": DeliveryChannel.SMS, "target": {"phone": "+79991234567"}}]},
],
)
recipient = notification.recipients.get()
self.assertIsNone(recipient.user_id)
self.assertIsNone(recipient.content_type)
self.assertEqual(recipient.target, {"phone": "79991234567"})
def test_content_object_is_stored_separately_from_the_notification_subject(self):
subject = User.objects.create_user("alice", "alice@example.com", "pass")
patient = NotificationGroup.objects.create(code="patient", name="Patient")
notification = create_notification(
title="Запись",
content_object=subject,
recipients=[
{
"content_object": patient,
"channels": [
{"channel": DeliveryChannel.SMS, "target": {"phone": "8 (999) 123-45-67"}},
{"channel": DeliveryChannel.EMAIL, "target": {"email": "patient@example.com"}},
{"channel": DeliveryChannel.MAX, "target": {"chat_id": -5}},
],
}
],
)
self.assertEqual(notification.content_object, subject)
rows = {row.channel: row for row in notification.recipients.all()}
self.assertEqual(
set(rows),
{DeliveryChannel.SMS, DeliveryChannel.EMAIL, DeliveryChannel.MAX},
)
for row in rows.values():
self.assertIsNone(row.user_id)
self.assertEqual(row.content_object, patient)
self.assertEqual(rows[DeliveryChannel.SMS].target, {"phone": "79991234567"})
def test_browser_without_user_does_not_create_a_notification(self):
with self.assertRaisesMessage(ValueError, "browser requires a user"):
create_notification(
title="Hi",
recipients=[{"channels": [{"channel": DeliveryChannel.BROWSER}]}],
)
self.assertEqual(Notification.objects.count(), 0)
def test_same_phone_without_a_user_is_not_a_duplicate(self):
notification = create_notification(
title="Ping",
recipients=[
{"channels": [{"channel": DeliveryChannel.SMS, "target": {"phone": "79991234567"}}]},
{"channels": [{"channel": DeliveryChannel.SMS, "target": {"phone": "8 999 123-45-67"}}]},
],
)
self.assertEqual(notification.recipients.count(), 2)
def test_unsaved_content_object_rolls_back(self):
patient = User(username="ghost")
with self.assertRaisesMessage(ValueError, "must be saved"):
create_notification(
title="Hi",
recipients=[
{
"content_object": patient,
"channels": [{"channel": DeliveryChannel.SMS, "target": {"phone": "79991234567"}}],
}
],
)
self.assertEqual(Notification.objects.count(), 0)
def test_group_does_not_collapse_a_recipient_without_a_user(self):
subject = NotificationGroup.objects.create(code="visit", name="Visit")
first = create_notification(
title="Hello",
content_object=subject,
group=True,
recipients=[
{"channels": [{"channel": DeliveryChannel.SMS, "target": {"phone": "79991234567"}}]},
],
)
second = create_notification(
title="Hello again",
content_object=subject,
group=True,
recipients=[
{"channels": [{"channel": DeliveryChannel.SMS, "target": {"phone": "79991234567"}}]},
],
)
self.assertNotEqual(first.pk, second.pk)
self.assertEqual(Notification.objects.count(), 2)
class DeliveryEnqueueTests(TestCase):
def setUp(self):
self.user = User.objects.create_user("alice", "alice@example.com", "pass")
def test_async_channels_are_enqueued_after_commit(self):
with patch("notify.tasks.deliver_notification.apply_async") as apply_async:
with self.captureOnCommitCallbacks(execute=True):
notification = create_notification(
title="Hi",
recipients=[
{
"user": self.user,
"channels": [
{
"channel": DeliveryChannel.EMAIL,
"target": {"email": "alice@example.com"},
},
{"channel": DeliveryChannel.BROWSER},
],
}
],
)
email = notification.recipients.get(channel=DeliveryChannel.EMAIL)
browser = notification.recipients.get(channel=DeliveryChannel.BROWSER)
self.assertEqual(email.status, DeliveryStatus.UNSENT)
self.assertEqual(browser.status, DeliveryStatus.SENT)
apply_async.assert_called_once_with(args=(str(email.id),))
self.assertEqual(len(mail.outbox), 0)
def test_browser_channel_is_not_enqueued(self):
with patch("notify.tasks.deliver_notification.apply_async") as apply_async:
with self.captureOnCommitCallbacks(execute=True):
create_notification(
title="Hi",
recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
],
)
apply_async.assert_not_called()
def test_failed_create_does_not_enqueue(self):
with patch("notify.tasks.deliver_notification.apply_async") as apply_async:
with self.captureOnCommitCallbacks(execute=True):
with self.assertRaisesMessage(ValueError, "Duplicate"):
create_notification(
title="Hi",
recipients=[
{
"user": self.user,
"channels": [
{
"channel": DeliveryChannel.EMAIL,
"target": {"email": "alice@example.com"},
},
{
"channel": DeliveryChannel.EMAIL,
"target": {"email": "alice@example.com"},
},
],
}
],
)
apply_async.assert_not_called()
self.assertEqual(Notification.objects.count(), 0)
class ChannelPreferenceTests(TestCase):
def setUp(self):
self.user = User.objects.create_user("alice", "alice@example.com", "pass")
self.other = User.objects.create_user("bob", "bob@example.com", "pass")
self.group = NotificationGroup.objects.create(code="orders", name="Orders")
self.kind = NotificationType.objects.create(
code="approved",
name="Approved",
group=self.group,
channels=[DeliveryChannel.EMAIL, DeliveryChannel.BROWSER],
title="Approved",
is_configurable=True,
)
def test_disabled_channel_is_omitted_and_an_empty_result_rolls_back(self):
NotificationChannelPreference.objects.create(
user=self.user,
notification_type=self.kind,
channel=DeliveryChannel.EMAIL,
is_enabled=False,
)
notification = create_notification(
notification_type="approved",
recipients=[
{
"user": self.user,
"channels": [
{"channel": DeliveryChannel.BROWSER},
{"channel": DeliveryChannel.EMAIL, "target": {"email": self.user.email}},
],
}
],
)
self.assertEqual(
list(notification.recipients.values_list("channel", flat=True)),
[DeliveryChannel.BROWSER],
)
NotificationChannelPreference.objects.create(
user=self.user,
notification_type=self.kind,
channel=DeliveryChannel.BROWSER,
is_enabled=False,
)
with self.assertRaisesMessage(ValueError, "No recipients to deliver"):
create_notification(
notification_type="approved",
recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
],
)
self.assertEqual(Notification.objects.count(), 1)
def test_missing_preference_keeps_the_channel(self):
notification = create_notification(
notification_type="approved",
recipients=[
{
"user": self.user,
"channels": [
{"channel": DeliveryChannel.EMAIL, "target": {"email": self.user.email}},
],
}
],
)
self.assertEqual(notification.recipients.get().channel, DeliveryChannel.EMAIL)
def test_missing_preference_drops_a_channel_disabled_by_default(self):
self.kind.is_enabled_by_default = False
self.kind.save(update_fields=["is_enabled_by_default"])
self.assertEqual(
channel_preferences(self.user)[0]["channels"],
[
{"channel": DeliveryChannel.EMAIL, "is_enabled": False},
{"channel": DeliveryChannel.BROWSER, "is_enabled": False},
],
)
with self.assertRaisesMessage(ValueError, "No recipients to deliver"):
create_notification(
notification_type="approved",
recipients=[
{
"user": self.user,
"channels": [
{"channel": DeliveryChannel.EMAIL, "target": {"email": self.user.email}},
],
}
],
)
self.assertEqual(Notification.objects.count(), 0)
NotificationChannelPreference.objects.create(
user=self.user,
notification_type=self.kind,
channel=DeliveryChannel.EMAIL,
is_enabled=True,
)
notification = create_notification(
notification_type="approved",
recipients=[
{
"user": self.user,
"channels": [
{"channel": DeliveryChannel.EMAIL, "target": {"email": self.user.email}},
],
}
],
)
self.assertEqual(notification.recipients.get().channel, DeliveryChannel.EMAIL)
def test_external_recipient_ignores_channel_preferences(self):
self.kind.channels = [DeliveryChannel.EMAIL, DeliveryChannel.SMS]
self.kind.is_enabled_by_default = False
self.kind.save(update_fields=["channels", "is_enabled_by_default"])
notification = create_notification(
notification_type=self.kind,
recipients=[
{"channels": [{"channel": DeliveryChannel.SMS, "target": {"phone": "79991234567"}}]},
],
)
self.assertEqual(notification.recipients.get().channel, DeliveryChannel.SMS)
def test_locked_type_ignores_a_disabled_preference(self):
self.kind.is_configurable = False
self.kind.save(update_fields=["is_configurable"])
NotificationChannelPreference.objects.create(
user=self.user,
notification_type=self.kind,
channel=DeliveryChannel.EMAIL,
is_enabled=False,
)
notification = create_notification(
notification_type="approved",
recipients=[
{
"user": self.user,
"channels": [
{"channel": DeliveryChannel.EMAIL, "target": {"email": self.user.email}},
],
}
],
)
self.assertEqual(notification.recipients.get().channel, DeliveryChannel.EMAIL)
def test_preference_screen_reads_and_writes_switchable_channels(self):
hidden = NotificationType.objects.create(
code="security",
name="Security",
group=self.group,
channels=[DeliveryChannel.EMAIL],
is_configurable=False,
)
self.assertEqual(
channel_preferences(self.user),
[
{
"code": "approved",
"channels": [
{"channel": DeliveryChannel.EMAIL, "is_enabled": True},
{"channel": DeliveryChannel.BROWSER, "is_enabled": True},
],
}
],
)
save_channel_preferences(
self.user,
[
{
"code": "approved",
"channels": [
{"channel": DeliveryChannel.EMAIL, "is_enabled": False},
{"channel": DeliveryChannel.BROWSER, "is_enabled": True},
],
}
],
)
self.assertFalse(
NotificationChannelPreference.objects.get(
user=self.user,
notification_type=self.kind,
channel=DeliveryChannel.EMAIL,
).is_enabled
)
self.assertEqual(channel_preferences(self.user)[0]["channels"][0]["is_enabled"], False)
with self.assertRaisesMessage(ValueError, "not allowed"):
save_channel_preferences(
self.user,
[{"code": "approved", "channels": [{"channel": DeliveryChannel.MAX, "is_enabled": True}]}],
)
with self.assertRaises(NotificationType.DoesNotExist):
save_channel_preferences(
self.user,
[{"code": hidden.code, "channels": [{"channel": DeliveryChannel.EMAIL, "is_enabled": False}]}],
)
class GroupingAndIdempotencyTests(TestCase):
def setUp(self):
self.user = User.objects.create_user("alice", "alice@example.com", "pass")
self.group = NotificationGroup.objects.create(code="posts", name="Posts")
self.kind = NotificationType.objects.create(
code="comment",
name="Comment",
group=self.group,
channels=[DeliveryChannel.BROWSER, DeliveryChannel.EMAIL],
title="Comment",
)
def _recipients(self):
return [
{
"user": self.user,
"channels": [
{"channel": DeliveryChannel.BROWSER},
{"channel": DeliveryChannel.EMAIL, "target": {"email": self.user.email}},
],
}
]
def test_group_bumps_the_unread_browser_notification_without_a_new_delivery(self):
with patch("notify.tasks.deliver_notification.apply_async") as apply_async:
with self.captureOnCommitCallbacks(execute=True):
first = create_notification(
notification_type=self.kind,
content_object=self.user,
title="Новый комментарий",
group=True,
recipients=self._recipients(),
)
self.assertEqual(apply_async.call_count, 1)
with self.captureOnCommitCallbacks(execute=True):
second = create_notification(
notification_type=self.kind,
content_object=self.user,
title="Ещё комментарий",
group=True,
recipients=self._recipients(),
)
self.assertEqual(apply_async.call_count, 1)
self.assertEqual(second.pk, first.pk)
second.refresh_from_db()
self.assertEqual(second.data["count"], 2)
self.assertEqual(second.title, "Ещё комментарий")
self.assertEqual(Notification.objects.count(), 1)
self.assertEqual(second.recipients.count(), 2)
def test_group_does_not_collapse_across_models_with_the_same_pk(self):
other_model = Group.objects.create(name="same-pk", pk=self.user.pk)
first = create_notification(
notification_type=self.kind,
content_object=self.user,
group=True,
recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
)
second = create_notification(
notification_type=self.kind,
content_object=other_model,
group=True,
recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
)
self.assertNotEqual(second.pk, first.pk)
self.assertEqual(second.object_id, first.object_id)
self.assertNotEqual(second.content_type_id, first.content_type_id)
def test_unsaved_content_object_is_rejected(self):
with self.assertRaisesMessage(ValueError, "content_object must be saved"):
create_notification(
notification_type=self.kind,
content_object=User(username="ghost"),
recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
)
self.assertEqual(Notification.objects.count(), 0)
def test_group_starts_over_after_the_browser_row_is_read(self):
first = create_notification(
notification_type=self.kind,
content_object=self.user,
group=True,
recipients=self._recipients(),
)
first.recipients.filter(channel=DeliveryChannel.BROWSER).update(unread=False)
second = create_notification(
notification_type=self.kind,
content_object=self.user,
group=True,
recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
)
self.assertNotEqual(second.pk, first.pk)
self.assertEqual(Notification.objects.count(), 2)
def test_same_idempotency_key_returns_the_original_row(self):
first = create_notification(
notification_type=self.kind,
idempotency_key="approved:9",
recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
)
second = create_notification(
notification_type=self.kind,
title="Other",
idempotency_key="approved:9",
group=True,
content_object=self.user,
recipients=self._recipients(),
)
self.assertEqual(second.pk, first.pk)
self.assertEqual(second.title, first.title)
self.assertEqual(Notification.objects.count(), 1)
self.assertEqual(second.recipients.count(), 1)
self.assertEqual(second.data, {})
def test_idempotency_conflict_returns_the_existing_row(self):
existing = Notification.objects.create(title="Hi", idempotency_key="race")
with patch(
"notify.services._existing_idempotent",
side_effect=[None, existing],
):
returned = create_notification(
title="Hi",
idempotency_key="race",
recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
)
self.assertEqual(returned.pk, existing.pk)
self.assertEqual(Notification.objects.count(), 1)
self.assertEqual(existing.recipients.count(), 0)