test_smart_plug_manager.py 52 KB

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