test_notification_service.py 109 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770
  1. """Unit tests for NotificationService.
  2. Tests event-based notifications and toggle behavior.
  3. """
  4. import json
  5. from unittest.mock import AsyncMock, MagicMock, patch
  6. import pytest
  7. from backend.app.services.notification_service import NotificationService
  8. class TestNotificationService:
  9. """Tests for NotificationService class."""
  10. @pytest.fixture
  11. def service(self):
  12. """Create a fresh NotificationService instance."""
  13. return NotificationService()
  14. @pytest.fixture
  15. def mock_provider(self):
  16. """Create a mock notification provider."""
  17. provider = MagicMock()
  18. provider.id = 1
  19. provider.name = "Test Provider"
  20. provider.provider_type = "webhook"
  21. provider.enabled = True
  22. provider.config = json.dumps({"webhook_url": "http://test.local/webhook"})
  23. provider.on_print_start = True
  24. provider.on_print_complete = True
  25. provider.on_print_failed = True
  26. provider.on_print_stopped = False
  27. provider.on_print_progress = False
  28. provider.on_printer_offline = False
  29. provider.on_printer_error = False
  30. provider.on_filament_low = False
  31. provider.on_maintenance_due = False
  32. provider.on_ams_humidity_high = False
  33. provider.on_ams_temperature_high = False
  34. provider.quiet_hours_enabled = False
  35. provider.quiet_hours_start = None
  36. provider.quiet_hours_end = None
  37. provider.daily_digest_enabled = False
  38. provider.daily_digest_time = None
  39. provider.printer_id = None
  40. return provider
  41. @pytest.fixture
  42. def mock_db(self):
  43. """Create a mock database session."""
  44. db = AsyncMock()
  45. db.commit = AsyncMock()
  46. return db
  47. # ========================================================================
  48. # Tests for on_print_start
  49. # ========================================================================
  50. @pytest.mark.asyncio
  51. async def test_on_print_start_sends_notification(self, service, mock_provider, mock_db):
  52. """Verify notification is sent when print starts."""
  53. with (
  54. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  55. patch.object(service, "_send_to_providers", new_callable=AsyncMock) as mock_send,
  56. patch.object(service, "_build_message_from_template", new_callable=AsyncMock) as mock_build,
  57. ):
  58. mock_get.return_value = [mock_provider]
  59. mock_build.return_value = ("Print Started", "Test Printer: test.3mf")
  60. await service.on_print_start(
  61. printer_id=1,
  62. printer_name="Test Printer",
  63. data={"filename": "test.3mf", "subtask_name": "test"},
  64. db=mock_db,
  65. )
  66. mock_get.assert_called_once()
  67. mock_send.assert_called_once()
  68. @pytest.mark.asyncio
  69. async def test_on_print_start_skipped_when_no_providers(self, service, mock_db):
  70. """Verify no error when no providers are configured for event."""
  71. with (
  72. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  73. patch.object(service, "_send_to_providers", new_callable=AsyncMock) as mock_send,
  74. ):
  75. mock_get.return_value = []
  76. await service.on_print_start(
  77. printer_id=1,
  78. printer_name="Test Printer",
  79. data={},
  80. db=mock_db,
  81. )
  82. mock_send.assert_not_called()
  83. # ========================================================================
  84. # Tests for on_print_complete (status routing)
  85. # ========================================================================
  86. @pytest.mark.asyncio
  87. async def test_on_print_complete_routes_completed_status(self, service, mock_provider, mock_db):
  88. """Verify completed status uses on_print_complete field."""
  89. with (
  90. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  91. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  92. patch.object(service, "_build_message_from_template", new_callable=AsyncMock) as mock_build,
  93. ):
  94. mock_get.return_value = [mock_provider]
  95. mock_build.return_value = ("Test", "Test")
  96. await service.on_print_complete(
  97. printer_id=1,
  98. printer_name="Test",
  99. status="completed",
  100. data={},
  101. db=mock_db,
  102. )
  103. # Verify the correct event field was queried
  104. call_args = mock_get.call_args
  105. assert call_args[0][1] == "on_print_complete"
  106. @pytest.mark.asyncio
  107. async def test_on_print_complete_routes_failed_status(self, service, mock_provider, mock_db):
  108. """Verify failed status uses on_print_failed field."""
  109. with (
  110. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  111. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  112. patch.object(service, "_build_message_from_template", new_callable=AsyncMock) as mock_build,
  113. ):
  114. mock_get.return_value = [mock_provider]
  115. mock_build.return_value = ("Test", "Test")
  116. await service.on_print_complete(
  117. printer_id=1,
  118. printer_name="Test",
  119. status="failed",
  120. data={},
  121. db=mock_db,
  122. )
  123. call_args = mock_get.call_args
  124. assert call_args[0][1] == "on_print_failed"
  125. @pytest.mark.asyncio
  126. async def test_on_print_complete_routes_stopped_status(self, service, mock_provider, mock_db):
  127. """Verify stopped status uses on_print_stopped field."""
  128. with (
  129. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  130. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  131. patch.object(service, "_build_message_from_template", new_callable=AsyncMock) as mock_build,
  132. ):
  133. mock_get.return_value = [mock_provider]
  134. mock_build.return_value = ("Test", "Test")
  135. await service.on_print_complete(
  136. printer_id=1,
  137. printer_name="Test",
  138. status="stopped",
  139. data={},
  140. db=mock_db,
  141. )
  142. call_args = mock_get.call_args
  143. assert call_args[0][1] == "on_print_stopped"
  144. @pytest.mark.asyncio
  145. async def test_on_print_complete_routes_aborted_status(self, service, mock_provider, mock_db):
  146. """Verify aborted status uses on_print_stopped field."""
  147. with (
  148. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  149. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  150. patch.object(service, "_build_message_from_template", new_callable=AsyncMock) as mock_build,
  151. ):
  152. mock_get.return_value = [mock_provider]
  153. mock_build.return_value = ("Test", "Test")
  154. await service.on_print_complete(
  155. printer_id=1,
  156. printer_name="Test",
  157. status="aborted",
  158. data={},
  159. db=mock_db,
  160. )
  161. call_args = mock_get.call_args
  162. assert call_args[0][1] == "on_print_stopped"
  163. # ========================================================================
  164. # Tests for provider filtering
  165. # ========================================================================
  166. @pytest.mark.asyncio
  167. async def test_disabled_provider_not_returned(self, service, mock_provider, mock_db):
  168. """CRITICAL: Verify disabled providers don't receive notifications."""
  169. mock_provider.enabled = False
  170. # The actual filtering happens in _get_providers_for_event
  171. # which queries only enabled providers
  172. with patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get:
  173. # Simulate the query filtering out disabled providers
  174. mock_get.return_value = []
  175. result = await service._get_providers_for_event(mock_db, "on_print_start", printer_id=1)
  176. assert len(result) == 0
  177. @pytest.mark.asyncio
  178. async def test_provider_filtered_by_printer_id(self, service, mock_provider, mock_db):
  179. """Verify providers can be filtered by specific printer."""
  180. mock_provider.printer_id = 2 # Linked to printer 2
  181. with patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get:
  182. # When querying for printer 1, provider linked to printer 2 is excluded
  183. mock_get.return_value = []
  184. result = await service._get_providers_for_event(mock_db, "on_print_start", printer_id=1)
  185. assert len(result) == 0
  186. # ========================================================================
  187. # Tests for quiet hours
  188. # ========================================================================
  189. def test_is_in_quiet_hours_during_quiet_period(self, service, mock_provider):
  190. """Verify notifications are blocked during quiet hours."""
  191. mock_provider.quiet_hours_enabled = True
  192. mock_provider.quiet_hours_start = "22:00"
  193. mock_provider.quiet_hours_end = "07:00"
  194. with patch("backend.app.services.notification_service.datetime") as mock_datetime:
  195. # Test during quiet hours (23:00)
  196. mock_now = MagicMock()
  197. mock_now.hour = 23
  198. mock_now.minute = 0
  199. mock_datetime.now.return_value = mock_now
  200. result = service._is_in_quiet_hours(mock_provider)
  201. assert result is True
  202. def test_is_in_quiet_hours_outside_quiet_period(self, service, mock_provider):
  203. """Verify notifications are allowed outside quiet hours."""
  204. mock_provider.quiet_hours_enabled = True
  205. mock_provider.quiet_hours_start = "22:00"
  206. mock_provider.quiet_hours_end = "07:00"
  207. with patch("backend.app.services.notification_service.datetime") as mock_datetime:
  208. # Test outside quiet hours (12:00)
  209. mock_now = MagicMock()
  210. mock_now.hour = 12
  211. mock_now.minute = 0
  212. mock_datetime.now.return_value = mock_now
  213. result = service._is_in_quiet_hours(mock_provider)
  214. assert result is False
  215. def test_is_in_quiet_hours_disabled(self, service, mock_provider):
  216. """Verify quiet hours check returns False when disabled."""
  217. mock_provider.quiet_hours_enabled = False
  218. result = service._is_in_quiet_hours(mock_provider)
  219. assert result is False
  220. def test_is_in_quiet_hours_early_morning(self, service, mock_provider):
  221. """Verify quiet hours work across midnight (early morning)."""
  222. mock_provider.quiet_hours_enabled = True
  223. mock_provider.quiet_hours_start = "22:00"
  224. mock_provider.quiet_hours_end = "07:00"
  225. with patch("backend.app.services.notification_service.datetime") as mock_datetime:
  226. # Test early morning (03:00) - should be in quiet hours
  227. mock_now = MagicMock()
  228. mock_now.hour = 3
  229. mock_now.minute = 0
  230. mock_datetime.now.return_value = mock_now
  231. result = service._is_in_quiet_hours(mock_provider)
  232. assert result is True
  233. # ========================================================================
  234. # Tests for AMS alarms
  235. # ========================================================================
  236. @pytest.mark.asyncio
  237. async def test_on_ams_humidity_high_sends_notification(self, service, mock_provider, mock_db):
  238. """Verify AMS humidity alarm sends notification."""
  239. mock_provider.on_ams_humidity_high = True
  240. with (
  241. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  242. patch.object(service, "_send_to_providers", new_callable=AsyncMock) as mock_send,
  243. patch.object(service, "_build_message_from_template", new_callable=AsyncMock) as mock_build,
  244. ):
  245. mock_get.return_value = [mock_provider]
  246. mock_build.return_value = ("AMS Humidity Alert", "High humidity detected")
  247. await service.on_ams_humidity_high(
  248. printer_id=1,
  249. printer_name="Test Printer",
  250. ams_label="AMS-A",
  251. humidity=75.0,
  252. threshold=60.0,
  253. db=mock_db,
  254. )
  255. mock_send.assert_called_once()
  256. # Verify force_immediate is True for alarms
  257. call_kwargs = mock_send.call_args[1]
  258. assert call_kwargs.get("force_immediate") is True
  259. @pytest.mark.asyncio
  260. async def test_on_ams_temperature_high_sends_notification(self, service, mock_provider, mock_db):
  261. """Verify AMS temperature alarm sends notification."""
  262. mock_provider.on_ams_temperature_high = True
  263. with (
  264. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  265. patch.object(service, "_send_to_providers", new_callable=AsyncMock) as mock_send,
  266. patch.object(service, "_build_message_from_template", new_callable=AsyncMock) as mock_build,
  267. ):
  268. mock_get.return_value = [mock_provider]
  269. mock_build.return_value = ("AMS Temperature Alert", "High temp detected")
  270. await service.on_ams_temperature_high(
  271. printer_id=1,
  272. printer_name="Test Printer",
  273. ams_label="AMS-A",
  274. temperature=40.0,
  275. threshold=35.0,
  276. db=mock_db,
  277. )
  278. mock_send.assert_called_once()
  279. # Verify force_immediate is True for alarms
  280. call_kwargs = mock_send.call_args[1]
  281. assert call_kwargs.get("force_immediate") is True
  282. @pytest.mark.asyncio
  283. async def test_ams_alarm_skipped_when_toggle_disabled(self, service, mock_provider, mock_db):
  284. """CRITICAL: Verify AMS alarms respect toggle setting."""
  285. mock_provider.on_ams_humidity_high = False
  286. with (
  287. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  288. patch.object(service, "_send_to_providers", new_callable=AsyncMock) as mock_send,
  289. ):
  290. # Provider with toggle disabled won't be returned
  291. mock_get.return_value = []
  292. await service.on_ams_humidity_high(
  293. printer_id=1,
  294. printer_name="Test",
  295. ams_label="AMS-A",
  296. humidity=75.0,
  297. threshold=60.0,
  298. db=mock_db,
  299. )
  300. mock_send.assert_not_called()
  301. # ========================================================================
  302. # Tests for daily digest
  303. # ========================================================================
  304. @pytest.mark.asyncio
  305. async def test_daily_digest_queues_notification(self, service, mock_provider, mock_db):
  306. """Verify notifications are queued when digest mode is enabled."""
  307. mock_provider.daily_digest_enabled = True
  308. mock_provider.daily_digest_time = "09:00"
  309. with (
  310. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  311. patch.object(service, "_send_to_providers", new_callable=AsyncMock) as mock_send,
  312. patch.object(service, "_build_message_from_template", new_callable=AsyncMock) as mock_build,
  313. ):
  314. mock_get.return_value = [mock_provider]
  315. mock_build.return_value = ("Test", "Test")
  316. await service.on_print_complete(
  317. printer_id=1,
  318. printer_name="Test",
  319. status="completed",
  320. data={},
  321. db=mock_db,
  322. )
  323. # When digest is enabled, _send_to_providers should still be called
  324. # but internally it will queue instead of send immediately
  325. mock_send.assert_called_once()
  326. @pytest.mark.asyncio
  327. async def test_force_immediate_bypasses_digest(self, service, mock_provider, mock_db):
  328. """Verify force_immediate=True bypasses digest mode."""
  329. mock_provider.daily_digest_enabled = True
  330. mock_provider.on_ams_humidity_high = True
  331. with (
  332. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  333. patch.object(service, "_send_to_providers", new_callable=AsyncMock) as mock_send,
  334. patch.object(service, "_build_message_from_template", new_callable=AsyncMock) as mock_build,
  335. ):
  336. mock_get.return_value = [mock_provider]
  337. mock_build.return_value = ("Alert", "Alert message")
  338. await service.on_ams_humidity_high(
  339. printer_id=1,
  340. printer_name="Test",
  341. ams_label="AMS-A",
  342. humidity=75.0,
  343. threshold=60.0,
  344. db=mock_db,
  345. )
  346. # Verify force_immediate is passed
  347. call_kwargs = mock_send.call_args[1]
  348. assert call_kwargs.get("force_immediate") is True
  349. class TestDigestModeAlwaysSendsImmediately:
  350. """CRITICAL: Tests that notifications always send immediately regardless of digest setting."""
  351. @pytest.fixture
  352. def service(self):
  353. return NotificationService()
  354. @pytest.mark.asyncio
  355. async def test_notification_sends_immediately_even_with_digest_enabled(self, service):
  356. """CRITICAL: All notifications must be sent immediately, digest is just a summary."""
  357. # Create a mock provider with digest enabled
  358. mock_provider = MagicMock()
  359. mock_provider.id = 1
  360. mock_provider.name = "Test Provider"
  361. mock_provider.provider_type = "ntfy"
  362. mock_provider.enabled = True
  363. mock_provider.daily_digest_enabled = True # Digest enabled
  364. mock_provider.daily_digest_time = "23:59"
  365. mock_provider.config = '{"server": "https://ntfy.sh", "topic": "test"}'
  366. mock_db = AsyncMock()
  367. # Mock the _send_to_provider method
  368. with (
  369. patch.object(service, "_send_to_provider", new_callable=AsyncMock) as mock_send,
  370. patch.object(service, "_queue_for_digest", new_callable=AsyncMock) as mock_queue,
  371. patch.object(service, "_update_provider_status", new_callable=AsyncMock),
  372. patch.object(service, "_log_notification", new_callable=AsyncMock),
  373. ):
  374. mock_send.return_value = (True, None)
  375. await service._send_to_providers(
  376. providers=[mock_provider],
  377. title="Print Started",
  378. message="Your print has started",
  379. db=mock_db,
  380. event_type="print_start",
  381. )
  382. # CRITICAL: _send_to_provider MUST be called (immediate send)
  383. mock_send.assert_called_once()
  384. # Digest queue should also be called (for daily summary)
  385. mock_queue.assert_called_once()
  386. @pytest.mark.asyncio
  387. async def test_notification_sends_without_digest_queue_when_disabled(self, service):
  388. """When digest is disabled, notification sends but no digest queue."""
  389. mock_provider = MagicMock()
  390. mock_provider.id = 1
  391. mock_provider.name = "Test Provider"
  392. mock_provider.provider_type = "ntfy"
  393. mock_provider.enabled = True
  394. mock_provider.daily_digest_enabled = False # Digest disabled
  395. mock_provider.daily_digest_time = None
  396. mock_provider.config = '{"server": "https://ntfy.sh", "topic": "test"}'
  397. mock_db = AsyncMock()
  398. with (
  399. patch.object(service, "_send_to_provider", new_callable=AsyncMock) as mock_send,
  400. patch.object(service, "_queue_for_digest", new_callable=AsyncMock) as mock_queue,
  401. patch.object(service, "_update_provider_status", new_callable=AsyncMock),
  402. patch.object(service, "_log_notification", new_callable=AsyncMock),
  403. ):
  404. mock_send.return_value = (True, None)
  405. await service._send_to_providers(
  406. providers=[mock_provider],
  407. title="Print Started",
  408. message="Your print has started",
  409. db=mock_db,
  410. event_type="print_start",
  411. )
  412. # Notification must still be sent immediately
  413. mock_send.assert_called_once()
  414. # Digest queue should NOT be called when digest is disabled
  415. mock_queue.assert_not_called()
  416. class TestNotificationProviderTypes:
  417. """Tests for different notification provider types."""
  418. @pytest.fixture
  419. def service(self):
  420. return NotificationService()
  421. @pytest.mark.asyncio
  422. async def test_webhook_provider_sends_request(self, service):
  423. """Verify webhook provider sends HTTP request."""
  424. config = {
  425. "webhook_url": "http://test.local/webhook",
  426. "field_title": "title",
  427. "field_message": "message",
  428. }
  429. # Create a mock response
  430. mock_response = MagicMock()
  431. mock_response.status_code = 200
  432. # Mock the _get_client method
  433. mock_client = AsyncMock()
  434. mock_client.post = AsyncMock(return_value=mock_response)
  435. with patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client:
  436. mock_get_client.return_value = mock_client
  437. success, message = await service._send_webhook(config, "Test Title", "Test Message")
  438. assert success is True
  439. mock_client.post.assert_called_once()
  440. @pytest.mark.asyncio
  441. async def test_webhook_handles_failure(self, service):
  442. """Verify webhook gracefully handles HTTP errors."""
  443. config = {
  444. "webhook_url": "http://test.local/webhook",
  445. }
  446. with patch("httpx.AsyncClient") as mock_client_class:
  447. mock_instance = AsyncMock()
  448. mock_instance.post.side_effect = Exception("Connection failed")
  449. mock_client_class.return_value.__aenter__ = AsyncMock(return_value=mock_instance)
  450. mock_client_class.return_value.__aexit__ = AsyncMock()
  451. success, message = await service._send_webhook(config, "Test", "Test")
  452. assert success is False
  453. assert "Connection failed" in message or "error" in message.lower()
  454. @pytest.mark.asyncio
  455. async def test_webhook_slack_format_sends_text_only(self, service):
  456. """Verify Slack/Mattermost format sends only text field."""
  457. config = {
  458. "webhook_url": "http://mattermost.local/hooks/abc123",
  459. "payload_format": "slack",
  460. }
  461. mock_response = MagicMock()
  462. mock_response.status_code = 200
  463. mock_client = AsyncMock()
  464. mock_client.post = AsyncMock(return_value=mock_response)
  465. with patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client:
  466. mock_get_client.return_value = mock_client
  467. success, message = await service._send_webhook(config, "Test Title", "Test Message")
  468. assert success is True
  469. mock_client.post.assert_called_once()
  470. # Verify payload format is Slack-compatible
  471. call_args = mock_client.post.call_args
  472. payload = call_args.kwargs.get("json") or call_args[1].get("json")
  473. assert "text" in payload
  474. assert "*Test Title*" in payload["text"]
  475. assert "Test Message" in payload["text"]
  476. # Should NOT have generic fields
  477. assert "timestamp" not in payload
  478. assert "source" not in payload
  479. @pytest.mark.asyncio
  480. async def test_webhook_generic_format_includes_image(self, service):
  481. """Verify generic webhook includes base64-encoded image when provided."""
  482. config = {
  483. "webhook_url": "http://test.local/webhook",
  484. "field_title": "title",
  485. "field_message": "message",
  486. }
  487. mock_response = MagicMock()
  488. mock_response.status_code = 200
  489. mock_client = AsyncMock()
  490. mock_client.post = AsyncMock(return_value=mock_response)
  491. with patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client:
  492. mock_get_client.return_value = mock_client
  493. image_bytes = b"\xff\xd8\xff\xe0fake-jpeg-data"
  494. success, message = await service._send_webhook(config, "Test Title", "Test Message", image_data=image_bytes)
  495. assert success is True
  496. call_args = mock_client.post.call_args
  497. payload = call_args.kwargs.get("json") or call_args[1].get("json")
  498. assert "image" in payload
  499. import base64
  500. assert payload["image"] == base64.b64encode(image_bytes).decode("ascii")
  501. @pytest.mark.asyncio
  502. async def test_webhook_generic_format_no_image_when_none(self, service):
  503. """Verify generic webhook omits image field when no image_data provided."""
  504. config = {
  505. "webhook_url": "http://test.local/webhook",
  506. "field_title": "title",
  507. "field_message": "message",
  508. }
  509. mock_response = MagicMock()
  510. mock_response.status_code = 200
  511. mock_client = AsyncMock()
  512. mock_client.post = AsyncMock(return_value=mock_response)
  513. with patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client:
  514. mock_get_client.return_value = mock_client
  515. success, message = await service._send_webhook(config, "Test Title", "Test Message")
  516. assert success is True
  517. call_args = mock_client.post.call_args
  518. payload = call_args.kwargs.get("json") or call_args[1].get("json")
  519. assert "image" not in payload
  520. @pytest.mark.asyncio
  521. async def test_webhook_slack_format_excludes_image(self, service):
  522. """Verify Slack format does not include image even when provided."""
  523. config = {
  524. "webhook_url": "http://mattermost.local/hooks/abc123",
  525. "payload_format": "slack",
  526. }
  527. mock_response = MagicMock()
  528. mock_response.status_code = 200
  529. mock_client = AsyncMock()
  530. mock_client.post = AsyncMock(return_value=mock_response)
  531. with patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client:
  532. mock_get_client.return_value = mock_client
  533. success, message = await service._send_webhook(
  534. config, "Test Title", "Test Message", image_data=b"fake-image"
  535. )
  536. assert success is True
  537. call_args = mock_client.post.call_args
  538. payload = call_args.kwargs.get("json") or call_args[1].get("json")
  539. assert "image" not in payload
  540. class TestDiscordProvider:
  541. """Discord webhook URL host validation (#1363)."""
  542. @pytest.fixture
  543. def service(self):
  544. return NotificationService()
  545. @pytest.mark.asyncio
  546. async def test_discord_accepts_discord_com_url(self, service):
  547. config = {"webhook_url": "https://discord.com/api/webhooks/123/abc"}
  548. mock_response = MagicMock()
  549. mock_response.status_code = 204
  550. mock_client = AsyncMock()
  551. mock_client.post = AsyncMock(return_value=mock_response)
  552. with patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client:
  553. mock_get_client.return_value = mock_client
  554. success, _ = await service._send_discord(config, "Title", "Body")
  555. assert success is True
  556. mock_client.post.assert_called_once()
  557. @pytest.mark.asyncio
  558. async def test_discord_accepts_legacy_discordapp_com_url(self, service):
  559. """Discord's 'Copy Webhook URL' button emits discordapp.com URLs (#1363)."""
  560. config = {"webhook_url": "https://discordapp.com/api/webhooks/123/abc"}
  561. mock_response = MagicMock()
  562. mock_response.status_code = 204
  563. mock_client = AsyncMock()
  564. mock_client.post = AsyncMock(return_value=mock_response)
  565. with patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client:
  566. mock_get_client.return_value = mock_client
  567. success, _ = await service._send_discord(config, "Title", "Body")
  568. assert success is True
  569. mock_client.post.assert_called_once()
  570. @pytest.mark.asyncio
  571. async def test_discord_rejects_non_discord_host(self, service):
  572. config = {"webhook_url": "https://evil.example.com/api/webhooks/123/abc"}
  573. success, message = await service._send_discord(config, "Title", "Body")
  574. assert success is False
  575. assert "Invalid Discord webhook URL" in message
  576. @pytest.mark.asyncio
  577. async def test_discord_rejects_empty_url(self, service):
  578. success, message = await service._send_discord({"webhook_url": ""}, "Title", "Body")
  579. assert success is False
  580. assert "required" in message.lower()
  581. class TestNtfyPriority:
  582. """Per-event ntfy Priority header (#990)."""
  583. @pytest.fixture
  584. def service(self):
  585. return NotificationService()
  586. @staticmethod
  587. def _mock_client(service):
  588. """Patch _get_client and return the mock client + 200 response."""
  589. mock_response = MagicMock()
  590. mock_response.status_code = 200
  591. mock_client = AsyncMock()
  592. mock_client.post = AsyncMock(return_value=mock_response)
  593. mock_client.put = AsyncMock(return_value=mock_response)
  594. return mock_client
  595. @pytest.mark.asyncio
  596. async def test_priority_header_set_for_mapped_event(self, service):
  597. """Mapped event → ntfy Priority header carries the configured value."""
  598. config = {
  599. "topic": "bambuddy",
  600. "event_priorities": {"on_print_failed": 5, "on_print_complete": 2},
  601. }
  602. mock_client = self._mock_client(service)
  603. with patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get:
  604. mock_get.return_value = mock_client
  605. success, _ = await service._send_ntfy(config, "Title", "Body", event_type="on_print_failed")
  606. assert success is True
  607. headers = mock_client.post.call_args.kwargs["headers"]
  608. assert headers.get("Priority") == "5"
  609. @pytest.mark.asyncio
  610. async def test_priority_header_omitted_for_unmapped_event(self, service):
  611. """Unmapped event → no Priority header so ntfy uses its server default."""
  612. config = {
  613. "topic": "bambuddy",
  614. "event_priorities": {"on_print_failed": 5},
  615. }
  616. mock_client = self._mock_client(service)
  617. with patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get:
  618. mock_get.return_value = mock_client
  619. await service._send_ntfy(config, "Title", "Body", event_type="on_print_complete")
  620. headers = mock_client.post.call_args.kwargs["headers"]
  621. assert "Priority" not in headers
  622. @pytest.mark.asyncio
  623. async def test_priority_header_omitted_when_no_priorities_set(self, service):
  624. """Existing setups (no event_priorities key) keep current behaviour."""
  625. config = {"topic": "bambuddy"}
  626. mock_client = self._mock_client(service)
  627. with patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get:
  628. mock_get.return_value = mock_client
  629. await service._send_ntfy(config, "Title", "Body", event_type="on_print_failed")
  630. headers = mock_client.post.call_args.kwargs["headers"]
  631. assert "Priority" not in headers
  632. @pytest.mark.asyncio
  633. async def test_priority_header_omitted_when_event_type_missing(self, service):
  634. """Test sends (no event_type) must not emit a Priority header."""
  635. config = {
  636. "topic": "bambuddy",
  637. "event_priorities": {"on_print_failed": 5},
  638. }
  639. mock_client = self._mock_client(service)
  640. with patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get:
  641. mock_get.return_value = mock_client
  642. await service._send_ntfy(config, "Title", "Body")
  643. headers = mock_client.post.call_args.kwargs["headers"]
  644. assert "Priority" not in headers
  645. @pytest.mark.asyncio
  646. async def test_priority_out_of_range_is_ignored(self, service):
  647. """Values outside 1-5 (or non-numeric) are dropped, not clamped."""
  648. for bad in (0, 6, 99, -1, "not-a-number", None):
  649. config = {
  650. "topic": "bambuddy",
  651. "event_priorities": {"on_print_failed": bad},
  652. }
  653. mock_client = self._mock_client(service)
  654. with patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get:
  655. mock_get.return_value = mock_client
  656. await service._send_ntfy(config, "Title", "Body", event_type="on_print_failed")
  657. headers = mock_client.post.call_args.kwargs["headers"]
  658. assert "Priority" not in headers, f"unexpected header for bad value {bad!r}"
  659. @pytest.mark.asyncio
  660. async def test_priority_header_set_on_attachment_path(self, service):
  661. """Image-attachment path (PUT) must also carry the Priority header."""
  662. config = {
  663. "topic": "bambuddy",
  664. "event_priorities": {"on_first_layer_complete": 4},
  665. }
  666. mock_client = self._mock_client(service)
  667. with patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get:
  668. mock_get.return_value = mock_client
  669. await service._send_ntfy(
  670. config,
  671. "Title",
  672. "Body",
  673. image_data=b"\xff\xd8\xff\xe0fake-jpeg",
  674. event_type="on_first_layer_complete",
  675. )
  676. headers = mock_client.put.call_args.kwargs["headers"]
  677. assert headers.get("Priority") == "4"
  678. class TestHomeAssistantProvider:
  679. """Tests for Home Assistant notification provider."""
  680. @pytest.fixture
  681. def service(self):
  682. return NotificationService()
  683. @pytest.mark.asyncio
  684. async def test_send_homeassistant_success(self, service):
  685. """Verify HA provider sends persistent notification to correct endpoint."""
  686. mock_response = MagicMock()
  687. mock_response.status_code = 200
  688. mock_client = AsyncMock()
  689. mock_client.post = AsyncMock(return_value=mock_response)
  690. mock_db = AsyncMock()
  691. with (
  692. patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client,
  693. patch(
  694. "backend.app.api.routes.settings.get_homeassistant_settings",
  695. new_callable=AsyncMock,
  696. ) as mock_ha_settings,
  697. ):
  698. mock_get_client.return_value = mock_client
  699. mock_ha_settings.return_value = {
  700. "ha_url": "http://ha.local:8123",
  701. "ha_token": "test-token-123",
  702. "ha_enabled": True,
  703. }
  704. success, message = await service._send_homeassistant({}, "Test Title", "Test Message", db=mock_db)
  705. assert success is True
  706. mock_client.post.assert_called_once()
  707. call_args = mock_client.post.call_args
  708. assert call_args[0][0] == "http://ha.local:8123/api/services/persistent_notification/create"
  709. payload = call_args.kwargs.get("json") or call_args[1].get("json")
  710. assert payload["title"] == "Test Title"
  711. assert payload["message"] == "Test Message"
  712. @pytest.mark.asyncio
  713. async def test_send_homeassistant_custom_data_merged(self, service):
  714. """Custom service-data (#1441) is forwarded as HA's nested "data" object
  715. so mobile-app push options (priority, ttl, channel, ...) reach the
  716. notify service."""
  717. mock_response = MagicMock()
  718. mock_response.status_code = 200
  719. mock_client = AsyncMock()
  720. mock_client.post = AsyncMock(return_value=mock_response)
  721. mock_db = AsyncMock()
  722. with (
  723. patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client,
  724. patch(
  725. "backend.app.api.routes.settings.get_homeassistant_settings",
  726. new_callable=AsyncMock,
  727. ) as mock_ha_settings,
  728. ):
  729. mock_get_client.return_value = mock_client
  730. mock_ha_settings.return_value = {
  731. "ha_url": "http://ha.local:8123",
  732. "ha_token": "test-token-123",
  733. "ha_enabled": True,
  734. }
  735. config = {
  736. "service": "notify.mobile_app_myphone",
  737. "data": '{"priority": "high", "ttl": 0, "channel": "3D Printing"}',
  738. }
  739. success, _ = await service._send_homeassistant(config, "Title", "Body", db=mock_db)
  740. assert success is True
  741. call_args = mock_client.post.call_args
  742. assert call_args[0][0] == "http://ha.local:8123/api/services/notify/mobile_app_myphone"
  743. payload = call_args.kwargs.get("json") or call_args[1].get("json")
  744. assert payload["data"] == {"priority": "high", "ttl": 0, "channel": "3D Printing"}
  745. # ttl must survive as a number, not a string — that's why the
  746. # field is JSON rather than key=value lines.
  747. assert payload["data"]["ttl"] == 0
  748. @pytest.mark.asyncio
  749. async def test_send_homeassistant_without_data_omits_key(self, service):
  750. """Without configured data the payload carries no "data" key — the
  751. default persistent_notification.create schema rejects unknown keys."""
  752. mock_response = MagicMock()
  753. mock_response.status_code = 200
  754. mock_client = AsyncMock()
  755. mock_client.post = AsyncMock(return_value=mock_response)
  756. mock_db = AsyncMock()
  757. with (
  758. patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client,
  759. patch(
  760. "backend.app.api.routes.settings.get_homeassistant_settings",
  761. new_callable=AsyncMock,
  762. ) as mock_ha_settings,
  763. ):
  764. mock_get_client.return_value = mock_client
  765. mock_ha_settings.return_value = {
  766. "ha_url": "http://ha.local:8123",
  767. "ha_token": "test-token-123",
  768. "ha_enabled": True,
  769. }
  770. success, _ = await service._send_homeassistant({}, "Title", "Body", db=mock_db)
  771. assert success is True
  772. payload = mock_client.post.call_args.kwargs.get("json") or mock_client.post.call_args[1].get("json")
  773. assert "data" not in payload
  774. @pytest.mark.asyncio
  775. async def test_send_homeassistant_invalid_data_rejected(self, service):
  776. """Malformed JSON and non-object JSON in the data field fail loudly
  777. instead of sending a half-built payload."""
  778. mock_db = AsyncMock()
  779. with (
  780. patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client,
  781. patch(
  782. "backend.app.api.routes.settings.get_homeassistant_settings",
  783. new_callable=AsyncMock,
  784. ) as mock_ha_settings,
  785. ):
  786. mock_client = AsyncMock()
  787. mock_get_client.return_value = mock_client
  788. mock_ha_settings.return_value = {
  789. "ha_url": "http://ha.local:8123",
  790. "ha_token": "test-token-123",
  791. "ha_enabled": True,
  792. }
  793. success, message = await service._send_homeassistant(
  794. {"data": "{priority: high}"}, "Title", "Body", db=mock_db
  795. )
  796. assert success is False
  797. assert "Invalid JSON" in message
  798. success, message = await service._send_homeassistant({"data": '["a", "b"]'}, "Title", "Body", db=mock_db)
  799. assert success is False
  800. assert "JSON object" in message
  801. mock_client.post.assert_not_called()
  802. @pytest.mark.asyncio
  803. async def test_send_homeassistant_no_db_no_env(self, service):
  804. """Verify HA provider fails gracefully without DB or env vars."""
  805. with patch.dict("os.environ", {}, clear=True):
  806. success, message = await service._send_homeassistant({}, "Test", "Test", db=None)
  807. assert success is False
  808. assert "not configured" in message.lower()
  809. @pytest.mark.asyncio
  810. async def test_send_homeassistant_auth_failure(self, service):
  811. """Verify HA provider reports auth failure."""
  812. mock_response = MagicMock()
  813. mock_response.status_code = 401
  814. mock_client = AsyncMock()
  815. mock_client.post = AsyncMock(return_value=mock_response)
  816. mock_db = AsyncMock()
  817. with (
  818. patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client,
  819. patch(
  820. "backend.app.api.routes.settings.get_homeassistant_settings",
  821. new_callable=AsyncMock,
  822. ) as mock_ha_settings,
  823. ):
  824. mock_get_client.return_value = mock_client
  825. mock_ha_settings.return_value = {
  826. "ha_url": "http://ha.local:8123",
  827. "ha_token": "bad-token",
  828. "ha_enabled": True,
  829. }
  830. success, message = await service._send_homeassistant({}, "Test", "Test", db=mock_db)
  831. assert success is False
  832. assert "authentication" in message.lower()
  833. @pytest.mark.asyncio
  834. async def test_send_homeassistant_env_fallback(self, service):
  835. """Verify HA provider falls back to env vars when no DB session."""
  836. mock_response = MagicMock()
  837. mock_response.status_code = 200
  838. mock_client = AsyncMock()
  839. mock_client.post = AsyncMock(return_value=mock_response)
  840. with (
  841. patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client,
  842. patch.dict("os.environ", {"HA_URL": "http://env-ha:8123", "HA_TOKEN": "env-token"}),
  843. ):
  844. mock_get_client.return_value = mock_client
  845. success, message = await service._send_homeassistant({}, "Test", "Test", db=None)
  846. assert success is True
  847. call_args = mock_client.post.call_args
  848. assert "env-ha:8123" in call_args[0][0]
  849. @pytest.mark.asyncio
  850. async def test_send_homeassistant_empty_config_accepted(self, service):
  851. """Verify HA provider works with empty config dict (no fields needed)."""
  852. mock_response = MagicMock()
  853. mock_response.status_code = 200
  854. mock_client = AsyncMock()
  855. mock_client.post = AsyncMock(return_value=mock_response)
  856. mock_db = AsyncMock()
  857. with (
  858. patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client,
  859. patch(
  860. "backend.app.api.routes.settings.get_homeassistant_settings",
  861. new_callable=AsyncMock,
  862. ) as mock_ha_settings,
  863. ):
  864. mock_get_client.return_value = mock_client
  865. mock_ha_settings.return_value = {
  866. "ha_url": "http://ha.local:8123",
  867. "ha_token": "token",
  868. "ha_enabled": True,
  869. }
  870. success, _ = await service._send_homeassistant({}, "Title", "Body", db=mock_db)
  871. assert success is True
  872. @pytest.mark.asyncio
  873. async def test_send_to_provider_dispatches_homeassistant(self, service):
  874. """Verify _send_to_provider dispatches to _send_homeassistant."""
  875. provider = MagicMock()
  876. provider.provider_type = "homeassistant"
  877. provider.config = "{}"
  878. provider.quiet_hours_enabled = False
  879. with patch.object(service, "_send_homeassistant", new_callable=AsyncMock) as mock_send:
  880. mock_send.return_value = (True, "OK")
  881. success, _ = await service._send_to_provider(provider, "Title", "Message", db=AsyncMock())
  882. assert success is True
  883. mock_send.assert_called_once()
  884. class TestBarkProvider:
  885. """Bark (iOS push) provider (#1495)."""
  886. @pytest.fixture
  887. def service(self):
  888. return NotificationService()
  889. def _client_returning(self, status_code: int, json_body=None, text: str = ""):
  890. mock_response = MagicMock()
  891. mock_response.status_code = status_code
  892. mock_response.text = text
  893. if json_body is not None:
  894. mock_response.json = MagicMock(return_value=json_body)
  895. else:
  896. mock_response.json = MagicMock(side_effect=ValueError("not json"))
  897. mock_client = AsyncMock()
  898. mock_client.post = AsyncMock(return_value=mock_response)
  899. return mock_client
  900. @pytest.mark.asyncio
  901. async def test_send_bark_success_default_server(self, service):
  902. """Minimal config posts to the official relay with device_key/title/body."""
  903. mock_client = self._client_returning(200, {"code": 200, "message": "success"})
  904. with patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client:
  905. mock_get_client.return_value = mock_client
  906. success, _ = await service._send_bark({"device_key": "abc123"}, "Title", "Body")
  907. assert success is True
  908. call_args = mock_client.post.call_args
  909. assert call_args[0][0] == "https://api.day.app/push"
  910. payload = call_args.kwargs.get("json")
  911. assert payload == {"device_key": "abc123", "title": "Title", "body": "Body"}
  912. @pytest.mark.asyncio
  913. async def test_send_bark_options_and_custom_server(self, service):
  914. """group/sound/level are forwarded; an unknown level is dropped rather
  915. than sent; a self-hosted server URL (with trailing slash) is used."""
  916. mock_client = self._client_returning(200, {"code": 200})
  917. with patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client:
  918. mock_get_client.return_value = mock_client
  919. config = {
  920. "device_key": "abc123",
  921. "server": "https://bark.example.com/",
  922. "group": "Bambuddy",
  923. "sound": "minuet",
  924. "level": "timeSensitive",
  925. }
  926. success, _ = await service._send_bark(config, "Title", "Body")
  927. assert success is True
  928. call_args = mock_client.post.call_args
  929. assert call_args[0][0] == "https://bark.example.com/push"
  930. payload = call_args.kwargs.get("json")
  931. assert payload["group"] == "Bambuddy"
  932. assert payload["sound"] == "minuet"
  933. assert payload["level"] == "timeSensitive"
  934. mock_client.post.reset_mock()
  935. with patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client:
  936. mock_get_client.return_value = mock_client
  937. await service._send_bark({"device_key": "abc123", "level": "shouty"}, "Title", "Body")
  938. assert "level" not in mock_client.post.call_args.kwargs.get("json")
  939. @pytest.mark.asyncio
  940. async def test_send_bark_missing_device_key(self, service):
  941. mock_client = self._client_returning(200, {"code": 200})
  942. with patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client:
  943. mock_get_client.return_value = mock_client
  944. success, message = await service._send_bark({}, "Title", "Body")
  945. assert success is False
  946. assert "Device key" in message
  947. mock_client.post.assert_not_called()
  948. @pytest.mark.asyncio
  949. async def test_send_bark_error_in_200_body(self, service):
  950. """bark-server can wrap a failure in HTTP 200; the body code must win."""
  951. mock_client = self._client_returning(200, {"code": 400, "message": "device token invalid"})
  952. with patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client:
  953. mock_get_client.return_value = mock_client
  954. success, message = await service._send_bark({"device_key": "bad"}, "Title", "Body")
  955. assert success is False
  956. assert "device token invalid" in message
  957. @pytest.mark.asyncio
  958. async def test_send_bark_http_error(self, service):
  959. mock_client = self._client_returning(400, None, text="failed to get device token")
  960. with patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client:
  961. mock_get_client.return_value = mock_client
  962. success, message = await service._send_bark({"device_key": "bad"}, "Title", "Body")
  963. assert success is False
  964. assert "HTTP 400" in message
  965. @pytest.mark.asyncio
  966. async def test_send_to_provider_dispatches_bark(self, service):
  967. provider = MagicMock()
  968. provider.provider_type = "bark"
  969. provider.config = json.dumps({"device_key": "abc123"})
  970. provider.quiet_hours_enabled = False
  971. with patch.object(service, "_send_bark", new_callable=AsyncMock) as mock_send:
  972. mock_send.return_value = (True, "OK")
  973. success, _ = await service._send_to_provider(provider, "Title", "Message", db=AsyncMock())
  974. assert success is True
  975. mock_send.assert_called_once()
  976. class TestNotificationVariableFallbacks:
  977. """Tests for notification variable fallback values."""
  978. @pytest.fixture
  979. def service(self):
  980. return NotificationService()
  981. def test_format_duration_with_valid_seconds(self, service):
  982. """Verify duration formats correctly with valid input."""
  983. result = service._format_duration(3661) # 1h 1m 1s
  984. assert "1h" in result
  985. def test_format_duration_with_none_returns_unknown(self, service):
  986. """CRITICAL: Verify None duration returns 'Unknown' fallback."""
  987. result = service._format_duration(None)
  988. assert result == "Unknown"
  989. def test_format_duration_with_zero(self, service):
  990. """Verify zero duration formats correctly."""
  991. result = service._format_duration(0)
  992. # Should return some valid string, not "Unknown"
  993. assert result is not None
  994. assert isinstance(result, str)
  995. def test_format_duration_hours_and_minutes(self, service):
  996. """Verify duration formats hours and minutes."""
  997. result = service._format_duration(5400) # 1h 30m
  998. assert "1h" in result
  999. assert "30m" in result
  1000. def test_format_duration_minutes_only(self, service):
  1001. """Verify duration formats minutes only when < 1 hour."""
  1002. result = service._format_duration(1800) # 30m
  1003. assert "30m" in result or "30" in result
  1004. @pytest.mark.asyncio
  1005. async def test_print_complete_fallback_values(self, service):
  1006. """CRITICAL: Verify fallback values when archive_data is missing."""
  1007. mock_db = AsyncMock()
  1008. with (
  1009. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1010. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1011. patch.object(service, "_build_message_from_template", new_callable=AsyncMock) as mock_build,
  1012. ):
  1013. mock_get.return_value = [] # No providers, just testing variable setup
  1014. mock_build.return_value = ("Test", "Test")
  1015. await service.on_print_complete(
  1016. printer_id=1,
  1017. printer_name="Test",
  1018. status="completed",
  1019. data={"subtask_name": "test_print"},
  1020. db=mock_db,
  1021. archive_data=None, # No archive data - should use fallbacks
  1022. )
  1023. # Test passes if no exception is raised with missing archive_data
  1024. @pytest.mark.asyncio
  1025. async def test_print_complete_with_archive_data(self, service):
  1026. """Verify archive data values are used when provided."""
  1027. mock_db = AsyncMock()
  1028. captured_variables = {}
  1029. async def capture_build(db, event_type, variables):
  1030. captured_variables.update(variables)
  1031. return ("Test", "Test")
  1032. with (
  1033. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1034. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1035. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1036. ):
  1037. mock_get.return_value = []
  1038. await service.on_print_complete(
  1039. printer_id=1,
  1040. printer_name="Test",
  1041. status="completed",
  1042. data={"subtask_name": "test_print"},
  1043. db=mock_db,
  1044. archive_data={
  1045. "print_time_seconds": 3600,
  1046. "actual_filament_grams": 50.5,
  1047. },
  1048. )
  1049. # When archive data is provided, duration should not be "Unknown"
  1050. if captured_variables.get("duration"):
  1051. assert captured_variables["duration"] != "Unknown"
  1052. @pytest.mark.asyncio
  1053. async def test_duration_prefers_actual_time_seconds_over_slicer_estimate(self, service):
  1054. """#1198: completion notification duration must reflect *actual* elapsed
  1055. time from started_at/completed_at, not the slicer's pre-print estimate.
  1056. Pre-fix the duration variable read from `print_time_seconds` (slicer
  1057. estimate parsed from the 3MF at archive creation), so a print cancelled
  1058. 2 minutes into a 3-hour estimate would notify "duration: 3h"."""
  1059. mock_db = AsyncMock()
  1060. mock_provider = MagicMock()
  1061. mock_provider.id = 1
  1062. captured_variables: dict = {}
  1063. async def capture_build(db, event_type, variables):
  1064. captured_variables.update(variables)
  1065. return ("Test", "Test")
  1066. with (
  1067. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1068. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1069. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1070. ):
  1071. mock_get.return_value = [mock_provider]
  1072. await service.on_print_complete(
  1073. printer_id=1,
  1074. printer_name="Test",
  1075. status="cancelled",
  1076. data={"subtask_name": "test_print"},
  1077. db=mock_db,
  1078. archive_data={
  1079. "print_time_seconds": 10800, # 3h slicer estimate
  1080. "actual_time_seconds": 120, # 2m actual elapsed
  1081. },
  1082. )
  1083. # 2 minutes — not 3 hours — even though the slicer estimate is in the dict.
  1084. assert "2m" in captured_variables["duration"]
  1085. assert "3h" not in captured_variables["duration"]
  1086. @pytest.mark.asyncio
  1087. async def test_duration_falls_back_to_slicer_estimate_when_actual_time_missing(self, service):
  1088. """#1198: when actual_time_seconds is absent (e.g. timestamps weren't
  1089. recorded for some reason), the duration variable falls back to
  1090. print_time_seconds rather than rendering 'Unknown'. Preserves
  1091. backwards-compat for any code path that didn't compute actual elapsed."""
  1092. mock_db = AsyncMock()
  1093. mock_provider = MagicMock()
  1094. mock_provider.id = 1
  1095. captured_variables: dict = {}
  1096. async def capture_build(db, event_type, variables):
  1097. captured_variables.update(variables)
  1098. return ("Test", "Test")
  1099. with (
  1100. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1101. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1102. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1103. ):
  1104. mock_get.return_value = [mock_provider]
  1105. await service.on_print_complete(
  1106. printer_id=1,
  1107. printer_name="Test",
  1108. status="completed",
  1109. data={"subtask_name": "test_print"},
  1110. db=mock_db,
  1111. archive_data={
  1112. "print_time_seconds": 3600, # 1h slicer estimate, no actual
  1113. "actual_time_seconds": None,
  1114. },
  1115. )
  1116. assert captured_variables["duration"] != "Unknown"
  1117. assert "1h" in captured_variables["duration"]
  1118. @pytest.mark.asyncio
  1119. async def test_duration_unknown_when_both_time_fields_missing(self, service):
  1120. """#1198: with neither actual nor estimated time available the duration
  1121. variable surfaces the existing 'Unknown' fallback."""
  1122. mock_db = AsyncMock()
  1123. mock_provider = MagicMock()
  1124. mock_provider.id = 1
  1125. captured_variables: dict = {}
  1126. async def capture_build(db, event_type, variables):
  1127. captured_variables.update(variables)
  1128. return ("Test", "Test")
  1129. with (
  1130. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1131. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1132. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1133. ):
  1134. mock_get.return_value = [mock_provider]
  1135. await service.on_print_complete(
  1136. printer_id=1,
  1137. printer_name="Test",
  1138. status="completed",
  1139. data={"subtask_name": "test_print"},
  1140. db=mock_db,
  1141. archive_data={
  1142. "print_time_seconds": None,
  1143. "actual_time_seconds": None,
  1144. },
  1145. )
  1146. assert captured_variables["duration"] == "Unknown"
  1147. @pytest.mark.asyncio
  1148. async def test_print_complete_with_finish_photo_url(self, service):
  1149. """Verify finish_photo_url is passed through from archive_data."""
  1150. mock_db = AsyncMock()
  1151. mock_provider = MagicMock()
  1152. mock_provider.id = 1
  1153. captured_variables = {}
  1154. async def capture_build(db, event_type, variables):
  1155. captured_variables.update(variables)
  1156. return ("Test", "Test")
  1157. with (
  1158. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1159. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1160. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1161. ):
  1162. mock_get.return_value = [mock_provider]
  1163. await service.on_print_complete(
  1164. printer_id=1,
  1165. printer_name="Test",
  1166. status="completed",
  1167. data={"subtask_name": "test_print"},
  1168. db=mock_db,
  1169. archive_data={
  1170. "print_time_seconds": 3600,
  1171. "actual_filament_grams": 50.5,
  1172. "finish_photo_url": "http://localhost:8000/api/v1/archives/1/photos/finish_test.jpg",
  1173. },
  1174. )
  1175. # finish_photo_url should be passed through to template variables
  1176. assert (
  1177. captured_variables.get("finish_photo_url")
  1178. == "http://localhost:8000/api/v1/archives/1/photos/finish_test.jpg"
  1179. )
  1180. @pytest.mark.asyncio
  1181. async def test_print_start_estimated_time_fallback(self, service):
  1182. """Verify estimated time shows 'Unknown' when not available."""
  1183. mock_db = AsyncMock()
  1184. mock_provider = MagicMock()
  1185. mock_provider.id = 1
  1186. captured_variables = {}
  1187. async def capture_build(db, event_type, variables):
  1188. captured_variables.update(variables)
  1189. return ("Test", "Test")
  1190. with (
  1191. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1192. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1193. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1194. patch("backend.app.api.routes.settings.get_setting", new_callable=AsyncMock, return_value=None),
  1195. ):
  1196. # Need at least one provider to trigger message building
  1197. mock_get.return_value = [mock_provider]
  1198. await service.on_print_start(
  1199. printer_id=1,
  1200. printer_name="Test",
  1201. data={
  1202. "subtask_name": "test",
  1203. # No estimated_time or mc_remaining_time
  1204. },
  1205. db=mock_db,
  1206. )
  1207. # When no time data, should show "Unknown"
  1208. assert captured_variables.get("estimated_time") == "Unknown"
  1209. @pytest.mark.asyncio
  1210. async def test_print_progress_remaining_time_fallback(self, service):
  1211. """Verify remaining time shows 'Unknown' when not available."""
  1212. mock_db = AsyncMock()
  1213. mock_provider = MagicMock()
  1214. mock_provider.id = 1
  1215. captured_variables = {}
  1216. async def capture_build(db, event_type, variables):
  1217. captured_variables.update(variables)
  1218. return ("Test", "Test")
  1219. with (
  1220. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1221. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1222. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1223. patch("backend.app.api.routes.settings.get_setting", new_callable=AsyncMock, return_value=None),
  1224. ):
  1225. # Need at least one provider to trigger message building
  1226. mock_get.return_value = [mock_provider]
  1227. await service.on_print_progress(
  1228. printer_id=1,
  1229. printer_name="Test",
  1230. progress=50,
  1231. remaining_time=None, # No remaining time
  1232. filename="test.3mf",
  1233. db=mock_db,
  1234. )
  1235. # When no remaining time, should show "Unknown"
  1236. assert captured_variables.get("remaining_time") == "Unknown"
  1237. @pytest.mark.asyncio
  1238. async def test_filename_fallback_to_unknown(self, service):
  1239. """Verify filename defaults to 'Unknown' when not provided."""
  1240. mock_db = AsyncMock()
  1241. mock_provider = MagicMock()
  1242. mock_provider.id = 1
  1243. captured_variables = {}
  1244. async def capture_build(db, event_type, variables):
  1245. captured_variables.update(variables)
  1246. return ("Test", "Test")
  1247. with (
  1248. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1249. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1250. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1251. ):
  1252. # Need at least one provider to trigger message building
  1253. mock_get.return_value = [mock_provider]
  1254. await service.on_print_complete(
  1255. printer_id=1,
  1256. printer_name="Test",
  1257. status="completed",
  1258. data={}, # No subtask_name or filename
  1259. db=mock_db,
  1260. )
  1261. # Filename should default to something (either "Unknown" or cleaned empty)
  1262. assert "filename" in captured_variables
  1263. @pytest.mark.asyncio
  1264. async def test_print_start_uses_archive_print_time_seconds(self, service):
  1265. """Verify print_time_seconds from archive_data is used for estimated_time."""
  1266. mock_db = AsyncMock()
  1267. mock_provider = MagicMock()
  1268. mock_provider.id = 1
  1269. captured_variables = {}
  1270. async def capture_build(db, event_type, variables):
  1271. captured_variables.update(variables)
  1272. return ("Test", "Test")
  1273. with (
  1274. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1275. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1276. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1277. patch("backend.app.api.routes.settings.get_setting", new_callable=AsyncMock, return_value=None),
  1278. ):
  1279. mock_get.return_value = [mock_provider]
  1280. # Pass archive_data with print_time_seconds (7200 seconds = 2 hours)
  1281. await service.on_print_start(
  1282. printer_id=1,
  1283. printer_name="Test",
  1284. data={"subtask_name": "test"},
  1285. db=mock_db,
  1286. archive_data={"print_time_seconds": 7200},
  1287. )
  1288. # Should use archive's print_time_seconds: 7200 seconds = 2h 0m
  1289. assert captured_variables.get("estimated_time") == "2h 0m"
  1290. @pytest.mark.asyncio
  1291. async def test_print_start_archive_data_overrides_mqtt(self, service):
  1292. """Verify archive_data takes priority over MQTT remaining_time."""
  1293. mock_db = AsyncMock()
  1294. mock_provider = MagicMock()
  1295. mock_provider.id = 1
  1296. captured_variables = {}
  1297. async def capture_build(db, event_type, variables):
  1298. captured_variables.update(variables)
  1299. return ("Test", "Test")
  1300. with (
  1301. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1302. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1303. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1304. patch("backend.app.api.routes.settings.get_setting", new_callable=AsyncMock, return_value=None),
  1305. ):
  1306. mock_get.return_value = [mock_provider]
  1307. # Both archive_data and MQTT remaining_time provided
  1308. # Archive says 2 hours, MQTT says 30 minutes (wrong at start)
  1309. await service.on_print_start(
  1310. printer_id=1,
  1311. printer_name="Test",
  1312. data={
  1313. "subtask_name": "test",
  1314. "remaining_time": 1800, # 30 minutes from MQTT
  1315. },
  1316. db=mock_db,
  1317. archive_data={"print_time_seconds": 7200}, # 2 hours from 3MF
  1318. )
  1319. # Should use archive's print_time_seconds (more reliable)
  1320. assert captured_variables.get("estimated_time") == "2h 0m"
  1321. @pytest.mark.asyncio
  1322. async def test_print_start_falls_back_to_mqtt_when_no_archive(self, service):
  1323. """Verify MQTT remaining_time is used when archive_data not provided."""
  1324. mock_db = AsyncMock()
  1325. mock_provider = MagicMock()
  1326. mock_provider.id = 1
  1327. captured_variables = {}
  1328. async def capture_build(db, event_type, variables):
  1329. captured_variables.update(variables)
  1330. return ("Test", "Test")
  1331. with (
  1332. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1333. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1334. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1335. patch("backend.app.api.routes.settings.get_setting", new_callable=AsyncMock, return_value=None),
  1336. ):
  1337. mock_get.return_value = [mock_provider]
  1338. # Only MQTT remaining_time provided (1800 seconds = 30 minutes)
  1339. await service.on_print_start(
  1340. printer_id=1,
  1341. printer_name="Test",
  1342. data={
  1343. "subtask_name": "test",
  1344. "remaining_time": 1800,
  1345. },
  1346. db=mock_db,
  1347. # No archive_data
  1348. )
  1349. # Should use MQTT remaining_time
  1350. assert captured_variables.get("estimated_time") == "30m"
  1351. @pytest.mark.asyncio
  1352. async def test_print_start_eta_calculated_from_estimated_time(self, service):
  1353. """Verify ETA is calculated as wall-clock time from estimated_time."""
  1354. mock_db = AsyncMock()
  1355. mock_provider = MagicMock()
  1356. mock_provider.id = 1
  1357. captured_variables = {}
  1358. async def capture_build(db, event_type, variables):
  1359. captured_variables.update(variables)
  1360. return ("Test", "Test")
  1361. with (
  1362. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1363. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1364. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1365. patch("backend.app.api.routes.settings.get_setting", new_callable=AsyncMock, return_value=None),
  1366. ):
  1367. mock_get.return_value = [mock_provider]
  1368. await service.on_print_start(
  1369. printer_id=1,
  1370. printer_name="Test",
  1371. data={"subtask_name": "test"},
  1372. db=mock_db,
  1373. archive_data={"print_time_seconds": 3600}, # 1 hour
  1374. )
  1375. # ETA should be a time string in HH:MM format
  1376. eta = captured_variables.get("eta")
  1377. assert eta is not None
  1378. assert eta != "Unknown"
  1379. assert ":" in eta # HH:MM format
  1380. @pytest.mark.asyncio
  1381. async def test_print_start_eta_unknown_when_no_time(self, service):
  1382. """Verify ETA shows 'Unknown' when no time data available."""
  1383. mock_db = AsyncMock()
  1384. mock_provider = MagicMock()
  1385. mock_provider.id = 1
  1386. captured_variables = {}
  1387. async def capture_build(db, event_type, variables):
  1388. captured_variables.update(variables)
  1389. return ("Test", "Test")
  1390. with (
  1391. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1392. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1393. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1394. patch("backend.app.api.routes.settings.get_setting", new_callable=AsyncMock, return_value=None),
  1395. ):
  1396. mock_get.return_value = [mock_provider]
  1397. await service.on_print_start(
  1398. printer_id=1,
  1399. printer_name="Test",
  1400. data={"subtask_name": "test"},
  1401. db=mock_db,
  1402. )
  1403. assert captured_variables.get("eta") == "Unknown"
  1404. @pytest.mark.asyncio
  1405. async def test_print_start_eta_respects_12h_format(self, service):
  1406. """Verify ETA uses 12-hour format when time_format is '12h'."""
  1407. mock_db = AsyncMock()
  1408. mock_provider = MagicMock()
  1409. mock_provider.id = 1
  1410. captured_variables = {}
  1411. async def capture_build(db, event_type, variables):
  1412. captured_variables.update(variables)
  1413. return ("Test", "Test")
  1414. with (
  1415. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1416. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1417. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1418. patch("backend.app.api.routes.settings.get_setting", new_callable=AsyncMock, return_value="12h"),
  1419. ):
  1420. mock_get.return_value = [mock_provider]
  1421. await service.on_print_start(
  1422. printer_id=1,
  1423. printer_name="Test",
  1424. data={"subtask_name": "test"},
  1425. db=mock_db,
  1426. archive_data={"print_time_seconds": 3600},
  1427. )
  1428. eta = captured_variables.get("eta")
  1429. assert eta is not None
  1430. # 12h format should contain AM or PM
  1431. assert "AM" in eta or "PM" in eta
  1432. class TestNotificationTemplates:
  1433. """Tests for notification message template rendering."""
  1434. @pytest.fixture
  1435. def service(self):
  1436. return NotificationService()
  1437. @pytest.mark.asyncio
  1438. async def test_template_renders_variables(self, service):
  1439. """Verify template variables are replaced correctly."""
  1440. template_title = "Print {progress}% Complete"
  1441. template_body = "{printer}: {filename}\nRemaining: {remaining_time}"
  1442. variables = {
  1443. "printer": "Test Printer",
  1444. "filename": "test.3mf",
  1445. "progress": "50",
  1446. "remaining_time": "1h 30m",
  1447. }
  1448. title = template_title.format(**variables)
  1449. body = template_body.format(**variables)
  1450. assert title == "Print 50% Complete"
  1451. assert "Test Printer" in body
  1452. assert "test.3mf" in body
  1453. assert "1h 30m" in body
  1454. @pytest.mark.asyncio
  1455. async def test_template_handles_missing_variables(self, service):
  1456. """Verify missing template variables don't cause crashes."""
  1457. template = "{printer}: {unknown_var}"
  1458. variables = {"printer": "Test"}
  1459. # Should handle gracefully - either leave placeholder or skip
  1460. try:
  1461. result = template.format_map({**variables, "unknown_var": "{unknown_var}"})
  1462. assert "Test" in result
  1463. except KeyError:
  1464. pytest.fail("Template should handle missing variables gracefully")
  1465. class TestPrinterErrorNotifications:
  1466. """Tests for HMS error (printer error) notifications."""
  1467. @pytest.fixture
  1468. def service(self):
  1469. return NotificationService()
  1470. @pytest.fixture
  1471. def mock_provider(self):
  1472. """Create a mock notification provider with error notifications enabled."""
  1473. provider = MagicMock()
  1474. provider.id = 1
  1475. provider.name = "Test Provider"
  1476. provider.provider_type = "webhook"
  1477. provider.enabled = True
  1478. provider.config = json.dumps({"webhook_url": "http://test.local/webhook"})
  1479. provider.on_printer_error = True # Enable error notifications
  1480. provider.quiet_hours_enabled = False
  1481. provider.daily_digest_enabled = False
  1482. provider.printer_id = None
  1483. return provider
  1484. @pytest.fixture
  1485. def mock_db(self):
  1486. """Create a mock database session."""
  1487. db = AsyncMock()
  1488. db.commit = AsyncMock()
  1489. return db
  1490. @pytest.mark.asyncio
  1491. async def test_on_printer_error_sends_notification(self, service, mock_provider, mock_db):
  1492. """Verify HMS error notification is sent when triggered."""
  1493. with (
  1494. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1495. patch.object(service, "_send_to_providers", new_callable=AsyncMock) as mock_send,
  1496. patch.object(service, "_build_message_from_template", new_callable=AsyncMock) as mock_build,
  1497. ):
  1498. mock_get.return_value = [mock_provider]
  1499. mock_build.return_value = ("Printer Error", "AMS/Filament Error: 0700_8010")
  1500. await service.on_printer_error(
  1501. printer_id=1,
  1502. printer_name="Test Printer",
  1503. error_type="AMS/Filament Error",
  1504. db=mock_db,
  1505. error_detail="Error code: 0700_8010",
  1506. )
  1507. mock_get.assert_called_once()
  1508. mock_send.assert_called_once()
  1509. @pytest.mark.asyncio
  1510. async def test_on_printer_error_skipped_when_disabled(self, service, mock_provider, mock_db):
  1511. """CRITICAL: Verify error notifications respect toggle setting."""
  1512. mock_provider.on_printer_error = False
  1513. with (
  1514. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1515. patch.object(service, "_send_to_providers", new_callable=AsyncMock) as mock_send,
  1516. ):
  1517. # Provider with toggle disabled won't be returned
  1518. mock_get.return_value = []
  1519. await service.on_printer_error(
  1520. printer_id=1,
  1521. printer_name="Test",
  1522. error_type="AMS Error",
  1523. db=mock_db,
  1524. error_detail="Test error",
  1525. )
  1526. mock_send.assert_not_called()
  1527. @pytest.mark.asyncio
  1528. async def test_on_printer_error_includes_error_detail(self, service, mock_provider, mock_db):
  1529. """Verify error details are passed to template variables."""
  1530. captured_variables = {}
  1531. async def capture_build(db, event_type, variables):
  1532. captured_variables.update(variables)
  1533. return ("Test", "Test")
  1534. with (
  1535. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1536. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1537. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1538. ):
  1539. mock_get.return_value = [mock_provider]
  1540. await service.on_printer_error(
  1541. printer_id=1,
  1542. printer_name="X1 Carbon",
  1543. error_type="AMS/Filament Error",
  1544. db=mock_db,
  1545. error_detail="Error code: 0700_8010",
  1546. )
  1547. assert captured_variables["printer"] == "X1 Carbon"
  1548. assert captured_variables["error_type"] == "AMS/Filament Error"
  1549. assert captured_variables["error_detail"] == "Error code: 0700_8010"
  1550. @pytest.mark.asyncio
  1551. async def test_on_printer_error_fallback_when_no_detail(self, service, mock_provider, mock_db):
  1552. """Verify fallback message when error_detail is None."""
  1553. captured_variables = {}
  1554. async def capture_build(db, event_type, variables):
  1555. captured_variables.update(variables)
  1556. return ("Test", "Test")
  1557. with (
  1558. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1559. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1560. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1561. ):
  1562. mock_get.return_value = [mock_provider]
  1563. await service.on_printer_error(
  1564. printer_id=1,
  1565. printer_name="Test Printer",
  1566. error_type="Unknown Error",
  1567. db=mock_db,
  1568. error_detail=None, # No detail provided
  1569. )
  1570. assert captured_variables["error_detail"] == "No details available"
  1571. class TestAIFailureDetectionNotifications:
  1572. """Tests for the AI failure-detection event (#1794 — split out of on_printer_error).
  1573. Pins that Obico failure-detection dispatches go through the dedicated
  1574. on_ai_failure_detection event field, not the multiplexed printer-error
  1575. field. Mirrors the printer-error coverage above so a regression on either
  1576. surface fails its own case.
  1577. """
  1578. @pytest.fixture
  1579. def service(self):
  1580. return NotificationService()
  1581. @pytest.fixture
  1582. def mock_provider(self):
  1583. provider = MagicMock()
  1584. provider.id = 1
  1585. provider.name = "Test Provider"
  1586. provider.provider_type = "webhook"
  1587. provider.enabled = True
  1588. provider.config = json.dumps({"webhook_url": "http://test.local/webhook"})
  1589. provider.on_ai_failure_detection = True
  1590. provider.on_printer_error = False # disabled — the regression guard
  1591. provider.quiet_hours_enabled = False
  1592. provider.daily_digest_enabled = False
  1593. provider.printer_id = None
  1594. return provider
  1595. @pytest.fixture
  1596. def mock_db(self):
  1597. db = AsyncMock()
  1598. db.commit = AsyncMock()
  1599. return db
  1600. @pytest.mark.asyncio
  1601. async def test_dispatch_uses_ai_failure_detection_event_not_printer_error(self, service, mock_provider, mock_db):
  1602. """Regression guard: provider subscribed only to AI alerts must receive
  1603. the Obico notification."""
  1604. captured_event = []
  1605. async def capture(db, event_field, printer_id):
  1606. captured_event.append(event_field)
  1607. return [mock_provider]
  1608. with (
  1609. patch.object(service, "_get_providers_for_event", side_effect=capture),
  1610. patch.object(service, "_send_to_providers", new_callable=AsyncMock) as mock_send,
  1611. patch.object(service, "_build_message_from_template", new_callable=AsyncMock) as mock_build,
  1612. ):
  1613. mock_build.return_value = ("Possible Print Failure Detected", "details")
  1614. await service.on_ai_failure_detection(
  1615. printer_id=1,
  1616. printer_name="X1 Carbon",
  1617. task_name="benchy.3mf",
  1618. confidence=0.87,
  1619. action="notify",
  1620. db=mock_db,
  1621. )
  1622. assert captured_event == ["on_ai_failure_detection"]
  1623. mock_send.assert_called_once()
  1624. @pytest.mark.asyncio
  1625. async def test_skipped_when_only_printer_error_is_enabled(self, service, mock_provider, mock_db):
  1626. """Pre-#1794 behaviour MUST NOT survive: a provider with only the
  1627. legacy on_printer_error toggle should NOT receive AI notifications now."""
  1628. mock_provider.on_ai_failure_detection = False
  1629. mock_provider.on_printer_error = True
  1630. with (
  1631. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1632. patch.object(service, "_send_to_providers", new_callable=AsyncMock) as mock_send,
  1633. ):
  1634. mock_get.return_value = [] # the event-field filter excludes the provider
  1635. await service.on_ai_failure_detection(
  1636. printer_id=1,
  1637. printer_name="X1 Carbon",
  1638. task_name="benchy.3mf",
  1639. confidence=0.87,
  1640. action="notify",
  1641. db=mock_db,
  1642. )
  1643. mock_send.assert_not_called()
  1644. @pytest.mark.asyncio
  1645. async def test_variables_include_task_name_confidence_action(self, service, mock_provider, mock_db):
  1646. captured_variables = {}
  1647. async def capture_build(db, event_type, variables):
  1648. captured_variables.update(variables)
  1649. return ("Test", "Test")
  1650. with (
  1651. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1652. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1653. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1654. ):
  1655. mock_get.return_value = [mock_provider]
  1656. await service.on_ai_failure_detection(
  1657. printer_id=1,
  1658. printer_name="X1 Carbon",
  1659. task_name="benchy.3mf",
  1660. confidence=0.873,
  1661. action="pause_and_off",
  1662. db=mock_db,
  1663. )
  1664. assert captured_variables["printer"] == "X1 Carbon"
  1665. assert captured_variables["task_name"] == "benchy.3mf"
  1666. assert captured_variables["confidence"] == "0.87" # 2-decimal format
  1667. assert captured_variables["action"] == "pause_and_off"
  1668. @pytest.mark.asyncio
  1669. async def test_task_name_fallback_when_unknown(self, service, mock_provider, mock_db):
  1670. captured_variables = {}
  1671. async def capture_build(db, event_type, variables):
  1672. captured_variables.update(variables)
  1673. return ("Test", "Test")
  1674. with (
  1675. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1676. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1677. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1678. ):
  1679. mock_get.return_value = [mock_provider]
  1680. await service.on_ai_failure_detection(
  1681. printer_id=1,
  1682. printer_name="Test",
  1683. task_name="", # empty
  1684. confidence=0.5,
  1685. action="notify",
  1686. db=mock_db,
  1687. )
  1688. assert captured_variables["task_name"] == "current job"
  1689. class TestPlateNotEmptyNotifications:
  1690. """Tests for plate not empty (build plate detection) notifications."""
  1691. @pytest.fixture
  1692. def service(self):
  1693. return NotificationService()
  1694. @pytest.fixture
  1695. def mock_provider(self):
  1696. """Create a mock notification provider with plate detection enabled."""
  1697. provider = MagicMock()
  1698. provider.id = 1
  1699. provider.name = "Test Provider"
  1700. provider.provider_type = "webhook"
  1701. provider.enabled = True
  1702. provider.config = json.dumps({"webhook_url": "http://test.local/webhook"})
  1703. provider.on_plate_not_empty = True
  1704. provider.quiet_hours_enabled = False
  1705. provider.daily_digest_enabled = False
  1706. provider.printer_id = None
  1707. return provider
  1708. @pytest.fixture
  1709. def mock_db(self):
  1710. """Create a mock database session."""
  1711. db = AsyncMock()
  1712. db.commit = AsyncMock()
  1713. return db
  1714. @pytest.mark.asyncio
  1715. async def test_on_plate_not_empty_sends_notification(self, service, mock_provider, mock_db):
  1716. """Verify plate not empty notification is sent when triggered."""
  1717. with (
  1718. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1719. patch.object(service, "_send_to_providers", new_callable=AsyncMock) as mock_send,
  1720. patch.object(service, "_build_message_from_template", new_callable=AsyncMock) as mock_build,
  1721. ):
  1722. mock_get.return_value = [mock_provider]
  1723. mock_build.return_value = ("Plate Not Empty", "Objects detected on build plate")
  1724. await service.on_plate_not_empty(
  1725. printer_id=1,
  1726. printer_name="Test Printer",
  1727. db=mock_db,
  1728. difference_percent=5.2,
  1729. )
  1730. mock_get.assert_called_once()
  1731. mock_send.assert_called_once()
  1732. # Verify force_immediate is True (critical alert)
  1733. call_kwargs = mock_send.call_args[1]
  1734. assert call_kwargs.get("force_immediate") is True
  1735. @pytest.mark.asyncio
  1736. async def test_on_plate_not_empty_skipped_when_disabled(self, service, mock_provider, mock_db):
  1737. """Verify notification is skipped when toggle is disabled."""
  1738. mock_provider.on_plate_not_empty = False
  1739. with (
  1740. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1741. patch.object(service, "_send_to_providers", new_callable=AsyncMock) as mock_send,
  1742. ):
  1743. mock_get.return_value = []
  1744. await service.on_plate_not_empty(
  1745. printer_id=1,
  1746. printer_name="Test",
  1747. db=mock_db,
  1748. )
  1749. mock_send.assert_not_called()
  1750. @pytest.mark.asyncio
  1751. async def test_on_plate_not_empty_includes_difference_percent(self, service, mock_provider, mock_db):
  1752. """Verify difference percentage is passed to template variables."""
  1753. captured_variables = {}
  1754. async def capture_build(db, event_type, variables):
  1755. captured_variables.update(variables)
  1756. return ("Test", "Test")
  1757. with (
  1758. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1759. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1760. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1761. ):
  1762. mock_get.return_value = [mock_provider]
  1763. await service.on_plate_not_empty(
  1764. printer_id=1,
  1765. printer_name="X1 Carbon",
  1766. db=mock_db,
  1767. difference_percent=3.5,
  1768. )
  1769. assert captured_variables["printer"] == "X1 Carbon"
  1770. assert captured_variables["difference_percent"] == "3.5"
  1771. class TestBedCooledNotifications:
  1772. """Tests for bed cooled (after print) notifications."""
  1773. @pytest.fixture
  1774. def service(self):
  1775. return NotificationService()
  1776. @pytest.fixture
  1777. def mock_provider(self):
  1778. """Create a mock notification provider with bed cooled enabled."""
  1779. provider = MagicMock()
  1780. provider.id = 1
  1781. provider.name = "Test Provider"
  1782. provider.provider_type = "webhook"
  1783. provider.enabled = True
  1784. provider.config = json.dumps({"webhook_url": "http://test.local/webhook"})
  1785. provider.on_bed_cooled = True
  1786. provider.quiet_hours_enabled = False
  1787. provider.daily_digest_enabled = False
  1788. provider.printer_id = None
  1789. return provider
  1790. @pytest.fixture
  1791. def mock_db(self):
  1792. """Create a mock database session."""
  1793. db = AsyncMock()
  1794. db.commit = AsyncMock()
  1795. return db
  1796. @pytest.mark.asyncio
  1797. async def test_on_bed_cooled_sends_notification(self, service, mock_provider, mock_db):
  1798. """Verify bed cooled notification is sent when triggered."""
  1799. with (
  1800. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1801. patch.object(service, "_send_to_providers", new_callable=AsyncMock) as mock_send,
  1802. patch.object(service, "_build_message_from_template", new_callable=AsyncMock) as mock_build,
  1803. ):
  1804. mock_get.return_value = [mock_provider]
  1805. mock_build.return_value = ("Bed Cooled", "Test Printer: Bed cooled to 30°C")
  1806. await service.on_bed_cooled(
  1807. printer_id=1,
  1808. printer_name="Test Printer",
  1809. bed_temp=30.0,
  1810. threshold=35.0,
  1811. filename="benchy.3mf",
  1812. db=mock_db,
  1813. )
  1814. mock_get.assert_called_once()
  1815. mock_send.assert_called_once()
  1816. @pytest.mark.asyncio
  1817. async def test_on_bed_cooled_skipped_when_no_providers(self, service, mock_db):
  1818. """Verify notification is skipped when no providers have bed cooled enabled."""
  1819. with (
  1820. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1821. patch.object(service, "_send_to_providers", new_callable=AsyncMock) as mock_send,
  1822. ):
  1823. mock_get.return_value = []
  1824. await service.on_bed_cooled(
  1825. printer_id=1,
  1826. printer_name="Test Printer",
  1827. bed_temp=30.0,
  1828. threshold=35.0,
  1829. filename="benchy.3mf",
  1830. db=mock_db,
  1831. )
  1832. mock_send.assert_not_called()
  1833. @pytest.mark.asyncio
  1834. async def test_on_bed_cooled_includes_correct_variables(self, service, mock_provider, mock_db):
  1835. """Verify bed temp, threshold, and filename are passed to template variables."""
  1836. captured_variables = {}
  1837. async def capture_build(db, event_type, variables):
  1838. captured_variables.update(variables)
  1839. return ("Test", "Test")
  1840. with (
  1841. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1842. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1843. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1844. ):
  1845. mock_get.return_value = [mock_provider]
  1846. await service.on_bed_cooled(
  1847. printer_id=1,
  1848. printer_name="X1 Carbon",
  1849. bed_temp=28.7,
  1850. threshold=35.0,
  1851. filename="benchy.gcode.3mf",
  1852. db=mock_db,
  1853. )
  1854. assert captured_variables["printer"] == "X1 Carbon"
  1855. assert captured_variables["bed_temp"] == "29"
  1856. assert captured_variables["threshold"] == "35"
  1857. assert captured_variables["filename"] == "benchy"
  1858. @pytest.mark.asyncio
  1859. async def test_on_bed_cooled_handles_none_filename(self, service, mock_provider, mock_db):
  1860. """Verify None filename is handled gracefully."""
  1861. captured_variables = {}
  1862. async def capture_build(db, event_type, variables):
  1863. captured_variables.update(variables)
  1864. return ("Test", "Test")
  1865. with (
  1866. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1867. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1868. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1869. ):
  1870. mock_get.return_value = [mock_provider]
  1871. await service.on_bed_cooled(
  1872. printer_id=1,
  1873. printer_name="Test Printer",
  1874. bed_temp=30.0,
  1875. threshold=35.0,
  1876. filename=None,
  1877. db=mock_db,
  1878. )
  1879. assert captured_variables["filename"] == "Unknown"
  1880. class TestFirstLayerCompleteNotifications:
  1881. """Tests for first layer complete notifications."""
  1882. @pytest.fixture
  1883. def service(self):
  1884. return NotificationService()
  1885. @pytest.fixture
  1886. def mock_provider(self):
  1887. """Create a mock notification provider with first layer complete enabled."""
  1888. provider = MagicMock()
  1889. provider.id = 1
  1890. provider.name = "Test Provider"
  1891. provider.provider_type = "webhook"
  1892. provider.enabled = True
  1893. provider.config = json.dumps({"webhook_url": "http://test.local/webhook"})
  1894. provider.on_first_layer_complete = True
  1895. provider.quiet_hours_enabled = False
  1896. provider.daily_digest_enabled = False
  1897. provider.printer_id = None
  1898. return provider
  1899. @pytest.fixture
  1900. def mock_db(self):
  1901. """Create a mock database session."""
  1902. db = AsyncMock()
  1903. db.commit = AsyncMock()
  1904. return db
  1905. @pytest.mark.asyncio
  1906. async def test_on_first_layer_complete_sends_notification(self, service, mock_provider, mock_db):
  1907. """Verify first layer complete notification is sent when triggered."""
  1908. with (
  1909. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1910. patch.object(service, "_send_to_providers", new_callable=AsyncMock) as mock_send,
  1911. patch.object(service, "_build_message_from_template", new_callable=AsyncMock) as mock_build,
  1912. ):
  1913. mock_get.return_value = [mock_provider]
  1914. mock_build.return_value = ("First Layer Complete", "Test Printer: benchy.3mf")
  1915. await service.on_first_layer_complete(
  1916. printer_id=1,
  1917. printer_name="Test Printer",
  1918. filename="benchy.3mf",
  1919. total_layers=50,
  1920. db=mock_db,
  1921. )
  1922. mock_get.assert_called_once()
  1923. mock_send.assert_called_once()
  1924. @pytest.mark.asyncio
  1925. async def test_on_first_layer_complete_skipped_when_no_providers(self, service, mock_db):
  1926. """Verify notification is skipped when no providers have first layer complete enabled."""
  1927. with (
  1928. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1929. patch.object(service, "_send_to_providers", new_callable=AsyncMock) as mock_send,
  1930. ):
  1931. mock_get.return_value = []
  1932. await service.on_first_layer_complete(
  1933. printer_id=1,
  1934. printer_name="Test Printer",
  1935. filename="benchy.3mf",
  1936. total_layers=50,
  1937. db=mock_db,
  1938. )
  1939. mock_send.assert_not_called()
  1940. @pytest.mark.asyncio
  1941. async def test_on_first_layer_complete_includes_correct_variables(self, service, mock_provider, mock_db):
  1942. """Verify printer name, filename, and total_layers are passed to template variables."""
  1943. captured_variables = {}
  1944. async def capture_build(db, event_type, variables):
  1945. captured_variables.update(variables)
  1946. return ("Test", "Test")
  1947. with (
  1948. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1949. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1950. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1951. ):
  1952. mock_get.return_value = [mock_provider]
  1953. await service.on_first_layer_complete(
  1954. printer_id=1,
  1955. printer_name="X1 Carbon",
  1956. filename="benchy.gcode.3mf",
  1957. total_layers=120,
  1958. db=mock_db,
  1959. )
  1960. assert captured_variables["printer"] == "X1 Carbon"
  1961. assert captured_variables["filename"] == "benchy"
  1962. assert captured_variables["total_layers"] == "120"
  1963. @pytest.mark.asyncio
  1964. async def test_on_first_layer_complete_passes_image_data(self, service, mock_provider, mock_db):
  1965. """Verify image_data is passed through to _send_to_providers."""
  1966. with (
  1967. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1968. patch.object(service, "_send_to_providers", new_callable=AsyncMock) as mock_send,
  1969. patch.object(service, "_build_message_from_template", new_callable=AsyncMock) as mock_build,
  1970. ):
  1971. mock_get.return_value = [mock_provider]
  1972. mock_build.return_value = ("First Layer Complete", "Test message")
  1973. fake_image = b"\x89PNG\r\n\x1a\nfakeimage"
  1974. await service.on_first_layer_complete(
  1975. printer_id=1,
  1976. printer_name="Test Printer",
  1977. filename="benchy.3mf",
  1978. total_layers=50,
  1979. db=mock_db,
  1980. image_data=fake_image,
  1981. )
  1982. mock_send.assert_called_once()
  1983. call_kwargs = mock_send.call_args
  1984. assert call_kwargs.kwargs.get("image_data") == fake_image
  1985. class TestNtfyOutbound:
  1986. """Regression for #1534 — UA hygiene and Cloudflare-challenge detection."""
  1987. @pytest.fixture
  1988. def service(self):
  1989. return NotificationService()
  1990. @pytest.mark.asyncio
  1991. async def test_notification_client_sets_honest_user_agent(self, service):
  1992. """Default httpx UA leaks `python-httpx/<version>` — every other
  1993. outbound client in the codebase identifies as Bambuddy. The
  1994. notification client must too."""
  1995. client = await service._get_client()
  1996. try:
  1997. assert client.headers.get("user-agent") == "Bambuddy/1.0 (+https://github.com/maziggy/bambuddy)"
  1998. finally:
  1999. await service.close()
  2000. @pytest.mark.asyncio
  2001. async def test_ntfy_cloudflare_challenge_returns_actionable_error(self, service):
  2002. """When ntfy is fronted by Cloudflare and CF returns its JS
  2003. challenge, the user must see a message that points at the actual
  2004. fix (CF security skip), not the raw HTML."""
  2005. import httpx
  2006. challenge_html = (
  2007. '<!DOCTYPE html><html lang="en-US"><head><title>Just a moment...</title>'
  2008. '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">'
  2009. )
  2010. mock_response = httpx.Response(
  2011. 403,
  2012. content=challenge_html.encode(),
  2013. headers={"server": "cloudflare", "content-type": "text/html; charset=UTF-8"},
  2014. )
  2015. mock_client = AsyncMock()
  2016. mock_client.post = AsyncMock(return_value=mock_response)
  2017. with patch.object(service, "_get_client", AsyncMock(return_value=mock_client)):
  2018. ok, detail = await service._send_ntfy(
  2019. {"server": "https://ntfy.example", "topic": "alerts", "auth_token": "tk_xxx"},
  2020. title="t",
  2021. message="m",
  2022. )
  2023. assert ok is False
  2024. assert "Cloudflare" in detail
  2025. assert "security-skip" in detail or "Bot Fight Mode" in detail
  2026. # The raw HTML must not be the dominant content shown to the user.
  2027. assert "<!DOCTYPE" not in detail
  2028. @pytest.mark.asyncio
  2029. async def test_ntfy_normal_403_still_surfaces_body(self, service):
  2030. """A non-Cloudflare 403 (e.g. ntfy auth fail) must keep showing
  2031. the original body so the user can debug the real error — we
  2032. only intercept the Cloudflare-challenge shape."""
  2033. import httpx
  2034. mock_response = httpx.Response(
  2035. 403,
  2036. content=b"forbidden: invalid auth token",
  2037. headers={"content-type": "text/plain"},
  2038. )
  2039. mock_client = AsyncMock()
  2040. mock_client.post = AsyncMock(return_value=mock_response)
  2041. with patch.object(service, "_get_client", AsyncMock(return_value=mock_client)):
  2042. ok, detail = await service._send_ntfy(
  2043. {"server": "https://ntfy.sh", "topic": "alerts", "auth_token": "bad"},
  2044. title="t",
  2045. message="m",
  2046. )
  2047. assert ok is False
  2048. assert "Cloudflare" not in detail
  2049. assert "invalid auth token" in detail
  2050. assert detail.startswith("HTTP 403:")
  2051. @pytest.mark.asyncio
  2052. async def test_ntfy_origin_error_through_cloudflare_is_not_misclassified(self, service):
  2053. """Cloudflare adds Server: cloudflare to EVERY proxied response,
  2054. including legitimate origin errors. A real 401 "wrong token"
  2055. from an ntfy server that happens to sit behind Cloudflare must
  2056. still surface the origin's actual error body — we must not flip
  2057. every CF-fronted 4xx into a "your Cloudflare is blocking" message.
  2058. """
  2059. import httpx
  2060. mock_response = httpx.Response(
  2061. 401,
  2062. content=b'{"code":40101,"http":401,"error":"unauthorized"}',
  2063. headers={
  2064. "server": "cloudflare",
  2065. "cf-ray": "abc123-FRA",
  2066. "content-type": "application/json",
  2067. # No cf-mitigated — CF just proxied the origin response.
  2068. },
  2069. )
  2070. mock_client = AsyncMock()
  2071. mock_client.post = AsyncMock(return_value=mock_response)
  2072. with patch.object(service, "_get_client", AsyncMock(return_value=mock_client)):
  2073. ok, detail = await service._send_ntfy(
  2074. {"server": "https://ntfy.example", "topic": "alerts", "auth_token": "wrong"},
  2075. title="t",
  2076. message="m",
  2077. )
  2078. assert ok is False
  2079. assert "Cloudflare" not in detail
  2080. assert "unauthorized" in detail
  2081. assert detail.startswith("HTTP 401:")
  2082. @pytest.mark.asyncio
  2083. async def test_ntfy_cloudflare_cf_mitigated_header_alone_triggers(self, service):
  2084. """The cf-mitigated header on its own is enough — that's the
  2085. canonical CF "I actively blocked this" signal, even if the
  2086. response body shape changes between CF challenge generations."""
  2087. import httpx
  2088. mock_response = httpx.Response(
  2089. 403,
  2090. content=b"<html>some future CF block page</html>",
  2091. headers={
  2092. "server": "cloudflare",
  2093. "cf-mitigated": "challenge",
  2094. "content-type": "text/html",
  2095. },
  2096. )
  2097. mock_client = AsyncMock()
  2098. mock_client.post = AsyncMock(return_value=mock_response)
  2099. with patch.object(service, "_get_client", AsyncMock(return_value=mock_client)):
  2100. ok, detail = await service._send_ntfy(
  2101. {"server": "https://ntfy.example", "topic": "alerts"},
  2102. title="t",
  2103. message="m",
  2104. )
  2105. assert ok is False
  2106. assert "Cloudflare" in detail
  2107. class TestEmailProvider:
  2108. """Tests for SMTP email provider, including #1792 finish-photo inline embed.
  2109. Embed is opt-in via the template: only when the user's template referenced
  2110. ``{finish_photo_url}`` (so the URL appears in the rendered body) AND the
  2111. photo bytes are available does ``_send_email`` build the multipart/related
  2112. shape. Otherwise it stays single-part text — no surprise inline image.
  2113. """
  2114. PHOTO_URL = "https://printer.local/api/v1/archives/42/photos/finish.jpg"
  2115. @pytest.fixture
  2116. def service(self):
  2117. return NotificationService()
  2118. @pytest.fixture
  2119. def smtp_config(self):
  2120. return {
  2121. "smtp_server": "smtp.example.com",
  2122. "smtp_port": "587",
  2123. "username": "alice",
  2124. "password": "secret",
  2125. "from_email": "bambuddy@example.com",
  2126. "to_email": "alice@example.com",
  2127. "security": "starttls",
  2128. "auth_enabled": "true",
  2129. }
  2130. @staticmethod
  2131. def _fake_smtp_class(captured: dict):
  2132. class FakeSMTP:
  2133. # timeout matches the real smtplib.SMTP/SMTP_SSL signature — the
  2134. # service passes an explicit timeout so a wedged relay can't hang
  2135. # the send (#2572).
  2136. def __init__(self, host, port, timeout=None):
  2137. captured["host"] = host
  2138. captured["port"] = port
  2139. captured["timeout"] = timeout
  2140. def starttls(self):
  2141. captured["starttls"] = True
  2142. def login(self, u, p):
  2143. captured["login"] = (u, p)
  2144. def sendmail(self, frm, to, body):
  2145. captured["from"] = frm
  2146. captured["to"] = to
  2147. captured["raw"] = body
  2148. def quit(self):
  2149. captured["quit"] = True
  2150. return FakeSMTP
  2151. @pytest.mark.asyncio
  2152. async def test_email_without_image_or_url_stays_text_only(self, service, smtp_config):
  2153. """No image_data and no URL in body → original single-part text shape."""
  2154. captured: dict = {}
  2155. with patch("backend.app.services.notification_service.smtplib.SMTP", self._fake_smtp_class(captured)):
  2156. ok, _ = await service._send_email(smtp_config, "Print Failed", "Reason: unknown")
  2157. assert ok is True
  2158. assert "image/jpeg" not in captured["raw"]
  2159. assert "multipart/related" not in captured["raw"]
  2160. assert "cid:bambuddy-finish-photo" not in captured["raw"]
  2161. assert "Reason: unknown" in captured["raw"]
  2162. @pytest.mark.asyncio
  2163. async def test_email_image_without_template_reference_stays_text_only(self, service, smtp_config):
  2164. """image_data present but template didn't include {finish_photo_url} → no embed.
  2165. Pins the template-driven contract: a user whose body is just
  2166. "Print failed. Reason: unknown" does NOT get a surprise inline image
  2167. stapled to the bottom, even though the photo bytes are available
  2168. upstream from the archive.
  2169. """
  2170. captured: dict = {}
  2171. with patch("backend.app.services.notification_service.smtplib.SMTP", self._fake_smtp_class(captured)):
  2172. ok, _ = await service._send_email(
  2173. smtp_config,
  2174. "Print Failed",
  2175. "Reason: unknown",
  2176. image_data=b"\xff\xd8\xff\xe0jpeg",
  2177. finish_photo_url=self.PHOTO_URL,
  2178. )
  2179. assert ok is True
  2180. raw = captured["raw"]
  2181. assert "image/jpeg" not in raw
  2182. assert "multipart/related" not in raw
  2183. assert "cid:bambuddy-finish-photo" not in raw
  2184. @pytest.mark.asyncio
  2185. async def test_email_inlines_when_template_uses_finish_photo_url(self, service, smtp_config):
  2186. """URL in body + image_data present → multipart/related + cid embed; HTML swaps URL for <img>."""
  2187. captured: dict = {}
  2188. body = f"Print failed. Reason: unknown\n\nSnapshot: {self.PHOTO_URL}"
  2189. with patch("backend.app.services.notification_service.smtplib.SMTP", self._fake_smtp_class(captured)):
  2190. ok, _ = await service._send_email(
  2191. smtp_config,
  2192. "Print Failed",
  2193. body,
  2194. image_data=b"\xff\xd8\xff\xe0fake-jpeg-bytes",
  2195. finish_photo_url=self.PHOTO_URL,
  2196. )
  2197. assert ok is True
  2198. raw = captured["raw"]
  2199. # multipart/related shape with both alt parts and an image part
  2200. assert "multipart/related" in raw
  2201. assert "multipart/alternative" in raw
  2202. assert "text/plain" in raw
  2203. assert "text/html" in raw
  2204. assert "image/jpeg" in raw
  2205. # HTML references the exact cid the Content-ID header registers
  2206. assert "Content-ID: <bambuddy-finish-photo>" in raw
  2207. assert 'src="cid:bambuddy-finish-photo"' in raw
  2208. # Inline disposition so renders embedded, not as download attachment
  2209. assert 'Content-Disposition: inline; filename="finish-photo.jpg"' in raw
  2210. # Plain-text body keeps the URL so non-HTML clients still get a clickable link
  2211. assert self.PHOTO_URL in raw
  2212. @pytest.mark.asyncio
  2213. async def test_email_image_data_without_url_arg_stays_text_only(self, service, smtp_config):
  2214. """image_data passed but finish_photo_url=None → defence-in-depth, no embed.
  2215. Even if a future caller forgets to thread the URL through but does pass
  2216. the bytes, the conservative default is no embed (avoids attaching an
  2217. unreferenced image to an unrelated event type).
  2218. """
  2219. captured: dict = {}
  2220. with patch("backend.app.services.notification_service.smtplib.SMTP", self._fake_smtp_class(captured)):
  2221. ok, _ = await service._send_email(
  2222. smtp_config,
  2223. "Print Failed",
  2224. f"Snapshot: {self.PHOTO_URL}",
  2225. image_data=b"\xff\xd8\xff\xe0jpeg",
  2226. finish_photo_url=None,
  2227. )
  2228. assert ok is True
  2229. assert "image/jpeg" not in captured["raw"]
  2230. assert "multipart/related" not in captured["raw"]
  2231. @pytest.mark.asyncio
  2232. async def test_email_html_body_escapes_user_content(self, service, smtp_config):
  2233. """Template-rendered body must not be injected raw into the HTML part."""
  2234. captured: dict = {}
  2235. body = f"Filename: <script>alert(1)</script>\nLine 2\nSnapshot: {self.PHOTO_URL}"
  2236. with patch("backend.app.services.notification_service.smtplib.SMTP", self._fake_smtp_class(captured)):
  2237. ok, _ = await service._send_email(
  2238. smtp_config,
  2239. "Print Failed",
  2240. body,
  2241. image_data=b"\xff\xd8\xff\xe0jpeg",
  2242. finish_photo_url=self.PHOTO_URL,
  2243. )
  2244. assert ok is True
  2245. raw = captured["raw"]
  2246. # Raw HTML must NOT round-trip into the HTML part — verify escaped form is present.
  2247. assert "&lt;script&gt;alert(1)&lt;/script&gt;" in raw
  2248. # Newlines in the body become <br> in HTML
  2249. assert "Line 2" in raw
  2250. assert "<br>" in raw
  2251. @pytest.mark.asyncio
  2252. async def test_email_html_swaps_url_for_img_tag(self, service, smtp_config):
  2253. """In the HTML part, the URL substring is replaced with the <img cid:...> tag.
  2254. Plain text keeps the URL; HTML clients see the inline image where the
  2255. URL was. The URL must NOT appear inside an <a href> wrapping the image
  2256. — we replace the URL outright with the img tag (renderers don't need
  2257. the URL twice in the HTML part when the image is already inline).
  2258. """
  2259. captured: dict = {}
  2260. body = f"See: {self.PHOTO_URL} for the snapshot."
  2261. with patch("backend.app.services.notification_service.smtplib.SMTP", self._fake_smtp_class(captured)):
  2262. ok, _ = await service._send_email(
  2263. smtp_config,
  2264. "Print Failed",
  2265. body,
  2266. image_data=b"\xff\xd8\xff\xe0jpeg",
  2267. finish_photo_url=self.PHOTO_URL,
  2268. )
  2269. assert ok is True
  2270. raw = captured["raw"]
  2271. # The <img> tag appears in the HTML part
  2272. assert 'src="cid:bambuddy-finish-photo"' in raw
  2273. # The escaped URL is the marker we replaced — the HTML part should not
  2274. # contain BOTH the escaped URL AND the cid img (we swapped, not duplicated).
  2275. # The plain-text part still has the URL; check it's there at least once.
  2276. assert self.PHOTO_URL in raw