test_notifications_api.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. """Integration tests for Notifications API endpoints.
  2. Tests the full request/response cycle for /api/v1/notifications/ endpoints.
  3. """
  4. import pytest
  5. from httpx import AsyncClient
  6. class TestNotificationsAPI:
  7. """Integration tests for /api/v1/notifications/ endpoints."""
  8. # ========================================================================
  9. # List endpoints
  10. # ========================================================================
  11. @pytest.mark.asyncio
  12. @pytest.mark.integration
  13. async def test_list_notification_providers_empty(self, async_client: AsyncClient):
  14. """Verify empty list is returned when no providers exist."""
  15. response = await async_client.get("/api/v1/notifications/")
  16. assert response.status_code == 200
  17. assert response.json() == []
  18. @pytest.mark.asyncio
  19. @pytest.mark.integration
  20. async def test_list_notification_providers_with_data(
  21. self, async_client: AsyncClient, notification_provider_factory, db_session
  22. ):
  23. """Verify list returns existing providers."""
  24. _provider = await notification_provider_factory(name="Test Provider")
  25. response = await async_client.get("/api/v1/notifications/")
  26. assert response.status_code == 200
  27. data = response.json()
  28. assert len(data) >= 1
  29. assert any(p["name"] == "Test Provider" for p in data)
  30. # ========================================================================
  31. # Create endpoints
  32. # ========================================================================
  33. @pytest.mark.asyncio
  34. @pytest.mark.integration
  35. async def test_create_callmebot_provider(self, async_client: AsyncClient):
  36. """Verify callmebot notification provider can be created."""
  37. data = {
  38. "name": "Test CallMeBot",
  39. "provider_type": "callmebot",
  40. "enabled": True,
  41. "config": {"phone_number": "+1234567890", "api_key": "test-api-key"},
  42. "on_print_start": True,
  43. "on_print_complete": True,
  44. "on_print_failed": True,
  45. "on_print_stopped": False,
  46. }
  47. response = await async_client.post("/api/v1/notifications/", json=data)
  48. assert response.status_code == 200
  49. result = response.json()
  50. assert result["name"] == "Test CallMeBot"
  51. assert result["provider_type"] == "callmebot"
  52. assert result["on_print_start"] is True
  53. assert result["on_print_stopped"] is False
  54. @pytest.mark.asyncio
  55. @pytest.mark.integration
  56. async def test_create_ntfy_provider(self, async_client: AsyncClient):
  57. """Verify ntfy notification provider can be created."""
  58. data = {
  59. "name": "Test Ntfy",
  60. "provider_type": "ntfy",
  61. "enabled": True,
  62. "config": {
  63. "server": "https://ntfy.sh",
  64. "topic": "test-topic",
  65. },
  66. "on_print_complete": True,
  67. }
  68. response = await async_client.post("/api/v1/notifications/", json=data)
  69. assert response.status_code == 200
  70. result = response.json()
  71. assert result["provider_type"] == "ntfy"
  72. @pytest.mark.asyncio
  73. @pytest.mark.integration
  74. async def test_create_provider_with_printer(self, async_client: AsyncClient, printer_factory, db_session):
  75. """Verify provider can be linked to specific printer."""
  76. printer = await printer_factory(name="Test Printer")
  77. data = {
  78. "name": "Printer Ntfy",
  79. "provider_type": "ntfy",
  80. "config": {"server": "https://ntfy.sh", "topic": "test-topic"},
  81. "printer_id": printer.id,
  82. }
  83. response = await async_client.post("/api/v1/notifications/", json=data)
  84. assert response.status_code == 200
  85. result = response.json()
  86. assert result["printer_id"] == printer.id
  87. # ========================================================================
  88. # Get single endpoint
  89. # ========================================================================
  90. @pytest.mark.asyncio
  91. @pytest.mark.integration
  92. async def test_get_notification_provider(
  93. self, async_client: AsyncClient, notification_provider_factory, db_session
  94. ):
  95. """Verify single provider can be retrieved."""
  96. provider = await notification_provider_factory(name="Get Test Provider")
  97. response = await async_client.get(f"/api/v1/notifications/{provider.id}")
  98. assert response.status_code == 200
  99. result = response.json()
  100. assert result["id"] == provider.id
  101. assert result["name"] == "Get Test Provider"
  102. @pytest.mark.asyncio
  103. @pytest.mark.integration
  104. async def test_get_provider_not_found(self, async_client: AsyncClient):
  105. """Verify 404 for non-existent provider."""
  106. response = await async_client.get("/api/v1/notifications/9999")
  107. assert response.status_code == 404
  108. # ========================================================================
  109. # Update endpoints (CRITICAL - toggle persistence)
  110. # ========================================================================
  111. @pytest.mark.asyncio
  112. @pytest.mark.integration
  113. async def test_update_event_toggles(self, async_client: AsyncClient, notification_provider_factory, db_session):
  114. """CRITICAL: Verify notification event toggles persist correctly."""
  115. provider = await notification_provider_factory(
  116. on_print_start=True,
  117. on_print_complete=True,
  118. on_print_stopped=False,
  119. )
  120. # Toggle on_print_stopped to True
  121. response = await async_client.patch(f"/api/v1/notifications/{provider.id}", json={"on_print_stopped": True})
  122. assert response.status_code == 200
  123. assert response.json()["on_print_stopped"] is True
  124. # Verify change persisted
  125. response = await async_client.get(f"/api/v1/notifications/{provider.id}")
  126. assert response.json()["on_print_stopped"] is True
  127. @pytest.mark.asyncio
  128. @pytest.mark.integration
  129. async def test_update_ams_alarm_toggles(self, async_client: AsyncClient, notification_provider_factory, db_session):
  130. """CRITICAL: Verify AMS alarm toggles persist correctly."""
  131. provider = await notification_provider_factory(
  132. on_ams_humidity_high=False,
  133. on_ams_temperature_high=False,
  134. )
  135. # Enable AMS alarms
  136. response = await async_client.patch(
  137. f"/api/v1/notifications/{provider.id}",
  138. json={
  139. "on_ams_humidity_high": True,
  140. "on_ams_temperature_high": True,
  141. },
  142. )
  143. assert response.status_code == 200
  144. result = response.json()
  145. assert result["on_ams_humidity_high"] is True
  146. assert result["on_ams_temperature_high"] is True
  147. # Verify persistence
  148. response = await async_client.get(f"/api/v1/notifications/{provider.id}")
  149. result = response.json()
  150. assert result["on_ams_humidity_high"] is True
  151. assert result["on_ams_temperature_high"] is True
  152. @pytest.mark.asyncio
  153. @pytest.mark.integration
  154. async def test_enable_disable_provider(self, async_client: AsyncClient, notification_provider_factory, db_session):
  155. """Verify provider can be enabled/disabled."""
  156. provider = await notification_provider_factory(enabled=True)
  157. # Disable
  158. response = await async_client.patch(f"/api/v1/notifications/{provider.id}", json={"enabled": False})
  159. assert response.status_code == 200
  160. assert response.json()["enabled"] is False
  161. # Enable
  162. response = await async_client.patch(f"/api/v1/notifications/{provider.id}", json={"enabled": True})
  163. assert response.status_code == 200
  164. assert response.json()["enabled"] is True
  165. @pytest.mark.asyncio
  166. @pytest.mark.integration
  167. async def test_update_quiet_hours(self, async_client: AsyncClient, notification_provider_factory, db_session):
  168. """Verify quiet hours can be configured."""
  169. provider = await notification_provider_factory(quiet_hours_enabled=False)
  170. response = await async_client.patch(
  171. f"/api/v1/notifications/{provider.id}",
  172. json={
  173. "quiet_hours_enabled": True,
  174. "quiet_hours_start": "22:00",
  175. "quiet_hours_end": "07:00",
  176. },
  177. )
  178. assert response.status_code == 200
  179. result = response.json()
  180. assert result["quiet_hours_enabled"] is True
  181. assert result["quiet_hours_start"] == "22:00"
  182. assert result["quiet_hours_end"] == "07:00"
  183. @pytest.mark.asyncio
  184. @pytest.mark.integration
  185. async def test_update_daily_digest(self, async_client: AsyncClient, notification_provider_factory, db_session):
  186. """Verify daily digest can be configured."""
  187. provider = await notification_provider_factory(daily_digest_enabled=False)
  188. response = await async_client.patch(
  189. f"/api/v1/notifications/{provider.id}",
  190. json={
  191. "daily_digest_enabled": True,
  192. "daily_digest_time": "09:00",
  193. },
  194. )
  195. assert response.status_code == 200
  196. result = response.json()
  197. assert result["daily_digest_enabled"] is True
  198. assert result["daily_digest_time"] == "09:00"
  199. @pytest.mark.asyncio
  200. @pytest.mark.integration
  201. async def test_update_multiple_event_toggles(
  202. self, async_client: AsyncClient, notification_provider_factory, db_session
  203. ):
  204. """Verify multiple event toggles can be updated at once."""
  205. provider = await notification_provider_factory(
  206. on_print_start=True,
  207. on_print_complete=True,
  208. on_print_failed=True,
  209. on_print_stopped=False,
  210. on_printer_offline=False,
  211. )
  212. response = await async_client.patch(
  213. f"/api/v1/notifications/{provider.id}",
  214. json={
  215. "on_print_start": False,
  216. "on_print_stopped": True,
  217. "on_printer_offline": True,
  218. },
  219. )
  220. assert response.status_code == 200
  221. result = response.json()
  222. assert result["on_print_start"] is False
  223. assert result["on_print_stopped"] is True
  224. assert result["on_printer_offline"] is True
  225. # Unchanged fields should remain
  226. assert result["on_print_complete"] is True
  227. assert result["on_print_failed"] is True
  228. # ========================================================================
  229. # Test notification endpoint
  230. # ========================================================================
  231. @pytest.mark.asyncio
  232. @pytest.mark.integration
  233. async def test_test_notification(
  234. self, async_client: AsyncClient, notification_provider_factory, mock_httpx_client, db_session
  235. ):
  236. """Verify test notification can be sent."""
  237. provider = await notification_provider_factory()
  238. response = await async_client.post(f"/api/v1/notifications/{provider.id}/test")
  239. assert response.status_code == 200
  240. result = response.json()
  241. assert result["success"] is True
  242. @pytest.mark.asyncio
  243. @pytest.mark.integration
  244. async def test_test_notification_disabled_provider(
  245. self, async_client: AsyncClient, notification_provider_factory, db_session
  246. ):
  247. """Verify test notification works even for disabled provider."""
  248. provider = await notification_provider_factory(enabled=False)
  249. response = await async_client.post(f"/api/v1/notifications/{provider.id}/test")
  250. # Test should still work for disabled providers
  251. assert response.status_code == 200
  252. # ========================================================================
  253. # Delete endpoint
  254. # ========================================================================
  255. @pytest.mark.asyncio
  256. @pytest.mark.integration
  257. async def test_delete_notification_provider(
  258. self, async_client: AsyncClient, notification_provider_factory, db_session
  259. ):
  260. """Verify notification provider can be deleted."""
  261. provider = await notification_provider_factory()
  262. provider_id = provider.id
  263. response = await async_client.delete(f"/api/v1/notifications/{provider_id}")
  264. assert response.status_code == 200
  265. # Verify deleted
  266. response = await async_client.get(f"/api/v1/notifications/{provider_id}")
  267. assert response.status_code == 404
  268. @pytest.mark.asyncio
  269. @pytest.mark.integration
  270. async def test_delete_nonexistent_provider(self, async_client: AsyncClient):
  271. """Verify deleting non-existent provider returns 404."""
  272. response = await async_client.delete("/api/v1/notifications/9999")
  273. assert response.status_code == 404
  274. class TestNotificationTemplatesAPI:
  275. """Integration tests for /api/v1/notification-templates/ endpoints."""
  276. @pytest.fixture
  277. async def seeded_templates(self, db_session):
  278. """Seed notification templates for tests."""
  279. from backend.app.models.notification_template import DEFAULT_TEMPLATES, NotificationTemplate
  280. templates = []
  281. for template_data in DEFAULT_TEMPLATES:
  282. template = NotificationTemplate(**template_data)
  283. db_session.add(template)
  284. templates.append(template)
  285. await db_session.commit()
  286. for template in templates:
  287. await db_session.refresh(template)
  288. return templates
  289. @pytest.mark.asyncio
  290. @pytest.mark.integration
  291. async def test_list_templates(self, async_client: AsyncClient, seeded_templates):
  292. """Verify default templates are seeded and can be listed."""
  293. response = await async_client.get("/api/v1/notification-templates/")
  294. assert response.status_code == 200
  295. templates = response.json()
  296. # Should have default templates seeded
  297. assert len(templates) >= 1
  298. @pytest.mark.asyncio
  299. @pytest.mark.integration
  300. async def test_get_template_by_id(self, async_client: AsyncClient, seeded_templates):
  301. """Verify template can be retrieved by ID."""
  302. # Get first template ID from seeded data
  303. template_id = seeded_templates[0].id
  304. response = await async_client.get(f"/api/v1/notification-templates/{template_id}")
  305. assert response.status_code == 200
  306. template = response.json()
  307. assert template["id"] == template_id
  308. @pytest.mark.asyncio
  309. @pytest.mark.integration
  310. async def test_update_template(self, async_client: AsyncClient, seeded_templates):
  311. """Verify template can be updated."""
  312. # Get first template
  313. template_id = seeded_templates[0].id
  314. # Update it (route uses PUT, not PATCH)
  315. response = await async_client.put(
  316. f"/api/v1/notification-templates/{template_id}",
  317. json={
  318. "title_template": "Custom Title: {printer}",
  319. "body_template": "Custom body for {filename}",
  320. },
  321. )
  322. assert response.status_code == 200
  323. result = response.json()
  324. assert result["title_template"] == "Custom Title: {printer}"
  325. assert result["body_template"] == "Custom body for {filename}"
  326. @pytest.mark.asyncio
  327. @pytest.mark.integration
  328. async def test_reset_template_to_default(self, async_client: AsyncClient, seeded_templates):
  329. """Verify template can be reset to default."""
  330. template_id = seeded_templates[0].id
  331. response = await async_client.post(f"/api/v1/notification-templates/{template_id}/reset")
  332. assert response.status_code == 200
  333. result = response.json()
  334. assert result["is_default"] is True
  335. class TestHomeAssistantNotificationProvider:
  336. """Integration tests for Home Assistant notification provider."""
  337. @pytest.mark.asyncio
  338. @pytest.mark.integration
  339. async def test_create_homeassistant_provider(self, async_client: AsyncClient):
  340. """Verify homeassistant notification provider can be created with empty config."""
  341. data = {
  342. "name": "HA Notifications",
  343. "provider_type": "homeassistant",
  344. "enabled": True,
  345. "config": {},
  346. "on_print_complete": True,
  347. "on_print_failed": True,
  348. }
  349. response = await async_client.post("/api/v1/notifications/", json=data)
  350. assert response.status_code == 200
  351. result = response.json()
  352. assert result["name"] == "HA Notifications"
  353. assert result["provider_type"] == "homeassistant"
  354. assert result["on_print_complete"] is True
  355. assert result["on_print_failed"] is True
  356. @pytest.mark.asyncio
  357. @pytest.mark.integration
  358. async def test_update_homeassistant_provider(
  359. self, async_client: AsyncClient, notification_provider_factory, db_session
  360. ):
  361. """Verify homeassistant provider can be updated."""
  362. provider = await notification_provider_factory(
  363. name="HA Test",
  364. provider_type="homeassistant",
  365. config="{}",
  366. )
  367. response = await async_client.patch(
  368. f"/api/v1/notifications/{provider.id}",
  369. json={"on_print_start": True, "on_printer_offline": True},
  370. )
  371. assert response.status_code == 200
  372. result = response.json()
  373. assert result["on_print_start"] is True
  374. assert result["on_printer_offline"] is True
  375. @pytest.mark.asyncio
  376. @pytest.mark.integration
  377. async def test_test_homeassistant_config_without_ha_settings(self, async_client: AsyncClient):
  378. """Verify test-config returns error when HA is not configured."""
  379. response = await async_client.post(
  380. "/api/v1/notifications/test-config",
  381. json={"provider_type": "homeassistant", "config": {}},
  382. )
  383. assert response.status_code == 200
  384. result = response.json()
  385. assert result["success"] is False
  386. assert "not configured" in result["message"].lower() or "Home Assistant" in result["message"]