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, 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, verb, expires_at=None, **extra): if expires_at is not None: extra["expires_at"] = expires_at return create_notification( verb=verb, 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], verb=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["verb"] 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/"): 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/", ): 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) notification = self._browser( self.user, "Invoice paid", expires_at=when, type=kind, url="https://example.com/orders/1?x=1", object_id="1", 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["verb"] 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["object_id"], "1") self.assertEqual(item["description"], "wire") self.assertEqual(item["data"], {"n": 1}) self.assertTrue(item["unread"]) self.assertNotIn("delivery_channel", item) self.assertNotIn("delivery_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( verb="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["verb"] 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(delivery_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()["verb"], "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") self._browser( self.user, "Invoice paid", type=approved, object_id="1", description="wire", ) self._browser(self.user, "Nope", type=rejected, object_id="2", description="card") self._browser( self.user, "Due", type=billing, object_id="3", description="Invoice reminder", ) paid = NotificationRecipient.objects.get(notification__object_id="1") paid.make_read() def verbs(response): return [item["verb"] 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": "2"})), ["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": ["2"]})), ["Invoice paid", "Due"], ) self.assertEqual( verbs(self.client.get("/api/list/", {"object_id__ne__in": "1,3"})), ["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", type=orders) self._browser(self.user, "bill", type=billing) self._browser(self.other, "foreign", type=orders) self._browser( self.user, "old order", type=orders, expires_at=timezone.now() - timedelta(minutes=1), ) mailed = create_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(verb): return NotificationRecipient.objects.get(notification__verb=verb).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()) 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 verb in ("a", "b", "c"): create_notification( verb=verb, recipients=[ {"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}, ], ) paginator = CustomPagination(page_size=2) queryset = NotificationRecipient.objects.order_by("notification__verb") 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.verb for item in first["results"]], ["a", "b"]) second = paginator.paginate_queryset(queryset, CustomPagination.Input(page=2)) self.assertEqual([item.notification.verb 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)