test: migrate backend suites to pytest with module coverage gate
Split backend tests into unit and integration suites, add isolated fixtures and coverage enforcement, and update CI and test documentation. Cover current authentication, content, notification, payment, media, and admin flows; fix behaviors revealed by the new tests. Validate both suites and the per-module gate against local PostgreSQL.
This commit is contained in:
29
apps/communications/tests/integration/test_announcements.py
Normal file
29
apps/communications/tests/integration/test_announcements.py
Normal file
@@ -0,0 +1,29 @@
|
||||
import pytest
|
||||
import json
|
||||
from apps.communications.models import Announcement
|
||||
from apps.users.models import User
|
||||
from core.authentication import create_jwt_token
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.integration
|
||||
class TestAnnouncementDeliveryTests:
|
||||
|
||||
def setup_method(self):
|
||||
self.staff = User.objects.create_user(username='announcement_staff', mobile='09193000001', password='password', is_staff=True)
|
||||
self.auth = {'HTTP_AUTHORIZATION': f'Bearer {create_jwt_token(self.staff)}'}
|
||||
|
||||
def test_publishing_announcement_does_not_send_manual_notifications(self, mocker):
|
||||
notify_user = mocker.patch('apps.notifications.services.notify_user')
|
||||
response = self.client.post('/api/communications/announcements/', json.dumps({'title': 'News', 'content': '# Story', 'is_published': True}), content_type='application/json', **self.auth)
|
||||
assert response.status_code == 200
|
||||
assert Announcement.objects.filter(title='News').exists()
|
||||
notify_user.assert_not_called()
|
||||
|
||||
def test_newsletter_category_and_routes_are_removed(self):
|
||||
response = self.client.post('/api/communications/announcements/', json.dumps({'title': 'News', 'content': 'Story', 'announcement_type': 'newsletter'}), content_type='application/json', **self.auth)
|
||||
assert response.status_code == 422
|
||||
assert self.client.post('/api/communications/newsletter/subscribe/').status_code == 404
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _pytest_client(self, client):
|
||||
self.client = client
|
||||
66
apps/communications/tests/integration/test_api.py
Normal file
66
apps/communications/tests/integration/test_api.py
Normal file
@@ -0,0 +1,66 @@
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from apps.communications.models import Announcement, PushNotificationDevice
|
||||
|
||||
|
||||
pytestmark = [pytest.mark.integration, pytest.mark.django_db]
|
||||
|
||||
|
||||
def _send(client, method, path, headers, payload=None):
|
||||
kwargs = dict(headers)
|
||||
if payload is not None:
|
||||
kwargs.update(data=json.dumps(payload), content_type="application/json")
|
||||
return getattr(client, method)(path, **kwargs)
|
||||
|
||||
|
||||
def test_announcement_staff_crud_and_public_listing(client, user_factory, auth_headers):
|
||||
staff = user_factory(is_staff=True)
|
||||
member = user_factory()
|
||||
staff_headers = auth_headers(staff)
|
||||
member_headers = auth_headers(member)
|
||||
payload = {"title": "Meeting", "content": "Welcome", "is_published": True}
|
||||
assert _send(client, "post", "/api/communications/announcements/", member_headers, payload).status_code == 403
|
||||
created = _send(client, "post", "/api/communications/announcements/", staff_headers, payload)
|
||||
assert created.status_code == 200, created.content
|
||||
item = Announcement.objects.get(title="Meeting")
|
||||
listing = client.get("/api/communications/announcements/").json()
|
||||
assert listing["items"][0]["id"] == item.id
|
||||
assert client.get(f"/api/communications/announcements/{item.id}/").json()["title"] == "Meeting"
|
||||
stats = _send(client, "get", "/api/communications/announcements/stats/", staff_headers)
|
||||
assert stats.status_code == 200, stats.content
|
||||
assert stats.json()["published_announcements"] == 1
|
||||
updated = _send(client, "put", f"/api/communications/announcements/{item.id}/", staff_headers,
|
||||
{"title": "Revised", "content": "New", "is_published": False})
|
||||
assert updated.status_code == 200, updated.content
|
||||
item.refresh_from_db()
|
||||
assert item.title == "Revised" and not item.is_published
|
||||
assert client.get("/api/communications/announcements/").json()["items"] == []
|
||||
deleted = _send(client, "delete", f"/api/communications/announcements/{item.id}/", staff_headers)
|
||||
assert deleted.status_code == 200, deleted.content
|
||||
assert Announcement.deleted_objects.filter(pk=item.pk).exists()
|
||||
|
||||
|
||||
def test_push_device_registration_update_and_removal(client, user_factory, auth_headers):
|
||||
user = user_factory()
|
||||
other = user_factory()
|
||||
headers = auth_headers(user)
|
||||
path = "/api/communications/push-devices/"
|
||||
payload = {"device_token": "device-1", "device_type": "web"}
|
||||
assert client.get(path).status_code == 401
|
||||
first = _send(client, "post", path, headers, payload)
|
||||
assert first.status_code == 200, first.content
|
||||
device = PushNotificationDevice.objects.get(user=user, device_token="device-1")
|
||||
device.is_active = False
|
||||
device.save()
|
||||
assert _send(client, "post", path, headers, payload).status_code == 200
|
||||
device.refresh_from_db()
|
||||
assert device.is_active
|
||||
assert [row["id"] for row in _send(client, "get", path, headers).json()] == [device.id]
|
||||
assert _send(client, "put", f"{path}{device.id}/", auth_headers(other), {"is_active": False}).status_code == 404
|
||||
assert _send(client, "put", f"{path}{device.id}/", headers, {"is_active": False}).status_code == 200
|
||||
device.refresh_from_db()
|
||||
assert not device.is_active
|
||||
assert _send(client, "delete", path + "?device_token=device-1", headers).status_code == 200
|
||||
assert not PushNotificationDevice.objects.filter(pk=device.pk).exists()
|
||||
23
apps/communications/tests/integration/test_reminders.py
Normal file
23
apps/communications/tests/integration/test_reminders.py
Normal file
@@ -0,0 +1,23 @@
|
||||
from datetime import timedelta
|
||||
|
||||
import pytest
|
||||
from django.utils import timezone
|
||||
|
||||
from apps.communications.tasks import send_event_reminders
|
||||
from apps.events.models import Registration
|
||||
|
||||
|
||||
pytestmark = [pytest.mark.integration, pytest.mark.django_db]
|
||||
|
||||
|
||||
def test_reminder_targets_confirmed_attendees_only(event_factory, user_factory, mocker):
|
||||
notify = mocker.patch("apps.communications.tasks.notify_user")
|
||||
now = timezone.now()
|
||||
event = event_factory(start_time=now + timedelta(hours=24), end_time=now + timedelta(hours=26))
|
||||
confirmed = user_factory()
|
||||
pending = user_factory()
|
||||
Registration.objects.create(event=event, user=confirmed, status=Registration.StatusChoices.CONFIRMED)
|
||||
Registration.objects.create(event=event, user=pending, status=Registration.StatusChoices.PENDING)
|
||||
assert send_event_reminders.run() == "Event reminders sent to 1 users"
|
||||
notify.assert_called_once()
|
||||
assert notify.call_args.args[0] == confirmed.id
|
||||
@@ -1,32 +0,0 @@
|
||||
import json
|
||||
from unittest import mock
|
||||
|
||||
from django.test import TestCase
|
||||
|
||||
from apps.communications.models import Announcement
|
||||
from apps.users.models import User
|
||||
from core.authentication import create_jwt_token
|
||||
|
||||
|
||||
class AnnouncementDeliveryTests(TestCase):
|
||||
def setUp(self):
|
||||
self.staff = User.objects.create_user(
|
||||
username="announcement_staff", mobile="09193000001", password="password", is_staff=True,
|
||||
)
|
||||
self.auth = {"HTTP_AUTHORIZATION": f"Bearer {create_jwt_token(self.staff)}"}
|
||||
|
||||
@mock.patch("apps.notifications.services.notify_user")
|
||||
def test_publishing_announcement_does_not_send_manual_notifications(self, notify_user):
|
||||
response = self.client.post("/api/communications/announcements/", json.dumps({
|
||||
"title": "News", "content": "# Story", "is_published": True,
|
||||
}), content_type="application/json", **self.auth)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertTrue(Announcement.objects.filter(title="News").exists())
|
||||
notify_user.assert_not_called()
|
||||
|
||||
def test_newsletter_category_and_routes_are_removed(self):
|
||||
response = self.client.post("/api/communications/announcements/", json.dumps({
|
||||
"title": "News", "content": "Story", "announcement_type": "newsletter",
|
||||
}), content_type="application/json", **self.auth)
|
||||
self.assertEqual(response.status_code, 422)
|
||||
self.assertEqual(self.client.post("/api/communications/newsletter/subscribe/").status_code, 404)
|
||||
76
apps/communications/tests/unit/test_push.py
Normal file
76
apps/communications/tests/unit/test_push.py
Normal file
@@ -0,0 +1,76 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from apps.communications.push_notifications import PushNotificationService
|
||||
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
|
||||
def test_push_delivery_passes_payload_to_gateway(mocker):
|
||||
gateway = mocker.patch("apps.communications.push_notifications.webpush")
|
||||
service = PushNotificationService()
|
||||
assert service.send_notification({"endpoint": "https://push.test"}, {"title": "News"})
|
||||
assert gateway.call_args.kwargs["ttl"] == 86400
|
||||
assert '"title": "News"' in gateway.call_args.kwargs["data"]
|
||||
|
||||
|
||||
def test_push_batch_counts_success_and_failures(mocker):
|
||||
service = PushNotificationService()
|
||||
mocker.patch.object(service, "send_notification", side_effect=[True, False])
|
||||
devices = [SimpleNamespace(endpoint="a", p256dh_key="key", auth_key="auth"), SimpleNamespace(endpoint="b", p256dh_key="key", auth_key="auth")]
|
||||
assert service.send_to_multiple(devices, {"title": "News"}) == {"sent": 1, "failed": 1}
|
||||
|
||||
|
||||
def test_push_delivery_handles_gateway_failure(mocker):
|
||||
gateway = mocker.patch("apps.communications.push_notifications.webpush", side_effect=RuntimeError("offline"))
|
||||
service = PushNotificationService()
|
||||
assert not service.send_notification({"endpoint": "https://push.test"}, {"title": "News"})
|
||||
gateway.assert_called_once()
|
||||
|
||||
|
||||
def test_push_announcement_and_reminder_build_expected_payloads(mocker):
|
||||
service = PushNotificationService()
|
||||
sender = mocker.patch.object(service, "send_to_multiple", return_value={"sent": 1, "failed": 0})
|
||||
device = SimpleNamespace(endpoint="push", p256dh_key="key", auth_key="auth")
|
||||
announcement = SimpleNamespace(id=7, title="Notice", content="x" * 110)
|
||||
assert service.send_announcement_notification(announcement, [device]) == {"sent": 1, "failed": 0}
|
||||
assert sender.call_args.args[0] == [device]
|
||||
assert sender.call_args.args[1]["body"] == "x" * 100 + "..."
|
||||
event = SimpleNamespace(id=9, title="Workshop")
|
||||
service.send_event_reminder_notification(event, [device])
|
||||
assert sender.call_args.args[1]["data"]["url"] == "/events/9/"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("audience,expected", [("all", {"is_active": True}),
|
||||
("members", {"user__is_member": True, "is_active": True}),
|
||||
("committee", {"user__is_committee_member": True, "is_active": True})])
|
||||
def test_push_announcement_selects_audience(mocker, audience, expected):
|
||||
service = PushNotificationService()
|
||||
devices = mocker.patch("apps.communications.push_notifications.PushNotificationDevice.objects.filter")
|
||||
sender = mocker.patch.object(service, "send_to_multiple", return_value={"sent": 0, "failed": 0})
|
||||
announcement = SimpleNamespace(id=1, title="Alert", content="Short", audience=audience)
|
||||
service.send_announcement_notification(announcement)
|
||||
devices.assert_called_once_with(**expected)
|
||||
sender.assert_called_once()
|
||||
|
||||
|
||||
def test_push_reminder_selects_registered_devices(mocker):
|
||||
service = PushNotificationService()
|
||||
registrations = mocker.patch("apps.communications.push_notifications.Registration.objects.filter")
|
||||
registrations.return_value.values_list.return_value = [1, 2]
|
||||
devices = mocker.patch("apps.communications.push_notifications.PushNotificationDevice.objects.filter")
|
||||
mocker.patch.object(service, "send_to_multiple", return_value={"sent": 0, "failed": 0})
|
||||
event = SimpleNamespace(id=3, title="Event")
|
||||
service.send_event_reminder_notification(event)
|
||||
registrations.assert_called_once_with(event=event, status="confirmed")
|
||||
devices.assert_called_once_with(user_id__in=[1, 2], is_active=True)
|
||||
|
||||
|
||||
def test_invalid_push_subscription_is_removed(mocker):
|
||||
service = PushNotificationService()
|
||||
deleted = mocker.patch("apps.communications.push_notifications.PushNotificationDevice.objects.filter")
|
||||
service._remove_invalid_subscription({"endpoint": "https://push.test"})
|
||||
deleted.assert_called_once_with(endpoint="https://push.test")
|
||||
deleted.return_value.delete.assert_called_once()
|
||||
13
apps/communications/tests/unit/test_resources.py
Normal file
13
apps/communications/tests/unit/test_resources.py
Normal file
@@ -0,0 +1,13 @@
|
||||
import pytest
|
||||
|
||||
from apps.communications.resources import AnnouncementResource, PushNotificationDeviceResource
|
||||
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
|
||||
def test_communication_exports_reference_users_by_username():
|
||||
announcements = AnnouncementResource()
|
||||
devices = PushNotificationDeviceResource()
|
||||
assert announcements.fields["author"].widget.field == "username"
|
||||
assert devices.fields["user"].widget.field == "username"
|
||||
Reference in New Issue
Block a user