test_notification_service.py 113 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851
  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_custom_data_keeps_nested_structures(self, service):
  750. """Nested objects and lists reach the notify service unaltered (#1441).
  751. The three tests around this one all use flat scalars, which is also all
  752. the placeholder and the wiki showed — so a user asking whether action
  753. buttons work had nothing telling them the field is a verbatim
  754. pass-through rather than a key/value list. ``actions`` is the case they
  755. asked about: a list of objects, the shape an HA automation writes under
  756. ``data.actions``. Nothing between the textarea and the POST inspects the
  757. parsed value beyond "is it an object", so this asserts the whole
  758. structure rather than a key at a time.
  759. """
  760. mock_response = MagicMock()
  761. mock_response.status_code = 200
  762. mock_client = AsyncMock()
  763. mock_client.post = AsyncMock(return_value=mock_response)
  764. mock_db = AsyncMock()
  765. with (
  766. patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client,
  767. patch(
  768. "backend.app.api.routes.settings.get_homeassistant_settings",
  769. new_callable=AsyncMock,
  770. ) as mock_ha_settings,
  771. ):
  772. mock_get_client.return_value = mock_client
  773. mock_ha_settings.return_value = {
  774. "ha_url": "http://ha.local:8123",
  775. "ha_token": "test-token-123",
  776. "ha_enabled": True,
  777. }
  778. actions = [
  779. {"action": "SNOOZE_PRINT_FINISHED", "title": "Snooze 20 min"},
  780. {"action": "BED_COOL_NOTIFY_ON", "title": "Notify on Bed Cool"},
  781. ]
  782. config = {
  783. "service": "notify.mobile_app_myphone",
  784. "data": json.dumps({"ttl": 0, "priority": "high", "group": "3D Printer", "actions": actions}),
  785. }
  786. success, _ = await service._send_homeassistant(config, "Print Finished", "Print is finished", db=mock_db)
  787. assert success is True
  788. payload = mock_client.post.call_args.kwargs.get("json") or mock_client.post.call_args[1].get("json")
  789. assert payload["data"] == {
  790. "ttl": 0,
  791. "priority": "high",
  792. "group": "3D Printer",
  793. "actions": actions,
  794. }
  795. # Spelled out separately: a flattening or scalar-only filter would
  796. # still leave the three sibling keys correct, so the equality above
  797. # is not on its own evidence that the list survived.
  798. assert payload["data"]["actions"] == actions
  799. @pytest.mark.asyncio
  800. async def test_send_homeassistant_without_data_omits_key(self, service):
  801. """Without configured data the payload carries no "data" key — the
  802. default persistent_notification.create schema rejects unknown keys."""
  803. mock_response = MagicMock()
  804. mock_response.status_code = 200
  805. mock_client = AsyncMock()
  806. mock_client.post = AsyncMock(return_value=mock_response)
  807. mock_db = AsyncMock()
  808. with (
  809. patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client,
  810. patch(
  811. "backend.app.api.routes.settings.get_homeassistant_settings",
  812. new_callable=AsyncMock,
  813. ) as mock_ha_settings,
  814. ):
  815. mock_get_client.return_value = mock_client
  816. mock_ha_settings.return_value = {
  817. "ha_url": "http://ha.local:8123",
  818. "ha_token": "test-token-123",
  819. "ha_enabled": True,
  820. }
  821. success, _ = await service._send_homeassistant({}, "Title", "Body", db=mock_db)
  822. assert success is True
  823. payload = mock_client.post.call_args.kwargs.get("json") or mock_client.post.call_args[1].get("json")
  824. assert "data" not in payload
  825. @pytest.mark.asyncio
  826. async def test_send_homeassistant_invalid_data_rejected(self, service):
  827. """Malformed JSON and non-object JSON in the data field fail loudly
  828. instead of sending a half-built payload."""
  829. mock_db = AsyncMock()
  830. with (
  831. patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client,
  832. patch(
  833. "backend.app.api.routes.settings.get_homeassistant_settings",
  834. new_callable=AsyncMock,
  835. ) as mock_ha_settings,
  836. ):
  837. mock_client = AsyncMock()
  838. mock_get_client.return_value = mock_client
  839. mock_ha_settings.return_value = {
  840. "ha_url": "http://ha.local:8123",
  841. "ha_token": "test-token-123",
  842. "ha_enabled": True,
  843. }
  844. success, message = await service._send_homeassistant(
  845. {"data": "{priority: high}"}, "Title", "Body", db=mock_db
  846. )
  847. assert success is False
  848. assert "Invalid JSON" in message
  849. success, message = await service._send_homeassistant({"data": '["a", "b"]'}, "Title", "Body", db=mock_db)
  850. assert success is False
  851. assert "JSON object" in message
  852. mock_client.post.assert_not_called()
  853. @pytest.mark.asyncio
  854. async def test_send_homeassistant_no_db_no_env(self, service):
  855. """Verify HA provider fails gracefully without DB or env vars."""
  856. with patch.dict("os.environ", {}, clear=True):
  857. success, message = await service._send_homeassistant({}, "Test", "Test", db=None)
  858. assert success is False
  859. assert "not configured" in message.lower()
  860. @pytest.mark.asyncio
  861. async def test_send_homeassistant_auth_failure(self, service):
  862. """Verify HA provider reports auth failure."""
  863. mock_response = MagicMock()
  864. mock_response.status_code = 401
  865. mock_client = AsyncMock()
  866. mock_client.post = AsyncMock(return_value=mock_response)
  867. mock_db = AsyncMock()
  868. with (
  869. patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client,
  870. patch(
  871. "backend.app.api.routes.settings.get_homeassistant_settings",
  872. new_callable=AsyncMock,
  873. ) as mock_ha_settings,
  874. ):
  875. mock_get_client.return_value = mock_client
  876. mock_ha_settings.return_value = {
  877. "ha_url": "http://ha.local:8123",
  878. "ha_token": "bad-token",
  879. "ha_enabled": True,
  880. }
  881. success, message = await service._send_homeassistant({}, "Test", "Test", db=mock_db)
  882. assert success is False
  883. assert "authentication" in message.lower()
  884. @pytest.mark.asyncio
  885. async def test_send_homeassistant_env_fallback(self, service):
  886. """Verify HA provider falls back to env vars when no DB session."""
  887. mock_response = MagicMock()
  888. mock_response.status_code = 200
  889. mock_client = AsyncMock()
  890. mock_client.post = AsyncMock(return_value=mock_response)
  891. with (
  892. patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client,
  893. patch.dict("os.environ", {"HA_URL": "http://env-ha:8123", "HA_TOKEN": "env-token"}),
  894. ):
  895. mock_get_client.return_value = mock_client
  896. success, message = await service._send_homeassistant({}, "Test", "Test", db=None)
  897. assert success is True
  898. call_args = mock_client.post.call_args
  899. assert "env-ha:8123" in call_args[0][0]
  900. @pytest.mark.asyncio
  901. async def test_send_homeassistant_empty_config_accepted(self, service):
  902. """Verify HA provider works with empty config dict (no fields needed)."""
  903. mock_response = MagicMock()
  904. mock_response.status_code = 200
  905. mock_client = AsyncMock()
  906. mock_client.post = AsyncMock(return_value=mock_response)
  907. mock_db = AsyncMock()
  908. with (
  909. patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client,
  910. patch(
  911. "backend.app.api.routes.settings.get_homeassistant_settings",
  912. new_callable=AsyncMock,
  913. ) as mock_ha_settings,
  914. ):
  915. mock_get_client.return_value = mock_client
  916. mock_ha_settings.return_value = {
  917. "ha_url": "http://ha.local:8123",
  918. "ha_token": "token",
  919. "ha_enabled": True,
  920. }
  921. success, _ = await service._send_homeassistant({}, "Title", "Body", db=mock_db)
  922. assert success is True
  923. @pytest.mark.asyncio
  924. async def test_send_to_provider_dispatches_homeassistant(self, service):
  925. """Verify _send_to_provider dispatches to _send_homeassistant."""
  926. provider = MagicMock()
  927. provider.provider_type = "homeassistant"
  928. provider.config = "{}"
  929. provider.quiet_hours_enabled = False
  930. with patch.object(service, "_send_homeassistant", new_callable=AsyncMock) as mock_send:
  931. mock_send.return_value = (True, "OK")
  932. success, _ = await service._send_to_provider(provider, "Title", "Message", db=AsyncMock())
  933. assert success is True
  934. mock_send.assert_called_once()
  935. class TestBarkProvider:
  936. """Bark (iOS push) provider (#1495)."""
  937. @pytest.fixture
  938. def service(self):
  939. return NotificationService()
  940. def _client_returning(self, status_code: int, json_body=None, text: str = ""):
  941. mock_response = MagicMock()
  942. mock_response.status_code = status_code
  943. mock_response.text = text
  944. if json_body is not None:
  945. mock_response.json = MagicMock(return_value=json_body)
  946. else:
  947. mock_response.json = MagicMock(side_effect=ValueError("not json"))
  948. mock_client = AsyncMock()
  949. mock_client.post = AsyncMock(return_value=mock_response)
  950. return mock_client
  951. @pytest.mark.asyncio
  952. async def test_send_bark_success_default_server(self, service):
  953. """Minimal config posts to the official relay with device_key/title/body."""
  954. mock_client = self._client_returning(200, {"code": 200, "message": "success"})
  955. with patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client:
  956. mock_get_client.return_value = mock_client
  957. success, _ = await service._send_bark({"device_key": "abc123"}, "Title", "Body")
  958. assert success is True
  959. call_args = mock_client.post.call_args
  960. assert call_args[0][0] == "https://api.day.app/push"
  961. payload = call_args.kwargs.get("json")
  962. assert payload == {"device_key": "abc123", "title": "Title", "body": "Body"}
  963. @pytest.mark.asyncio
  964. async def test_send_bark_options_and_custom_server(self, service):
  965. """group/sound/level are forwarded; an unknown level is dropped rather
  966. than sent; a self-hosted server URL (with trailing slash) is used."""
  967. mock_client = self._client_returning(200, {"code": 200})
  968. with patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client:
  969. mock_get_client.return_value = mock_client
  970. config = {
  971. "device_key": "abc123",
  972. "server": "https://bark.example.com/",
  973. "group": "Bambuddy",
  974. "sound": "minuet",
  975. "level": "timeSensitive",
  976. }
  977. success, _ = await service._send_bark(config, "Title", "Body")
  978. assert success is True
  979. call_args = mock_client.post.call_args
  980. assert call_args[0][0] == "https://bark.example.com/push"
  981. payload = call_args.kwargs.get("json")
  982. assert payload["group"] == "Bambuddy"
  983. assert payload["sound"] == "minuet"
  984. assert payload["level"] == "timeSensitive"
  985. mock_client.post.reset_mock()
  986. with patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client:
  987. mock_get_client.return_value = mock_client
  988. await service._send_bark({"device_key": "abc123", "level": "shouty"}, "Title", "Body")
  989. assert "level" not in mock_client.post.call_args.kwargs.get("json")
  990. @pytest.mark.asyncio
  991. async def test_send_bark_missing_device_key(self, service):
  992. mock_client = self._client_returning(200, {"code": 200})
  993. with patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client:
  994. mock_get_client.return_value = mock_client
  995. success, message = await service._send_bark({}, "Title", "Body")
  996. assert success is False
  997. assert "Device key" in message
  998. mock_client.post.assert_not_called()
  999. @pytest.mark.asyncio
  1000. async def test_send_bark_error_in_200_body(self, service, caplog):
  1001. """bark-server can wrap a failure in HTTP 200; the body code must win.
  1002. Only the numeric code is returned — the server is caller-supplied
  1003. (bark is self-hostable), so its free-text message is the same read
  1004. channel the HTTP-failure path closes. The text goes to the debug log.
  1005. """
  1006. mock_client = self._client_returning(200, {"code": 400, "message": "device token invalid"})
  1007. with patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client:
  1008. mock_get_client.return_value = mock_client
  1009. with caplog.at_level("DEBUG", logger="backend.app.services.notification_service"):
  1010. success, message = await service._send_bark({"device_key": "bad"}, "Title", "Body")
  1011. assert success is False
  1012. assert "Bark error 400" in message
  1013. assert "device token invalid" not in message
  1014. assert "device token invalid" in caplog.text
  1015. @pytest.mark.asyncio
  1016. async def test_send_bark_http_error(self, service):
  1017. mock_client = self._client_returning(400, None, text="failed to get device token")
  1018. with patch.object(service, "_get_client", new_callable=AsyncMock) as mock_get_client:
  1019. mock_get_client.return_value = mock_client
  1020. success, message = await service._send_bark({"device_key": "bad"}, "Title", "Body")
  1021. assert success is False
  1022. assert "HTTP 400" in message
  1023. @pytest.mark.asyncio
  1024. async def test_send_to_provider_dispatches_bark(self, service):
  1025. provider = MagicMock()
  1026. provider.provider_type = "bark"
  1027. provider.config = json.dumps({"device_key": "abc123"})
  1028. provider.quiet_hours_enabled = False
  1029. with patch.object(service, "_send_bark", new_callable=AsyncMock) as mock_send:
  1030. mock_send.return_value = (True, "OK")
  1031. success, _ = await service._send_to_provider(provider, "Title", "Message", db=AsyncMock())
  1032. assert success is True
  1033. mock_send.assert_called_once()
  1034. class TestNotificationVariableFallbacks:
  1035. """Tests for notification variable fallback values."""
  1036. @pytest.fixture
  1037. def service(self):
  1038. return NotificationService()
  1039. def test_format_duration_with_valid_seconds(self, service):
  1040. """Verify duration formats correctly with valid input."""
  1041. result = service._format_duration(3661) # 1h 1m 1s
  1042. assert "1h" in result
  1043. def test_format_duration_with_none_returns_unknown(self, service):
  1044. """CRITICAL: Verify None duration returns 'Unknown' fallback."""
  1045. result = service._format_duration(None)
  1046. assert result == "Unknown"
  1047. def test_format_duration_with_zero(self, service):
  1048. """Verify zero duration formats correctly."""
  1049. result = service._format_duration(0)
  1050. # Should return some valid string, not "Unknown"
  1051. assert result is not None
  1052. assert isinstance(result, str)
  1053. def test_format_duration_hours_and_minutes(self, service):
  1054. """Verify duration formats hours and minutes."""
  1055. result = service._format_duration(5400) # 1h 30m
  1056. assert "1h" in result
  1057. assert "30m" in result
  1058. def test_format_duration_minutes_only(self, service):
  1059. """Verify duration formats minutes only when < 1 hour."""
  1060. result = service._format_duration(1800) # 30m
  1061. assert "30m" in result or "30" in result
  1062. @pytest.mark.asyncio
  1063. async def test_print_complete_fallback_values(self, service):
  1064. """CRITICAL: Verify fallback values when archive_data is missing."""
  1065. mock_db = AsyncMock()
  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", new_callable=AsyncMock) as mock_build,
  1070. ):
  1071. mock_get.return_value = [] # No providers, just testing variable setup
  1072. mock_build.return_value = ("Test", "Test")
  1073. await service.on_print_complete(
  1074. printer_id=1,
  1075. printer_name="Test",
  1076. status="completed",
  1077. data={"subtask_name": "test_print"},
  1078. db=mock_db,
  1079. archive_data=None, # No archive data - should use fallbacks
  1080. )
  1081. # Test passes if no exception is raised with missing archive_data
  1082. @pytest.mark.asyncio
  1083. async def test_print_complete_with_archive_data(self, service):
  1084. """Verify archive data values are used when provided."""
  1085. mock_db = AsyncMock()
  1086. captured_variables = {}
  1087. async def capture_build(db, event_type, variables):
  1088. captured_variables.update(variables)
  1089. return ("Test", "Test")
  1090. with (
  1091. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1092. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1093. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1094. ):
  1095. mock_get.return_value = []
  1096. await service.on_print_complete(
  1097. printer_id=1,
  1098. printer_name="Test",
  1099. status="completed",
  1100. data={"subtask_name": "test_print"},
  1101. db=mock_db,
  1102. archive_data={
  1103. "print_time_seconds": 3600,
  1104. "actual_filament_grams": 50.5,
  1105. },
  1106. )
  1107. # When archive data is provided, duration should not be "Unknown"
  1108. if captured_variables.get("duration"):
  1109. assert captured_variables["duration"] != "Unknown"
  1110. @pytest.mark.asyncio
  1111. async def test_duration_prefers_actual_time_seconds_over_slicer_estimate(self, service):
  1112. """#1198: completion notification duration must reflect *actual* elapsed
  1113. time from started_at/completed_at, not the slicer's pre-print estimate.
  1114. Pre-fix the duration variable read from `print_time_seconds` (slicer
  1115. estimate parsed from the 3MF at archive creation), so a print cancelled
  1116. 2 minutes into a 3-hour estimate would notify "duration: 3h"."""
  1117. mock_db = AsyncMock()
  1118. mock_provider = MagicMock()
  1119. mock_provider.id = 1
  1120. captured_variables: dict = {}
  1121. async def capture_build(db, event_type, variables):
  1122. captured_variables.update(variables)
  1123. return ("Test", "Test")
  1124. with (
  1125. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1126. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1127. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1128. ):
  1129. mock_get.return_value = [mock_provider]
  1130. await service.on_print_complete(
  1131. printer_id=1,
  1132. printer_name="Test",
  1133. status="cancelled",
  1134. data={"subtask_name": "test_print"},
  1135. db=mock_db,
  1136. archive_data={
  1137. "print_time_seconds": 10800, # 3h slicer estimate
  1138. "actual_time_seconds": 120, # 2m actual elapsed
  1139. },
  1140. )
  1141. # 2 minutes — not 3 hours — even though the slicer estimate is in the dict.
  1142. assert "2m" in captured_variables["duration"]
  1143. assert "3h" not in captured_variables["duration"]
  1144. @pytest.mark.asyncio
  1145. async def test_duration_falls_back_to_slicer_estimate_when_actual_time_missing(self, service):
  1146. """#1198: when actual_time_seconds is absent (e.g. timestamps weren't
  1147. recorded for some reason), the duration variable falls back to
  1148. print_time_seconds rather than rendering 'Unknown'. Preserves
  1149. backwards-compat for any code path that didn't compute actual elapsed."""
  1150. mock_db = AsyncMock()
  1151. mock_provider = MagicMock()
  1152. mock_provider.id = 1
  1153. captured_variables: dict = {}
  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, # 1h slicer estimate, no actual
  1171. "actual_time_seconds": None,
  1172. },
  1173. )
  1174. assert captured_variables["duration"] != "Unknown"
  1175. assert "1h" in captured_variables["duration"]
  1176. @pytest.mark.asyncio
  1177. async def test_duration_unknown_when_both_time_fields_missing(self, service):
  1178. """#1198: with neither actual nor estimated time available the duration
  1179. variable surfaces the existing 'Unknown' fallback."""
  1180. mock_db = AsyncMock()
  1181. mock_provider = MagicMock()
  1182. mock_provider.id = 1
  1183. captured_variables: dict = {}
  1184. async def capture_build(db, event_type, variables):
  1185. captured_variables.update(variables)
  1186. return ("Test", "Test")
  1187. with (
  1188. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1189. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1190. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1191. ):
  1192. mock_get.return_value = [mock_provider]
  1193. await service.on_print_complete(
  1194. printer_id=1,
  1195. printer_name="Test",
  1196. status="completed",
  1197. data={"subtask_name": "test_print"},
  1198. db=mock_db,
  1199. archive_data={
  1200. "print_time_seconds": None,
  1201. "actual_time_seconds": None,
  1202. },
  1203. )
  1204. assert captured_variables["duration"] == "Unknown"
  1205. @pytest.mark.asyncio
  1206. async def test_print_complete_with_finish_photo_url(self, service):
  1207. """Verify finish_photo_url is passed through from archive_data."""
  1208. mock_db = AsyncMock()
  1209. mock_provider = MagicMock()
  1210. mock_provider.id = 1
  1211. captured_variables = {}
  1212. async def capture_build(db, event_type, variables):
  1213. captured_variables.update(variables)
  1214. return ("Test", "Test")
  1215. with (
  1216. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1217. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1218. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1219. ):
  1220. mock_get.return_value = [mock_provider]
  1221. await service.on_print_complete(
  1222. printer_id=1,
  1223. printer_name="Test",
  1224. status="completed",
  1225. data={"subtask_name": "test_print"},
  1226. db=mock_db,
  1227. archive_data={
  1228. "print_time_seconds": 3600,
  1229. "actual_filament_grams": 50.5,
  1230. "finish_photo_url": "http://localhost:8000/api/v1/archives/1/photos/finish_test.jpg",
  1231. },
  1232. )
  1233. # finish_photo_url should be passed through to template variables
  1234. assert (
  1235. captured_variables.get("finish_photo_url")
  1236. == "http://localhost:8000/api/v1/archives/1/photos/finish_test.jpg"
  1237. )
  1238. @pytest.mark.asyncio
  1239. async def test_print_start_estimated_time_fallback(self, service):
  1240. """Verify estimated time shows 'Unknown' when not available."""
  1241. mock_db = AsyncMock()
  1242. mock_provider = MagicMock()
  1243. mock_provider.id = 1
  1244. captured_variables = {}
  1245. async def capture_build(db, event_type, variables):
  1246. captured_variables.update(variables)
  1247. return ("Test", "Test")
  1248. with (
  1249. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1250. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1251. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1252. patch("backend.app.api.routes.settings.get_setting", new_callable=AsyncMock, return_value=None),
  1253. ):
  1254. # Need at least one provider to trigger message building
  1255. mock_get.return_value = [mock_provider]
  1256. await service.on_print_start(
  1257. printer_id=1,
  1258. printer_name="Test",
  1259. data={
  1260. "subtask_name": "test",
  1261. # No estimated_time or mc_remaining_time
  1262. },
  1263. db=mock_db,
  1264. )
  1265. # When no time data, should show "Unknown"
  1266. assert captured_variables.get("estimated_time") == "Unknown"
  1267. @pytest.mark.asyncio
  1268. async def test_print_progress_remaining_time_fallback(self, service):
  1269. """Verify remaining time shows 'Unknown' when not available."""
  1270. mock_db = AsyncMock()
  1271. mock_provider = MagicMock()
  1272. mock_provider.id = 1
  1273. captured_variables = {}
  1274. async def capture_build(db, event_type, variables):
  1275. captured_variables.update(variables)
  1276. return ("Test", "Test")
  1277. with (
  1278. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1279. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1280. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1281. patch("backend.app.api.routes.settings.get_setting", new_callable=AsyncMock, return_value=None),
  1282. ):
  1283. # Need at least one provider to trigger message building
  1284. mock_get.return_value = [mock_provider]
  1285. await service.on_print_progress(
  1286. printer_id=1,
  1287. printer_name="Test",
  1288. progress=50,
  1289. remaining_time=None, # No remaining time
  1290. filename="test.3mf",
  1291. db=mock_db,
  1292. )
  1293. # When no remaining time, should show "Unknown"
  1294. assert captured_variables.get("remaining_time") == "Unknown"
  1295. @pytest.mark.asyncio
  1296. async def test_filename_fallback_to_unknown(self, service):
  1297. """Verify filename defaults to 'Unknown' when not provided."""
  1298. mock_db = AsyncMock()
  1299. mock_provider = MagicMock()
  1300. mock_provider.id = 1
  1301. captured_variables = {}
  1302. async def capture_build(db, event_type, variables):
  1303. captured_variables.update(variables)
  1304. return ("Test", "Test")
  1305. with (
  1306. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1307. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1308. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1309. ):
  1310. # Need at least one provider to trigger message building
  1311. mock_get.return_value = [mock_provider]
  1312. await service.on_print_complete(
  1313. printer_id=1,
  1314. printer_name="Test",
  1315. status="completed",
  1316. data={}, # No subtask_name or filename
  1317. db=mock_db,
  1318. )
  1319. # Filename should default to something (either "Unknown" or cleaned empty)
  1320. assert "filename" in captured_variables
  1321. @pytest.mark.asyncio
  1322. async def test_print_start_uses_archive_print_time_seconds(self, service):
  1323. """Verify print_time_seconds from archive_data is used for estimated_time."""
  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. # Pass archive_data with print_time_seconds (7200 seconds = 2 hours)
  1339. await service.on_print_start(
  1340. printer_id=1,
  1341. printer_name="Test",
  1342. data={"subtask_name": "test"},
  1343. db=mock_db,
  1344. archive_data={"print_time_seconds": 7200},
  1345. )
  1346. # Should use archive's print_time_seconds: 7200 seconds = 2h 0m
  1347. assert captured_variables.get("estimated_time") == "2h 0m"
  1348. @pytest.mark.asyncio
  1349. async def test_print_start_archive_data_overrides_mqtt(self, service):
  1350. """Verify archive_data takes priority over MQTT remaining_time."""
  1351. mock_db = AsyncMock()
  1352. mock_provider = MagicMock()
  1353. mock_provider.id = 1
  1354. captured_variables = {}
  1355. async def capture_build(db, event_type, variables):
  1356. captured_variables.update(variables)
  1357. return ("Test", "Test")
  1358. with (
  1359. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1360. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1361. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1362. patch("backend.app.api.routes.settings.get_setting", new_callable=AsyncMock, return_value=None),
  1363. ):
  1364. mock_get.return_value = [mock_provider]
  1365. # Both archive_data and MQTT remaining_time provided
  1366. # Archive says 2 hours, MQTT says 30 minutes (wrong at start)
  1367. await service.on_print_start(
  1368. printer_id=1,
  1369. printer_name="Test",
  1370. data={
  1371. "subtask_name": "test",
  1372. "remaining_time": 1800, # 30 minutes from MQTT
  1373. },
  1374. db=mock_db,
  1375. archive_data={"print_time_seconds": 7200}, # 2 hours from 3MF
  1376. )
  1377. # Should use archive's print_time_seconds (more reliable)
  1378. assert captured_variables.get("estimated_time") == "2h 0m"
  1379. @pytest.mark.asyncio
  1380. async def test_print_start_falls_back_to_mqtt_when_no_archive(self, service):
  1381. """Verify MQTT remaining_time is used when archive_data not provided."""
  1382. mock_db = AsyncMock()
  1383. mock_provider = MagicMock()
  1384. mock_provider.id = 1
  1385. captured_variables = {}
  1386. async def capture_build(db, event_type, variables):
  1387. captured_variables.update(variables)
  1388. return ("Test", "Test")
  1389. with (
  1390. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1391. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1392. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1393. patch("backend.app.api.routes.settings.get_setting", new_callable=AsyncMock, return_value=None),
  1394. ):
  1395. mock_get.return_value = [mock_provider]
  1396. # Only MQTT remaining_time provided (1800 seconds = 30 minutes)
  1397. await service.on_print_start(
  1398. printer_id=1,
  1399. printer_name="Test",
  1400. data={
  1401. "subtask_name": "test",
  1402. "remaining_time": 1800,
  1403. },
  1404. db=mock_db,
  1405. # No archive_data
  1406. )
  1407. # Should use MQTT remaining_time
  1408. assert captured_variables.get("estimated_time") == "30m"
  1409. @pytest.mark.asyncio
  1410. async def test_print_start_eta_calculated_from_estimated_time(self, service):
  1411. """Verify ETA is calculated as wall-clock time from estimated_time."""
  1412. mock_db = AsyncMock()
  1413. mock_provider = MagicMock()
  1414. mock_provider.id = 1
  1415. captured_variables = {}
  1416. async def capture_build(db, event_type, variables):
  1417. captured_variables.update(variables)
  1418. return ("Test", "Test")
  1419. with (
  1420. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1421. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1422. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1423. patch("backend.app.api.routes.settings.get_setting", new_callable=AsyncMock, return_value=None),
  1424. ):
  1425. mock_get.return_value = [mock_provider]
  1426. await service.on_print_start(
  1427. printer_id=1,
  1428. printer_name="Test",
  1429. data={"subtask_name": "test"},
  1430. db=mock_db,
  1431. archive_data={"print_time_seconds": 3600}, # 1 hour
  1432. )
  1433. # ETA should be a time string in HH:MM format
  1434. eta = captured_variables.get("eta")
  1435. assert eta is not None
  1436. assert eta != "Unknown"
  1437. assert ":" in eta # HH:MM format
  1438. @pytest.mark.asyncio
  1439. async def test_print_start_eta_unknown_when_no_time(self, service):
  1440. """Verify ETA shows 'Unknown' when no time data available."""
  1441. mock_db = AsyncMock()
  1442. mock_provider = MagicMock()
  1443. mock_provider.id = 1
  1444. captured_variables = {}
  1445. async def capture_build(db, event_type, variables):
  1446. captured_variables.update(variables)
  1447. return ("Test", "Test")
  1448. with (
  1449. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1450. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1451. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1452. patch("backend.app.api.routes.settings.get_setting", new_callable=AsyncMock, return_value=None),
  1453. ):
  1454. mock_get.return_value = [mock_provider]
  1455. await service.on_print_start(
  1456. printer_id=1,
  1457. printer_name="Test",
  1458. data={"subtask_name": "test"},
  1459. db=mock_db,
  1460. )
  1461. assert captured_variables.get("eta") == "Unknown"
  1462. @pytest.mark.asyncio
  1463. async def test_print_start_eta_respects_12h_format(self, service):
  1464. """Verify ETA uses 12-hour format when time_format is '12h'."""
  1465. mock_db = AsyncMock()
  1466. mock_provider = MagicMock()
  1467. mock_provider.id = 1
  1468. captured_variables = {}
  1469. async def capture_build(db, event_type, variables):
  1470. captured_variables.update(variables)
  1471. return ("Test", "Test")
  1472. with (
  1473. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1474. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1475. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1476. patch("backend.app.api.routes.settings.get_setting", new_callable=AsyncMock, return_value="12h"),
  1477. ):
  1478. mock_get.return_value = [mock_provider]
  1479. await service.on_print_start(
  1480. printer_id=1,
  1481. printer_name="Test",
  1482. data={"subtask_name": "test"},
  1483. db=mock_db,
  1484. archive_data={"print_time_seconds": 3600},
  1485. )
  1486. eta = captured_variables.get("eta")
  1487. assert eta is not None
  1488. # 12h format should contain AM or PM
  1489. assert "AM" in eta or "PM" in eta
  1490. class TestNotificationTemplates:
  1491. """Tests for notification message template rendering."""
  1492. @pytest.fixture
  1493. def service(self):
  1494. return NotificationService()
  1495. @pytest.mark.asyncio
  1496. async def test_template_renders_variables(self, service):
  1497. """Verify template variables are replaced correctly."""
  1498. template_title = "Print {progress}% Complete"
  1499. template_body = "{printer}: {filename}\nRemaining: {remaining_time}"
  1500. variables = {
  1501. "printer": "Test Printer",
  1502. "filename": "test.3mf",
  1503. "progress": "50",
  1504. "remaining_time": "1h 30m",
  1505. }
  1506. title = template_title.format(**variables)
  1507. body = template_body.format(**variables)
  1508. assert title == "Print 50% Complete"
  1509. assert "Test Printer" in body
  1510. assert "test.3mf" in body
  1511. assert "1h 30m" in body
  1512. @pytest.mark.asyncio
  1513. async def test_template_handles_missing_variables(self, service):
  1514. """Verify missing template variables don't cause crashes."""
  1515. template = "{printer}: {unknown_var}"
  1516. variables = {"printer": "Test"}
  1517. # Should handle gracefully - either leave placeholder or skip
  1518. try:
  1519. result = template.format_map({**variables, "unknown_var": "{unknown_var}"})
  1520. assert "Test" in result
  1521. except KeyError:
  1522. pytest.fail("Template should handle missing variables gracefully")
  1523. class TestPrinterErrorNotifications:
  1524. """Tests for HMS error (printer error) notifications."""
  1525. @pytest.fixture
  1526. def service(self):
  1527. return NotificationService()
  1528. @pytest.fixture
  1529. def mock_provider(self):
  1530. """Create a mock notification provider with error notifications enabled."""
  1531. provider = MagicMock()
  1532. provider.id = 1
  1533. provider.name = "Test Provider"
  1534. provider.provider_type = "webhook"
  1535. provider.enabled = True
  1536. provider.config = json.dumps({"webhook_url": "http://test.local/webhook"})
  1537. provider.on_printer_error = True # Enable error notifications
  1538. provider.quiet_hours_enabled = False
  1539. provider.daily_digest_enabled = False
  1540. provider.printer_id = None
  1541. return provider
  1542. @pytest.fixture
  1543. def mock_db(self):
  1544. """Create a mock database session."""
  1545. db = AsyncMock()
  1546. db.commit = AsyncMock()
  1547. return db
  1548. @pytest.mark.asyncio
  1549. async def test_on_printer_error_sends_notification(self, service, mock_provider, mock_db):
  1550. """Verify HMS error notification is sent when triggered."""
  1551. with (
  1552. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1553. patch.object(service, "_send_to_providers", new_callable=AsyncMock) as mock_send,
  1554. patch.object(service, "_build_message_from_template", new_callable=AsyncMock) as mock_build,
  1555. ):
  1556. mock_get.return_value = [mock_provider]
  1557. mock_build.return_value = ("Printer Error", "AMS/Filament Error: 0700_8010")
  1558. await service.on_printer_error(
  1559. printer_id=1,
  1560. printer_name="Test Printer",
  1561. error_type="AMS/Filament Error",
  1562. db=mock_db,
  1563. error_detail="Error code: 0700_8010",
  1564. )
  1565. mock_get.assert_called_once()
  1566. mock_send.assert_called_once()
  1567. @pytest.mark.asyncio
  1568. async def test_on_printer_error_skipped_when_disabled(self, service, mock_provider, mock_db):
  1569. """CRITICAL: Verify error notifications respect toggle setting."""
  1570. mock_provider.on_printer_error = False
  1571. with (
  1572. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1573. patch.object(service, "_send_to_providers", new_callable=AsyncMock) as mock_send,
  1574. ):
  1575. # Provider with toggle disabled won't be returned
  1576. mock_get.return_value = []
  1577. await service.on_printer_error(
  1578. printer_id=1,
  1579. printer_name="Test",
  1580. error_type="AMS Error",
  1581. db=mock_db,
  1582. error_detail="Test error",
  1583. )
  1584. mock_send.assert_not_called()
  1585. @pytest.mark.asyncio
  1586. async def test_on_printer_error_includes_error_detail(self, service, mock_provider, mock_db):
  1587. """Verify error details are passed to template variables."""
  1588. captured_variables = {}
  1589. async def capture_build(db, event_type, variables):
  1590. captured_variables.update(variables)
  1591. return ("Test", "Test")
  1592. with (
  1593. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1594. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1595. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1596. ):
  1597. mock_get.return_value = [mock_provider]
  1598. await service.on_printer_error(
  1599. printer_id=1,
  1600. printer_name="X1 Carbon",
  1601. error_type="AMS/Filament Error",
  1602. db=mock_db,
  1603. error_detail="Error code: 0700_8010",
  1604. )
  1605. assert captured_variables["printer"] == "X1 Carbon"
  1606. assert captured_variables["error_type"] == "AMS/Filament Error"
  1607. assert captured_variables["error_detail"] == "Error code: 0700_8010"
  1608. @pytest.mark.asyncio
  1609. async def test_on_printer_error_fallback_when_no_detail(self, service, mock_provider, mock_db):
  1610. """Verify fallback message when error_detail is None."""
  1611. captured_variables = {}
  1612. async def capture_build(db, event_type, variables):
  1613. captured_variables.update(variables)
  1614. return ("Test", "Test")
  1615. with (
  1616. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1617. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1618. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1619. ):
  1620. mock_get.return_value = [mock_provider]
  1621. await service.on_printer_error(
  1622. printer_id=1,
  1623. printer_name="Test Printer",
  1624. error_type="Unknown Error",
  1625. db=mock_db,
  1626. error_detail=None, # No detail provided
  1627. )
  1628. assert captured_variables["error_detail"] == "No details available"
  1629. class TestAIFailureDetectionNotifications:
  1630. """Tests for the AI failure-detection event (#1794 — split out of on_printer_error).
  1631. Pins that Obico failure-detection dispatches go through the dedicated
  1632. on_ai_failure_detection event field, not the multiplexed printer-error
  1633. field. Mirrors the printer-error coverage above so a regression on either
  1634. surface fails its own case.
  1635. """
  1636. @pytest.fixture
  1637. def service(self):
  1638. return NotificationService()
  1639. @pytest.fixture
  1640. def mock_provider(self):
  1641. provider = MagicMock()
  1642. provider.id = 1
  1643. provider.name = "Test Provider"
  1644. provider.provider_type = "webhook"
  1645. provider.enabled = True
  1646. provider.config = json.dumps({"webhook_url": "http://test.local/webhook"})
  1647. provider.on_ai_failure_detection = True
  1648. provider.on_printer_error = False # disabled — the regression guard
  1649. provider.quiet_hours_enabled = False
  1650. provider.daily_digest_enabled = False
  1651. provider.printer_id = None
  1652. return provider
  1653. @pytest.fixture
  1654. def mock_db(self):
  1655. db = AsyncMock()
  1656. db.commit = AsyncMock()
  1657. return db
  1658. @pytest.mark.asyncio
  1659. async def test_dispatch_uses_ai_failure_detection_event_not_printer_error(self, service, mock_provider, mock_db):
  1660. """Regression guard: provider subscribed only to AI alerts must receive
  1661. the Obico notification."""
  1662. captured_event = []
  1663. async def capture(db, event_field, printer_id):
  1664. captured_event.append(event_field)
  1665. return [mock_provider]
  1666. with (
  1667. patch.object(service, "_get_providers_for_event", side_effect=capture),
  1668. patch.object(service, "_send_to_providers", new_callable=AsyncMock) as mock_send,
  1669. patch.object(service, "_build_message_from_template", new_callable=AsyncMock) as mock_build,
  1670. ):
  1671. mock_build.return_value = ("Possible Print Failure Detected", "details")
  1672. await service.on_ai_failure_detection(
  1673. printer_id=1,
  1674. printer_name="X1 Carbon",
  1675. task_name="benchy.3mf",
  1676. confidence=0.87,
  1677. action="notify",
  1678. db=mock_db,
  1679. )
  1680. assert captured_event == ["on_ai_failure_detection"]
  1681. mock_send.assert_called_once()
  1682. @pytest.mark.asyncio
  1683. async def test_skipped_when_only_printer_error_is_enabled(self, service, mock_provider, mock_db):
  1684. """Pre-#1794 behaviour MUST NOT survive: a provider with only the
  1685. legacy on_printer_error toggle should NOT receive AI notifications now."""
  1686. mock_provider.on_ai_failure_detection = False
  1687. mock_provider.on_printer_error = True
  1688. with (
  1689. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1690. patch.object(service, "_send_to_providers", new_callable=AsyncMock) as mock_send,
  1691. ):
  1692. mock_get.return_value = [] # the event-field filter excludes the provider
  1693. await service.on_ai_failure_detection(
  1694. printer_id=1,
  1695. printer_name="X1 Carbon",
  1696. task_name="benchy.3mf",
  1697. confidence=0.87,
  1698. action="notify",
  1699. db=mock_db,
  1700. )
  1701. mock_send.assert_not_called()
  1702. @pytest.mark.asyncio
  1703. async def test_variables_include_task_name_confidence_action(self, service, mock_provider, mock_db):
  1704. captured_variables = {}
  1705. async def capture_build(db, event_type, variables):
  1706. captured_variables.update(variables)
  1707. return ("Test", "Test")
  1708. with (
  1709. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1710. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1711. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1712. ):
  1713. mock_get.return_value = [mock_provider]
  1714. await service.on_ai_failure_detection(
  1715. printer_id=1,
  1716. printer_name="X1 Carbon",
  1717. task_name="benchy.3mf",
  1718. confidence=0.873,
  1719. action="pause_and_off",
  1720. db=mock_db,
  1721. )
  1722. assert captured_variables["printer"] == "X1 Carbon"
  1723. assert captured_variables["task_name"] == "benchy.3mf"
  1724. assert captured_variables["confidence"] == "0.87" # 2-decimal format
  1725. assert captured_variables["action"] == "pause_and_off"
  1726. @pytest.mark.asyncio
  1727. async def test_task_name_fallback_when_unknown(self, service, mock_provider, mock_db):
  1728. captured_variables = {}
  1729. async def capture_build(db, event_type, variables):
  1730. captured_variables.update(variables)
  1731. return ("Test", "Test")
  1732. with (
  1733. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1734. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1735. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1736. ):
  1737. mock_get.return_value = [mock_provider]
  1738. await service.on_ai_failure_detection(
  1739. printer_id=1,
  1740. printer_name="Test",
  1741. task_name="", # empty
  1742. confidence=0.5,
  1743. action="notify",
  1744. db=mock_db,
  1745. )
  1746. assert captured_variables["task_name"] == "current job"
  1747. class TestPlateNotEmptyNotifications:
  1748. """Tests for plate not empty (build plate detection) notifications."""
  1749. @pytest.fixture
  1750. def service(self):
  1751. return NotificationService()
  1752. @pytest.fixture
  1753. def mock_provider(self):
  1754. """Create a mock notification provider with plate detection enabled."""
  1755. provider = MagicMock()
  1756. provider.id = 1
  1757. provider.name = "Test Provider"
  1758. provider.provider_type = "webhook"
  1759. provider.enabled = True
  1760. provider.config = json.dumps({"webhook_url": "http://test.local/webhook"})
  1761. provider.on_plate_not_empty = True
  1762. provider.quiet_hours_enabled = False
  1763. provider.daily_digest_enabled = False
  1764. provider.printer_id = None
  1765. return provider
  1766. @pytest.fixture
  1767. def mock_db(self):
  1768. """Create a mock database session."""
  1769. db = AsyncMock()
  1770. db.commit = AsyncMock()
  1771. return db
  1772. @pytest.mark.asyncio
  1773. async def test_on_plate_not_empty_sends_notification(self, service, mock_provider, mock_db):
  1774. """Verify plate not empty notification is sent when triggered."""
  1775. with (
  1776. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1777. patch.object(service, "_send_to_providers", new_callable=AsyncMock) as mock_send,
  1778. patch.object(service, "_build_message_from_template", new_callable=AsyncMock) as mock_build,
  1779. ):
  1780. mock_get.return_value = [mock_provider]
  1781. mock_build.return_value = ("Plate Not Empty", "Objects detected on build plate")
  1782. await service.on_plate_not_empty(
  1783. printer_id=1,
  1784. printer_name="Test Printer",
  1785. db=mock_db,
  1786. difference_percent=5.2,
  1787. )
  1788. mock_get.assert_called_once()
  1789. mock_send.assert_called_once()
  1790. # Verify force_immediate is True (critical alert)
  1791. call_kwargs = mock_send.call_args[1]
  1792. assert call_kwargs.get("force_immediate") is True
  1793. @pytest.mark.asyncio
  1794. async def test_on_plate_not_empty_skipped_when_disabled(self, service, mock_provider, mock_db):
  1795. """Verify notification is skipped when toggle is disabled."""
  1796. mock_provider.on_plate_not_empty = False
  1797. with (
  1798. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1799. patch.object(service, "_send_to_providers", new_callable=AsyncMock) as mock_send,
  1800. ):
  1801. mock_get.return_value = []
  1802. await service.on_plate_not_empty(
  1803. printer_id=1,
  1804. printer_name="Test",
  1805. db=mock_db,
  1806. )
  1807. mock_send.assert_not_called()
  1808. @pytest.mark.asyncio
  1809. async def test_on_plate_not_empty_includes_difference_percent(self, service, mock_provider, mock_db):
  1810. """Verify difference percentage is passed to template variables."""
  1811. captured_variables = {}
  1812. async def capture_build(db, event_type, variables):
  1813. captured_variables.update(variables)
  1814. return ("Test", "Test")
  1815. with (
  1816. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1817. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1818. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1819. ):
  1820. mock_get.return_value = [mock_provider]
  1821. await service.on_plate_not_empty(
  1822. printer_id=1,
  1823. printer_name="X1 Carbon",
  1824. db=mock_db,
  1825. difference_percent=3.5,
  1826. )
  1827. assert captured_variables["printer"] == "X1 Carbon"
  1828. assert captured_variables["difference_percent"] == "3.5"
  1829. class TestBedCooledNotifications:
  1830. """Tests for bed cooled (after print) notifications."""
  1831. @pytest.fixture
  1832. def service(self):
  1833. return NotificationService()
  1834. @pytest.fixture
  1835. def mock_provider(self):
  1836. """Create a mock notification provider with bed cooled enabled."""
  1837. provider = MagicMock()
  1838. provider.id = 1
  1839. provider.name = "Test Provider"
  1840. provider.provider_type = "webhook"
  1841. provider.enabled = True
  1842. provider.config = json.dumps({"webhook_url": "http://test.local/webhook"})
  1843. provider.on_bed_cooled = True
  1844. provider.quiet_hours_enabled = False
  1845. provider.daily_digest_enabled = False
  1846. provider.printer_id = None
  1847. return provider
  1848. @pytest.fixture
  1849. def mock_db(self):
  1850. """Create a mock database session."""
  1851. db = AsyncMock()
  1852. db.commit = AsyncMock()
  1853. return db
  1854. @pytest.mark.asyncio
  1855. async def test_on_bed_cooled_sends_notification(self, service, mock_provider, mock_db):
  1856. """Verify bed cooled notification is sent when triggered."""
  1857. with (
  1858. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1859. patch.object(service, "_send_to_providers", new_callable=AsyncMock) as mock_send,
  1860. patch.object(service, "_build_message_from_template", new_callable=AsyncMock) as mock_build,
  1861. ):
  1862. mock_get.return_value = [mock_provider]
  1863. mock_build.return_value = ("Bed Cooled", "Test Printer: Bed cooled to 30°C")
  1864. await service.on_bed_cooled(
  1865. printer_id=1,
  1866. printer_name="Test Printer",
  1867. bed_temp=30.0,
  1868. threshold=35.0,
  1869. filename="benchy.3mf",
  1870. db=mock_db,
  1871. )
  1872. mock_get.assert_called_once()
  1873. mock_send.assert_called_once()
  1874. @pytest.mark.asyncio
  1875. async def test_on_bed_cooled_skipped_when_no_providers(self, service, mock_db):
  1876. """Verify notification is skipped when no providers have bed cooled enabled."""
  1877. with (
  1878. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1879. patch.object(service, "_send_to_providers", new_callable=AsyncMock) as mock_send,
  1880. ):
  1881. mock_get.return_value = []
  1882. await service.on_bed_cooled(
  1883. printer_id=1,
  1884. printer_name="Test Printer",
  1885. bed_temp=30.0,
  1886. threshold=35.0,
  1887. filename="benchy.3mf",
  1888. db=mock_db,
  1889. )
  1890. mock_send.assert_not_called()
  1891. @pytest.mark.asyncio
  1892. async def test_on_bed_cooled_includes_correct_variables(self, service, mock_provider, mock_db):
  1893. """Verify bed temp, threshold, and filename are passed to template variables."""
  1894. captured_variables = {}
  1895. async def capture_build(db, event_type, variables):
  1896. captured_variables.update(variables)
  1897. return ("Test", "Test")
  1898. with (
  1899. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1900. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1901. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1902. ):
  1903. mock_get.return_value = [mock_provider]
  1904. await service.on_bed_cooled(
  1905. printer_id=1,
  1906. printer_name="X1 Carbon",
  1907. bed_temp=28.7,
  1908. threshold=35.0,
  1909. filename="benchy.gcode.3mf",
  1910. db=mock_db,
  1911. )
  1912. assert captured_variables["printer"] == "X1 Carbon"
  1913. assert captured_variables["bed_temp"] == "29"
  1914. assert captured_variables["threshold"] == "35"
  1915. assert captured_variables["filename"] == "benchy"
  1916. @pytest.mark.asyncio
  1917. async def test_on_bed_cooled_handles_none_filename(self, service, mock_provider, mock_db):
  1918. """Verify None filename is handled gracefully."""
  1919. captured_variables = {}
  1920. async def capture_build(db, event_type, variables):
  1921. captured_variables.update(variables)
  1922. return ("Test", "Test")
  1923. with (
  1924. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1925. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  1926. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  1927. ):
  1928. mock_get.return_value = [mock_provider]
  1929. await service.on_bed_cooled(
  1930. printer_id=1,
  1931. printer_name="Test Printer",
  1932. bed_temp=30.0,
  1933. threshold=35.0,
  1934. filename=None,
  1935. db=mock_db,
  1936. )
  1937. assert captured_variables["filename"] == "Unknown"
  1938. class TestFirstLayerCompleteNotifications:
  1939. """Tests for first layer complete notifications."""
  1940. @pytest.fixture
  1941. def service(self):
  1942. return NotificationService()
  1943. @pytest.fixture
  1944. def mock_provider(self):
  1945. """Create a mock notification provider with first layer complete enabled."""
  1946. provider = MagicMock()
  1947. provider.id = 1
  1948. provider.name = "Test Provider"
  1949. provider.provider_type = "webhook"
  1950. provider.enabled = True
  1951. provider.config = json.dumps({"webhook_url": "http://test.local/webhook"})
  1952. provider.on_first_layer_complete = True
  1953. provider.quiet_hours_enabled = False
  1954. provider.daily_digest_enabled = False
  1955. provider.printer_id = None
  1956. return provider
  1957. @pytest.fixture
  1958. def mock_db(self):
  1959. """Create a mock database session."""
  1960. db = AsyncMock()
  1961. db.commit = AsyncMock()
  1962. return db
  1963. @pytest.mark.asyncio
  1964. async def test_on_first_layer_complete_sends_notification(self, service, mock_provider, mock_db):
  1965. """Verify first layer complete notification is sent when triggered."""
  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 Printer: benchy.3mf")
  1973. await service.on_first_layer_complete(
  1974. printer_id=1,
  1975. printer_name="Test Printer",
  1976. filename="benchy.3mf",
  1977. total_layers=50,
  1978. db=mock_db,
  1979. )
  1980. mock_get.assert_called_once()
  1981. mock_send.assert_called_once()
  1982. @pytest.mark.asyncio
  1983. async def test_on_first_layer_complete_skipped_when_no_providers(self, service, mock_db):
  1984. """Verify notification is skipped when no providers have first layer complete enabled."""
  1985. with (
  1986. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  1987. patch.object(service, "_send_to_providers", new_callable=AsyncMock) as mock_send,
  1988. ):
  1989. mock_get.return_value = []
  1990. await service.on_first_layer_complete(
  1991. printer_id=1,
  1992. printer_name="Test Printer",
  1993. filename="benchy.3mf",
  1994. total_layers=50,
  1995. db=mock_db,
  1996. )
  1997. mock_send.assert_not_called()
  1998. @pytest.mark.asyncio
  1999. async def test_on_first_layer_complete_includes_correct_variables(self, service, mock_provider, mock_db):
  2000. """Verify printer name, filename, and total_layers are passed to template variables."""
  2001. captured_variables = {}
  2002. async def capture_build(db, event_type, variables):
  2003. captured_variables.update(variables)
  2004. return ("Test", "Test")
  2005. with (
  2006. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  2007. patch.object(service, "_send_to_providers", new_callable=AsyncMock),
  2008. patch.object(service, "_build_message_from_template", side_effect=capture_build),
  2009. ):
  2010. mock_get.return_value = [mock_provider]
  2011. await service.on_first_layer_complete(
  2012. printer_id=1,
  2013. printer_name="X1 Carbon",
  2014. filename="benchy.gcode.3mf",
  2015. total_layers=120,
  2016. db=mock_db,
  2017. )
  2018. assert captured_variables["printer"] == "X1 Carbon"
  2019. assert captured_variables["filename"] == "benchy"
  2020. assert captured_variables["total_layers"] == "120"
  2021. @pytest.mark.asyncio
  2022. async def test_on_first_layer_complete_passes_image_data(self, service, mock_provider, mock_db):
  2023. """Verify image_data is passed through to _send_to_providers."""
  2024. with (
  2025. patch.object(service, "_get_providers_for_event", new_callable=AsyncMock) as mock_get,
  2026. patch.object(service, "_send_to_providers", new_callable=AsyncMock) as mock_send,
  2027. patch.object(service, "_build_message_from_template", new_callable=AsyncMock) as mock_build,
  2028. ):
  2029. mock_get.return_value = [mock_provider]
  2030. mock_build.return_value = ("First Layer Complete", "Test message")
  2031. fake_image = b"\x89PNG\r\n\x1a\nfakeimage"
  2032. await service.on_first_layer_complete(
  2033. printer_id=1,
  2034. printer_name="Test Printer",
  2035. filename="benchy.3mf",
  2036. total_layers=50,
  2037. db=mock_db,
  2038. image_data=fake_image,
  2039. )
  2040. mock_send.assert_called_once()
  2041. call_kwargs = mock_send.call_args
  2042. assert call_kwargs.kwargs.get("image_data") == fake_image
  2043. class TestNtfyOutbound:
  2044. """Regression for #1534 — UA hygiene and Cloudflare-challenge detection."""
  2045. @pytest.fixture
  2046. def service(self):
  2047. return NotificationService()
  2048. @pytest.mark.asyncio
  2049. async def test_notification_client_sets_honest_user_agent(self, service):
  2050. """Default httpx UA leaks `python-httpx/<version>` — every other
  2051. outbound client in the codebase identifies as Bambuddy. The
  2052. notification client must too."""
  2053. client = await service._get_client()
  2054. try:
  2055. assert client.headers.get("user-agent") == "Bambuddy/1.0 (+https://github.com/maziggy/bambuddy)"
  2056. finally:
  2057. await service.close()
  2058. @pytest.mark.asyncio
  2059. async def test_ntfy_cloudflare_challenge_returns_actionable_error(self, service):
  2060. """When ntfy is fronted by Cloudflare and CF returns its JS
  2061. challenge, the user must see a message that points at the actual
  2062. fix (CF security skip), not the raw HTML."""
  2063. import httpx
  2064. challenge_html = (
  2065. '<!DOCTYPE html><html lang="en-US"><head><title>Just a moment...</title>'
  2066. '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">'
  2067. )
  2068. mock_response = httpx.Response(
  2069. 403,
  2070. content=challenge_html.encode(),
  2071. headers={"server": "cloudflare", "content-type": "text/html; charset=UTF-8"},
  2072. )
  2073. mock_client = AsyncMock()
  2074. mock_client.post = AsyncMock(return_value=mock_response)
  2075. with patch.object(service, "_get_client", AsyncMock(return_value=mock_client)):
  2076. ok, detail = await service._send_ntfy(
  2077. {"server": "https://ntfy.example", "topic": "alerts", "auth_token": "tk_xxx"},
  2078. title="t",
  2079. message="m",
  2080. )
  2081. assert ok is False
  2082. assert "Cloudflare" in detail
  2083. assert "security-skip" in detail or "Bot Fight Mode" in detail
  2084. # The raw HTML must not be the dominant content shown to the user.
  2085. assert "<!DOCTYPE" not in detail
  2086. @pytest.mark.asyncio
  2087. async def test_ntfy_normal_403_is_not_misread_as_a_cloudflare_challenge(self, service, caplog):
  2088. """A non-Cloudflare 403 (e.g. ntfy auth fail) must report the real
  2089. status rather than the Cloudflare-challenge advice — we only intercept
  2090. the challenge shape.
  2091. The origin's body is no longer returned to the API caller: the ntfy
  2092. server URL is caller-supplied, so echoing it made this an SSRF read
  2093. primitive. It goes to the debug log instead.
  2094. """
  2095. import httpx
  2096. mock_response = httpx.Response(
  2097. 403,
  2098. content=b"forbidden: invalid auth token",
  2099. headers={"content-type": "text/plain"},
  2100. )
  2101. mock_client = AsyncMock()
  2102. mock_client.post = AsyncMock(return_value=mock_response)
  2103. with (
  2104. patch.object(service, "_get_client", AsyncMock(return_value=mock_client)),
  2105. caplog.at_level("DEBUG", logger="backend.app.services.notification_service"),
  2106. ):
  2107. ok, detail = await service._send_ntfy(
  2108. {"server": "https://ntfy.sh", "topic": "alerts", "auth_token": "bad"},
  2109. title="t",
  2110. message="m",
  2111. )
  2112. assert ok is False
  2113. assert "Cloudflare" not in detail
  2114. assert detail.startswith("HTTP 403")
  2115. assert "invalid auth token" not in detail
  2116. assert "invalid auth token" in caplog.text
  2117. @pytest.mark.asyncio
  2118. async def test_ntfy_origin_error_through_cloudflare_is_not_misclassified(self, service, caplog):
  2119. """Cloudflare adds Server: cloudflare to EVERY proxied response,
  2120. including legitimate origin errors. A real 401 "wrong token"
  2121. from an ntfy server that happens to sit behind Cloudflare must
  2122. still be reported as the origin's status — we must not flip
  2123. every CF-fronted 4xx into a "your Cloudflare is blocking" message.
  2124. As above, the origin body reaches the debug log rather than the caller.
  2125. """
  2126. import httpx
  2127. mock_response = httpx.Response(
  2128. 401,
  2129. content=b'{"code":40101,"http":401,"error":"unauthorized"}',
  2130. headers={
  2131. "server": "cloudflare",
  2132. "cf-ray": "abc123-FRA",
  2133. "content-type": "application/json",
  2134. # No cf-mitigated — CF just proxied the origin response.
  2135. },
  2136. )
  2137. mock_client = AsyncMock()
  2138. mock_client.post = AsyncMock(return_value=mock_response)
  2139. with (
  2140. patch.object(service, "_get_client", AsyncMock(return_value=mock_client)),
  2141. caplog.at_level("DEBUG", logger="backend.app.services.notification_service"),
  2142. ):
  2143. ok, detail = await service._send_ntfy(
  2144. {"server": "https://ntfy.example", "topic": "alerts", "auth_token": "wrong"},
  2145. title="t",
  2146. message="m",
  2147. )
  2148. assert ok is False
  2149. assert "Cloudflare" not in detail
  2150. assert detail.startswith("HTTP 401")
  2151. assert "unauthorized" not in detail
  2152. assert "unauthorized" in caplog.text
  2153. @pytest.mark.asyncio
  2154. async def test_ntfy_cloudflare_cf_mitigated_header_alone_triggers(self, service):
  2155. """The cf-mitigated header on its own is enough — that's the
  2156. canonical CF "I actively blocked this" signal, even if the
  2157. response body shape changes between CF challenge generations."""
  2158. import httpx
  2159. mock_response = httpx.Response(
  2160. 403,
  2161. content=b"<html>some future CF block page</html>",
  2162. headers={
  2163. "server": "cloudflare",
  2164. "cf-mitigated": "challenge",
  2165. "content-type": "text/html",
  2166. },
  2167. )
  2168. mock_client = AsyncMock()
  2169. mock_client.post = AsyncMock(return_value=mock_response)
  2170. with patch.object(service, "_get_client", AsyncMock(return_value=mock_client)):
  2171. ok, detail = await service._send_ntfy(
  2172. {"server": "https://ntfy.example", "topic": "alerts"},
  2173. title="t",
  2174. message="m",
  2175. )
  2176. assert ok is False
  2177. assert "Cloudflare" in detail
  2178. class TestEmailProvider:
  2179. """Tests for SMTP email provider, including #1792 finish-photo inline embed.
  2180. Embed is opt-in via the template: only when the user's template referenced
  2181. ``{finish_photo_url}`` (so the URL appears in the rendered body) AND the
  2182. photo bytes are available does ``_send_email`` build the multipart/related
  2183. shape. Otherwise it stays single-part text — no surprise inline image.
  2184. """
  2185. PHOTO_URL = "https://printer.local/api/v1/archives/42/photos/finish.jpg"
  2186. @pytest.fixture
  2187. def service(self):
  2188. return NotificationService()
  2189. @pytest.fixture
  2190. def smtp_config(self):
  2191. return {
  2192. "smtp_server": "smtp.example.com",
  2193. "smtp_port": "587",
  2194. "username": "alice",
  2195. "password": "secret",
  2196. "from_email": "bambuddy@example.com",
  2197. "to_email": "alice@example.com",
  2198. "security": "starttls",
  2199. "auth_enabled": "true",
  2200. }
  2201. @staticmethod
  2202. def _fake_smtp_class(captured: dict):
  2203. class FakeSMTP:
  2204. # timeout matches the real smtplib.SMTP/SMTP_SSL signature — the
  2205. # service passes an explicit timeout so a wedged relay can't hang
  2206. # the send (#2572).
  2207. def __init__(self, host, port, timeout=None):
  2208. captured["host"] = host
  2209. captured["port"] = port
  2210. captured["timeout"] = timeout
  2211. def starttls(self):
  2212. captured["starttls"] = True
  2213. def login(self, u, p):
  2214. captured["login"] = (u, p)
  2215. def sendmail(self, frm, to, body):
  2216. captured["from"] = frm
  2217. captured["to"] = to
  2218. captured["raw"] = body
  2219. def quit(self):
  2220. captured["quit"] = True
  2221. return FakeSMTP
  2222. @pytest.mark.asyncio
  2223. async def test_email_without_image_or_url_stays_text_only(self, service, smtp_config):
  2224. """No image_data and no URL in body → original single-part text shape."""
  2225. captured: dict = {}
  2226. with patch("backend.app.services.notification_service.smtplib.SMTP", self._fake_smtp_class(captured)):
  2227. ok, _ = await service._send_email(smtp_config, "Print Failed", "Reason: unknown")
  2228. assert ok is True
  2229. assert "image/jpeg" not in captured["raw"]
  2230. assert "multipart/related" not in captured["raw"]
  2231. assert "cid:bambuddy-finish-photo" not in captured["raw"]
  2232. assert "Reason: unknown" in captured["raw"]
  2233. @pytest.mark.asyncio
  2234. async def test_email_image_without_template_reference_stays_text_only(self, service, smtp_config):
  2235. """image_data present but template didn't include {finish_photo_url} → no embed.
  2236. Pins the template-driven contract: a user whose body is just
  2237. "Print failed. Reason: unknown" does NOT get a surprise inline image
  2238. stapled to the bottom, even though the photo bytes are available
  2239. upstream from the archive.
  2240. """
  2241. captured: dict = {}
  2242. with patch("backend.app.services.notification_service.smtplib.SMTP", self._fake_smtp_class(captured)):
  2243. ok, _ = await service._send_email(
  2244. smtp_config,
  2245. "Print Failed",
  2246. "Reason: unknown",
  2247. image_data=b"\xff\xd8\xff\xe0jpeg",
  2248. finish_photo_url=self.PHOTO_URL,
  2249. )
  2250. assert ok is True
  2251. raw = captured["raw"]
  2252. assert "image/jpeg" not in raw
  2253. assert "multipart/related" not in raw
  2254. assert "cid:bambuddy-finish-photo" not in raw
  2255. @pytest.mark.asyncio
  2256. async def test_email_inlines_when_template_uses_finish_photo_url(self, service, smtp_config):
  2257. """URL in body + image_data present → multipart/related + cid embed; HTML swaps URL for <img>."""
  2258. captured: dict = {}
  2259. body = f"Print failed. Reason: unknown\n\nSnapshot: {self.PHOTO_URL}"
  2260. with patch("backend.app.services.notification_service.smtplib.SMTP", self._fake_smtp_class(captured)):
  2261. ok, _ = await service._send_email(
  2262. smtp_config,
  2263. "Print Failed",
  2264. body,
  2265. image_data=b"\xff\xd8\xff\xe0fake-jpeg-bytes",
  2266. finish_photo_url=self.PHOTO_URL,
  2267. )
  2268. assert ok is True
  2269. raw = captured["raw"]
  2270. # multipart/related shape with both alt parts and an image part
  2271. assert "multipart/related" in raw
  2272. assert "multipart/alternative" in raw
  2273. assert "text/plain" in raw
  2274. assert "text/html" in raw
  2275. assert "image/jpeg" in raw
  2276. # HTML references the exact cid the Content-ID header registers
  2277. assert "Content-ID: <bambuddy-finish-photo>" in raw
  2278. assert 'src="cid:bambuddy-finish-photo"' in raw
  2279. # Inline disposition so renders embedded, not as download attachment
  2280. assert 'Content-Disposition: inline; filename="finish-photo.jpg"' in raw
  2281. # Plain-text body keeps the URL so non-HTML clients still get a clickable link
  2282. assert self.PHOTO_URL in raw
  2283. @pytest.mark.asyncio
  2284. async def test_email_image_data_without_url_arg_stays_text_only(self, service, smtp_config):
  2285. """image_data passed but finish_photo_url=None → defence-in-depth, no embed.
  2286. Even if a future caller forgets to thread the URL through but does pass
  2287. the bytes, the conservative default is no embed (avoids attaching an
  2288. unreferenced image to an unrelated event type).
  2289. """
  2290. captured: dict = {}
  2291. with patch("backend.app.services.notification_service.smtplib.SMTP", self._fake_smtp_class(captured)):
  2292. ok, _ = await service._send_email(
  2293. smtp_config,
  2294. "Print Failed",
  2295. f"Snapshot: {self.PHOTO_URL}",
  2296. image_data=b"\xff\xd8\xff\xe0jpeg",
  2297. finish_photo_url=None,
  2298. )
  2299. assert ok is True
  2300. assert "image/jpeg" not in captured["raw"]
  2301. assert "multipart/related" not in captured["raw"]
  2302. @pytest.mark.asyncio
  2303. async def test_email_html_body_escapes_user_content(self, service, smtp_config):
  2304. """Template-rendered body must not be injected raw into the HTML part."""
  2305. captured: dict = {}
  2306. body = f"Filename: <script>alert(1)</script>\nLine 2\nSnapshot: {self.PHOTO_URL}"
  2307. with patch("backend.app.services.notification_service.smtplib.SMTP", self._fake_smtp_class(captured)):
  2308. ok, _ = await service._send_email(
  2309. smtp_config,
  2310. "Print Failed",
  2311. body,
  2312. image_data=b"\xff\xd8\xff\xe0jpeg",
  2313. finish_photo_url=self.PHOTO_URL,
  2314. )
  2315. assert ok is True
  2316. raw = captured["raw"]
  2317. # Raw HTML must NOT round-trip into the HTML part — verify escaped form is present.
  2318. assert "&lt;script&gt;alert(1)&lt;/script&gt;" in raw
  2319. # Newlines in the body become <br> in HTML
  2320. assert "Line 2" in raw
  2321. assert "<br>" in raw
  2322. @pytest.mark.asyncio
  2323. async def test_email_html_swaps_url_for_img_tag(self, service, smtp_config):
  2324. """In the HTML part, the URL substring is replaced with the <img cid:...> tag.
  2325. Plain text keeps the URL; HTML clients see the inline image where the
  2326. URL was. The URL must NOT appear inside an <a href> wrapping the image
  2327. — we replace the URL outright with the img tag (renderers don't need
  2328. the URL twice in the HTML part when the image is already inline).
  2329. """
  2330. captured: dict = {}
  2331. body = f"See: {self.PHOTO_URL} for the snapshot."
  2332. with patch("backend.app.services.notification_service.smtplib.SMTP", self._fake_smtp_class(captured)):
  2333. ok, _ = await service._send_email(
  2334. smtp_config,
  2335. "Print Failed",
  2336. body,
  2337. image_data=b"\xff\xd8\xff\xe0jpeg",
  2338. finish_photo_url=self.PHOTO_URL,
  2339. )
  2340. assert ok is True
  2341. raw = captured["raw"]
  2342. # The <img> tag appears in the HTML part
  2343. assert 'src="cid:bambuddy-finish-photo"' in raw
  2344. # The escaped URL is the marker we replaced — the HTML part should not
  2345. # contain BOTH the escaped URL AND the cid img (we swapped, not duplicated).
  2346. # The plain-text part still has the URL; check it's there at least once.
  2347. assert self.PHOTO_URL in raw