test_smart_plug_manager.py 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  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 (
  308. patch.object(manager, "_schedule_loop") as mock_loop,
  309. patch.object(manager, "_snapshot_loop"),
  310. patch.object(manager, "_power_alert_loop") as mock_power_alert,
  311. patch("asyncio.create_task") as mock_create,
  312. ):
  313. mock_create.return_value = MagicMock()
  314. manager.start_scheduler()
  315. assert manager._scheduler_task is not None
  316. mock_loop.assert_called_once()
  317. # Power alerts are checked in the background, not only while a page is open.
  318. assert manager._power_alert_task is not None
  319. mock_power_alert.assert_called_once()
  320. def test_stop_scheduler(self, manager):
  321. """Verify scheduler can be stopped."""
  322. mock_task = MagicMock()
  323. manager._scheduler_task = mock_task
  324. manager.stop_scheduler()
  325. mock_task.cancel.assert_called_once()
  326. assert manager._scheduler_task is None
  327. def test_start_scheduler_idempotent(self, manager):
  328. """Verify starting scheduler twice doesn't create multiple tasks."""
  329. mock_schedule_task = MagicMock()
  330. mock_snapshot_task = MagicMock()
  331. manager._scheduler_task = mock_schedule_task
  332. manager._snapshot_task = mock_snapshot_task
  333. manager._power_alert_task = MagicMock()
  334. # Mock the loop coroutines to avoid unawaited coroutine warnings
  335. with (
  336. patch.object(manager, "_schedule_loop") as mock_loop,
  337. patch.object(manager, "_snapshot_loop") as mock_snapshot,
  338. patch.object(manager, "_power_alert_loop") as mock_power_alert,
  339. patch("asyncio.create_task") as mock_create,
  340. ):
  341. manager.start_scheduler()
  342. mock_create.assert_not_called() # Should not create new tasks
  343. mock_loop.assert_not_called()
  344. mock_snapshot.assert_not_called()
  345. mock_power_alert.assert_not_called()
  346. def test_stop_scheduler_cancels_snapshot_task(self, manager):
  347. """Verify stopping scheduler also cancels the snapshot loop (#941)."""
  348. mock_schedule_task = MagicMock()
  349. mock_snapshot_task = MagicMock()
  350. manager._scheduler_task = mock_schedule_task
  351. manager._snapshot_task = mock_snapshot_task
  352. mock_power_alert_task = MagicMock()
  353. manager._power_alert_task = mock_power_alert_task
  354. manager.stop_scheduler()
  355. mock_schedule_task.cancel.assert_called_once()
  356. mock_snapshot_task.cancel.assert_called_once()
  357. mock_power_alert_task.cancel.assert_called_once()
  358. assert manager._power_alert_task is None
  359. assert manager._scheduler_task is None
  360. assert manager._snapshot_task is None
  361. class TestGetPlugsForPrinter:
  362. """Tests for _get_plugs_for_printer — returns all plugs for a printer (#903)."""
  363. @pytest.fixture
  364. def manager(self):
  365. return SmartPlugManager()
  366. @pytest.mark.asyncio
  367. async def test_returns_empty_list_when_no_plugs(self, manager):
  368. """Verify empty list is returned when no plugs are linked to printer."""
  369. mock_db = AsyncMock()
  370. mock_result = MagicMock()
  371. mock_result.scalars.return_value.all.return_value = []
  372. mock_db.execute = AsyncMock(return_value=mock_result)
  373. result = await manager._get_plugs_for_printer(1, mock_db)
  374. assert result == []
  375. @pytest.mark.asyncio
  376. async def test_returns_single_plug_as_list(self, manager):
  377. """Verify single plug is returned in a list."""
  378. plug = MagicMock()
  379. plug.plug_type = "tasmota"
  380. mock_db = AsyncMock()
  381. mock_result = MagicMock()
  382. mock_result.scalars.return_value.all.return_value = [plug]
  383. mock_db.execute = AsyncMock(return_value=mock_result)
  384. result = await manager._get_plugs_for_printer(1, mock_db)
  385. assert result == [plug]
  386. @pytest.mark.asyncio
  387. async def test_returns_all_plugs(self, manager):
  388. """Verify all plugs are returned when multiple exist (#903)."""
  389. plug1 = MagicMock()
  390. plug1.plug_type = "homeassistant"
  391. plug1.ha_entity_id = "switch.printer"
  392. plug2 = MagicMock()
  393. plug2.plug_type = "homeassistant"
  394. plug2.ha_entity_id = "switch.filter"
  395. mock_db = AsyncMock()
  396. mock_result = MagicMock()
  397. mock_result.scalars.return_value.all.return_value = [plug1, plug2]
  398. mock_db.execute = AsyncMock(return_value=mock_result)
  399. result = await manager._get_plugs_for_printer(1, mock_db)
  400. assert result == [plug1, plug2]
  401. class TestAutoOffPersistent:
  402. """Tests for persistent auto-off behavior (Issue #826).
  403. When auto_off_persistent is True, auto_off should remain enabled after
  404. execution instead of being disabled (one-shot default).
  405. """
  406. @pytest.fixture
  407. def manager(self):
  408. return SmartPlugManager()
  409. @pytest.mark.asyncio
  410. async def test_mark_auto_off_executed_one_shot_disables_auto_off(self, manager):
  411. """Default one-shot: auto_off should be set to False after execution."""
  412. mock_plug = MagicMock()
  413. mock_plug.id = 1
  414. mock_plug.auto_off = True
  415. mock_plug.auto_off_persistent = False
  416. mock_plug.auto_off_executed = False
  417. mock_plug.auto_off_pending = True
  418. mock_plug.auto_off_pending_since = datetime.now(timezone.utc)
  419. with patch("backend.app.core.database.async_session") as mock_session_ctx:
  420. mock_db = AsyncMock()
  421. mock_result = MagicMock()
  422. mock_result.scalar_one_or_none.return_value = mock_plug
  423. mock_db.execute = AsyncMock(return_value=mock_result)
  424. mock_db.commit = AsyncMock()
  425. mock_session_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_db)
  426. mock_session_ctx.return_value.__aexit__ = AsyncMock()
  427. await manager._mark_auto_off_executed(1)
  428. assert mock_plug.auto_off is False, "One-shot: auto_off should be disabled"
  429. assert mock_plug.auto_off_pending is False
  430. assert mock_plug.auto_off_pending_since is None
  431. mock_db.commit.assert_called_once()
  432. @pytest.mark.asyncio
  433. async def test_mark_auto_off_executed_persistent_keeps_auto_off_enabled(self, manager):
  434. """Persistent mode: auto_off should remain True after execution."""
  435. mock_plug = MagicMock()
  436. mock_plug.id = 2
  437. mock_plug.auto_off = True
  438. mock_plug.auto_off_persistent = True
  439. mock_plug.auto_off_executed = False
  440. mock_plug.auto_off_pending = True
  441. mock_plug.auto_off_pending_since = datetime.now(timezone.utc)
  442. with patch("backend.app.core.database.async_session") as mock_session_ctx:
  443. mock_db = AsyncMock()
  444. mock_result = MagicMock()
  445. mock_result.scalar_one_or_none.return_value = mock_plug
  446. mock_db.execute = AsyncMock(return_value=mock_result)
  447. mock_db.commit = AsyncMock()
  448. mock_session_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_db)
  449. mock_session_ctx.return_value.__aexit__ = AsyncMock()
  450. await manager._mark_auto_off_executed(2)
  451. assert mock_plug.auto_off is True, "Persistent: auto_off should stay enabled"
  452. assert mock_plug.auto_off_pending is False
  453. assert mock_plug.auto_off_pending_since is None
  454. mock_db.commit.assert_called_once()
  455. @pytest.mark.asyncio
  456. async def test_persistent_auto_off_full_cycle(self, manager):
  457. """Verify persistent auto-off survives a full print cycle.
  458. Simulates: print start → print complete → auto-off executes → next print start.
  459. auto_off should remain True throughout for persistent plugs.
  460. """
  461. mock_plug = MagicMock()
  462. mock_plug.id = 3
  463. mock_plug.name = "HA BentoBox Filter"
  464. mock_plug.plug_type = "homeassistant"
  465. mock_plug.ha_entity_id = "switch.bentobox_filter"
  466. mock_plug.ip_address = None
  467. mock_plug.username = None
  468. mock_plug.password = None
  469. mock_plug.enabled = True
  470. mock_plug.auto_on = True
  471. mock_plug.auto_off = True
  472. mock_plug.auto_off_persistent = True
  473. mock_plug.off_delay_mode = "time"
  474. mock_plug.off_delay_minutes = 1
  475. mock_plug.off_temp_threshold = 70
  476. mock_plug.printer_id = 1
  477. mock_plug.auto_off_executed = False
  478. mock_plug.auto_off_pending = False
  479. mock_plug.last_state = "OFF"
  480. mock_plug.last_checked = None
  481. mock_db = AsyncMock()
  482. mock_db.commit = AsyncMock()
  483. # Step 1: Print starts — plug turns on
  484. with (
  485. patch.object(manager, "_get_plugs_for_printer", new_callable=AsyncMock) as mock_get,
  486. patch.object(manager, "get_service_for_plug", new_callable=AsyncMock) as mock_svc,
  487. ):
  488. mock_get.return_value = [mock_plug]
  489. mock_service = AsyncMock()
  490. mock_service.turn_on = AsyncMock(return_value=True)
  491. mock_svc.return_value = mock_service
  492. await manager.on_print_start(printer_id=1, db=mock_db)
  493. assert mock_plug.auto_off_executed is False
  494. assert mock_plug.auto_off is True # Still enabled
  495. # Step 2: Print completes — auto-off is scheduled
  496. with (
  497. patch.object(manager, "_get_plugs_for_printer", new_callable=AsyncMock) as mock_get,
  498. patch.object(manager, "_schedule_delayed_off") as mock_schedule,
  499. ):
  500. mock_get.return_value = [mock_plug]
  501. await manager.on_print_complete(printer_id=1, status="completed", db=mock_db)
  502. mock_schedule.assert_called_once()
  503. assert mock_plug.auto_off is True # Still enabled after scheduling
  504. # Step 3: Auto-off executes via _mark_auto_off_executed
  505. with patch("backend.app.core.database.async_session") as mock_session_ctx:
  506. mock_db2 = AsyncMock()
  507. mock_result = MagicMock()
  508. mock_result.scalar_one_or_none.return_value = mock_plug
  509. mock_db2.execute = AsyncMock(return_value=mock_result)
  510. mock_db2.commit = AsyncMock()
  511. mock_session_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_db2)
  512. mock_session_ctx.return_value.__aexit__ = AsyncMock()
  513. await manager._mark_auto_off_executed(3)
  514. # KEY ASSERTION: auto_off stays True for persistent mode
  515. assert mock_plug.auto_off is True, "Persistent auto_off must survive execution"
  516. assert mock_plug.auto_off_pending is False
  517. class TestScheduleLoop:
  518. """Tests for the schedule-based plug control."""
  519. @pytest.fixture
  520. def manager(self):
  521. return SmartPlugManager()
  522. @pytest.mark.asyncio
  523. async def test_check_schedules_turns_on_at_scheduled_time(self, manager):
  524. """Verify scheduled on-time turns plug on."""
  525. mock_plug = MagicMock()
  526. mock_plug.id = 1
  527. mock_plug.name = "Test Plug"
  528. mock_plug.enabled = True
  529. mock_plug.schedule_enabled = True
  530. mock_plug.schedule_on_time = "08:00"
  531. mock_plug.schedule_off_time = "22:00"
  532. mock_plug.printer_id = None
  533. mock_plug.last_state = "OFF"
  534. with (
  535. patch("backend.app.services.smart_plug_manager.datetime") as mock_datetime,
  536. patch("backend.app.core.database.async_session") as mock_session_ctx,
  537. patch("backend.app.services.smart_plug_manager.tasmota_service") as mock_tasmota,
  538. ):
  539. # Set current time to 08:00
  540. mock_now = MagicMock()
  541. mock_now.strftime.return_value = "08:00"
  542. mock_datetime.now.return_value = mock_now
  543. mock_datetime.utcnow.return_value = datetime.now(timezone.utc)
  544. # Set up async session mock
  545. mock_db = AsyncMock()
  546. mock_result = MagicMock()
  547. mock_result.scalars.return_value.all.return_value = [mock_plug]
  548. mock_db.execute = AsyncMock(return_value=mock_result)
  549. mock_db.commit = AsyncMock()
  550. mock_session_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_db)
  551. mock_session_ctx.return_value.__aexit__ = AsyncMock()
  552. mock_tasmota.turn_on = AsyncMock(return_value=True)
  553. await manager._check_schedules()
  554. mock_tasmota.turn_on.assert_called_once_with(mock_plug)
  555. @pytest.mark.asyncio
  556. async def test_check_schedules_turns_off_at_scheduled_time(self, manager):
  557. """Verify scheduled off-time turns plug off."""
  558. mock_plug = MagicMock()
  559. mock_plug.id = 1
  560. mock_plug.name = "Test Plug"
  561. mock_plug.enabled = True
  562. mock_plug.schedule_enabled = True
  563. mock_plug.schedule_on_time = "08:00"
  564. mock_plug.schedule_off_time = "22:00"
  565. mock_plug.printer_id = 1
  566. mock_plug.last_state = "ON"
  567. with (
  568. patch("backend.app.services.smart_plug_manager.datetime") as mock_datetime,
  569. patch("backend.app.core.database.async_session") as mock_session_ctx,
  570. patch("backend.app.services.smart_plug_manager.tasmota_service") as mock_tasmota,
  571. patch("backend.app.services.smart_plug_manager.printer_manager") as mock_pm,
  572. ):
  573. # Set current time to 22:00
  574. mock_now = MagicMock()
  575. mock_now.strftime.return_value = "22:00"
  576. mock_datetime.now.return_value = mock_now
  577. mock_datetime.utcnow.return_value = datetime.now(timezone.utc)
  578. # Set up async session mock
  579. mock_db = AsyncMock()
  580. mock_result = MagicMock()
  581. mock_result.scalars.return_value.all.return_value = [mock_plug]
  582. mock_db.execute = AsyncMock(return_value=mock_result)
  583. mock_db.commit = AsyncMock()
  584. mock_session_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_db)
  585. mock_session_ctx.return_value.__aexit__ = AsyncMock()
  586. mock_tasmota.turn_off = AsyncMock(return_value=True)
  587. mock_pm.mark_printer_offline = MagicMock()
  588. await manager._check_schedules()
  589. mock_tasmota.turn_off.assert_called_once_with(mock_plug)
  590. @pytest.mark.asyncio
  591. async def test_check_schedules_skipped_when_disabled(self, manager):
  592. """Verify schedule is skipped when schedule_enabled is False."""
  593. mock_plug = MagicMock()
  594. mock_plug.id = 1
  595. mock_plug.enabled = True
  596. mock_plug.schedule_enabled = False # Disabled
  597. with (
  598. patch("backend.app.services.smart_plug_manager.datetime") as mock_datetime,
  599. patch("backend.app.core.database.async_session") as mock_session_ctx,
  600. patch("backend.app.services.smart_plug_manager.tasmota_service") as mock_tasmota,
  601. ):
  602. mock_now = MagicMock()
  603. mock_now.strftime.return_value = "08:00"
  604. mock_datetime.now.return_value = mock_now
  605. # Set up async session mock - returns no plugs (filtered by schedule_enabled)
  606. mock_db = AsyncMock()
  607. mock_result = MagicMock()
  608. mock_result.scalars.return_value.all.return_value = []
  609. mock_db.execute = AsyncMock(return_value=mock_result)
  610. mock_db.commit = AsyncMock()
  611. mock_session_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_db)
  612. mock_session_ctx.return_value.__aexit__ = AsyncMock()
  613. mock_tasmota.turn_on = AsyncMock()
  614. await manager._check_schedules()
  615. mock_tasmota.turn_on.assert_not_called()
  616. class TestPendingAutoOffPersistence:
  617. """Tests for auto-off pending state persistence (restart recovery)."""
  618. @pytest.fixture
  619. def manager(self):
  620. return SmartPlugManager()
  621. @pytest.mark.asyncio
  622. async def test_resume_pending_auto_offs_temperature_mode(self, manager):
  623. """Verify temperature-based pending auto-offs are resumed on startup."""
  624. mock_plug = MagicMock()
  625. mock_plug.id = 1
  626. mock_plug.name = "Test Plug"
  627. mock_plug.ip_address = "192.168.1.100"
  628. mock_plug.username = None
  629. mock_plug.password = None
  630. mock_plug.printer_id = 1
  631. mock_plug.auto_off_pending = True
  632. mock_plug.auto_off_pending_since = datetime.now(timezone.utc)
  633. mock_plug.off_delay_mode = "temperature"
  634. mock_plug.off_temp_threshold = 70
  635. with (
  636. patch("backend.app.core.database.async_session") as mock_session_ctx,
  637. patch.object(manager, "_schedule_temp_based_off") as mock_schedule,
  638. ):
  639. mock_db = AsyncMock()
  640. mock_result = MagicMock()
  641. mock_result.scalars.return_value.all.return_value = [mock_plug]
  642. mock_db.execute = AsyncMock(return_value=mock_result)
  643. mock_session_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_db)
  644. mock_session_ctx.return_value.__aexit__ = AsyncMock()
  645. await manager.resume_pending_auto_offs()
  646. mock_schedule.assert_called_once_with(mock_plug, 1, 70)
  647. @pytest.mark.asyncio
  648. async def test_resume_pending_auto_offs_time_mode_immediate_off(self, manager):
  649. """Verify time-based pending auto-offs turn off immediately on resume."""
  650. mock_plug = MagicMock()
  651. mock_plug.id = 1
  652. mock_plug.name = "Test Plug"
  653. mock_plug.ip_address = "192.168.1.100"
  654. mock_plug.username = None
  655. mock_plug.password = None
  656. mock_plug.printer_id = 1
  657. mock_plug.auto_off_pending = True
  658. mock_plug.auto_off_pending_since = datetime.now(timezone.utc)
  659. mock_plug.off_delay_mode = "time"
  660. with (
  661. patch("backend.app.core.database.async_session") as mock_session_ctx,
  662. patch("backend.app.services.smart_plug_manager.tasmota_service") as mock_tasmota,
  663. patch.object(manager, "_mark_auto_off_executed", new_callable=AsyncMock) as mock_mark,
  664. patch("backend.app.services.smart_plug_manager.printer_manager") as mock_pm,
  665. ):
  666. mock_db = AsyncMock()
  667. mock_result = MagicMock()
  668. mock_result.scalars.return_value.all.return_value = [mock_plug]
  669. mock_db.execute = AsyncMock(return_value=mock_result)
  670. mock_session_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_db)
  671. mock_session_ctx.return_value.__aexit__ = AsyncMock()
  672. mock_tasmota.turn_off = AsyncMock(return_value=True)
  673. mock_pm.is_print_active.return_value = False # printer idle on restart
  674. await manager.resume_pending_auto_offs()
  675. mock_tasmota.turn_off.assert_called_once()
  676. mock_mark.assert_called_once_with(1)
  677. @pytest.mark.asyncio
  678. async def test_resume_pending_auto_off_skipped_when_printing(self, manager):
  679. """#1890: on restart, a stale pending off must NOT power off a live print;
  680. the pending flag is cleared instead."""
  681. mock_plug = MagicMock()
  682. mock_plug.id = 1
  683. mock_plug.name = "Test Plug"
  684. mock_plug.printer_id = 1
  685. mock_plug.auto_off_pending = True
  686. mock_plug.auto_off_pending_since = datetime.now(timezone.utc)
  687. mock_plug.off_delay_mode = "time"
  688. with (
  689. patch("backend.app.core.database.async_session") as mock_session_ctx,
  690. patch("backend.app.services.smart_plug_manager.tasmota_service") as mock_tasmota,
  691. patch("backend.app.services.smart_plug_manager.printer_manager") as mock_pm,
  692. patch.object(manager, "_schedule_temp_based_off") as mock_temp,
  693. ):
  694. mock_db = AsyncMock()
  695. mock_result = MagicMock()
  696. mock_result.scalars.return_value.all.return_value = [mock_plug]
  697. mock_db.execute = AsyncMock(return_value=mock_result)
  698. mock_session_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_db)
  699. mock_session_ctx.return_value.__aexit__ = AsyncMock()
  700. mock_tasmota.turn_off = AsyncMock(return_value=True)
  701. mock_pm.is_print_active.return_value = True # printer printing again on restart
  702. mock_pm.get_status.return_value = MagicMock(state="RUNNING")
  703. await manager.resume_pending_auto_offs()
  704. mock_tasmota.turn_off.assert_not_called() # never cut power on the live print
  705. mock_temp.assert_not_called()
  706. assert mock_plug.auto_off_pending is False # stale pending cleared
  707. class TestActivePrintGuard:
  708. """#1890 — auto-off must never cut power while a print is loaded/running.
  709. Covers the two off-executors (`_delayed_off`, `_temp_based_off`), the new
  710. queue-override scheduler that honours per-plug settings, and the
  711. on_print_start cancellation gap.
  712. """
  713. @pytest.fixture
  714. def manager(self):
  715. return SmartPlugManager()
  716. @pytest.fixture
  717. def mock_plug(self):
  718. plug = MagicMock()
  719. plug.id = 1
  720. plug.name = "Test Plug"
  721. plug.ip_address = "192.168.1.100"
  722. plug.username = None
  723. plug.password = None
  724. plug.enabled = True
  725. plug.auto_on = True
  726. plug.auto_off = True
  727. plug.off_delay_mode = "time"
  728. plug.off_delay_minutes = 5
  729. plug.off_temp_threshold = 70
  730. plug.printer_id = 1
  731. plug.plug_type = "tasmota"
  732. plug.ha_entity_id = None
  733. return plug
  734. # ---- _delayed_off (time mode) ----------------------------------------
  735. @pytest.mark.asyncio
  736. async def test_delayed_off_skips_when_printer_printing_again(self, manager):
  737. """Time-delay fires after N min; if a reprint is running, skip the off."""
  738. with (
  739. patch("backend.app.services.smart_plug_manager.printer_manager") as mock_pm,
  740. patch.object(manager, "get_service_for_plug", new_callable=AsyncMock) as mock_get_svc,
  741. patch.object(manager, "_mark_auto_off_pending", new_callable=AsyncMock) as mock_mark_pending,
  742. patch.object(manager, "_mark_auto_off_executed", new_callable=AsyncMock) as mock_mark_exec,
  743. ):
  744. mock_pm.is_print_active.return_value = True
  745. mock_pm.get_status.return_value = MagicMock(state="RUNNING")
  746. await manager._delayed_off(1, "tasmota", "1.2.3.4", None, None, None, printer_id=1, delay_seconds=0)
  747. mock_get_svc.assert_not_called() # never even resolved a service to turn off
  748. mock_mark_exec.assert_not_called()
  749. mock_mark_pending.assert_awaited_with(1, False) # pending flag cleared
  750. @pytest.mark.asyncio
  751. async def test_delayed_off_powers_off_when_idle(self, manager):
  752. """When the printer is genuinely idle, the delayed off still fires."""
  753. mock_service = AsyncMock()
  754. mock_service.turn_off = AsyncMock(return_value=True)
  755. with (
  756. patch("backend.app.services.smart_plug_manager.printer_manager") as mock_pm,
  757. patch.object(manager, "get_service_for_plug", new_callable=AsyncMock, return_value=mock_service),
  758. patch.object(manager, "_mark_auto_off_executed", new_callable=AsyncMock),
  759. ):
  760. mock_pm.is_print_active.return_value = False
  761. await manager._delayed_off(1, "tasmota", "1.2.3.4", None, None, None, printer_id=1, delay_seconds=0)
  762. mock_service.turn_off.assert_awaited_once()
  763. mock_pm.mark_printer_offline.assert_called_once_with(1)
  764. # ---- _temp_based_off (temperature mode) ------------------------------
  765. @pytest.mark.asyncio
  766. async def test_temp_based_off_defers_while_printing_even_if_cool(self, manager):
  767. """Nozzle can dip below threshold during a reprint's PREPARE/heat phase;
  768. the guard must defer rather than cut power on the loaded print."""
  769. with (
  770. patch("backend.app.services.smart_plug_manager.printer_manager") as mock_pm,
  771. patch("backend.app.services.smart_plug_manager.asyncio.sleep", new_callable=AsyncMock) as mock_sleep,
  772. patch.object(manager, "get_service_for_plug", new_callable=AsyncMock) as mock_get_svc,
  773. ):
  774. # Cool enough to trip the threshold, but a print is active.
  775. mock_pm.get_status.return_value = MagicMock(state="PREPARE", temperatures={"nozzle": 30})
  776. mock_pm.is_print_active.return_value = True
  777. # Break the poll loop after the first deferral so the test terminates.
  778. mock_sleep.side_effect = asyncio.CancelledError()
  779. await manager._temp_based_off(1, "tasmota", "1.2.3.4", None, None, None, printer_id=1, temp_threshold=70)
  780. mock_get_svc.assert_not_called() # never turned off despite temp < threshold
  781. @pytest.mark.asyncio
  782. async def test_temp_based_off_powers_off_when_cool_and_idle(self, manager):
  783. """Cool nozzle + idle printer → turn off using the plug's threshold."""
  784. mock_service = AsyncMock()
  785. mock_service.turn_off = AsyncMock(return_value=True)
  786. with (
  787. patch("backend.app.services.smart_plug_manager.printer_manager") as mock_pm,
  788. patch("backend.app.services.smart_plug_manager.asyncio.sleep", new_callable=AsyncMock),
  789. patch.object(manager, "get_service_for_plug", new_callable=AsyncMock, return_value=mock_service),
  790. patch.object(manager, "_mark_auto_off_executed", new_callable=AsyncMock),
  791. ):
  792. mock_pm.get_status.return_value = MagicMock(state="FINISH", temperatures={"nozzle": 40})
  793. mock_pm.is_print_active.return_value = False
  794. await manager._temp_based_off(1, "tasmota", "1.2.3.4", None, None, None, printer_id=1, temp_threshold=55)
  795. mock_service.turn_off.assert_awaited_once()
  796. # ---- schedule_off_after_queue_job (uses plug settings, not hardcoded 50/600)
  797. @pytest.mark.asyncio
  798. async def test_queue_off_uses_time_mode_regardless_of_global_auto_off(self, manager, mock_plug):
  799. """Queue 'auto off after this job' is a per-job override — it schedules
  800. even when the plug's global auto_off is disabled, and honours the plug's
  801. configured time-delay mode."""
  802. mock_plug.auto_off = False
  803. mock_plug.off_delay_mode = "time"
  804. mock_plug.off_delay_minutes = 8
  805. with (
  806. patch.object(manager, "_get_plugs_for_printer", new_callable=AsyncMock, return_value=[mock_plug]),
  807. patch.object(manager, "_schedule_delayed_off") as mock_delayed,
  808. patch.object(manager, "_schedule_temp_based_off") as mock_temp,
  809. ):
  810. await manager.schedule_off_after_queue_job(printer_id=1, db=AsyncMock())
  811. mock_delayed.assert_called_once_with(mock_plug, 1, 8 * 60) # plug's minutes, not hardcoded
  812. mock_temp.assert_not_called()
  813. @pytest.mark.asyncio
  814. async def test_queue_off_uses_configured_temp_threshold(self, manager, mock_plug):
  815. """Temperature mode passes the plug's off_temp_threshold, not a hardcoded 50."""
  816. mock_plug.off_delay_mode = "temperature"
  817. mock_plug.off_temp_threshold = 65
  818. with (
  819. patch.object(manager, "_get_plugs_for_printer", new_callable=AsyncMock, return_value=[mock_plug]),
  820. patch.object(manager, "_schedule_delayed_off") as mock_delayed,
  821. patch.object(manager, "_schedule_temp_based_off") as mock_temp,
  822. ):
  823. await manager.schedule_off_after_queue_job(printer_id=1, db=AsyncMock())
  824. mock_temp.assert_called_once_with(mock_plug, 1, 65)
  825. mock_delayed.assert_not_called()
  826. @pytest.mark.asyncio
  827. async def test_queue_off_skips_disabled_and_ha_script_plugs(self, manager, mock_plug):
  828. """Disabled plugs and HA-script entities are never scheduled."""
  829. disabled = MagicMock(id=2, name="disabled", enabled=False, plug_type="tasmota", ha_entity_id=None)
  830. ha_script = MagicMock(
  831. id=3, name="ha", enabled=True, plug_type="homeassistant", ha_entity_id="script.printer_off"
  832. )
  833. with (
  834. patch.object(manager, "_get_plugs_for_printer", new_callable=AsyncMock, return_value=[disabled, ha_script]),
  835. patch.object(manager, "_schedule_off_per_mode") as mock_sched,
  836. ):
  837. await manager.schedule_off_after_queue_job(printer_id=1, db=AsyncMock())
  838. mock_sched.assert_not_called()
  839. # ---- on_print_start cancellation gap ---------------------------------
  840. @pytest.mark.asyncio
  841. async def test_reprint_cancels_pending_off_even_when_auto_on_disabled(self, manager, mock_plug):
  842. """A reprint must abort a scheduled auto-off regardless of auto_on (#1890).
  843. Previously the cancel lived behind the auto_on gate, so a plug with
  844. auto_on disabled kept its pending off and cut power mid-reprint.
  845. """
  846. mock_plug.auto_on = False
  847. mock_task = MagicMock()
  848. manager._pending_off[mock_plug.id] = mock_task
  849. with (
  850. patch.object(manager, "_get_plugs_for_printer", new_callable=AsyncMock, return_value=[mock_plug]),
  851. patch.object(manager, "_mark_auto_off_pending", new_callable=AsyncMock),
  852. patch("backend.app.services.smart_plug_manager.tasmota_service") as mock_tasmota,
  853. ):
  854. mock_tasmota.turn_on = AsyncMock()
  855. await manager.on_print_start(printer_id=1, db=AsyncMock())
  856. mock_task.cancel.assert_called_once() # cancelled despite auto_on=False
  857. assert mock_plug.id not in manager._pending_off
  858. mock_tasmota.turn_on.assert_not_called() # but not powered on
  859. class TestAccessoryPlugDoesNotMarkPrinterOffline:
  860. """#2629 — a plug linked to a printer is not necessarily its power supply.
  861. Filter fans, chamber lights and enclosure heaters are linked so they follow
  862. the print cycle. Marking the printer offline when one of those switches off
  863. blanks the printer state and stalls the queue until a manual Force Refresh.
  864. """
  865. @pytest.fixture
  866. def manager(self):
  867. return SmartPlugManager()
  868. @pytest.fixture
  869. def accessory_plug(self):
  870. plug = MagicMock()
  871. plug.id = 1
  872. plug.name = "BentoBox Filter"
  873. plug.ip_address = "192.168.1.100"
  874. plug.username = None
  875. plug.password = None
  876. plug.enabled = True
  877. plug.auto_off = True
  878. plug.off_delay_mode = "time"
  879. plug.off_delay_minutes = 1
  880. plug.off_temp_threshold = 70
  881. plug.printer_id = 1
  882. plug.plug_type = "tasmota"
  883. plug.ha_entity_id = None
  884. plug.controls_printer_power = False
  885. return plug
  886. @pytest.mark.asyncio
  887. async def test_delayed_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.object(manager, "get_service_for_plug", new_callable=AsyncMock, return_value=mock_service),
  893. patch.object(manager, "_mark_auto_off_executed", new_callable=AsyncMock),
  894. ):
  895. mock_pm.is_print_active.return_value = False
  896. await manager._delayed_off(
  897. 1, "tasmota", "1.2.3.4", None, None, None, printer_id=1, delay_seconds=0, controls_printer_power=False
  898. )
  899. mock_service.turn_off.assert_awaited_once() # the plug still switches off
  900. mock_pm.mark_printer_offline.assert_not_called() # but the printer is untouched
  901. @pytest.mark.asyncio
  902. async def test_temp_based_off_skips_offline_mark_for_accessory(self, manager):
  903. mock_service = AsyncMock()
  904. mock_service.turn_off = AsyncMock(return_value=True)
  905. with (
  906. patch("backend.app.services.smart_plug_manager.printer_manager") as mock_pm,
  907. patch("backend.app.services.smart_plug_manager.asyncio.sleep", new_callable=AsyncMock),
  908. patch.object(manager, "get_service_for_plug", new_callable=AsyncMock, return_value=mock_service),
  909. patch.object(manager, "_mark_auto_off_executed", new_callable=AsyncMock),
  910. ):
  911. mock_pm.get_status.return_value = MagicMock(state="FINISH", temperatures={"nozzle": 40})
  912. mock_pm.is_print_active.return_value = False
  913. await manager._temp_based_off(
  914. 1,
  915. "tasmota",
  916. "1.2.3.4",
  917. None,
  918. None,
  919. None,
  920. printer_id=1,
  921. temp_threshold=55,
  922. controls_printer_power=False,
  923. )
  924. mock_service.turn_off.assert_awaited_once()
  925. mock_pm.mark_printer_offline.assert_not_called()
  926. @pytest.mark.asyncio
  927. async def test_schedulers_forward_the_flag(self, manager, accessory_plug):
  928. """The flag lives on the plug row; both schedulers must pass it into the
  929. detached task, which only receives primitives."""
  930. with (
  931. patch.object(manager, "_mark_auto_off_pending", new_callable=AsyncMock),
  932. patch.object(manager, "_delayed_off", new_callable=AsyncMock) as mock_delayed,
  933. patch.object(manager, "_temp_based_off", new_callable=AsyncMock) as mock_temp,
  934. ):
  935. manager._schedule_delayed_off(accessory_plug, 1, 60)
  936. manager._schedule_temp_based_off(accessory_plug, 1, 70)
  937. assert mock_delayed.call_args.kwargs["controls_printer_power"] is False
  938. assert mock_temp.call_args.kwargs["controls_printer_power"] is False
  939. @pytest.mark.asyncio
  940. async def test_scheduled_off_skips_offline_mark_for_accessory(self, manager, accessory_plug):
  941. """The time-of-day schedule path has its own turn-off + offline mark."""
  942. accessory_plug.schedule_enabled = True
  943. accessory_plug.schedule_on_time = None
  944. accessory_plug.schedule_off_time = "22:00"
  945. with (
  946. patch("backend.app.services.smart_plug_manager.datetime") as mock_datetime,
  947. patch("backend.app.core.database.async_session") as mock_session_ctx,
  948. patch("backend.app.services.smart_plug_manager.tasmota_service") as mock_tasmota,
  949. patch("backend.app.services.smart_plug_manager.printer_manager") as mock_pm,
  950. ):
  951. mock_now = MagicMock()
  952. mock_now.strftime.return_value = "22:00"
  953. mock_datetime.now.return_value = mock_now
  954. mock_db = AsyncMock()
  955. mock_result = MagicMock()
  956. mock_result.scalars.return_value.all.return_value = [accessory_plug]
  957. mock_db.execute = AsyncMock(return_value=mock_result)
  958. mock_db.commit = AsyncMock()
  959. mock_session_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_db)
  960. mock_session_ctx.return_value.__aexit__ = AsyncMock()
  961. mock_tasmota.turn_off = AsyncMock(return_value=True)
  962. await manager._check_schedules()
  963. mock_tasmota.turn_off.assert_awaited_once_with(accessory_plug)
  964. mock_pm.mark_printer_offline.assert_not_called()
  965. @pytest.mark.asyncio
  966. async def test_scheduled_off_still_marks_offline_for_power_plug(self, manager, accessory_plug):
  967. """Default (a plug that really feeds the printer) keeps the old behaviour."""
  968. accessory_plug.controls_printer_power = True
  969. accessory_plug.schedule_enabled = True
  970. accessory_plug.schedule_on_time = None
  971. accessory_plug.schedule_off_time = "22:00"
  972. with (
  973. patch("backend.app.services.smart_plug_manager.datetime") as mock_datetime,
  974. patch("backend.app.core.database.async_session") as mock_session_ctx,
  975. patch("backend.app.services.smart_plug_manager.tasmota_service") as mock_tasmota,
  976. patch("backend.app.services.smart_plug_manager.printer_manager") as mock_pm,
  977. ):
  978. mock_now = MagicMock()
  979. mock_now.strftime.return_value = "22:00"
  980. mock_datetime.now.return_value = mock_now
  981. mock_db = AsyncMock()
  982. mock_result = MagicMock()
  983. mock_result.scalars.return_value.all.return_value = [accessory_plug]
  984. mock_db.execute = AsyncMock(return_value=mock_result)
  985. mock_db.commit = AsyncMock()
  986. mock_session_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_db)
  987. mock_session_ctx.return_value.__aexit__ = AsyncMock()
  988. mock_tasmota.turn_off = AsyncMock(return_value=True)
  989. await manager._check_schedules()
  990. mock_pm.mark_printer_offline.assert_called_once_with(1)