notify/tests/test_services.py

602 lines
23 KiB
Python

from datetime import timedelta
from unittest.mock import patch
from django.contrib.auth import get_user_model
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],
verb="Approved",
)
def test_type_supplies_the_verb_and_links_the_row(self):
notification = create_notification(
type=self.kind,
recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
],
)
self.assertEqual(notification.verb, "Approved")
self.assertEqual(notification.type, self.kind)
self.assertEqual(notification.level, NotificationLevel.INFO)
self.assertEqual(notification.data, {})
self.assertEqual(notification.object_id, "")
recipient = notification.recipients.get()
self.assertEqual(recipient.delivery_status, DeliveryStatus.SENT)
self.assertTrue(recipient.unread)
def test_code_resolves_to_the_same_type(self):
notification = create_notification(
type="approved",
recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
],
)
self.assertEqual(notification.type, self.kind)
self.assertEqual(notification.verb, "Approved")
def test_explicit_fields_override_the_type(self):
when = timezone.now() + timedelta(days=2)
notification = create_notification(
type="approved",
verb="Custom",
url="https://example.com/orders/9?x=1",
level=NotificationLevel.ERROR,
object_id="9",
description="Done",
data={"n": 1},
expires_at=when,
recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
],
)
self.assertEqual(notification.verb, "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.object_id, "9")
self.assertEqual(notification.description, "Done")
self.assertEqual(notification.data, {"n": 1})
self.assertEqual(notification.expires_at, when)
def test_verb_is_required(self):
self.kind.verb = ""
self.kind.save(update_fields=["verb"])
with self.assertRaisesMessage(ValueError, "verb is required"):
create_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(
type="missing",
verb="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(verb="Hi", recipients=[])
self.assertEqual(Notification.objects.count(), 0)
def test_recipient_without_channels_rolls_back(self):
with self.assertRaisesMessage(ValueError, "no channels"):
create_notification(
verb="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(
verb="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(
verb="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(
verb="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(
verb="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(
verb="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(
verb="Hi",
recipients=[
{
"user": self.user,
"channels": [{"channel": DeliveryChannel.EMAIL, "target": {"email": "alice@example.com"}}],
}
],
)
self.assertEqual(notification.recipients.get().delivery_target, {"email": "alice@example.com"})
def test_browser_rejects_target(self):
with self.assertRaisesMessage(ValueError, "target is not supported"):
create_notification(
verb="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(
verb="Hi",
recipients=[
{
"user": self.user,
"channels": [{"channel": DeliveryChannel.MAX, "target": {"chat_id": -5}}],
}
],
)
self.assertEqual(
notification.recipients.get().delivery_target,
{"chat_id": -5, "user_id": None},
)
self.assertEqual(notification.recipients.get().delivery_status, DeliveryStatus.UNSENT)
def test_max_user_and_chat_are_stored(self):
notification = create_notification(
verb="Hi",
recipients=[
{
"user": self.other,
"channels": [
{
"channel": DeliveryChannel.MAX,
"target": {"chat_id": 3, "user_id": 8},
}
],
}
],
)
self.assertEqual(
notification.recipients.get().delivery_target,
{"chat_id": 3, "user_id": 8},
)
def test_max_requires_target(self):
with self.assertRaisesMessage(ValueError, "target is required"):
create_notification(
verb="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(
verb="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(
verb="Hi",
recipients=[
{
"user": self.user,
"channels": [
{
"channel": DeliveryChannel.MAX,
"target": {"chat_id": -1, "user_id": 2},
}
],
}
],
)
self.assertEqual(Notification.objects.count(), 0)
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(
verb="Hi",
recipients=[
{
"user": self.user,
"channels": [
{
"channel": DeliveryChannel.EMAIL,
"target": {"email": "alice@example.com"},
},
{"channel": DeliveryChannel.BROWSER},
],
}
],
)
email = notification.recipients.get(delivery_channel=DeliveryChannel.EMAIL)
browser = notification.recipients.get(delivery_channel=DeliveryChannel.BROWSER)
self.assertEqual(email.delivery_status, DeliveryStatus.UNSENT)
self.assertEqual(browser.delivery_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(
verb="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(
verb="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],
verb="Approved",
can_switch=True,
)
def test_disabled_channel_is_omitted_and_an_empty_result_rolls_back(self):
NotificationChannelPreference.objects.create(
user=self.user,
type=self.kind,
channel=DeliveryChannel.EMAIL,
enabled=False,
)
notification = create_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("delivery_channel", flat=True)),
[DeliveryChannel.BROWSER],
)
NotificationChannelPreference.objects.create(
user=self.user,
type=self.kind,
channel=DeliveryChannel.BROWSER,
enabled=False,
)
with self.assertRaisesMessage(ValueError, "No recipients to deliver"):
create_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(
type="approved",
recipients=[
{
"user": self.user,
"channels": [
{"channel": DeliveryChannel.EMAIL, "target": {"email": self.user.email}},
],
}
],
)
self.assertEqual(notification.recipients.get().delivery_channel, DeliveryChannel.EMAIL)
def test_locked_type_ignores_a_disabled_preference(self):
self.kind.can_switch = False
self.kind.save(update_fields=["can_switch"])
NotificationChannelPreference.objects.create(
user=self.user,
type=self.kind,
channel=DeliveryChannel.EMAIL,
enabled=False,
)
notification = create_notification(
type="approved",
recipients=[
{
"user": self.user,
"channels": [
{"channel": DeliveryChannel.EMAIL, "target": {"email": self.user.email}},
],
}
],
)
self.assertEqual(notification.recipients.get().delivery_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],
can_switch=False,
)
self.assertEqual(
channel_preferences(self.user),
[
{
"code": "approved",
"channels": [
{"channel": DeliveryChannel.EMAIL, "enabled": True},
{"channel": DeliveryChannel.BROWSER, "enabled": True},
],
}
],
)
save_channel_preferences(
self.user,
[
{
"code": "approved",
"channels": [
{"channel": DeliveryChannel.EMAIL, "enabled": False},
{"channel": DeliveryChannel.BROWSER, "enabled": True},
],
}
],
)
self.assertFalse(
NotificationChannelPreference.objects.get(
user=self.user,
type=self.kind,
channel=DeliveryChannel.EMAIL,
).enabled
)
self.assertEqual(channel_preferences(self.user)[0]["channels"][0]["enabled"], False)
with self.assertRaisesMessage(ValueError, "not allowed"):
save_channel_preferences(
self.user,
[{"code": "approved", "channels": [{"channel": DeliveryChannel.MAX, "enabled": True}]}],
)
with self.assertRaises(NotificationType.DoesNotExist):
save_channel_preferences(
self.user,
[{"code": hidden.code, "channels": [{"channel": DeliveryChannel.EMAIL, "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],
verb="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(
type=self.kind,
object_id="post-9",
verb="Новый комментарий",
group=True,
recipients=self._recipients(),
)
self.assertEqual(apply_async.call_count, 1)
with self.captureOnCommitCallbacks(execute=True):
second = create_notification(
type=self.kind,
object_id="post-9",
verb="Ещё комментарий",
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.verb, "Ещё комментарий")
self.assertEqual(Notification.objects.count(), 1)
self.assertEqual(second.recipients.count(), 2)
def test_group_starts_over_after_the_browser_row_is_read(self):
first = create_notification(
type=self.kind,
object_id="post-9",
group=True,
recipients=self._recipients(),
)
first.recipients.filter(delivery_channel=DeliveryChannel.BROWSER).update(unread=False)
second = create_notification(
type=self.kind,
object_id="post-9",
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(
type=self.kind,
idempotency_key="approved:9",
recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
)
second = create_notification(
type=self.kind,
verb="Other",
idempotency_key="approved:9",
group=True,
object_id="post-9",
recipients=self._recipients(),
)
self.assertEqual(second.pk, first.pk)
self.assertEqual(second.verb, first.verb)
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(verb="Hi", idempotency_key="race")
with patch(
"notify.services._existing_idempotent",
side_effect=[None, existing],
):
returned = create_notification(
verb="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)