import unittest from pathlib import Path from tempfile import TemporaryDirectory from unittest.mock import patch import httpx from app import main class IngestionLoggingTests(unittest.IsolatedAsyncioTestCase): API_TOKEN = "test-api-token-that-is-long-enough" SENTINELS = { "token-ingestion-sentinel", "device-ingestion-sentinel", "https://url-ingestion-sentinel.example/secret", "url-ingestion-invalid-sentinel", "title-ingestion-sentinel", "transition-ingestion-sentinel", "2049-07-28T15:41:26+00:00", } async def request(self, **kwargs): transport = httpx.ASGITransport(app=main.app, raise_app_exceptions=False) async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client: return await client.post("/v1/visits", **kwargs) def setUp(self): main.API_TOKEN = self.API_TOKEN def assert_local_timestamp(self, line): self.assertRegex(line, r"ingestion_timestamp=\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{2}:\d{2}") def assert_no_sentinels(self, line): for sentinel in self.SENTINELS: self.assertNotIn(sentinel, line) def valid_payload(self): return { "device_id": "device-ingestion-sentinel", "visits": [{ "url": "https://url-ingestion-sentinel.example/secret", "title": "title-ingestion-sentinel", "visit_time": "2049-07-28T15:41:26+00:00", "transition": "transition-ingestion-sentinel", }], } async def test_invalid_token_is_logged_without_authorization_value(self): invalid_token = "token-ingestion-sentinel" with self.assertLogs(main.logger, "WARNING") as captured: response = await self.request( headers={"Authorization": f"Bearer {invalid_token}"}, json=self.valid_payload(), ) self.assertEqual(response.status_code, 401) self.assertEqual(response.json(), {"detail": "Invalid API token"}) line = "\n".join(captured.output) self.assert_local_timestamp(line) self.assertIn("timezone=Europe/Ljubljana", line) self.assertIn("status=401", line) self.assertIn("reason=invalid_api_token", line) self.assert_no_sentinels(line) async def test_validation_log_is_sanitized_and_response_is_standard_422(self): payload = self.valid_payload() payload["visits"][0]["url"] = "url-ingestion-invalid-sentinel" with self.assertLogs(main.logger, "WARNING") as captured: response = await self.request(json=payload) self.assertEqual(response.status_code, 422) self.assertEqual(set(response.json()), {"detail"}) self.assertIsInstance(response.json()["detail"], list) line = "\n".join(captured.output) self.assert_local_timestamp(line) self.assertIn("timezone=Europe/Ljubljana", line) self.assertIn("status=422", line) self.assertIn("body.visits.index_0", line) self.assert_no_sentinels(line) async def test_database_failure_is_logged_and_returns_500(self): with patch.object(main, "save_batch", side_effect=RuntimeError("database unavailable")): with self.assertLogs(main.logger, "ERROR") as captured: response = await self.request( headers={"Authorization": f"Bearer {self.API_TOKEN}"}, json=self.valid_payload(), ) self.assertEqual(response.status_code, 500) self.assertEqual(response.text, "Internal Server Error") line = "\n".join(captured.output) self.assert_local_timestamp(line) self.assertIn("timezone=Europe/Ljubljana", line) self.assertIn("status=500", line) self.assertIn("validated_visits=1", line) self.assertNotIn("device_id=", line) self.assertNotIn("accepted=", line) self.assert_no_sentinels(line) async def test_malformed_json_is_logged_as_422_without_body_contents(self): invalid_body = b'{"device_id":"test-device",' with self.assertLogs(main.logger, "WARNING") as captured: response = await self.request( content=invalid_body, headers={"Content-Type": "application/json"}, ) self.assertEqual(response.status_code, 422) self.assertEqual(set(response.json()), {"detail"}) self.assertIsInstance(response.json()["detail"], list) line = "\n".join(captured.output) self.assert_local_timestamp(line) self.assertIn("status=422", line) self.assertNotIn(invalid_body.decode(), line) def test_file_logging_is_append_only_and_idempotent(self): original_data_dir = main.DATA_DIR original_handler_ids = {id(handler) for handler in main.logger.handlers} with TemporaryDirectory() as temp_dir: main.DATA_DIR = Path(temp_dir) log_path = main.ingestion_log_path() log_path.write_text("existing line\n", encoding="utf-8") try: main.configure_file_logging() main.logger.info("file_logging_sentinel") for handler in main.logger.handlers: handler.flush() main.configure_file_logging() file_handlers = [handler for handler in main.logger.handlers if getattr(handler, main._FILE_HANDLER_MARKER, False)] self.assertEqual(len(file_handlers), 1) lines = log_path.read_text(encoding="utf-8").splitlines() self.assertEqual(lines[0], "existing line") self.assertEqual(len(lines), 2) self.assertRegex(lines[1], r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{2}:\d{2} INFO file_logging_sentinel$") self.assertEqual(log_path.stat().st_mode & 0o777, 0o600) finally: for handler in list(main.logger.handlers): if id(handler) not in original_handler_ids: main.logger.removeHandler(handler) handler.close() main.DATA_DIR = original_data_dir if __name__ == "__main__": unittest.main()