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:
2026-09-26 16:50:29 +03:30
parent 3ec28638d1
commit ff99130938
76 changed files with 3271 additions and 1357 deletions

View File

@@ -13,9 +13,9 @@ class AnnouncementSchema(ModelSchema):
author: AuthorSchema
content_html: str
class Config:
class Meta:
model = Announcement
model_fields = [
fields = [
"id",
"title",
"content",
@@ -64,9 +64,9 @@ class AnnouncementUpdateSchema(Schema):
class PushDeviceSchema(ModelSchema):
user: AuthorSchema
class Config:
class Meta:
model = PushNotificationDevice
model_fields = ["id", "device_token", "device_type", "is_active", "created_at"]
fields = ["id", "device_token", "device_type", "is_active", "created_at"]
class PushDeviceCreateSchema(Schema):

View File

@@ -17,6 +17,7 @@ from apps.communications.api.schemas import (
PushDeviceUpdateSchema,
)
from apps.communications.models import Announcement, AnnouncementPriority, AnnouncementType, PushNotificationDevice
from core.api.schemas import ErrorSchema
from core.authentication import jwt_auth
communications_router = Router()
@@ -31,7 +32,7 @@ def _is_staff_user(user) -> bool:
def list_announcements(request, published_only: bool = True):
queryset = Announcement.objects.select_related("author").filter(is_deleted=False)
if published_only:
queryset = queryset.filter(is_published=True, publish_date__lte=timezone.now())
queryset = queryset.filter(is_published=True).filter(Q(publish_date__isnull=True) | Q(publish_date__lte=timezone.now()))
items = []
for announcement in queryset.order_by("-created_at"):
@@ -51,22 +52,35 @@ def list_announcements(request, published_only: bool = True):
return items
@communications_router.get("/announcements/{announcement_id}/", response=AnnouncementSchema)
@communications_router.get("/announcements/stats/", response={200: AnnouncementStatsSchema, 403: ErrorSchema}, auth=jwt_auth)
def get_announcement_stats(request):
user = request.auth
if not _is_staff_user(user):
return 403, {"error": "Permission denied"}
return Announcement.objects.filter(is_deleted=False).aggregate(
total_announcements=Count("id"),
published_announcements=Count("id", filter=Q(is_published=True)),
draft_announcements=Count("id", filter=Q(is_published=False)),
urgent_announcements=Count("id", filter=Q(priority="urgent")),
)
@communications_router.get("/announcements/{announcement_id}/", response={200: AnnouncementSchema, 404: ErrorSchema})
def get_announcement(request, announcement_id: int):
announcement = get_object_or_404(
Announcement.objects.select_related("author").filter(is_deleted=False),
id=announcement_id,
)
if not announcement.is_published and not _is_staff_user(getattr(request, "auth", None)):
return {"error": "Announcement not found"}, 404
return 404, {"error": "Announcement not found"}
return announcement
@communications_router.post("/announcements/", response=AnnouncementSchema, auth=jwt_auth)
@communications_router.post("/announcements/", response={200: AnnouncementSchema, 403: ErrorSchema}, auth=jwt_auth)
def create_announcement(request, payload: AnnouncementCreateSchema):
user = request.auth
if not _is_staff_user(user):
return {"error": "Permission denied"}, 403
return 403, {"error": "Permission denied"}
announcement = Announcement.objects.create(
author=user,
@@ -81,11 +95,11 @@ def create_announcement(request, payload: AnnouncementCreateSchema):
return announcement
@communications_router.put("/announcements/{announcement_id}/", response=AnnouncementSchema, auth=jwt_auth)
@communications_router.put("/announcements/{announcement_id}/", response={200: AnnouncementSchema, 403: ErrorSchema}, auth=jwt_auth)
def update_announcement(request, announcement_id: int, payload: AnnouncementCreateSchema):
user = request.auth
if not _is_staff_user(user):
return {"error": "Permission denied"}, 403
return 403, {"error": "Permission denied"}
announcement = get_object_or_404(Announcement, id=announcement_id, is_deleted=False)
announcement.title = payload.title
@@ -99,30 +113,16 @@ def update_announcement(request, announcement_id: int, payload: AnnouncementCrea
return announcement
@communications_router.delete("/announcements/{announcement_id}/", response=MessageResponseSchema, auth=jwt_auth)
@communications_router.delete("/announcements/{announcement_id}/", response={200: MessageResponseSchema, 403: ErrorSchema}, auth=jwt_auth)
def delete_announcement(request, announcement_id: int):
user = request.auth
if not _is_staff_user(user):
return {"error": "Permission denied"}, 403
return 403, {"error": "Permission denied"}
announcement = get_object_or_404(Announcement, id=announcement_id, is_deleted=False)
announcement.soft_delete()
announcement.delete()
return {"message": "Announcement deleted successfully"}
@communications_router.get("/announcements/stats/", response=AnnouncementStatsSchema, auth=jwt_auth)
def get_announcement_stats(request):
user = request.auth
if not _is_staff_user(user):
return {"error": "Permission denied"}, 403
stats = Announcement.objects.filter(is_deleted=False).aggregate(
total_announcements=Count("id"),
published_announcements=Count("id", filter=Q(is_published=True)),
draft_announcements=Count("id", filter=Q(is_published=False)),
urgent_announcements=Count("id", filter=Q(priority="urgent")),
)
return stats
@communications_router.post("/push-devices/", response=PushDeviceSchema, auth=jwt_auth)
def register_push_device(request, payload: PushDeviceCreateSchema):
user = request.auth
@@ -138,7 +138,7 @@ def register_push_device(request, payload: PushDeviceCreateSchema):
return device
@communications_router.delete("/push-devices/", response=MessageResponseSchema, auth=jwt_auth)
@communications_router.delete("/push-devices/", response={200: MessageResponseSchema, 404: MessageResponseSchema}, auth=jwt_auth)
def unregister_push_device(request, device_token: str):
user = request.auth
try:
@@ -146,7 +146,7 @@ def unregister_push_device(request, device_token: str):
device.delete()
return {"message": "Device unregistered successfully"}
except PushNotificationDevice.DoesNotExist:
return {"message": "Device not found"}, 404
return 404, {"message": "Device not found"}
@communications_router.get("/push-devices/", response=List[PushDeviceSchema], auth=jwt_auth)

View 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

View 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()

View 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

View File

@@ -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)

View 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()

View 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"