from datetime import timedelta from unittest.mock import patch from django.contrib.auth import get_user_model from django.core import mail from django.core.files.base import ContentFile from django.core.files.storage import default_storage from django.core.files.uploadedfile import SimpleUploadedFile from django.test import TestCase, override_settings from django.utils import timezone from notify.models import ( DeliveryChannel, DeliveryEmailConfig, Notification, NotificationAttachment, NotificationGroup, NotificationType, ) from notify.services import create_notification from notify.tasks import deliver_notification User = get_user_model() MEMORY_STORAGES = { "default": {"BACKEND": "django.core.files.storage.memory.InMemoryStorage"}, "staticfiles": {"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"}, } @override_settings(STORAGES=MEMORY_STORAGES) class AttachmentServiceTests(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.BROWSER, DeliveryChannel.EMAIL], verb="Approved", ) def _browser(self, user, **extra): return create_notification( verb=extra.pop("verb", "Hello"), recipients=[{"user": user, "channels": [{"channel": DeliveryChannel.BROWSER}]}], **extra, ) def test_files_are_stored_with_a_cleaned_name(self): uploaded = SimpleUploadedFile("notes.txt", b"abc", content_type="text/plain; charset=utf-8") notification = self._browser( self.user, attachments=[ uploaded, ContentFile(b"%PDF", name="../../secret/report.pdf"), ], ) stored = list(notification.attachments.order_by("name")) self.assertEqual([item.name for item in stored], ["notes.txt", "report.pdf"]) self.assertEqual(stored[0].content_type, "text/plain") self.assertEqual(stored[0].size, 3) self.assertEqual(stored[0].file.read(), b"abc") self.assertEqual(stored[1].content_type, "application/pdf") self.assertEqual(stored[1].size, 4) self.assertTrue(default_storage.exists(stored[1].file.name)) def test_limits_reject_the_notification(self): with override_settings(NOTIFY_MAX_ATTACHMENTS=1): with self.assertRaisesMessage(ValueError, "At most 1 attachments are allowed"): self._browser( self.user, attachments=[ ContentFile(b"a", name="a.txt"), ContentFile(b"b", name="b.txt"), ], ) with override_settings(NOTIFY_MAX_ATTACHMENT_BYTES=4): with self.assertRaisesMessage(ValueError, "exceeds the size limit"): self._browser(self.user, attachments=[ContentFile(b"hello", name="a.txt")]) with self.assertRaisesMessage(ValueError, "Attachment must have a file name"): self._browser(self.user, attachments=[ContentFile(b"x", name="")]) with self.assertRaisesMessage(ValueError, "Attachment must be a file"): self._browser(self.user, attachments=["nope"]) self.assertEqual(Notification.objects.count(), 0) def test_oversized_declared_size_is_not_read(self): class BigFile: name = "big.bin" size = 100 def read(self): raise AssertionError("should not read") with override_settings(NOTIFY_MAX_ATTACHMENT_BYTES=10): with self.assertRaisesMessage(ValueError, "exceeds the size limit"): self._browser(self.user, attachments=[BigFile()]) self.assertEqual(Notification.objects.count(), 0) def test_failed_save_removes_stored_files(self): real_save = NotificationAttachment.save names = [] def fail_second(row, *args, **kwargs): names.append(row.file.name) if len(names) == 2: raise RuntimeError("disk") return real_save(row, *args, **kwargs) with patch("notify.attachments.NotificationAttachment.save", fail_second): with self.assertRaisesMessage(RuntimeError, "disk"): self._browser( self.user, attachments=[ ContentFile(b"one", name="first.txt"), ContentFile(b"two", name="second.txt"), ], ) self.assertEqual(Notification.objects.count(), 0) self.assertEqual(NotificationAttachment.objects.count(), 0) self.assertEqual(len(names), 2) for name in names: self.assertFalse(default_storage.exists(name)) def test_same_idempotency_key_does_not_add_files(self): first = self._browser(self.user, idempotency_key="approved:9") with override_settings(NOTIFY_MAX_ATTACHMENT_BYTES=1): second = self._browser( self.user, verb="Other", idempotency_key="approved:9", attachments=[ContentFile(b"hello", name="late.txt")], ) self.assertEqual(second.pk, first.pk) self.assertEqual(first.attachments.count(), 0) def test_group_copies_files_onto_collapsed_and_new_notifications(self): first = create_notification( type=self.kind, object_id="post-9", group=True, recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}], ) second = create_notification( type=self.kind, object_id="post-9", verb="Ещё", group=True, attachments=[ContentFile(b"note", name="note.txt")], recipients=[ {"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}, {"user": self.other, "channels": [{"channel": DeliveryChannel.BROWSER}]}, ], ) self.assertNotEqual(second.pk, first.pk) self.assertEqual(Notification.objects.count(), 2) self.assertEqual(first.attachments.get().name, "note.txt") self.assertEqual(second.attachments.get().file.read(), b"note") self.assertNotEqual(first.attachments.get().file.name, second.attachments.get().file.name) collapsed = create_notification( type=self.kind, object_id="post-9", group=True, attachments=[ContentFile(b"more", name="more.txt")], recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}], ) self.assertEqual(collapsed.pk, first.pk) self.assertEqual(set(first.attachments.values_list("name", flat=True)), {"note.txt", "more.txt"}) self.assertEqual(Notification.objects.count(), 2) def test_deleting_a_notification_deletes_its_file(self): notification = self._browser(self.user, attachments=[ContentFile(b"gone", name="gone.txt")]) other = self._browser(self.other, attachments=[ContentFile(b"stay", name="stay.txt")]) removed = notification.attachments.get().file.name kept = other.attachments.get().file.name Notification.objects.filter(pk=notification.pk).delete() self.assertFalse(default_storage.exists(removed)) self.assertTrue(default_storage.exists(kept)) self.assertEqual(other.attachments.get().file.read(), b"stay") @override_settings(STORAGES=MEMORY_STORAGES) class AttachmentApiTests(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 test_list_and_download_are_limited_to_the_recipient(self): create_notification( verb="With file", attachments=[ContentFile(b"hello", name="report.txt")], recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}], ) create_notification( verb="Foreign", attachments=[ContentFile(b"secret", name="secret.txt")], recipients=[{"user": self.other, "channels": [{"channel": DeliveryChannel.BROWSER}]}], ) listing = self.client.get("/api/list/") self.assertEqual(listing.status_code, 200) item = listing.json()["results"][0] self.assertEqual(item["verb"], "With file") self.assertEqual(len(item["attachments"]), 1) attachment = item["attachments"][0] self.assertEqual(attachment["name"], "report.txt") self.assertEqual(attachment["size"], 5) self.assertEqual(attachment["content_type"], "text/plain") self.assertIn("/api/attachments/", attachment["url"]) downloaded = self.client.get(attachment["url"]) self.assertEqual(downloaded.status_code, 200) self.assertEqual(b"".join(downloaded.streaming_content), b"hello") self.assertIn("report.txt", downloaded["Content-Disposition"]) foreign = NotificationAttachment.objects.get(name="secret.txt") hidden = self.client.get(f"/api/attachments/{foreign.id}/") self.assertEqual(hidden.status_code, 404) self.assertEqual(hidden.json()["message"], "Not found") self.client.logout() anonymous = self.client.get(attachment["url"]) self.assertEqual(anonymous.status_code, 401) def test_expired_and_invalid_ids_are_hidden(self): notification = create_notification( verb="Stale", expires_at=timezone.now() - timedelta(minutes=1), attachments=[ContentFile(b"old", name="old.txt")], recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}], ) attachment = notification.attachments.get() missing = self.client.get(f"/api/attachments/{attachment.id}/") self.assertEqual(missing.status_code, 404) invalid = self.client.get("/api/attachments/not-a-number/") self.assertEqual(invalid.status_code, 404) def test_email_recipient_can_download(self): notification = create_notification( verb="Mail", attachments=[ContentFile(b"body", name="body.txt")], recipients=[ { "user": self.user, "channels": [{"channel": DeliveryChannel.EMAIL, "target": {"email": "alice@example.com"}}], } ], ) attachment = notification.attachments.get() downloaded = self.client.get(f"/api/attachments/{attachment.id}/") self.assertEqual(downloaded.status_code, 200) self.assertEqual(b"".join(downloaded.streaming_content), b"body") @override_settings(STORAGES=MEMORY_STORAGES) class AttachmentEmailTests(TestCase): def setUp(self): 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, ) def test_email_includes_the_file(self): notification = create_notification( verb="Hello", description="Body", attachments=[ContentFile(b"pdf-bytes", name="report.pdf")], recipients=[ { "user": self.user, "channels": [{"channel": DeliveryChannel.EMAIL, "target": {"email": "alice@example.com"}}], } ], ) recipient = notification.recipients.get() deliver_notification.apply(args=[str(recipient.id)], throw=True) self.assertEqual( mail.outbox[0].attachments, [("report.pdf", b"pdf-bytes", "application/pdf")], )