notify/tests/test_api.py

497 lines
18 KiB
Python

import json
from datetime import timedelta
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.utils import timezone
from notify.api_pagination import CustomPagination
from notify.models import (
DeliveryChannel,
NotificationChannelPreference,
NotificationGroup,
NotificationRecipient,
NotificationType,
)
from notify.services import create_notification
User = get_user_model()
class ApiTests(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.client.force_login(self.user)
def _browser(self, user, title, expires_at=None, **extra):
if expires_at is not None:
extra["expires_at"] = expires_at
return create_notification(
title=title,
recipients=[{"user": user, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
**extra,
)
def _type(self, code):
group, _ = NotificationGroup.objects.get_or_create(
code="catalog",
defaults={"name": "Catalog"},
)
return NotificationType.objects.create(
code=code,
name=code,
group=group,
channels=[DeliveryChannel.BROWSER, DeliveryChannel.EMAIL],
title=code,
)
def test_expired_notifications_are_hidden(self):
self._browser(self.user, "fresh")
self._browser(self.user, "stale", expires_at=timezone.now() - timedelta(minutes=1))
self._browser(self.other, "foreign")
unread = self.client.get("/api/unread-count/")
self.assertEqual(unread.status_code, 200)
self.assertEqual(unread.json()["result"], 1)
listing = self.client.get("/api/list/")
self.assertEqual(listing.status_code, 200)
verbs = [item["title"] for item in listing.json()["results"]]
self.assertEqual(verbs, ["fresh"])
def test_invalid_recipient_id_is_not_found(self):
response = self.client.post("/api/make-read/not-a-number/")
self.assertEqual(response.status_code, 404)
self.assertEqual(response.json()["message"], "Not found")
missing = self.client.post("/api/make-read/999999/")
self.assertEqual(missing.status_code, 404)
self.assertEqual(missing.json()["message"], "Object not found")
def test_anonymous_requests_are_rejected(self):
self.client.logout()
recipient_id = 1
for url in ("/api/unread-count/", "/api/count/", "/api/list/", "/api/preferences/"):
with self.subTest(url=url):
self.assertEqual(self.client.get(url).status_code, 401)
for url in (
f"/api/make-read/{recipient_id}/",
f"/api/make-unread/{recipient_id}/",
"/api/make-all-read/",
"/api/preferences/",
):
with self.subTest(url=url):
self.assertEqual(self.client.post(url).status_code, 401)
def test_list_returns_the_browser_inbox(self):
kind = self._type("orders.approved")
when = timezone.now() + timedelta(days=3)
subject = User.objects.create_user("carol", "carol@example.com", "pass")
notification = self._browser(
self.user,
"Invoice paid",
expires_at=when,
notification_type=kind,
url="https://example.com/orders/1?x=1",
content_object=subject,
description="wire",
data={"n": 1},
level="success",
)
self._browser(self.other, "foreign")
older = notification.recipients.get()
older.created_at = timezone.now() - timedelta(hours=1)
older.save(update_fields=["created_at"])
self._browser(self.user, "Newer")
listing = self.client.get("/api/list/")
self.assertEqual(listing.status_code, 200)
body = listing.json()
self.assertEqual(body["total"], 2)
self.assertEqual(body["pagination"], {"page": 1, "total_pages": 1})
self.assertEqual([item["title"] for item in body["results"]], ["Newer", "Invoice paid"])
item = body["results"][1]
self.assertEqual(item["id"], older.id)
self.assertEqual(item["type"], "orders.approved")
self.assertEqual(item["level"], "success")
self.assertEqual(item["url"], "https://example.com/orders/1?x=1")
self.assertEqual(item["content_type"], "auth.user")
self.assertEqual(item["object_id"], str(subject.pk))
self.assertEqual(item["description"], "wire")
self.assertEqual(item["data"], {"n": 1})
self.assertTrue(item["unread"])
self.assertNotIn("channel", item)
self.assertNotIn("target", item)
count = self.client.get("/api/count/")
self.assertEqual(count.json()["result"], 2)
def test_other_channels_and_other_users_stay_out_of_the_inbox(self):
create_notification(
title="mail",
recipients=[
{
"user": self.user,
"channels": [{"channel": DeliveryChannel.EMAIL, "target": {"email": "alice@example.com"}}],
}
],
)
foreign = self._browser(self.other, "foreign")
self._browser(self.user, "mine")
listing = self.client.get("/api/list/")
self.assertEqual([item["title"] for item in listing.json()["results"]], ["mine"])
foreign_id = foreign.recipients.get().id
denied = self.client.post(f"/api/make-read/{foreign_id}/")
self.assertEqual(denied.status_code, 404)
foreign.recipients.get().refresh_from_db()
self.assertTrue(foreign.recipients.get().unread)
email_id = NotificationRecipient.objects.get(channel=DeliveryChannel.EMAIL).id
self.assertEqual(self.client.post(f"/api/make-read/{email_id}/").status_code, 404)
def test_expired_recipient_cannot_be_marked(self):
stale = self._browser(self.user, "stale", expires_at=timezone.now() - timedelta(minutes=1))
response = self.client.post(f"/api/make-read/{stale.recipients.get().id}/")
self.assertEqual(response.status_code, 404)
stale.recipients.get().refresh_from_db()
self.assertTrue(stale.recipients.get().unread)
def test_make_read_and_make_unread(self):
notification = self._browser(self.user, "fresh")
recipient = notification.recipients.get()
read = self.client.post(f"/api/make-read/{recipient.id}/")
self.assertEqual(read.status_code, 200)
self.assertFalse(read.json()["unread"])
self.assertEqual(read.json()["title"], "fresh")
self.assertEqual(self.client.get("/api/unread-count/").json()["result"], 0)
again = self.client.post(f"/api/make-unread/{recipient.id}/")
self.assertEqual(again.status_code, 200)
self.assertTrue(again.json()["unread"])
recipient.refresh_from_db()
self.assertTrue(recipient.unread)
def test_filters_narrow_the_inbox(self):
approved = self._type("orders.approved")
rejected = self._type("orders.rejected")
billing = self._type("billing.due")
invoice = User.objects.create_user("invoice", "invoice@example.com", "pass")
card = User.objects.create_user("card", "card@example.com", "pass")
reminder = User.objects.create_user("reminder", "reminder@example.com", "pass")
self._browser(
self.user,
"Invoice paid",
notification_type=approved,
content_object=invoice,
description="wire",
)
self._browser(self.user, "Nope", notification_type=rejected, content_object=card, description="card")
self._browser(
self.user,
"Due",
notification_type=billing,
content_object=reminder,
description="Invoice reminder",
)
paid = NotificationRecipient.objects.get(notification__object_id=str(invoice.pk))
paid.make_read()
def verbs(response):
return [item["title"] for item in response.json()["results"]]
self.assertEqual(
verbs(self.client.get("/api/list/", {"type": "orders.approved"})),
["Invoice paid"],
)
self.assertCountEqual(
verbs(self.client.get("/api/list/", {"type__startswith": "orders"})),
["Invoice paid", "Nope"],
)
self.assertEqual(
verbs(self.client.get("/api/list/", {"object_id": str(card.pk)})),
["Nope"],
)
self.assertEqual(
verbs(self.client.get("/api/list/", {"content_type": "auth.user", "object_id": str(card.pk)})),
["Nope"],
)
self.assertCountEqual(
verbs(self.client.get("/api/list/", {"search": "invoice"})),
["Invoice paid", "Due"],
)
self.assertCountEqual(
verbs(self.client.get("/api/list/", {"unread": "true"})),
["Nope", "Due"],
)
self.assertEqual(
verbs(self.client.get("/api/list/", {"unread": "false"})),
["Invoice paid"],
)
self.assertCountEqual(
verbs(self.client.get("/api/list/", {"object_id__ne": [str(card.pk)]})),
["Invoice paid", "Due"],
)
self.assertEqual(
verbs(self.client.get("/api/list/", {"object_id__ne__in": f"{invoice.pk},{reminder.pk}"})),
["Nope"],
)
self.assertEqual(
self.client.get("/api/count/", {"type__startswith": "orders"}).json()["result"],
2,
)
def test_make_all_read_respects_filters(self):
orders = self._type("orders.approved")
billing = self._type("billing.due")
self._browser(self.user, "order", notification_type=orders)
self._browser(self.user, "bill", notification_type=billing)
self._browser(self.other, "foreign", notification_type=orders)
self._browser(
self.user,
"old order",
notification_type=orders,
expires_at=timezone.now() - timedelta(minutes=1),
)
mailed = create_notification(
notification_type=orders,
recipients=[
{
"user": self.user,
"channels": [{"channel": DeliveryChannel.EMAIL, "target": {"email": "alice@example.com"}}],
}
],
)
response = self.client.post("/api/make-all-read/?type=orders.approved")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), {})
def unread(title):
return NotificationRecipient.objects.get(notification__title=title).unread
self.assertFalse(unread("order"))
self.assertTrue(unread("bill"))
self.assertTrue(unread("foreign"))
self.assertTrue(unread("old order"))
self.assertTrue(mailed.recipients.get().unread)
self.assertEqual(self.client.get("/api/unread-count/").json()["result"], 1)
def test_invalid_page_is_rejected(self):
self._browser(self.user, "fresh")
response = self.client.get("/api/list/", {"page": "0"})
self.assertEqual(response.status_code, 422)
self.assertIn("detail", response.json())
def _post_preferences(self, payload):
return self.client.post(
"/api/preferences/",
data=json.dumps(payload),
content_type="application/json",
)
def test_preferences_list_switchable_types(self):
group = NotificationGroup.objects.create(code="orders", name="Orders")
NotificationType.objects.create(
code="later",
name="Later",
group=group,
channels=[DeliveryChannel.BROWSER],
position=2,
)
approved = NotificationType.objects.create(
code="approved",
name="Approved",
group=group,
channels=[DeliveryChannel.EMAIL, DeliveryChannel.BROWSER],
position=1,
)
NotificationType.objects.create(
code="security",
name="Security",
group=group,
channels=[DeliveryChannel.EMAIL],
is_configurable=False,
)
NotificationType.objects.create(
code="retired",
name="Retired",
group=group,
channels=[DeliveryChannel.EMAIL],
is_active=False,
)
NotificationChannelPreference.objects.create(
user=self.user,
notification_type=approved,
channel=DeliveryChannel.EMAIL,
is_enabled=False,
)
response = self.client.get("/api/preferences/")
self.assertEqual(response.status_code, 200)
self.assertEqual(
response.json(),
[
{
"code": "approved",
"name": "Approved",
"group_name": "Orders",
"channels": [
{"channel": DeliveryChannel.EMAIL, "is_enabled": False},
{"channel": DeliveryChannel.BROWSER, "is_enabled": True},
],
},
{
"code": "later",
"name": "Later",
"group_name": "Orders",
"channels": [
{"channel": DeliveryChannel.BROWSER, "is_enabled": True},
],
},
],
)
def test_preferences_save_and_reread(self):
self._type("orders.approved")
empty = self._post_preferences({})
self.assertEqual(empty.status_code, 200)
self.assertEqual(empty.json(), {"ok": True})
self.assertFalse(NotificationChannelPreference.objects.exists())
saved = self._post_preferences(
{
"items": [
{
"code": "orders.approved",
"channels": [
{"channel": DeliveryChannel.EMAIL, "is_enabled": False},
],
}
]
}
)
self.assertEqual(saved.status_code, 200)
self.assertEqual(saved.json(), {"ok": True})
listing = self.client.get("/api/preferences/")
channels = {
item["channel"]: item["is_enabled"]
for item in listing.json()[0]["channels"]
}
self.assertEqual(
channels,
{DeliveryChannel.EMAIL: False, DeliveryChannel.BROWSER: True},
)
def test_preferences_reject_unknown_channel_and_locked_type(self):
self._type("orders.approved")
group = NotificationGroup.objects.get(code="catalog")
NotificationType.objects.create(
code="security",
name="Security",
group=group,
channels=[DeliveryChannel.EMAIL],
is_configurable=False,
)
unknown_channel = self._post_preferences(
{
"items": [
{
"code": "orders.approved",
"channels": [{"channel": DeliveryChannel.MAX, "is_enabled": True}],
}
]
}
)
self.assertEqual(unknown_channel.status_code, 400)
self.assertIn("not allowed", unknown_channel.json()["detail"])
locked = self._post_preferences(
{
"items": [
{
"code": "security",
"channels": [{"channel": DeliveryChannel.EMAIL, "is_enabled": False}],
}
]
}
)
self.assertEqual(locked.status_code, 400)
self.assertIn("detail", locked.json())
self.assertFalse(NotificationChannelPreference.objects.exists())
def test_preferences_use_is_enabled_by_default_until_overridden(self):
kind = self._type("orders.digest")
kind.is_enabled_by_default = False
kind.save(update_fields=["is_enabled_by_default"])
listing = self.client.get("/api/preferences/")
self.assertEqual(listing.status_code, 200)
self.assertEqual(
listing.json()[0]["channels"],
[
{"channel": DeliveryChannel.BROWSER, "is_enabled": False},
{"channel": DeliveryChannel.EMAIL, "is_enabled": False},
],
)
saved = self._post_preferences(
{
"items": [
{
"code": "orders.digest",
"channels": [
{"channel": DeliveryChannel.EMAIL, "is_enabled": True},
],
}
]
}
)
self.assertEqual(saved.status_code, 200)
channels = {
item["channel"]: item["is_enabled"]
for item in self.client.get("/api/preferences/").json()[0]["channels"]
}
self.assertEqual(
channels,
{DeliveryChannel.BROWSER: False, DeliveryChannel.EMAIL: True},
)
class PaginationTests(TestCase):
def setUp(self):
self.user = User.objects.create_user("alice", "alice@example.com", "pass")
def test_pages_are_counted_from_the_queryset(self):
for title in ("a", "b", "c"):
create_notification(
title=title,
recipients=[
{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]},
],
)
paginator = CustomPagination(page_size=2)
queryset = NotificationRecipient.objects.order_by("notification__title")
first = paginator.paginate_queryset(queryset, CustomPagination.Input(page=1))
self.assertEqual(first["total"], 3)
self.assertEqual(first["pagination"], {"page": 1, "total_pages": 2})
self.assertEqual([item.notification.title for item in first["results"]], ["a", "b"])
second = paginator.paginate_queryset(queryset, CustomPagination.Input(page=2))
self.assertEqual([item.notification.title for item in second["results"]], ["c"])
empty = paginator.paginate_queryset(
NotificationRecipient.objects.none(),
CustomPagination.Input(page=1),
)
self.assertEqual(empty["results"], [])
self.assertEqual(empty["total"], 0)
self.assertEqual(empty["pagination"]["total_pages"], 0)