374 lines
14 KiB
Python
374 lines
14 KiB
Python
from django.apps import apps
|
||
from django.contrib.auth import get_user_model
|
||
from django.core import mail
|
||
from django.db.models.signals import post_migrate
|
||
from django.test import TestCase
|
||
|
||
from notify.models import (
|
||
DeliveryChannel,
|
||
DeliveryEmailConfig,
|
||
NotificationGroup,
|
||
NotificationTemplate,
|
||
NotificationType,
|
||
NotificationTypeRecipientGroup,
|
||
)
|
||
from notify.registry import (
|
||
GroupSpec,
|
||
RecipientGroupSpec,
|
||
TemplateSpec,
|
||
TypeSpec,
|
||
clear,
|
||
register,
|
||
sync_registered,
|
||
)
|
||
from notify.services import create_notification
|
||
from notify.tasks import deliver_notification
|
||
|
||
User = get_user_model()
|
||
|
||
|
||
def appointment_specs(
|
||
*,
|
||
group_name="Записи",
|
||
created_body="когда={{ notification.description }}",
|
||
created_templates=None,
|
||
):
|
||
if created_templates is None:
|
||
created_templates = (
|
||
TemplateSpec(
|
||
"email",
|
||
subject="Создана: {{ notification.title }}",
|
||
body=created_body,
|
||
),
|
||
TemplateSpec("telegram", subject="Запись", body="Новая запись"),
|
||
)
|
||
return (
|
||
GroupSpec("appointment", group_name),
|
||
TypeSpec(
|
||
code="appointment.created",
|
||
name="Запись создана",
|
||
group="appointment",
|
||
channels=("browser", "email", "telegram"),
|
||
title="Запись создана",
|
||
templates=created_templates,
|
||
),
|
||
TypeSpec(
|
||
code="appointment.confirmed",
|
||
name="Запись подтверждена",
|
||
group="appointment",
|
||
channels=("browser", "email"),
|
||
title="Запись подтверждена",
|
||
position=1,
|
||
templates=(
|
||
TemplateSpec("email", subject="Подтверждена", body="Запись подтверждена"),
|
||
),
|
||
),
|
||
TypeSpec(
|
||
code="appointment.cancelled",
|
||
name="Запись отменена",
|
||
group="appointment",
|
||
channels=("browser", "email"),
|
||
title="Запись отменена",
|
||
position=2,
|
||
templates=(
|
||
TemplateSpec("email", subject="Отменена", body="Запись отменена"),
|
||
),
|
||
),
|
||
TypeSpec(
|
||
code="appointment.reminder",
|
||
name="Напоминание о записи",
|
||
group="appointment",
|
||
channels=("browser", "email"),
|
||
title="Напоминание о записи",
|
||
position=3,
|
||
is_configurable=False,
|
||
templates=(
|
||
TemplateSpec("email", subject="Напоминание", body="Скоро запись"),
|
||
),
|
||
),
|
||
)
|
||
|
||
|
||
class RegistryTests(TestCase):
|
||
def setUp(self):
|
||
clear()
|
||
|
||
def tearDown(self):
|
||
clear()
|
||
|
||
def test_sync_creates_group_types_and_templates(self):
|
||
register(*appointment_specs())
|
||
register(*appointment_specs())
|
||
sync_registered()
|
||
first_ids = self._ids()
|
||
sync_registered()
|
||
|
||
self.assertEqual(self._ids(), first_ids)
|
||
group = NotificationGroup.objects.get(code="appointment")
|
||
self.assertEqual(group.name, "Записи")
|
||
self.assertEqual(
|
||
list(NotificationType.objects.filter(group=group).values_list("code", flat=True)),
|
||
[
|
||
"appointment.created",
|
||
"appointment.confirmed",
|
||
"appointment.cancelled",
|
||
"appointment.reminder",
|
||
],
|
||
)
|
||
created = NotificationType.objects.get(code="appointment.created")
|
||
self.assertEqual(created.channels, ["browser", "email", "telegram"])
|
||
self.assertEqual(created.title, "Запись создана")
|
||
email = created.templates.get(channel=DeliveryChannel.EMAIL)
|
||
self.assertEqual(email.name, "appointment.created.email")
|
||
self.assertEqual(email.subject, "Создана: {{ notification.title }}")
|
||
self.assertEqual(email.body, "когда={{ notification.description }}")
|
||
reminder = NotificationType.objects.get(code="appointment.reminder")
|
||
self.assertEqual(reminder.position, 3)
|
||
self.assertFalse(reminder.is_configurable)
|
||
self.assertEqual(NotificationTemplate.objects.filter(notification_type__group=group).count(), 5)
|
||
|
||
def test_sync_overwrites_template_body_and_keeps_the_row(self):
|
||
register(*appointment_specs())
|
||
sync_registered()
|
||
template = NotificationTemplate.objects.get(
|
||
notification_type__code="appointment.created",
|
||
channel=DeliveryChannel.EMAIL,
|
||
)
|
||
template.name = "custom-email"
|
||
template.save(update_fields=["name"])
|
||
|
||
clear()
|
||
register(*appointment_specs(group_name="Записи к врачу", created_body="обновлено"))
|
||
sync_registered()
|
||
|
||
template.refresh_from_db()
|
||
self.assertEqual(template.body, "обновлено")
|
||
self.assertEqual(template.name, "custom-email")
|
||
self.assertEqual(NotificationGroup.objects.get(code="appointment").name, "Записи к врачу")
|
||
|
||
def test_sync_deletes_template_removed_from_the_spec(self):
|
||
register(*appointment_specs())
|
||
sync_registered()
|
||
created = NotificationType.objects.get(code="appointment.created")
|
||
self.assertTrue(created.templates.filter(channel=DeliveryChannel.TELEGRAM).exists())
|
||
|
||
clear()
|
||
register(
|
||
*appointment_specs(
|
||
created_templates=(
|
||
TemplateSpec(
|
||
"email",
|
||
subject="Создана: {{ notification.title }}",
|
||
body="когда={{ notification.description }}",
|
||
),
|
||
)
|
||
)
|
||
)
|
||
sync_registered()
|
||
|
||
self.assertFalse(created.templates.filter(channel=DeliveryChannel.TELEGRAM).exists())
|
||
self.assertTrue(created.templates.filter(channel=DeliveryChannel.EMAIL).exists())
|
||
|
||
def test_sync_leaves_unregistered_rows(self):
|
||
group = NotificationGroup.objects.create(code="billing", name="Billing")
|
||
kind = NotificationType.objects.create(
|
||
code="invoice",
|
||
name="Invoice",
|
||
group=group,
|
||
channels=[DeliveryChannel.EMAIL],
|
||
title="Invoice",
|
||
)
|
||
typed = NotificationTemplate.objects.create(
|
||
name="invoice-email",
|
||
channel=DeliveryChannel.EMAIL,
|
||
notification_type=kind,
|
||
subject="Invoice",
|
||
body="Pay",
|
||
)
|
||
default = NotificationTemplate.objects.create(
|
||
name="default-email",
|
||
channel=DeliveryChannel.EMAIL,
|
||
is_default=True,
|
||
subject="Default",
|
||
body="Default body",
|
||
)
|
||
register(*appointment_specs())
|
||
sync_registered()
|
||
|
||
typed.refresh_from_db()
|
||
default.refresh_from_db()
|
||
kind.refresh_from_db()
|
||
self.assertEqual(typed.body, "Pay")
|
||
self.assertEqual(default.body, "Default body")
|
||
self.assertEqual(kind.name, "Invoice")
|
||
self.assertTrue(NotificationGroup.objects.filter(code="billing").exists())
|
||
|
||
def test_same_code_with_different_data_is_rejected(self):
|
||
register(*appointment_specs())
|
||
with self.assertRaisesMessage(ValueError, "already registered"):
|
||
register(
|
||
TypeSpec(
|
||
code="appointment.created",
|
||
name="Другое имя",
|
||
group="appointment",
|
||
channels=("browser",),
|
||
title="Другое",
|
||
)
|
||
)
|
||
with self.assertRaisesMessage(ValueError, "already registered"):
|
||
register(GroupSpec("appointment", "Другое"))
|
||
self.assertFalse(NotificationType.objects.exists())
|
||
|
||
def test_unknown_channel_is_rejected(self):
|
||
with self.assertRaisesMessage(ValueError, "Unknown channels"):
|
||
TypeSpec(
|
||
code="appointment.created",
|
||
name="Запись создана",
|
||
group="appointment",
|
||
channels=("fax",),
|
||
title="Запись создана",
|
||
)
|
||
|
||
def test_template_channel_must_belong_to_the_type(self):
|
||
with self.assertRaisesMessage(ValueError, "is not allowed"):
|
||
TypeSpec(
|
||
code="appointment.created",
|
||
name="Запись создана",
|
||
group="appointment",
|
||
channels=("browser",),
|
||
title="Запись создана",
|
||
templates=(TemplateSpec("email", subject="Тема", body="Текст"),),
|
||
)
|
||
|
||
def test_type_requires_a_registered_group(self):
|
||
with self.assertRaisesMessage(ValueError, "is not registered"):
|
||
register(
|
||
TypeSpec(
|
||
code="appointment.created",
|
||
name="Запись создана",
|
||
group="appointment",
|
||
channels=("browser",),
|
||
title="Запись создана",
|
||
)
|
||
)
|
||
|
||
def test_sync_writes_recipient_groups_and_drops_removed_ones(self):
|
||
register(
|
||
GroupSpec("appointment", "Записи"),
|
||
TypeSpec(
|
||
code="appointment.online",
|
||
name="Онлайн запись",
|
||
group="appointment",
|
||
channels=("browser",),
|
||
title="Онлайн-запись",
|
||
is_enabled_by_default=False,
|
||
recipient_groups=(
|
||
RecipientGroupSpec("registrars", is_configurable=False),
|
||
RecipientGroupSpec("doctors", is_enabled_by_default=False),
|
||
),
|
||
),
|
||
)
|
||
sync_registered()
|
||
kind = NotificationType.objects.get(code="appointment.online")
|
||
registrars = kind.recipient_groups.get(group_name="registrars")
|
||
self.assertFalse(registrars.is_configurable)
|
||
self.assertTrue(registrars.is_enabled_by_default)
|
||
self.assertFalse(kind.recipient_groups.get(group_name="doctors").is_enabled_by_default)
|
||
|
||
other = NotificationType.objects.create(
|
||
code="invoice",
|
||
name="Invoice",
|
||
group=NotificationGroup.objects.create(code="billing", name="Billing"),
|
||
channels=["browser"],
|
||
)
|
||
kept = NotificationTypeRecipientGroup.objects.create(
|
||
notification_type=other,
|
||
group_name="billing",
|
||
)
|
||
|
||
clear()
|
||
register(
|
||
GroupSpec("appointment", "Записи"),
|
||
TypeSpec(
|
||
code="appointment.online",
|
||
name="Онлайн запись",
|
||
group="appointment",
|
||
channels=("browser",),
|
||
title="Онлайн-запись",
|
||
recipient_groups=(
|
||
RecipientGroupSpec("registrars", is_configurable=True, is_enabled_by_default=False),
|
||
),
|
||
),
|
||
)
|
||
sync_registered()
|
||
|
||
registrars.refresh_from_db()
|
||
self.assertTrue(registrars.is_configurable)
|
||
self.assertFalse(registrars.is_enabled_by_default)
|
||
self.assertFalse(kind.recipient_groups.filter(group_name="doctors").exists())
|
||
kept.refresh_from_db()
|
||
self.assertEqual(kept.group_name, "billing")
|
||
|
||
def test_duplicate_recipient_group_is_rejected(self):
|
||
with self.assertRaisesMessage(ValueError, "Duplicate recipient group registrars"):
|
||
TypeSpec(
|
||
code="appointment.online",
|
||
name="Онлайн запись",
|
||
group="appointment",
|
||
channels=("browser",),
|
||
recipient_groups=(
|
||
RecipientGroupSpec("registrars"),
|
||
RecipientGroupSpec("registrars", is_configurable=False),
|
||
),
|
||
)
|
||
with self.assertRaisesMessage(ValueError, "Recipient group name is required"):
|
||
RecipientGroupSpec(" ")
|
||
|
||
def test_post_migrate_syncs_registered_types(self):
|
||
register(*appointment_specs())
|
||
receiver = next(
|
||
receiver
|
||
for (receiver_key, _), receiver, _is_async in post_migrate.receivers
|
||
if receiver_key == "notify.sync_registered"
|
||
)
|
||
receiver(sender=apps.get_app_config("notify"))
|
||
self.assertTrue(NotificationType.objects.filter(code="appointment.confirmed").exists())
|
||
|
||
def test_create_notification_uses_the_synced_email_template(self):
|
||
user = User.objects.create_user("alice", "alice@example.com", "pass")
|
||
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,
|
||
)
|
||
register(*appointment_specs())
|
||
sync_registered()
|
||
notification = create_notification(
|
||
notification_type="appointment.created",
|
||
description="12 октября, 10:00",
|
||
recipients=[
|
||
{
|
||
"user": user,
|
||
"channels": [
|
||
{"channel": DeliveryChannel.EMAIL, "target": {"email": "alice@example.com"}},
|
||
],
|
||
}
|
||
],
|
||
)
|
||
self.assertEqual(notification.title, "Запись создана")
|
||
deliver_notification.apply(args=[str(notification.recipients.get().id)], throw=True)
|
||
self.assertEqual(mail.outbox[0].subject, "Создана: Запись создана")
|
||
self.assertIn("когда=12 октября, 10:00", mail.outbox[0].body)
|
||
|
||
def _ids(self):
|
||
return {
|
||
"group": NotificationGroup.objects.get(code="appointment").pk,
|
||
"types": set(NotificationType.objects.values_list("pk", flat=True)),
|
||
"templates": set(NotificationTemplate.objects.values_list("pk", flat=True)),
|
||
}
|