test_notifications_api.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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. @pytest.mark.asyncio
  275. @pytest.mark.integration
  276. async def test_create_provider_with_first_layer_complete(self, async_client: AsyncClient):
  277. """Verify first layer complete toggle persists on create."""
  278. data = {
  279. "name": "First Layer Test",
  280. "provider_type": "ntfy",
  281. "config": {"server": "https://ntfy.sh", "topic": "test"},
  282. "on_first_layer_complete": True,
  283. }
  284. response = await async_client.post("/api/v1/notifications/", json=data)
  285. assert response.status_code == 200
  286. result = response.json()
  287. assert result["on_first_layer_complete"] is True
  288. @pytest.mark.asyncio
  289. @pytest.mark.integration
  290. async def test_update_first_layer_complete_toggle(
  291. self, async_client: AsyncClient, notification_provider_factory, db_session
  292. ):
  293. """CRITICAL: Verify first layer complete toggle persists correctly."""
  294. provider = await notification_provider_factory(on_first_layer_complete=False)
  295. response = await async_client.patch(
  296. f"/api/v1/notifications/{provider.id}",
  297. json={"on_first_layer_complete": True},
  298. )
  299. assert response.status_code == 200
  300. assert response.json()["on_first_layer_complete"] is True
  301. # Verify persistence
  302. response = await async_client.get(f"/api/v1/notifications/{provider.id}")
  303. assert response.json()["on_first_layer_complete"] is True
  304. @pytest.mark.asyncio
  305. @pytest.mark.integration
  306. async def test_first_layer_complete_independent_from_other_toggles(
  307. self, async_client: AsyncClient, notification_provider_factory, db_session
  308. ):
  309. """Verify first layer complete is independent from bed cooled and print complete."""
  310. provider = await notification_provider_factory(
  311. on_print_complete=True,
  312. on_bed_cooled=False,
  313. on_first_layer_complete=True,
  314. )
  315. response = await async_client.get(f"/api/v1/notifications/{provider.id}")
  316. result = response.json()
  317. assert result["on_print_complete"] is True
  318. assert result["on_bed_cooled"] is False
  319. assert result["on_first_layer_complete"] is True
  320. @pytest.mark.asyncio
  321. @pytest.mark.integration
  322. async def test_create_provider_with_missing_spool_assignment_toggle(self, async_client: AsyncClient):
  323. """Verify missing spool assignment toggle persists on create."""
  324. data = {
  325. "name": "Missing Spool Assignment Test",
  326. "provider_type": "ntfy",
  327. "config": {"server": "https://ntfy.sh", "topic": "test"},
  328. "on_print_missing_spool_assignment": True,
  329. }
  330. response = await async_client.post("/api/v1/notifications/", json=data)
  331. assert response.status_code == 200
  332. result = response.json()
  333. assert result["on_print_missing_spool_assignment"] is True
  334. @pytest.mark.asyncio
  335. @pytest.mark.integration
  336. async def test_update_missing_spool_assignment_toggle(
  337. self, async_client: AsyncClient, notification_provider_factory, db_session
  338. ):
  339. """CRITICAL: Verify missing spool assignment toggle persists correctly."""
  340. provider = await notification_provider_factory(on_print_missing_spool_assignment=False)
  341. response = await async_client.patch(
  342. f"/api/v1/notifications/{provider.id}",
  343. json={"on_print_missing_spool_assignment": True},
  344. )
  345. assert response.status_code == 200
  346. assert response.json()["on_print_missing_spool_assignment"] is True
  347. response = await async_client.get(f"/api/v1/notifications/{provider.id}")
  348. assert response.json()["on_print_missing_spool_assignment"] is True
  349. @pytest.mark.asyncio
  350. @pytest.mark.integration
  351. async def test_update_billing_charge_failed_toggle(
  352. self, async_client: AsyncClient, notification_provider_factory, db_session
  353. ):
  354. """Billing alerts can be enabled independently for each provider."""
  355. provider = await notification_provider_factory(on_billing_charge_failed=True)
  356. response = await async_client.patch(
  357. f"/api/v1/notifications/{provider.id}",
  358. json={"on_billing_charge_failed": False},
  359. )
  360. assert response.status_code == 200
  361. assert response.json()["on_billing_charge_failed"] is False
  362. response = await async_client.get(f"/api/v1/notifications/{provider.id}")
  363. assert response.json()["on_billing_charge_failed"] is False
  364. class TestNotificationTemplatesAPI:
  365. """Integration tests for /api/v1/notification-templates/ endpoints."""
  366. @pytest.fixture
  367. async def seeded_templates(self, db_session):
  368. """Seed notification templates for tests."""
  369. from backend.app.models.notification_template import DEFAULT_TEMPLATES, NotificationTemplate
  370. templates = []
  371. for template_data in DEFAULT_TEMPLATES:
  372. template = NotificationTemplate(**template_data)
  373. db_session.add(template)
  374. templates.append(template)
  375. await db_session.commit()
  376. for template in templates:
  377. await db_session.refresh(template)
  378. return templates
  379. @pytest.mark.asyncio
  380. @pytest.mark.integration
  381. async def test_list_templates(self, async_client: AsyncClient, seeded_templates):
  382. """Verify default templates are seeded and can be listed."""
  383. response = await async_client.get("/api/v1/notification-templates/")
  384. assert response.status_code == 200
  385. templates = response.json()
  386. # Should have default templates seeded
  387. assert len(templates) >= 1
  388. @pytest.mark.asyncio
  389. @pytest.mark.integration
  390. async def test_get_template_by_id(self, async_client: AsyncClient, seeded_templates):
  391. """Verify template can be retrieved by ID."""
  392. # Get first template ID from seeded data
  393. template_id = seeded_templates[0].id
  394. response = await async_client.get(f"/api/v1/notification-templates/{template_id}")
  395. assert response.status_code == 200
  396. template = response.json()
  397. assert template["id"] == template_id
  398. @pytest.mark.asyncio
  399. @pytest.mark.integration
  400. async def test_update_template(self, async_client: AsyncClient, seeded_templates):
  401. """Verify template can be updated."""
  402. # Get first template
  403. template_id = seeded_templates[0].id
  404. # Update it (route uses PUT, not PATCH)
  405. response = await async_client.put(
  406. f"/api/v1/notification-templates/{template_id}",
  407. json={
  408. "title_template": "Custom Title: {printer}",
  409. "body_template": "Custom body for {filename}",
  410. },
  411. )
  412. assert response.status_code == 200
  413. result = response.json()
  414. assert result["title_template"] == "Custom Title: {printer}"
  415. assert result["body_template"] == "Custom body for {filename}"
  416. @pytest.mark.asyncio
  417. @pytest.mark.integration
  418. async def test_reset_template_to_default(self, async_client: AsyncClient, seeded_templates):
  419. """Verify template can be reset to default."""
  420. template_id = seeded_templates[0].id
  421. response = await async_client.post(f"/api/v1/notification-templates/{template_id}/reset")
  422. assert response.status_code == 200
  423. result = response.json()
  424. assert result["is_default"] is True
  425. class TestHomeAssistantNotificationProvider:
  426. """Integration tests for Home Assistant notification provider."""
  427. @pytest.mark.asyncio
  428. @pytest.mark.integration
  429. async def test_create_homeassistant_provider(self, async_client: AsyncClient):
  430. """Verify homeassistant notification provider can be created with empty config."""
  431. data = {
  432. "name": "HA Notifications",
  433. "provider_type": "homeassistant",
  434. "enabled": True,
  435. "config": {},
  436. "on_print_complete": True,
  437. "on_print_failed": True,
  438. }
  439. response = await async_client.post("/api/v1/notifications/", json=data)
  440. assert response.status_code == 200
  441. result = response.json()
  442. assert result["name"] == "HA Notifications"
  443. assert result["provider_type"] == "homeassistant"
  444. assert result["on_print_complete"] is True
  445. assert result["on_print_failed"] is True
  446. @pytest.mark.asyncio
  447. @pytest.mark.integration
  448. async def test_update_homeassistant_provider(
  449. self, async_client: AsyncClient, notification_provider_factory, db_session
  450. ):
  451. """Verify homeassistant provider can be updated."""
  452. provider = await notification_provider_factory(
  453. name="HA Test",
  454. provider_type="homeassistant",
  455. config="{}",
  456. )
  457. response = await async_client.patch(
  458. f"/api/v1/notifications/{provider.id}",
  459. json={"on_print_start": True, "on_printer_offline": True},
  460. )
  461. assert response.status_code == 200
  462. result = response.json()
  463. assert result["on_print_start"] is True
  464. assert result["on_printer_offline"] is True
  465. @pytest.mark.asyncio
  466. @pytest.mark.integration
  467. async def test_test_homeassistant_config_without_ha_settings(self, async_client: AsyncClient):
  468. """Verify test-config returns error when HA is not configured."""
  469. response = await async_client.post(
  470. "/api/v1/notifications/test-config",
  471. json={"provider_type": "homeassistant", "config": {}},
  472. )
  473. assert response.status_code == 200
  474. result = response.json()
  475. assert result["success"] is False
  476. assert "not configured" in result["message"].lower() or "Home Assistant" in result["message"]