test_smart_plug_manager.py 53 KB

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