test_notification_service.py 110 KB

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