""" Tests for the observation_send_to fix (Fix 1.2): the department branch used to read observation.reference_number (which does not exist on Observation) and crash with AttributeError. It now uses tracking_code. """ from unittest.mock import patch from django.contrib.auth.models import Group from django.test import TestCase from django.urls import reverse from apps.accounts.models import User from apps.observations.models import Observation, ObservationStatus from apps.organizations.models import Department, Hospital, LocationType class ObservationSendToFixTests(TestCase): """Fix 1.2 — observation_send_to department branch must not crash.""" def setUp(self): self.hospital = Hospital.objects.create(name="Obs Fix Hospital", code="OFX", status="active") px_group = Group.objects.create(name="PX Admin") self.user = User.objects.create_user(email="obs@example.com", password="pass12345") self.user.groups.add(px_group) self.client.force_login(self.user) self.observation = Observation.objects.create( hospital=self.hospital, location_type=LocationType.OP, description="Spilled hazard in the corridor near the lab.", status=ObservationStatus.IN_PROGRESS.value, severity="medium", ) self.department = Department.objects.create( hospital=self.hospital, name="Lab", name_en="Lab", code="ofx_lab", status="active" ) @patch("apps.notifications.services.NotificationService.send_sms") @patch("apps.notifications.services.NotificationService.send_email") @patch("apps.organizations.department_contacts.get_champion_and_manager") def test_send_to_department_returns_200_not_500(self, mock_champions, mock_email, mock_sms): # Provide a minimal champion target so the department branch is taken # and the notification loop (which used to reference reference_number) runs. mock_champions.return_value = [ { "staff": None, "user": self.user, "email": "champ@example.com", "phone": "0500000000", "label": "Champion", } ] response = self.client.post( reverse("observations:observation_send_to", kwargs={"pk": self.observation.pk}), {"recipient_type": "department", "department_id": str(self.department.id)}, HTTP_X_REQUESTED_WITH="XMLHttpRequest", ) # Before the fix this raised AttributeError -> HTTP 500. self.assertEqual(response.status_code, 200, response.content) result = response.json() self.assertTrue(result.get("success", False)) self.observation.refresh_from_db() self.assertTrue(self.observation.sent_to_department) self.assertEqual(self.observation.assigned_department_id, self.department.id)