test_notification_service.py 114 KB

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