from datetime import timedelta from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.core.exceptions import PermissionDenied, ValidationError from django.test import TestCase from django.urls import reverse from django.utils import timezone from .field_notes import draft_token, regroup_event_notes, reportable_notes from .models import Event, FieldNote, FieldNoteContext, FieldNoteAssociation, PendingEvent class FieldNotesTests(TestCase): def setUp(self): User = get_user_model() self.alice = User.objects.create_user('alice', password='test-password') self.bob = User.objects.create_user('bob', password='test-password') self.event = Event.objects.create(original_filename='Burst', classifier_response={}, source_type='manual', occurrences=15) self.url = reverse('fireworks_detect:field_notes') self.client.force_login(self.alice) def note(self, user=None, visibility='private', **kwargs): user = user or self.alice context = FieldNoteContext.objects.create(author=user, event=self.event) return FieldNote.objects.create(author=user, context=context, content='A private observation', visibility=visibility, **kwargs) def test_only_content_required_private_defaults_plain_text(self): response = self.client.post(self.url, {'content': '\nSecond line'}) self.assertEqual(response.status_code, 302) note = FieldNote.objects.get() self.assertEqual(note.visibility, 'private') self.assertEqual(note.source_type, 'unknown') self.assertEqual(note.verification_status, 'unverified') response = self.client.get(self.url) self.assertContains(response, '<script>') self.assertNotContains(response, '') def test_cross_user_read_create_link_and_export_are_scoped(self): note = self.note() self.client.force_login(self.bob) self.assertNotContains(self.client.get(self.url), note.content) self.assertNotContains(self.client.get(reverse('fireworks_detect:event_detail', args=[self.event.pk])), note.content) response = self.client.post(self.url, {'content':'forged', 'token':draft_token(self.alice)}) self.assertEqual(response.status_code, 403) self.assertEqual(self.client.post(reverse('fireworks_detect:link_field_note', args=[note.context_id]), {'event': self.event.pk}).status_code, 404) self.assertEqual(self.client.get(reverse('fireworks_detect:export_field_notes', args=['json'])).json()['notes'], []) def test_anonymous_cannot_create_read_or_export_notes(self): self.note() self.client.logout() self.assertEqual(self.client.post(self.url, {'content':'no'}).status_code, 302) self.assertEqual(self.client.get(self.url).status_code, 302) self.assertNotContains(self.client.get(reverse('fireworks_detect:event_detail', args=[self.event.pk])), 'A private observation') self.assertEqual(self.client.get(reverse('fireworks_detect:export_field_notes', args=['json'])).status_code, 302) def test_export_always_excludes_private_even_for_superuser(self): self.note() public = self.note(visibility='reportable', source_type='second_hand') self.note(self.bob, visibility='reportable') self.assertEqual(list(reportable_notes(self.alice)), [public]) self.alice.is_superuser = self.alice.is_staff = True self.alice.save() for format in ['json','csv']: response = self.client.get(reverse('fireworks_detect:export_field_notes', args=[format])) self.assertEqual(response.status_code, 200) self.assertNotIn('"visibility": "private"', response.content.decode()) rows = self.client.get(reverse('fireworks_detect:export_field_notes', args=['json'])).json()['notes'] self.assertEqual(len(rows), 2) self.assertEqual(rows[0]['source_type'], 'second_hand') self.assertEqual(rows[0]['verification_status'], 'unverified') def test_reportable_does_not_grant_other_users_read_access(self): note = self.note(visibility='reportable') self.client.force_login(self.bob) self.assertNotContains(self.client.get(self.url), note.content) def test_observed_time_entry_time_and_append_only(self): self.client.post(self.url, {'content':'Later information', 'observed_at':'2026-10-09T14:00'}) note = FieldNote.objects.get() self.assertTrue(timezone.is_aware(note.observed_at)) self.assertLess(note.observed_at, note.created_at) entered = note.created_at note.content = 'rewrite' with self.assertRaises(ValidationError): note.save() note.refresh_from_db() self.assertEqual(note.content, 'Later information') self.assertEqual(note.created_at, entered) def test_invalid_forms_render_with_and_without_htmx(self): for headers in [{}, {'HTTP_HX_REQUEST':'true'}]: response = self.client.post(self.url, {'content':' ', 'visibility':'public'}, **headers) self.assertEqual(response.status_code, 200) self.assertContains(response, 'errorlist') self.assertFalse(FieldNote.objects.exists()) def test_live_notes_bind_to_report_and_survive_approval(self): token = draft_token(self.alice) self.client.post(self.url, {'token':token, 'content':'Heard during listening'}, HTTP_HX_REQUEST='true') note = FieldNote.objects.get() original_time = note.created_at response = self.client.post(reverse('fireworks_detect:submit_manual_pending'), {'occurrences':'15', 'field_note_context':token}) self.assertEqual(response.status_code, 200) pending = PendingEvent.objects.get() note.context.refresh_from_db() self.assertEqual(note.context.pending_event_id, pending.pk) event = pending.approve(actor=self.alice) note.context.refresh_from_db() self.assertEqual(note.context.event_id, event.pk) self.assertIsNone(note.context.pending_event_id) note.refresh_from_db() self.assertEqual(note.created_at, original_time) self.assertEqual(note.context.associations.count(), 2) self.assertEqual(note.context.associations.last().actor_id, self.alice.pk) # A note submitted from an already-open form follows the approved report. self.client.post(self.url, {'token':token, 'content':'Late save'}) self.assertEqual(FieldNote.objects.get(content='Late save').context.event_id, event.pk) # Reusing a report token cannot reparent existing notes or create a report. self.assertEqual(self.client.post(reverse('fireworks_detect:submit_manual_pending'), {'occurrences':'1', 'field_note_context':token}).status_code, 403) self.assertFalse(PendingEvent.objects.exists()) def test_pending_access_checked_and_historical_append(self): pending = PendingEvent.objects.create(original_filename='secret', classifier_response={}) self.assertEqual(self.client.get(self.url, {'pending':pending.pk}).status_code, 404) self.assertEqual(self.client.post(self.url, {'pending':pending.pk,'content':'no'}).status_code, 404) self.assertEqual(self.client.post(self.url, {'event':self.event.pk,'content':'Historical follow-up'}).status_code, 302) self.assertEqual(FieldNote.objects.get().context.event_id, self.event.pk) def test_standalone_link_and_regroup_preserve_provenance(self): self.client.post(self.url, {'content':'Possible camera lead'}) note = FieldNote.objects.get() response = self.client.post(reverse('fireworks_detect:link_field_note', args=[note.context_id]), {'event':self.event.pk}) self.assertEqual(response.status_code, 302) target = Event.objects.create(original_filename='Grouped burst', classifier_response={}, occurrences=20) with self.assertRaises(PermissionDenied): regroup_event_notes(self.alice, self.event, target) self.alice.is_superuser = self.alice.is_staff = True; self.alice.save() regroup_event_notes(self.alice, self.event, target) self.event.delete() note.context.refresh_from_db() self.assertEqual(note.context.event_id, target.pk) self.assertEqual(note.context.associations.count(), 2) self.assertEqual(note.context.associations.last().previous['id'], self.event.pk or note.context.associations.first().target['id']) self.assertEqual(FieldNote.objects.count(), 1) def test_denied_report_retains_notes_and_original_reference(self): token = draft_token(self.alice) self.client.post(self.url, {'token':token,'content':'Retain observation'}) self.client.post(reverse('fireworks_detect:submit_manual_pending'), {'occurrences':'3','field_note_context':token}) pending = PendingEvent.objects.get(); old_id = pending.pk; pending.deny() note = FieldNote.objects.get() self.assertIsNone(note.context.pending_event_id) self.assertEqual(note.context.associations.get().target, {'kind':'pending','id':old_id}) def test_staff_needs_explicit_permission_for_private_notes(self): self.note() self.bob.is_staff = True; self.bob.save() self.assertFalse(FieldNote.objects.visible_to(self.bob).exists()) self.bob.user_permissions.add(Permission.objects.get(codename='view_all_fieldnotes')) bob = get_user_model().objects.get(pk=self.bob.pk) self.assertEqual(FieldNote.objects.visible_to(bob).count(), 1) self.assertFalse(reportable_notes(bob).exists()) def test_csv_formula_is_escaped(self): ctx = FieldNoteContext.objects.create(author=self.alice) FieldNote.objects.create(author=self.alice, context=ctx, content='=1+1', visibility='reportable') self.assertContains(self.client.get(reverse('fireworks_detect:export_field_notes', args=['csv'])), "'=1+1") def test_note_posts_require_csrf(self): from django.test import Client browser = Client(enforce_csrf_checks=True) browser.force_login(self.alice) self.assertEqual(browser.post(self.url, {"content":"forged"}).status_code, 403) self.assertFalse(FieldNote.objects.exists()) def test_history_orders_by_entry_not_backdated_observation(self): first = self.note(observed_at=timezone.now()) second = self.note(observed_at=timezone.now()-timedelta(days=7)) self.assertEqual(list(FieldNote.objects.values_list("pk", flat=True)), [first.pk, second.pk]) self.client.force_login(self.bob) self.bob.user_permissions.add(Permission.objects.get(codename="export_reportable_fieldnotes")) # Export permission does not grant read access to private history. self.assertNotContains(self.client.get(self.url), first.content)