test_smart_plug_manager.py 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208
  1. """Unit tests for SmartPlugManager service.
  2. These tests specifically target the auto-off behavior and toggle functionality
  3. that were identified as common regression points.
  4. """
  5. import asyncio
  6. from datetime import datetime, timezone
  7. from unittest.mock import AsyncMock, MagicMock, patch
  8. import pytest
  9. from backend.app.services.smart_plug_manager import SmartPlugManager
  10. class TestSmartPlugManager:
  11. """Tests for SmartPlugManager class."""
  12. @pytest.fixture
  13. def manager(self):
  14. """Create a fresh SmartPlugManager instance."""
  15. return SmartPlugManager()
  16. @pytest.fixture
  17. def mock_plug(self):
  18. """Create a mock SmartPlug object."""
  19. plug = MagicMock()
  20. plug.id = 1
  21. plug.name = "Test Plug"
  22. plug.ip_address = "192.168.1.100"
  23. plug.username = None
  24. plug.password = None
  25. plug.enabled = True
  26. plug.auto_on = True
  27. plug.auto_off = True
  28. plug.off_delay_mode = "time"
  29. plug.off_delay_minutes = 5
  30. plug.off_temp_threshold = 70
  31. plug.printer_id = 1
  32. plug.auto_off_executed = False
  33. plug.auto_off_pending = False
  34. plug.last_state = "ON"
  35. plug.last_checked = None
  36. # #1349: drying defaults match the new schema — both off until the
  37. # user opts in, so existing tests don't accidentally activate the
  38. # post-drying path.
  39. plug.plug_type = "tasmota"
  40. plug.ha_entity_id = None
  41. plug.auto_off_after_drying = False
  42. plug.off_delay_after_drying_minutes = 10
  43. return plug
  44. @pytest.fixture
  45. def mock_db(self):
  46. """Create a mock database session."""
  47. db = AsyncMock()
  48. db.commit = AsyncMock()
  49. db.refresh = AsyncMock()
  50. return db
  51. # ========================================================================
  52. # Tests for on_print_start
  53. # ========================================================================
  54. @pytest.mark.asyncio
  55. async def test_on_print_start_turns_on_plug(self, manager, mock_plug, mock_db):
  56. """Verify plug is turned ON when print starts with auto_on enabled."""
  57. with (
  58. patch.object(manager, "_get_plugs_for_printer", new_callable=AsyncMock) as mock_get_plug,
  59. patch("backend.app.services.smart_plug_manager.tasmota_service") as mock_tasmota,
  60. ):
  61. mock_get_plug.return_value = [mock_plug]
  62. mock_tasmota.turn_on = AsyncMock(return_value=True)
  63. await manager.on_print_start(printer_id=1, db=mock_db)
  64. mock_tasmota.turn_on.assert_called_once_with(mock_plug)
  65. @pytest.mark.asyncio
  66. async def test_on_print_start_skipped_when_auto_on_disabled(self, manager, mock_plug, mock_db):
  67. """Verify plug is NOT turned on when auto_on is disabled."""
  68. mock_plug.auto_on = False
  69. with (
  70. patch.object(manager, "_get_plugs_for_printer", new_callable=AsyncMock) as mock_get_plug,
  71. patch("backend.app.services.smart_plug_manager.tasmota_service") as mock_tasmota,
  72. ):
  73. mock_get_plug.return_value = [mock_plug]
  74. mock_tasmota.turn_on = AsyncMock()
  75. await manager.on_print_start(printer_id=1, db=mock_db)
  76. mock_tasmota.turn_on.assert_not_called()
  77. @pytest.mark.asyncio
  78. async def test_on_print_start_skipped_when_plug_disabled(self, manager, mock_plug, mock_db):
  79. """Verify plug is NOT turned on when plug.enabled is False."""
  80. mock_plug.enabled = False
  81. with (
  82. patch.object(manager, "_get_plugs_for_printer", new_callable=AsyncMock) as mock_get_plug,
  83. patch("backend.app.services.smart_plug_manager.tasmota_service") as mock_tasmota,
  84. ):
  85. mock_get_plug.return_value = [mock_plug]
  86. mock_tasmota.turn_on = AsyncMock()
  87. await manager.on_print_start(printer_id=1, db=mock_db)
  88. mock_tasmota.turn_on.assert_not_called()
  89. @pytest.mark.asyncio
  90. async def test_on_print_start_skipped_when_no_plug_found(self, manager, mock_db):
  91. """Verify graceful handling when no plug is linked to printer."""
  92. with (
  93. patch.object(manager, "_get_plugs_for_printer", new_callable=AsyncMock) as mock_get_plug,
  94. patch("backend.app.services.smart_plug_manager.tasmota_service") as mock_tasmota,
  95. ):
  96. mock_get_plug.return_value = []
  97. mock_tasmota.turn_on = AsyncMock()
  98. # Should not raise any exception
  99. await manager.on_print_start(printer_id=999, db=mock_db)
  100. mock_tasmota.turn_on.assert_not_called()
  101. @pytest.mark.asyncio
  102. async def test_on_print_start_cancels_pending_off(self, manager, mock_plug, mock_db):
  103. """Verify starting a new print cancels any pending auto-off."""
  104. # Set up a pending task
  105. mock_task = MagicMock()
  106. manager._pending_off[mock_plug.id] = mock_task
  107. with (
  108. patch.object(manager, "_get_plugs_for_printer", new_callable=AsyncMock) as mock_get_plug,
  109. patch.object(manager, "_mark_auto_off_pending", new_callable=AsyncMock),
  110. patch("backend.app.services.smart_plug_manager.tasmota_service") as mock_tasmota,
  111. ):
  112. mock_get_plug.return_value = [mock_plug]
  113. mock_tasmota.turn_on = AsyncMock(return_value=True)
  114. await manager.on_print_start(printer_id=1, db=mock_db)
  115. mock_task.cancel.assert_called_once()
  116. assert mock_plug.id not in manager._pending_off
  117. @pytest.mark.asyncio
  118. async def test_on_print_start_resets_auto_off_executed_flag(self, manager, mock_plug, mock_db):
  119. """Verify auto_off_executed flag is reset when turning on."""
  120. mock_plug.auto_off_executed = True
  121. with (
  122. patch.object(manager, "_get_plugs_for_printer", new_callable=AsyncMock) as mock_get_plug,
  123. patch("backend.app.services.smart_plug_manager.tasmota_service") as mock_tasmota,
  124. ):
  125. mock_get_plug.return_value = [mock_plug]
  126. mock_tasmota.turn_on = AsyncMock(return_value=True)
  127. await manager.on_print_start(printer_id=1, db=mock_db)
  128. assert mock_plug.auto_off_executed is False
  129. # ========================================================================
  130. # Tests for on_print_complete
  131. # ========================================================================
  132. @pytest.mark.asyncio
  133. async def test_on_print_complete_schedules_time_based_off(self, manager, mock_plug, mock_db):
  134. """Verify time-based auto-off is scheduled when print completes."""
  135. mock_plug.off_delay_mode = "time"
  136. mock_plug.off_delay_minutes = 5
  137. with (
  138. patch.object(manager, "_get_plugs_for_printer", new_callable=AsyncMock) as mock_get_plug,
  139. patch.object(manager, "_schedule_delayed_off") as mock_schedule,
  140. ):
  141. mock_get_plug.return_value = [mock_plug]
  142. await manager.on_print_complete(printer_id=1, status="completed", db=mock_db)
  143. mock_schedule.assert_called_once_with(mock_plug, 1, 300) # 5 min * 60 sec
  144. @pytest.mark.asyncio
  145. async def test_on_print_complete_schedules_temp_based_off(self, manager, mock_plug, mock_db):
  146. """Verify temperature-based auto-off is scheduled when print completes."""
  147. mock_plug.off_delay_mode = "temperature"
  148. mock_plug.off_temp_threshold = 70
  149. with (
  150. patch.object(manager, "_get_plugs_for_printer", new_callable=AsyncMock) as mock_get_plug,
  151. patch.object(manager, "_schedule_temp_based_off") as mock_schedule,
  152. ):
  153. mock_get_plug.return_value = [mock_plug]
  154. await manager.on_print_complete(printer_id=1, status="completed", db=mock_db)
  155. mock_schedule.assert_called_once_with(mock_plug, 1, 70)
  156. @pytest.mark.asyncio
  157. async def test_on_print_complete_skipped_when_auto_off_disabled(self, manager, mock_plug, mock_db):
  158. """CRITICAL: Verify auto-off does NOT trigger when auto_off is False.
  159. This is a key regression test - the toggle must respect the setting.
  160. """
  161. mock_plug.auto_off = False
  162. with (
  163. patch.object(manager, "_get_plugs_for_printer", new_callable=AsyncMock) as mock_get_plug,
  164. patch.object(manager, "_schedule_delayed_off") as mock_schedule,
  165. patch.object(manager, "_schedule_temp_based_off") as mock_temp,
  166. ):
  167. mock_get_plug.return_value = [mock_plug]
  168. await manager.on_print_complete(printer_id=1, status="completed", db=mock_db)
  169. mock_schedule.assert_not_called()
  170. mock_temp.assert_not_called()
  171. @pytest.mark.asyncio
  172. async def test_on_print_complete_skipped_when_plug_disabled(self, manager, mock_plug, mock_db):
  173. """Verify auto-off does NOT trigger when plug is disabled."""
  174. mock_plug.enabled = False
  175. with (
  176. patch.object(manager, "_get_plugs_for_printer", new_callable=AsyncMock) as mock_get_plug,
  177. patch.object(manager, "_schedule_delayed_off") as mock_schedule,
  178. ):
  179. mock_get_plug.return_value = [mock_plug]
  180. await manager.on_print_complete(printer_id=1, status="completed", db=mock_db)
  181. mock_schedule.assert_not_called()
  182. @pytest.mark.asyncio
  183. async def test_on_print_complete_skipped_on_failed_print(self, manager, mock_plug, mock_db):
  184. """Verify auto-off does NOT trigger on failed prints for investigation."""
  185. with (
  186. patch.object(manager, "_get_plugs_for_printer", new_callable=AsyncMock) as mock_get_plug,
  187. patch.object(manager, "_schedule_delayed_off") as mock_schedule,
  188. ):
  189. mock_get_plug.return_value = [mock_plug]
  190. await manager.on_print_complete(printer_id=1, status="failed", db=mock_db)
  191. mock_schedule.assert_not_called()
  192. @pytest.mark.asyncio
  193. async def test_on_print_complete_skipped_on_aborted_print(self, manager, mock_plug, mock_db):
  194. """Verify auto-off does NOT trigger on aborted prints."""
  195. with (
  196. patch.object(manager, "_get_plugs_for_printer", new_callable=AsyncMock) as mock_get_plug,
  197. patch.object(manager, "_schedule_delayed_off") as mock_schedule,
  198. ):
  199. mock_get_plug.return_value = [mock_plug]
  200. await manager.on_print_complete(printer_id=1, status="aborted", db=mock_db)
  201. mock_schedule.assert_not_called()
  202. # ========================================================================
  203. # Tests for on_drying_complete (#1349)
  204. # ========================================================================
  205. @pytest.mark.asyncio
  206. async def test_on_drying_complete_schedules_delayed_off_when_enabled(self, manager, mock_plug, mock_db):
  207. """Plug with ``auto_off_after_drying=True`` gets a delayed-off scheduled
  208. using its drying-specific delay (independent of print-finish delay)."""
  209. mock_plug.auto_off_after_drying = True
  210. mock_plug.off_delay_after_drying_minutes = 15
  211. with (
  212. patch.object(manager, "_get_plugs_for_printer", new_callable=AsyncMock) as mock_get_plug,
  213. patch.object(manager, "_schedule_delayed_off") as mock_schedule,
  214. ):
  215. mock_get_plug.return_value = [mock_plug]
  216. await manager.on_drying_complete(printer_id=1, db=mock_db)
  217. mock_schedule.assert_called_once_with(mock_plug, 1, 15 * 60)
  218. @pytest.mark.asyncio
  219. async def test_on_drying_complete_skipped_when_toggle_off(self, manager, mock_plug, mock_db):
  220. """Default state — toggle off → nothing scheduled. This is the regression
  221. guard for users who only enable the print-finish auto-off and don't
  222. want the AMS-drying path silently running on the same plug."""
  223. mock_plug.auto_off_after_drying = False
  224. # auto_off itself is True (existing print-finish behaviour) — the
  225. # drying path must still be a no-op without its own toggle.
  226. mock_plug.auto_off = True
  227. with (
  228. patch.object(manager, "_get_plugs_for_printer", new_callable=AsyncMock) as mock_get_plug,
  229. patch.object(manager, "_schedule_delayed_off") as mock_schedule,
  230. ):
  231. mock_get_plug.return_value = [mock_plug]
  232. await manager.on_drying_complete(printer_id=1, db=mock_db)
  233. mock_schedule.assert_not_called()
  234. @pytest.mark.asyncio
  235. async def test_on_drying_complete_skipped_when_plug_disabled(self, manager, mock_plug, mock_db):
  236. """Drying auto-off honours the master ``enabled`` flag."""
  237. mock_plug.auto_off_after_drying = True
  238. mock_plug.enabled = False
  239. with (
  240. patch.object(manager, "_get_plugs_for_printer", new_callable=AsyncMock) as mock_get_plug,
  241. patch.object(manager, "_schedule_delayed_off") as mock_schedule,
  242. ):
  243. mock_get_plug.return_value = [mock_plug]
  244. await manager.on_drying_complete(printer_id=1, db=mock_db)
  245. mock_schedule.assert_not_called()
  246. @pytest.mark.asyncio
  247. async def test_on_drying_complete_skipped_for_ha_script_entity(self, manager, mock_plug, mock_db):
  248. """HA script entities can be triggered but not turned off — same
  249. guard the print-finish path has."""
  250. mock_plug.auto_off_after_drying = True
  251. mock_plug.plug_type = "homeassistant"
  252. mock_plug.ha_entity_id = "script.lights_off"
  253. with (
  254. patch.object(manager, "_get_plugs_for_printer", new_callable=AsyncMock) as mock_get_plug,
  255. patch.object(manager, "_schedule_delayed_off") as mock_schedule,
  256. ):
  257. mock_get_plug.return_value = [mock_plug]
  258. await manager.on_drying_complete(printer_id=1, db=mock_db)
  259. mock_schedule.assert_not_called()
  260. @pytest.mark.asyncio
  261. async def test_on_drying_complete_no_op_when_no_plugs(self, manager, mock_db):
  262. """Printer without any linked plugs is a silent no-op (not an error)."""
  263. with (
  264. patch.object(manager, "_get_plugs_for_printer", new_callable=AsyncMock) as mock_get_plug,
  265. patch.object(manager, "_schedule_delayed_off") as mock_schedule,
  266. ):
  267. mock_get_plug.return_value = []
  268. await manager.on_drying_complete(printer_id=1, db=mock_db)
  269. mock_schedule.assert_not_called()
  270. # ========================================================================
  271. # Tests for _cancel_pending_off
  272. # ========================================================================
  273. @pytest.mark.asyncio
  274. async def test_cancel_pending_off_removes_task(self, manager, mock_plug):
  275. """Verify pending off tasks can be cancelled."""
  276. mock_task = MagicMock()
  277. manager._pending_off[mock_plug.id] = mock_task
  278. with patch.object(manager, "_mark_auto_off_pending", new_callable=AsyncMock):
  279. manager._cancel_pending_off(mock_plug.id)
  280. assert mock_plug.id not in manager._pending_off
  281. mock_task.cancel.assert_called_once()
  282. @pytest.mark.asyncio
  283. async def test_cancel_pending_off_handles_missing_task(self, manager):
  284. """Verify no error when cancelling non-existent task."""
  285. # Should not raise any exception
  286. with patch.object(manager, "_mark_auto_off_pending", new_callable=AsyncMock):
  287. manager._cancel_pending_off(999) # Non-existent plug ID
  288. @pytest.mark.asyncio
  289. async def test_cancel_all_pending(self, manager, mock_plug):
  290. """Verify all pending tasks can be cancelled."""
  291. mock_task1 = MagicMock()
  292. mock_task2 = MagicMock()
  293. manager._pending_off[1] = mock_task1
  294. manager._pending_off[2] = mock_task2
  295. with patch("asyncio.create_task"):
  296. manager.cancel_all_pending()
  297. assert len(manager._pending_off) == 0
  298. mock_task1.cancel.assert_called_once()
  299. mock_task2.cancel.assert_called_once()
  300. # ========================================================================
  301. # Tests for scheduler
  302. # ========================================================================
  303. def test_start_scheduler(self, manager):
  304. """Verify scheduler can be started."""
  305. assert manager._scheduler_task is None
  306. # Mock _schedule_loop to return a mock coroutine to avoid unawaited coroutine warning
  307. with patch.object(manager, "_schedule_loop") as mock_loop, patch("asyncio.create_task") as mock_create:
  308. mock_create.return_value = MagicMock()
  309. manager.start_scheduler()
  310. assert manager._scheduler_task is not None
  311. mock_loop.assert_called_once()
  312. def test_stop_scheduler(self, manager):
  313. """Verify scheduler can be stopped."""
  314. mock_task = MagicMock()
  315. manager._scheduler_task = mock_task
  316. manager.stop_scheduler()
  317. mock_task.cancel.assert_called_once()
  318. assert manager._scheduler_task is None
  319. def test_start_scheduler_idempotent(self, manager):
  320. """Verify starting scheduler twice doesn't create multiple tasks."""
  321. mock_schedule_task = MagicMock()
  322. mock_snapshot_task = MagicMock()
  323. manager._scheduler_task = mock_schedule_task
  324. manager._snapshot_task = mock_snapshot_task
  325. # Mock the loop coroutines to avoid unawaited coroutine warnings
  326. with (
  327. patch.object(manager, "_schedule_loop") as mock_loop,
  328. patch.object(manager, "_snapshot_loop") as mock_snapshot,
  329. patch("asyncio.create_task") as mock_create,
  330. ):
  331. manager.start_scheduler()
  332. mock_create.assert_not_called() # Should not create new tasks
  333. mock_loop.assert_not_called()
  334. mock_snapshot.assert_not_called()
  335. def test_stop_scheduler_cancels_snapshot_task(self, manager):
  336. """Verify stopping scheduler also cancels the snapshot loop (#941)."""
  337. mock_schedule_task = MagicMock()
  338. mock_snapshot_task = MagicMock()
  339. manager._scheduler_task = mock_schedule_task
  340. manager._snapshot_task = mock_snapshot_task
  341. manager.stop_scheduler()
  342. mock_schedule_task.cancel.assert_called_once()
  343. mock_snapshot_task.cancel.assert_called_once()
  344. assert manager._scheduler_task is None
  345. assert manager._snapshot_task is None
  346. class TestGetPlugsForPrinter:
  347. """Tests for _get_plugs_for_printer — returns all plugs for a printer (#903)."""
  348. @pytest.fixture
  349. def manager(self):
  350. return SmartPlugManager()
  351. @pytest.mark.asyncio
  352. async def test_returns_empty_list_when_no_plugs(self, manager):
  353. """Verify empty list is returned when no plugs are linked to printer."""
  354. mock_db = AsyncMock()
  355. mock_result = MagicMock()
  356. mock_result.scalars.return_value.all.return_value = []
  357. mock_db.execute = AsyncMock(return_value=mock_result)
  358. result = await manager._get_plugs_for_printer(1, mock_db)
  359. assert result == []
  360. @pytest.mark.asyncio
  361. async def test_returns_single_plug_as_list(self, manager):
  362. """Verify single plug is returned in a list."""
  363. plug = MagicMock()
  364. plug.plug_type = "tasmota"
  365. mock_db = AsyncMock()
  366. mock_result = MagicMock()
  367. mock_result.scalars.return_value.all.return_value = [plug]
  368. mock_db.execute = AsyncMock(return_value=mock_result)
  369. result = await manager._get_plugs_for_printer(1, mock_db)
  370. assert result == [plug]
  371. @pytest.mark.asyncio
  372. async def test_returns_all_plugs(self, manager):
  373. """Verify all plugs are returned when multiple exist (#903)."""
  374. plug1 = MagicMock()
  375. plug1.plug_type = "homeassistant"
  376. plug1.ha_entity_id = "switch.printer"
  377. plug2 = MagicMock()
  378. plug2.plug_type = "homeassistant"
  379. plug2.ha_entity_id = "switch.filter"
  380. mock_db = AsyncMock()
  381. mock_result = MagicMock()
  382. mock_result.scalars.return_value.all.return_value = [plug1, plug2]
  383. mock_db.execute = AsyncMock(return_value=mock_result)
  384. result = await manager._get_plugs_for_printer(1, mock_db)
  385. assert result == [plug1, plug2]
  386. class TestAutoOffPersistent:
  387. """Tests for persistent auto-off behavior (Issue #826).
  388. When auto_off_persistent is True, auto_off should remain enabled after
  389. execution instead of being disabled (one-shot default).
  390. """
  391. @pytest.fixture
  392. def manager(self):
  393. return SmartPlugManager()
  394. @pytest.mark.asyncio
  395. async def test_mark_auto_off_executed_one_shot_disables_auto_off(self, manager):
  396. """Default one-shot: auto_off should be set to False after execution."""
  397. mock_plug = MagicMock()
  398. mock_plug.id = 1
  399. mock_plug.auto_off = True
  400. mock_plug.auto_off_persistent = False
  401. mock_plug.auto_off_executed = False
  402. mock_plug.auto_off_pending = True
  403. mock_plug.auto_off_pending_since = datetime.now(timezone.utc)
  404. with patch("backend.app.core.database.async_session") as mock_session_ctx:
  405. mock_db = AsyncMock()
  406. mock_result = MagicMock()
  407. mock_result.scalar_one_or_none.return_value = mock_plug
  408. mock_db.execute = AsyncMock(return_value=mock_result)
  409. mock_db.commit = AsyncMock()
  410. mock_session_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_db)
  411. mock_session_ctx.return_value.__aexit__ = AsyncMock()
  412. await manager._mark_auto_off_executed(1)
  413. assert mock_plug.auto_off is False, "One-shot: auto_off should be disabled"
  414. assert mock_plug.auto_off_pending is False
  415. assert mock_plug.auto_off_pending_since is None
  416. mock_db.commit.assert_called_once()
  417. @pytest.mark.asyncio
  418. async def test_mark_auto_off_executed_persistent_keeps_auto_off_enabled(self, manager):
  419. """Persistent mode: auto_off should remain True after execution."""
  420. mock_plug = MagicMock()
  421. mock_plug.id = 2
  422. mock_plug.auto_off = True
  423. mock_plug.auto_off_persistent = True
  424. mock_plug.auto_off_executed = False
  425. mock_plug.auto_off_pending = True
  426. mock_plug.auto_off_pending_since = datetime.now(timezone.utc)
  427. with patch("backend.app.core.database.async_session") as mock_session_ctx:
  428. mock_db = AsyncMock()
  429. mock_result = MagicMock()
  430. mock_result.scalar_one_or_none.return_value = mock_plug
  431. mock_db.execute = AsyncMock(return_value=mock_result)
  432. mock_db.commit = AsyncMock()
  433. mock_session_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_db)
  434. mock_session_ctx.return_value.__aexit__ = AsyncMock()
  435. await manager._mark_auto_off_executed(2)
  436. assert mock_plug.auto_off is True, "Persistent: auto_off should stay enabled"
  437. assert mock_plug.auto_off_pending is False
  438. assert mock_plug.auto_off_pending_since is None
  439. mock_db.commit.assert_called_once()
  440. @pytest.mark.asyncio
  441. async def test_persistent_auto_off_full_cycle(self, manager):
  442. """Verify persistent auto-off survives a full print cycle.
  443. Simulates: print start → print complete → auto-off executes → next print start.
  444. auto_off should remain True throughout for persistent plugs.
  445. """
  446. mock_plug = MagicMock()
  447. mock_plug.id = 3
  448. mock_plug.name = "HA BentoBox Filter"
  449. mock_plug.plug_type = "homeassistant"
  450. mock_plug.ha_entity_id = "switch.bentobox_filter"
  451. mock_plug.ip_address = None
  452. mock_plug.username = None
  453. mock_plug.password = None
  454. mock_plug.enabled = True
  455. mock_plug.auto_on = True
  456. mock_plug.auto_off = True
  457. mock_plug.auto_off_persistent = True
  458. mock_plug.off_delay_mode = "time"
  459. mock_plug.off_delay_minutes = 1
  460. mock_plug.off_temp_threshold = 70
  461. mock_plug.printer_id = 1
  462. mock_plug.auto_off_executed = False
  463. mock_plug.auto_off_pending = False
  464. mock_plug.last_state = "OFF"
  465. mock_plug.last_checked = None
  466. mock_db = AsyncMock()
  467. mock_db.commit = AsyncMock()
  468. # Step 1: Print starts — plug turns on
  469. with (
  470. patch.object(manager, "_get_plugs_for_printer", new_callable=AsyncMock) as mock_get,
  471. patch.object(manager, "get_service_for_plug", new_callable=AsyncMock) as mock_svc,
  472. ):
  473. mock_get.return_value = [mock_plug]
  474. mock_service = AsyncMock()
  475. mock_service.turn_on = AsyncMock(return_value=True)
  476. mock_svc.return_value = mock_service
  477. await manager.on_print_start(printer_id=1, db=mock_db)
  478. assert mock_plug.auto_off_executed is False
  479. assert mock_plug.auto_off is True # Still enabled
  480. # Step 2: Print completes — auto-off is scheduled
  481. with (
  482. patch.object(manager, "_get_plugs_for_printer", new_callable=AsyncMock) as mock_get,
  483. patch.object(manager, "_schedule_delayed_off") as mock_schedule,
  484. ):
  485. mock_get.return_value = [mock_plug]
  486. await manager.on_print_complete(printer_id=1, status="completed", db=mock_db)
  487. mock_schedule.assert_called_once()
  488. assert mock_plug.auto_off is True # Still enabled after scheduling
  489. # Step 3: Auto-off executes via _mark_auto_off_executed
  490. with patch("backend.app.core.database.async_session") as mock_session_ctx:
  491. mock_db2 = AsyncMock()
  492. mock_result = MagicMock()
  493. mock_result.scalar_one_or_none.return_value = mock_plug
  494. mock_db2.execute = AsyncMock(return_value=mock_result)
  495. mock_db2.commit = AsyncMock()
  496. mock_session_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_db2)
  497. mock_session_ctx.return_value.__aexit__ = AsyncMock()
  498. await manager._mark_auto_off_executed(3)
  499. # KEY ASSERTION: auto_off stays True for persistent mode
  500. assert mock_plug.auto_off is True, "Persistent auto_off must survive execution"
  501. assert mock_plug.auto_off_pending is False
  502. class TestScheduleLoop:
  503. """Tests for the schedule-based plug control."""
  504. @pytest.fixture
  505. def manager(self):
  506. return SmartPlugManager()
  507. @pytest.mark.asyncio
  508. async def test_check_schedules_turns_on_at_scheduled_time(self, manager):
  509. """Verify scheduled on-time turns plug on."""
  510. mock_plug = MagicMock()
  511. mock_plug.id = 1
  512. mock_plug.name = "Test Plug"
  513. mock_plug.enabled = True
  514. mock_plug.schedule_enabled = True
  515. mock_plug.schedule_on_time = "08:00"
  516. mock_plug.schedule_off_time = "22:00"
  517. mock_plug.printer_id = None
  518. mock_plug.last_state = "OFF"
  519. with (
  520. patch("backend.app.services.smart_plug_manager.datetime") as mock_datetime,
  521. patch("backend.app.core.database.async_session") as mock_session_ctx,
  522. patch("backend.app.services.smart_plug_manager.tasmota_service") as mock_tasmota,
  523. ):
  524. # Set current time to 08:00
  525. mock_now = MagicMock()
  526. mock_now.strftime.return_value = "08:00"
  527. mock_datetime.now.return_value = mock_now
  528. mock_datetime.utcnow.return_value = datetime.now(timezone.utc)
  529. # Set up async session mock
  530. mock_db = AsyncMock()
  531. mock_result = MagicMock()
  532. mock_result.scalars.return_value.all.return_value = [mock_plug]
  533. mock_db.execute = AsyncMock(return_value=mock_result)
  534. mock_db.commit = AsyncMock()
  535. mock_session_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_db)
  536. mock_session_ctx.return_value.__aexit__ = AsyncMock()
  537. mock_tasmota.turn_on = AsyncMock(return_value=True)
  538. await manager._check_schedules()
  539. mock_tasmota.turn_on.assert_called_once_with(mock_plug)
  540. @pytest.mark.asyncio
  541. async def test_check_schedules_turns_off_at_scheduled_time(self, manager):
  542. """Verify scheduled off-time turns plug off."""
  543. mock_plug = MagicMock()
  544. mock_plug.id = 1
  545. mock_plug.name = "Test Plug"
  546. mock_plug.enabled = True
  547. mock_plug.schedule_enabled = True
  548. mock_plug.schedule_on_time = "08:00"
  549. mock_plug.schedule_off_time = "22:00"
  550. mock_plug.printer_id = 1
  551. mock_plug.last_state = "ON"
  552. with (
  553. patch("backend.app.services.smart_plug_manager.datetime") as mock_datetime,
  554. patch("backend.app.core.database.async_session") as mock_session_ctx,
  555. patch("backend.app.services.smart_plug_manager.tasmota_service") as mock_tasmota,
  556. patch("backend.app.services.smart_plug_manager.printer_manager") as mock_pm,
  557. ):
  558. # Set current time to 22:00
  559. mock_now = MagicMock()
  560. mock_now.strftime.return_value = "22:00"
  561. mock_datetime.now.return_value = mock_now
  562. mock_datetime.utcnow.return_value = datetime.now(timezone.utc)
  563. # Set up async session mock
  564. mock_db = AsyncMock()
  565. mock_result = MagicMock()
  566. mock_result.scalars.return_value.all.return_value = [mock_plug]
  567. mock_db.execute = AsyncMock(return_value=mock_result)
  568. mock_db.commit = AsyncMock()
  569. mock_session_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_db)
  570. mock_session_ctx.return_value.__aexit__ = AsyncMock()
  571. mock_tasmota.turn_off = AsyncMock(return_value=True)
  572. mock_pm.mark_printer_offline = MagicMock()
  573. await manager._check_schedules()
  574. mock_tasmota.turn_off.assert_called_once_with(mock_plug)
  575. @pytest.mark.asyncio
  576. async def test_check_schedules_skipped_when_disabled(self, manager):
  577. """Verify schedule is skipped when schedule_enabled is False."""
  578. mock_plug = MagicMock()
  579. mock_plug.id = 1
  580. mock_plug.enabled = True
  581. mock_plug.schedule_enabled = False # Disabled
  582. with (
  583. patch("backend.app.services.smart_plug_manager.datetime") as mock_datetime,
  584. patch("backend.app.core.database.async_session") as mock_session_ctx,
  585. patch("backend.app.services.smart_plug_manager.tasmota_service") as mock_tasmota,
  586. ):
  587. mock_now = MagicMock()
  588. mock_now.strftime.return_value = "08:00"
  589. mock_datetime.now.return_value = mock_now
  590. # Set up async session mock - returns no plugs (filtered by schedule_enabled)
  591. mock_db = AsyncMock()
  592. mock_result = MagicMock()
  593. mock_result.scalars.return_value.all.return_value = []
  594. mock_db.execute = AsyncMock(return_value=mock_result)
  595. mock_db.commit = AsyncMock()
  596. mock_session_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_db)
  597. mock_session_ctx.return_value.__aexit__ = AsyncMock()
  598. mock_tasmota.turn_on = AsyncMock()
  599. await manager._check_schedules()
  600. mock_tasmota.turn_on.assert_not_called()
  601. class TestPendingAutoOffPersistence:
  602. """Tests for auto-off pending state persistence (restart recovery)."""
  603. @pytest.fixture
  604. def manager(self):
  605. return SmartPlugManager()
  606. @pytest.mark.asyncio
  607. async def test_resume_pending_auto_offs_temperature_mode(self, manager):
  608. """Verify temperature-based pending auto-offs are resumed on startup."""
  609. mock_plug = MagicMock()
  610. mock_plug.id = 1
  611. mock_plug.name = "Test Plug"
  612. mock_plug.ip_address = "192.168.1.100"
  613. mock_plug.username = None
  614. mock_plug.password = None
  615. mock_plug.printer_id = 1
  616. mock_plug.auto_off_pending = True
  617. mock_plug.auto_off_pending_since = datetime.now(timezone.utc)
  618. mock_plug.off_delay_mode = "temperature"
  619. mock_plug.off_temp_threshold = 70
  620. with (
  621. patch("backend.app.core.database.async_session") as mock_session_ctx,
  622. patch.object(manager, "_schedule_temp_based_off") as mock_schedule,
  623. ):
  624. mock_db = AsyncMock()
  625. mock_result = MagicMock()
  626. mock_result.scalars.return_value.all.return_value = [mock_plug]
  627. mock_db.execute = AsyncMock(return_value=mock_result)
  628. mock_session_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_db)
  629. mock_session_ctx.return_value.__aexit__ = AsyncMock()
  630. await manager.resume_pending_auto_offs()
  631. mock_schedule.assert_called_once_with(mock_plug, 1, 70)
  632. @pytest.mark.asyncio
  633. async def test_resume_pending_auto_offs_time_mode_immediate_off(self, manager):
  634. """Verify time-based pending auto-offs turn off immediately on resume."""
  635. mock_plug = MagicMock()
  636. mock_plug.id = 1
  637. mock_plug.name = "Test Plug"
  638. mock_plug.ip_address = "192.168.1.100"
  639. mock_plug.username = None
  640. mock_plug.password = None
  641. mock_plug.printer_id = 1
  642. mock_plug.auto_off_pending = True
  643. mock_plug.auto_off_pending_since = datetime.now(timezone.utc)
  644. mock_plug.off_delay_mode = "time"
  645. with (
  646. patch("backend.app.core.database.async_session") as mock_session_ctx,
  647. patch("backend.app.services.smart_plug_manager.tasmota_service") as mock_tasmota,
  648. patch.object(manager, "_mark_auto_off_executed", new_callable=AsyncMock) as mock_mark,
  649. patch("backend.app.services.smart_plug_manager.printer_manager") as mock_pm,
  650. ):
  651. mock_db = AsyncMock()
  652. mock_result = MagicMock()
  653. mock_result.scalars.return_value.all.return_value = [mock_plug]
  654. mock_db.execute = AsyncMock(return_value=mock_result)
  655. mock_session_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_db)
  656. mock_session_ctx.return_value.__aexit__ = AsyncMock()
  657. mock_tasmota.turn_off = AsyncMock(return_value=True)
  658. mock_pm.is_print_active.return_value = False # printer idle on restart
  659. await manager.resume_pending_auto_offs()
  660. mock_tasmota.turn_off.assert_called_once()
  661. mock_mark.assert_called_once_with(1)
  662. @pytest.mark.asyncio
  663. async def test_resume_pending_auto_off_skipped_when_printing(self, manager):
  664. """#1890: on restart, a stale pending off must NOT power off a live print;
  665. the pending flag is cleared instead."""
  666. mock_plug = MagicMock()
  667. mock_plug.id = 1
  668. mock_plug.name = "Test Plug"
  669. mock_plug.printer_id = 1
  670. mock_plug.auto_off_pending = True
  671. mock_plug.auto_off_pending_since = datetime.now(timezone.utc)
  672. mock_plug.off_delay_mode = "time"
  673. with (
  674. patch("backend.app.core.database.async_session") as mock_session_ctx,
  675. patch("backend.app.services.smart_plug_manager.tasmota_service") as mock_tasmota,
  676. patch("backend.app.services.smart_plug_manager.printer_manager") as mock_pm,
  677. patch.object(manager, "_schedule_temp_based_off") as mock_temp,
  678. ):
  679. mock_db = AsyncMock()
  680. mock_result = MagicMock()
  681. mock_result.scalars.return_value.all.return_value = [mock_plug]
  682. mock_db.execute = AsyncMock(return_value=mock_result)
  683. mock_session_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_db)
  684. mock_session_ctx.return_value.__aexit__ = AsyncMock()
  685. mock_tasmota.turn_off = AsyncMock(return_value=True)
  686. mock_pm.is_print_active.return_value = True # printer printing again on restart
  687. mock_pm.get_status.return_value = MagicMock(state="RUNNING")
  688. await manager.resume_pending_auto_offs()
  689. mock_tasmota.turn_off.assert_not_called() # never cut power on the live print
  690. mock_temp.assert_not_called()
  691. assert mock_plug.auto_off_pending is False # stale pending cleared
  692. class TestActivePrintGuard:
  693. """#1890 — auto-off must never cut power while a print is loaded/running.
  694. Covers the two off-executors (`_delayed_off`, `_temp_based_off`), the new
  695. queue-override scheduler that honours per-plug settings, and the
  696. on_print_start cancellation gap.
  697. """
  698. @pytest.fixture
  699. def manager(self):
  700. return SmartPlugManager()
  701. @pytest.fixture
  702. def mock_plug(self):
  703. plug = MagicMock()
  704. plug.id = 1
  705. plug.name = "Test Plug"
  706. plug.ip_address = "192.168.1.100"
  707. plug.username = None
  708. plug.password = None
  709. plug.enabled = True
  710. plug.auto_on = True
  711. plug.auto_off = True
  712. plug.off_delay_mode = "time"
  713. plug.off_delay_minutes = 5
  714. plug.off_temp_threshold = 70
  715. plug.printer_id = 1
  716. plug.plug_type = "tasmota"
  717. plug.ha_entity_id = None
  718. return plug
  719. # ---- _delayed_off (time mode) ----------------------------------------
  720. @pytest.mark.asyncio
  721. async def test_delayed_off_skips_when_printer_printing_again(self, manager):
  722. """Time-delay fires after N min; if a reprint is running, skip the off."""
  723. with (
  724. patch("backend.app.services.smart_plug_manager.printer_manager") as mock_pm,
  725. patch.object(manager, "get_service_for_plug", new_callable=AsyncMock) as mock_get_svc,
  726. patch.object(manager, "_mark_auto_off_pending", new_callable=AsyncMock) as mock_mark_pending,
  727. patch.object(manager, "_mark_auto_off_executed", new_callable=AsyncMock) as mock_mark_exec,
  728. ):
  729. mock_pm.is_print_active.return_value = True
  730. mock_pm.get_status.return_value = MagicMock(state="RUNNING")
  731. await manager._delayed_off(1, "tasmota", "1.2.3.4", None, None, None, printer_id=1, delay_seconds=0)
  732. mock_get_svc.assert_not_called() # never even resolved a service to turn off
  733. mock_mark_exec.assert_not_called()
  734. mock_mark_pending.assert_awaited_with(1, False) # pending flag cleared
  735. @pytest.mark.asyncio
  736. async def test_delayed_off_powers_off_when_idle(self, manager):
  737. """When the printer is genuinely idle, the delayed off still fires."""
  738. mock_service = AsyncMock()
  739. mock_service.turn_off = AsyncMock(return_value=True)
  740. with (
  741. patch("backend.app.services.smart_plug_manager.printer_manager") as mock_pm,
  742. patch.object(manager, "get_service_for_plug", new_callable=AsyncMock, return_value=mock_service),
  743. patch.object(manager, "_mark_auto_off_executed", new_callable=AsyncMock),
  744. ):
  745. mock_pm.is_print_active.return_value = False
  746. await manager._delayed_off(1, "tasmota", "1.2.3.4", None, None, None, printer_id=1, delay_seconds=0)
  747. mock_service.turn_off.assert_awaited_once()
  748. mock_pm.mark_printer_offline.assert_called_once_with(1)
  749. # ---- _temp_based_off (temperature mode) ------------------------------
  750. @pytest.mark.asyncio
  751. async def test_temp_based_off_defers_while_printing_even_if_cool(self, manager):
  752. """Nozzle can dip below threshold during a reprint's PREPARE/heat phase;
  753. the guard must defer rather than cut power on the loaded print."""
  754. with (
  755. patch("backend.app.services.smart_plug_manager.printer_manager") as mock_pm,
  756. patch("backend.app.services.smart_plug_manager.asyncio.sleep", new_callable=AsyncMock) as mock_sleep,
  757. patch.object(manager, "get_service_for_plug", new_callable=AsyncMock) as mock_get_svc,
  758. ):
  759. # Cool enough to trip the threshold, but a print is active.
  760. mock_pm.get_status.return_value = MagicMock(state="PREPARE", temperatures={"nozzle": 30})
  761. mock_pm.is_print_active.return_value = True
  762. # Break the poll loop after the first deferral so the test terminates.
  763. mock_sleep.side_effect = asyncio.CancelledError()
  764. await manager._temp_based_off(1, "tasmota", "1.2.3.4", None, None, None, printer_id=1, temp_threshold=70)
  765. mock_get_svc.assert_not_called() # never turned off despite temp < threshold
  766. @pytest.mark.asyncio
  767. async def test_temp_based_off_powers_off_when_cool_and_idle(self, manager):
  768. """Cool nozzle + idle printer → turn off using the plug's threshold."""
  769. mock_service = AsyncMock()
  770. mock_service.turn_off = AsyncMock(return_value=True)
  771. with (
  772. patch("backend.app.services.smart_plug_manager.printer_manager") as mock_pm,
  773. patch("backend.app.services.smart_plug_manager.asyncio.sleep", new_callable=AsyncMock),
  774. patch.object(manager, "get_service_for_plug", new_callable=AsyncMock, return_value=mock_service),
  775. patch.object(manager, "_mark_auto_off_executed", new_callable=AsyncMock),
  776. ):
  777. mock_pm.get_status.return_value = MagicMock(state="FINISH", temperatures={"nozzle": 40})
  778. mock_pm.is_print_active.return_value = False
  779. await manager._temp_based_off(1, "tasmota", "1.2.3.4", None, None, None, printer_id=1, temp_threshold=55)
  780. mock_service.turn_off.assert_awaited_once()
  781. # ---- schedule_off_after_queue_job (uses plug settings, not hardcoded 50/600)
  782. @pytest.mark.asyncio
  783. async def test_queue_off_uses_time_mode_regardless_of_global_auto_off(self, manager, mock_plug):
  784. """Queue 'auto off after this job' is a per-job override — it schedules
  785. even when the plug's global auto_off is disabled, and honours the plug's
  786. configured time-delay mode."""
  787. mock_plug.auto_off = False
  788. mock_plug.off_delay_mode = "time"
  789. mock_plug.off_delay_minutes = 8
  790. with (
  791. patch.object(manager, "_get_plugs_for_printer", new_callable=AsyncMock, return_value=[mock_plug]),
  792. patch.object(manager, "_schedule_delayed_off") as mock_delayed,
  793. patch.object(manager, "_schedule_temp_based_off") as mock_temp,
  794. ):
  795. await manager.schedule_off_after_queue_job(printer_id=1, db=AsyncMock())
  796. mock_delayed.assert_called_once_with(mock_plug, 1, 8 * 60) # plug's minutes, not hardcoded
  797. mock_temp.assert_not_called()
  798. @pytest.mark.asyncio
  799. async def test_queue_off_uses_configured_temp_threshold(self, manager, mock_plug):
  800. """Temperature mode passes the plug's off_temp_threshold, not a hardcoded 50."""
  801. mock_plug.off_delay_mode = "temperature"
  802. mock_plug.off_temp_threshold = 65
  803. with (
  804. patch.object(manager, "_get_plugs_for_printer", new_callable=AsyncMock, return_value=[mock_plug]),
  805. patch.object(manager, "_schedule_delayed_off") as mock_delayed,
  806. patch.object(manager, "_schedule_temp_based_off") as mock_temp,
  807. ):
  808. await manager.schedule_off_after_queue_job(printer_id=1, db=AsyncMock())
  809. mock_temp.assert_called_once_with(mock_plug, 1, 65)
  810. mock_delayed.assert_not_called()
  811. @pytest.mark.asyncio
  812. async def test_queue_off_skips_disabled_and_ha_script_plugs(self, manager, mock_plug):
  813. """Disabled plugs and HA-script entities are never scheduled."""
  814. disabled = MagicMock(id=2, name="disabled", enabled=False, plug_type="tasmota", ha_entity_id=None)
  815. ha_script = MagicMock(
  816. id=3, name="ha", enabled=True, plug_type="homeassistant", ha_entity_id="script.printer_off"
  817. )
  818. with (
  819. patch.object(manager, "_get_plugs_for_printer", new_callable=AsyncMock, return_value=[disabled, ha_script]),
  820. patch.object(manager, "_schedule_off_per_mode") as mock_sched,
  821. ):
  822. await manager.schedule_off_after_queue_job(printer_id=1, db=AsyncMock())
  823. mock_sched.assert_not_called()
  824. # ---- on_print_start cancellation gap ---------------------------------
  825. @pytest.mark.asyncio
  826. async def test_reprint_cancels_pending_off_even_when_auto_on_disabled(self, manager, mock_plug):
  827. """A reprint must abort a scheduled auto-off regardless of auto_on (#1890).
  828. Previously the cancel lived behind the auto_on gate, so a plug with
  829. auto_on disabled kept its pending off and cut power mid-reprint.
  830. """
  831. mock_plug.auto_on = False
  832. mock_task = MagicMock()
  833. manager._pending_off[mock_plug.id] = mock_task
  834. with (
  835. patch.object(manager, "_get_plugs_for_printer", new_callable=AsyncMock, return_value=[mock_plug]),
  836. patch.object(manager, "_mark_auto_off_pending", new_callable=AsyncMock),
  837. patch("backend.app.services.smart_plug_manager.tasmota_service") as mock_tasmota,
  838. ):
  839. mock_tasmota.turn_on = AsyncMock()
  840. await manager.on_print_start(printer_id=1, db=AsyncMock())
  841. mock_task.cancel.assert_called_once() # cancelled despite auto_on=False
  842. assert mock_plug.id not in manager._pending_off
  843. mock_tasmota.turn_on.assert_not_called() # but not powered on
  844. class TestAccessoryPlugDoesNotMarkPrinterOffline:
  845. """#2629 — a plug linked to a printer is not necessarily its power supply.
  846. Filter fans, chamber lights and enclosure heaters are linked so they follow
  847. the print cycle. Marking the printer offline when one of those switches off
  848. blanks the printer state and stalls the queue until a manual Force Refresh.
  849. """
  850. @pytest.fixture
  851. def manager(self):
  852. return SmartPlugManager()
  853. @pytest.fixture
  854. def accessory_plug(self):
  855. plug = MagicMock()
  856. plug.id = 1
  857. plug.name = "BentoBox Filter"
  858. plug.ip_address = "192.168.1.100"
  859. plug.username = None
  860. plug.password = None
  861. plug.enabled = True
  862. plug.auto_off = True
  863. plug.off_delay_mode = "time"
  864. plug.off_delay_minutes = 1
  865. plug.off_temp_threshold = 70
  866. plug.printer_id = 1
  867. plug.plug_type = "tasmota"
  868. plug.ha_entity_id = None
  869. plug.controls_printer_power = False
  870. return plug
  871. @pytest.mark.asyncio
  872. async def test_delayed_off_skips_offline_mark_for_accessory(self, manager):
  873. mock_service = AsyncMock()
  874. mock_service.turn_off = AsyncMock(return_value=True)
  875. with (
  876. patch("backend.app.services.smart_plug_manager.printer_manager") as mock_pm,
  877. patch.object(manager, "get_service_for_plug", new_callable=AsyncMock, return_value=mock_service),
  878. patch.object(manager, "_mark_auto_off_executed", new_callable=AsyncMock),
  879. ):
  880. mock_pm.is_print_active.return_value = False
  881. await manager._delayed_off(
  882. 1, "tasmota", "1.2.3.4", None, None, None, printer_id=1, delay_seconds=0, controls_printer_power=False
  883. )
  884. mock_service.turn_off.assert_awaited_once() # the plug still switches off
  885. mock_pm.mark_printer_offline.assert_not_called() # but the printer is untouched
  886. @pytest.mark.asyncio
  887. async def test_temp_based_off_skips_offline_mark_for_accessory(self, manager):
  888. mock_service = AsyncMock()
  889. mock_service.turn_off = AsyncMock(return_value=True)
  890. with (
  891. patch("backend.app.services.smart_plug_manager.printer_manager") as mock_pm,
  892. patch("backend.app.services.smart_plug_manager.asyncio.sleep", new_callable=AsyncMock),
  893. patch.object(manager, "get_service_for_plug", new_callable=AsyncMock, return_value=mock_service),
  894. patch.object(manager, "_mark_auto_off_executed", new_callable=AsyncMock),
  895. ):
  896. mock_pm.get_status.return_value = MagicMock(state="FINISH", temperatures={"nozzle": 40})
  897. mock_pm.is_print_active.return_value = False
  898. await manager._temp_based_off(
  899. 1,
  900. "tasmota",
  901. "1.2.3.4",
  902. None,
  903. None,
  904. None,
  905. printer_id=1,
  906. temp_threshold=55,
  907. controls_printer_power=False,
  908. )
  909. mock_service.turn_off.assert_awaited_once()
  910. mock_pm.mark_printer_offline.assert_not_called()
  911. @pytest.mark.asyncio
  912. async def test_schedulers_forward_the_flag(self, manager, accessory_plug):
  913. """The flag lives on the plug row; both schedulers must pass it into the
  914. detached task, which only receives primitives."""
  915. with (
  916. patch.object(manager, "_mark_auto_off_pending", new_callable=AsyncMock),
  917. patch.object(manager, "_delayed_off", new_callable=AsyncMock) as mock_delayed,
  918. patch.object(manager, "_temp_based_off", new_callable=AsyncMock) as mock_temp,
  919. ):
  920. manager._schedule_delayed_off(accessory_plug, 1, 60)
  921. manager._schedule_temp_based_off(accessory_plug, 1, 70)
  922. assert mock_delayed.call_args.kwargs["controls_printer_power"] is False
  923. assert mock_temp.call_args.kwargs["controls_printer_power"] is False
  924. @pytest.mark.asyncio
  925. async def test_scheduled_off_skips_offline_mark_for_accessory(self, manager, accessory_plug):
  926. """The time-of-day schedule path has its own turn-off + offline mark."""
  927. accessory_plug.schedule_enabled = True
  928. accessory_plug.schedule_on_time = None
  929. accessory_plug.schedule_off_time = "22:00"
  930. with (
  931. patch("backend.app.services.smart_plug_manager.datetime") as mock_datetime,
  932. patch("backend.app.core.database.async_session") as mock_session_ctx,
  933. patch("backend.app.services.smart_plug_manager.tasmota_service") as mock_tasmota,
  934. patch("backend.app.services.smart_plug_manager.printer_manager") as mock_pm,
  935. ):
  936. mock_now = MagicMock()
  937. mock_now.strftime.return_value = "22:00"
  938. mock_datetime.now.return_value = mock_now
  939. mock_db = AsyncMock()
  940. mock_result = MagicMock()
  941. mock_result.scalars.return_value.all.return_value = [accessory_plug]
  942. mock_db.execute = AsyncMock(return_value=mock_result)
  943. mock_db.commit = AsyncMock()
  944. mock_session_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_db)
  945. mock_session_ctx.return_value.__aexit__ = AsyncMock()
  946. mock_tasmota.turn_off = AsyncMock(return_value=True)
  947. await manager._check_schedules()
  948. mock_tasmota.turn_off.assert_awaited_once_with(accessory_plug)
  949. mock_pm.mark_printer_offline.assert_not_called()
  950. @pytest.mark.asyncio
  951. async def test_scheduled_off_still_marks_offline_for_power_plug(self, manager, accessory_plug):
  952. """Default (a plug that really feeds the printer) keeps the old behaviour."""
  953. accessory_plug.controls_printer_power = True
  954. accessory_plug.schedule_enabled = True
  955. accessory_plug.schedule_on_time = None
  956. accessory_plug.schedule_off_time = "22:00"
  957. with (
  958. patch("backend.app.services.smart_plug_manager.datetime") as mock_datetime,
  959. patch("backend.app.core.database.async_session") as mock_session_ctx,
  960. patch("backend.app.services.smart_plug_manager.tasmota_service") as mock_tasmota,
  961. patch("backend.app.services.smart_plug_manager.printer_manager") as mock_pm,
  962. ):
  963. mock_now = MagicMock()
  964. mock_now.strftime.return_value = "22:00"
  965. mock_datetime.now.return_value = mock_now
  966. mock_db = AsyncMock()
  967. mock_result = MagicMock()
  968. mock_result.scalars.return_value.all.return_value = [accessory_plug]
  969. mock_db.execute = AsyncMock(return_value=mock_result)
  970. mock_db.commit = AsyncMock()
  971. mock_session_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_db)
  972. mock_session_ctx.return_value.__aexit__ = AsyncMock()
  973. mock_tasmota.turn_off = AsyncMock(return_value=True)
  974. await manager._check_schedules()
  975. mock_pm.mark_printer_offline.assert_called_once_with(1)