test_scheduler_preheat.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. """Tests for the preheat & heat-soak scheduler stage (#1468).
  2. Three layered concerns the stage has to get right:
  3. 1. **Override resolution** (per-item beats global beats default).
  4. 2. **Chamber-target derivation** (item-override > filament-map max > 0).
  5. 3. **Hardware-tier branching** (chamber heater vs sensor-only vs no sensor).
  6. The fixtures construct a queue item with `preheat_override` + the override
  7. target both unset; tests flip those per case. `asyncio.sleep` is patched to
  8. AsyncMock so the soak phase doesn't actually wait — assertions are on what
  9. got scheduled, not wall-clock.
  10. """
  11. from types import SimpleNamespace
  12. from unittest.mock import AsyncMock, MagicMock, patch
  13. import pytest
  14. from backend.app.services.print_scheduler import PrintScheduler
  15. @pytest.fixture
  16. def scheduler():
  17. return PrintScheduler()
  18. @pytest.fixture
  19. def item():
  20. return SimpleNamespace(
  21. id=42,
  22. preheat_override="inherit",
  23. preheat_chamber_target_override=None,
  24. )
  25. @pytest.fixture
  26. def archive():
  27. return SimpleNamespace(bed_temperature=60)
  28. def _make_printer(model: str, printer_id: int = 7):
  29. return SimpleNamespace(id=printer_id, model=model)
  30. def _make_client():
  31. client = MagicMock()
  32. client.set_bed_temperature = MagicMock(return_value=True)
  33. client.set_chamber_temperature = MagicMock(return_value=True)
  34. client.set_airduct_mode = MagicMock(return_value=True)
  35. return client
  36. def _make_state(
  37. bed_temp: float = 0.0,
  38. chamber_temp: float = 0.0,
  39. trays: list[str] | None = None,
  40. airduct_mode: int = 0,
  41. ):
  42. """Build a PrinterState-shaped namespace with optional AMS tray types.
  43. `trays` is a list of tray_type strings (each becomes one loaded slot in
  44. AMS unit 0). Empty / None gives an empty AMS — the derivation falls
  45. through to 0. `airduct_mode` is 0 (cooling, default) or 1 (heating);
  46. matches the field on PrinterState that the preheat stage reads to
  47. decide whether to fire a redundant `set_airduct_mode` call."""
  48. raw_data: dict = {}
  49. if trays is not None:
  50. raw_data["ams"] = [{"tray": [{"tray_type": t} for t in trays]}]
  51. return SimpleNamespace(
  52. temperatures={"bed": bed_temp, "chamber": chamber_temp},
  53. raw_data=raw_data,
  54. airduct_mode=airduct_mode,
  55. )
  56. def _ints(**values):
  57. """Mock side_effect for _get_int_setting that returns the kwarg value
  58. when the key matches, else the helper's `default` argument."""
  59. return AsyncMock(side_effect=lambda _db, key, default: values.get(key, default))
  60. # ----------------------------------------------------------------------------
  61. # Override resolution
  62. # ----------------------------------------------------------------------------
  63. @pytest.mark.asyncio
  64. async def test_global_disabled_inherit_skips(scheduler, item, archive):
  65. """preheat_enabled=False + item.preheat_override='inherit' → no heater dispatch."""
  66. db = AsyncMock()
  67. client = _make_client()
  68. with (
  69. patch.object(scheduler, "_get_bool_setting", AsyncMock(return_value=False)),
  70. patch.object(scheduler, "_get_int_setting", _ints()),
  71. patch("backend.app.services.print_scheduler.printer_manager") as pm,
  72. ):
  73. pm.get_client.return_value = client
  74. await scheduler._preheat_and_soak(db, item, _make_printer("H2D"), archive)
  75. client.set_bed_temperature.assert_not_called()
  76. client.set_chamber_temperature.assert_not_called()
  77. @pytest.mark.asyncio
  78. async def test_item_override_off_bypasses_global_on(scheduler, item, archive):
  79. """preheat_enabled=True + item.preheat_override='off' → preheat suppressed."""
  80. db = AsyncMock()
  81. client = _make_client()
  82. item.preheat_override = "off"
  83. with (
  84. patch.object(scheduler, "_get_bool_setting", AsyncMock(return_value=True)),
  85. patch.object(scheduler, "_get_int_setting", _ints()),
  86. patch("backend.app.services.print_scheduler.printer_manager") as pm,
  87. ):
  88. pm.get_client.return_value = client
  89. await scheduler._preheat_and_soak(db, item, _make_printer("H2D"), archive)
  90. client.set_bed_temperature.assert_not_called()
  91. client.set_chamber_temperature.assert_not_called()
  92. @pytest.mark.asyncio
  93. async def test_item_override_on_runs_despite_global_off(scheduler, item, archive):
  94. """preheat_enabled=False + item.preheat_override='on' → preheat runs (bed
  95. fires, chamber depends on the resolved target)."""
  96. db = AsyncMock()
  97. client = _make_client()
  98. item.preheat_override = "on"
  99. item.preheat_chamber_target_override = 0 # explicit no-chamber so the assertion is sharp
  100. with (
  101. patch.object(scheduler, "_get_bool_setting", AsyncMock(return_value=False)),
  102. patch.object(scheduler, "_get_int_setting", _ints(preheat_soak_seconds=0)),
  103. patch("backend.app.services.print_scheduler.printer_manager") as pm,
  104. patch("backend.app.services.print_scheduler.asyncio.sleep", AsyncMock()),
  105. ):
  106. pm.get_client.return_value = client
  107. pm.get_status.return_value = _make_state(60.0, 0.0)
  108. await scheduler._preheat_and_soak(db, item, _make_printer("H2D"), archive)
  109. client.set_bed_temperature.assert_called_once_with(60)
  110. client.set_chamber_temperature.assert_not_called()
  111. # ----------------------------------------------------------------------------
  112. # Chamber-target derivation
  113. # ----------------------------------------------------------------------------
  114. @pytest.mark.asyncio
  115. async def test_chamber_target_override_beats_filament_map(scheduler, item, archive):
  116. """item.preheat_chamber_target_override is the highest-priority source —
  117. a PLA-only print with an explicit 50°C override still heats the chamber."""
  118. db = AsyncMock()
  119. client = _make_client()
  120. item.preheat_chamber_target_override = 50
  121. with (
  122. patch.object(scheduler, "_get_bool_setting", AsyncMock(return_value=True)),
  123. patch.object(scheduler, "_get_int_setting", _ints(preheat_soak_seconds=0)),
  124. patch("backend.app.services.print_scheduler.printer_manager") as pm,
  125. patch("backend.app.services.print_scheduler.asyncio.sleep", AsyncMock()),
  126. ):
  127. pm.get_client.return_value = client
  128. # Only PLA loaded — filament map would derive 0; override forces 50.
  129. pm.get_status.return_value = _make_state(60.0, 52.0, trays=["PLA Basic"])
  130. await scheduler._preheat_and_soak(db, item, _make_printer("H2D"), archive)
  131. client.set_bed_temperature.assert_called_once_with(60)
  132. client.set_chamber_temperature.assert_called_once_with(50)
  133. @pytest.mark.asyncio
  134. async def test_filament_map_picks_max_across_loaded_slots(scheduler, item, archive):
  135. """Mixed PA + PLA load: PA=50 + PLA=0 → chamber target 50 (the max).
  136. The "lowest common denominator" model is wrong here; PA's requirement
  137. is the binding constraint."""
  138. db = AsyncMock()
  139. client = _make_client()
  140. with (
  141. patch.object(scheduler, "_get_bool_setting", AsyncMock(return_value=True)),
  142. patch.object(scheduler, "_get_int_setting", _ints(preheat_soak_seconds=0)),
  143. patch.object(scheduler, "_get_setting", AsyncMock(return_value=None)),
  144. patch("backend.app.services.print_scheduler.printer_manager") as pm,
  145. patch("backend.app.services.print_scheduler.asyncio.sleep", AsyncMock()),
  146. ):
  147. pm.get_client.return_value = client
  148. # `PA Basic` (note the space) normalises to `PA` which the bundled
  149. # map keys against; a hyphenated `PA-Generic` would normalise to
  150. # `PA-GENERIC` and fall through to `default` (0) — that's a separate
  151. # behaviour the user editor handles by adding a custom key.
  152. pm.get_status.return_value = _make_state(60.0, 52.0, trays=["PLA Basic", "PA Basic"])
  153. await scheduler._preheat_and_soak(db, item, _make_printer("H2D"), archive)
  154. client.set_chamber_temperature.assert_called_once_with(50) # PA's recommendation, not PLA's
  155. @pytest.mark.asyncio
  156. async def test_pla_only_derives_zero_chamber_skips(scheduler, item, archive):
  157. """PLA-only print: filament-map lookup returns 0 → chamber phase skips
  158. automatically without the user touching anything."""
  159. db = AsyncMock()
  160. client = _make_client()
  161. with (
  162. patch.object(scheduler, "_get_bool_setting", AsyncMock(return_value=True)),
  163. patch.object(scheduler, "_get_int_setting", _ints(preheat_soak_seconds=0)),
  164. patch.object(scheduler, "_get_setting", AsyncMock(return_value=None)),
  165. patch("backend.app.services.print_scheduler.printer_manager") as pm,
  166. patch("backend.app.services.print_scheduler.asyncio.sleep", AsyncMock()),
  167. ):
  168. pm.get_client.return_value = client
  169. pm.get_status.return_value = _make_state(60.0, 0.0, trays=["PLA", "PLA"])
  170. await scheduler._preheat_and_soak(db, item, _make_printer("H2D"), archive)
  171. client.set_bed_temperature.assert_called_once_with(60)
  172. client.set_chamber_temperature.assert_not_called()
  173. @pytest.mark.asyncio
  174. async def test_unknown_filament_type_falls_to_default(scheduler, item, archive):
  175. """A loaded tray with a type not in the map uses the `default` entry —
  176. keeps users with custom filament names safe (they get 0 by default,
  177. can be tuned via the per-filament editor)."""
  178. db = AsyncMock()
  179. client = _make_client()
  180. with (
  181. patch.object(scheduler, "_get_bool_setting", AsyncMock(return_value=True)),
  182. patch.object(scheduler, "_get_int_setting", _ints(preheat_soak_seconds=0)),
  183. patch.object(scheduler, "_get_setting", AsyncMock(return_value=None)),
  184. patch("backend.app.services.print_scheduler.printer_manager") as pm,
  185. patch("backend.app.services.print_scheduler.asyncio.sleep", AsyncMock()),
  186. ):
  187. pm.get_client.return_value = client
  188. pm.get_status.return_value = _make_state(60.0, 0.0, trays=["MyCustomFilament"])
  189. await scheduler._preheat_and_soak(db, item, _make_printer("H2D"), archive)
  190. client.set_bed_temperature.assert_called_once_with(60)
  191. client.set_chamber_temperature.assert_not_called() # default = 0
  192. @pytest.mark.asyncio
  193. async def test_custom_filament_targets_json_parses(scheduler, item, archive):
  194. """User-customised filament-target JSON overrides the bundled defaults —
  195. raising PLA to 30°C makes a PLA-only print actually heat the chamber."""
  196. db = AsyncMock()
  197. client = _make_client()
  198. custom_map = '{"PLA": 30, "default": 0}'
  199. with (
  200. patch.object(scheduler, "_get_bool_setting", AsyncMock(return_value=True)),
  201. patch.object(scheduler, "_get_int_setting", _ints(preheat_soak_seconds=0)),
  202. patch.object(scheduler, "_get_setting", AsyncMock(return_value=custom_map)),
  203. patch("backend.app.services.print_scheduler.printer_manager") as pm,
  204. patch("backend.app.services.print_scheduler.asyncio.sleep", AsyncMock()),
  205. ):
  206. pm.get_client.return_value = client
  207. pm.get_status.return_value = _make_state(60.0, 31.0, trays=["PLA Basic"])
  208. await scheduler._preheat_and_soak(db, item, _make_printer("H2D"), archive)
  209. client.set_chamber_temperature.assert_called_once_with(30)
  210. @pytest.mark.asyncio
  211. async def test_malformed_filament_targets_falls_back_to_defaults(scheduler, item, archive):
  212. """A corrupted JSON in the setting must not break the scheduler — log
  213. and use bundled defaults."""
  214. db = AsyncMock()
  215. client = _make_client()
  216. with (
  217. patch.object(scheduler, "_get_bool_setting", AsyncMock(return_value=True)),
  218. patch.object(scheduler, "_get_int_setting", _ints(preheat_soak_seconds=0)),
  219. patch.object(scheduler, "_get_setting", AsyncMock(return_value="not-json{{{")),
  220. patch("backend.app.services.print_scheduler.printer_manager") as pm,
  221. patch("backend.app.services.print_scheduler.asyncio.sleep", AsyncMock()),
  222. ):
  223. pm.get_client.return_value = client
  224. # Bundled default for ABS = 45 → chamber should fire.
  225. pm.get_status.return_value = _make_state(60.0, 46.0, trays=["ABS"])
  226. await scheduler._preheat_and_soak(db, item, _make_printer("H2D"), archive)
  227. client.set_chamber_temperature.assert_called_once_with(45)
  228. # ----------------------------------------------------------------------------
  229. # Hardware-tier branching (unchanged from the first cut but updated for new
  230. # fixtures that include AMS data so the derivation lands at a non-zero target).
  231. # ----------------------------------------------------------------------------
  232. @pytest.mark.asyncio
  233. async def test_no_bed_temperature_but_chamber_needed_heats_bed_to_configured_temp(scheduler, item):
  234. """Archive without bed_temperature still preheats when the chamber needs heat.
  235. This branch used to return early, on the reasoning that guessing a bed
  236. temperature could wreck a print. Two things make the fallback safe, and
  237. skipping actively harmful:
  238. * Preheat's bed target is transient. The print's own gcode issues its
  239. M140/M190 the moment it starts, so preheat can never set the temperature
  240. the print actually runs at — it only decides how warm things are while
  241. the file uploads.
  242. * The fallback is gated on a non-zero chamber target, so it only applies to
  243. materials the filament map says want a hot chamber (ABS/ASA/PC …). The
  244. original concern — inventing a bed temperature for a PLA print — is still
  245. guarded, and covered by the sibling test below.
  246. Skipping meant a chamber-heated print whose slicer metadata carries no bed
  247. temperature started with a cold chamber, which is what preheat exists to
  248. prevent.
  249. """
  250. db = AsyncMock()
  251. client = _make_client()
  252. bare_archive = SimpleNamespace(bed_temperature=None)
  253. with (
  254. patch.object(scheduler, "_get_bool_setting", AsyncMock(return_value=True)),
  255. patch.object(
  256. scheduler,
  257. "_get_int_setting",
  258. _ints(queue_keep_warm_bed_temp=90, preheat_soak_seconds=0, preheat_max_wait_seconds=0),
  259. ),
  260. patch.object(scheduler, "_get_setting", AsyncMock(return_value=None)),
  261. patch("backend.app.services.print_scheduler.printer_manager") as pm,
  262. patch("backend.app.services.print_scheduler.asyncio.sleep", AsyncMock()),
  263. ):
  264. pm.get_client.return_value = client
  265. # Bed/chamber already at temperature so the convergence loop exits on its
  266. # first pass — its deadline is wall-clock, so a mocked `asyncio.sleep`
  267. # would otherwise spin for the full max_wait in real time.
  268. pm.get_status.return_value = _make_state(90.0, 46.0, trays=["ABS"])
  269. await scheduler._preheat_and_soak(db, item, _make_printer("H2D"), bare_archive)
  270. client.set_bed_temperature.assert_called_once_with(90)
  271. @pytest.mark.asyncio
  272. async def test_no_bed_temperature_and_no_chamber_target_still_skips(scheduler, item):
  273. """PLA (chamber target 0) with no bed metadata → skip, as before.
  274. Preserves the original guard: with nothing to preheat *for*, no bed
  275. temperature is invented for the print.
  276. """
  277. db = AsyncMock()
  278. client = _make_client()
  279. bare_archive = SimpleNamespace(bed_temperature=None)
  280. with (
  281. patch.object(scheduler, "_get_bool_setting", AsyncMock(return_value=True)),
  282. patch.object(scheduler, "_get_int_setting", _ints(queue_keep_warm_bed_temp=90)),
  283. patch.object(scheduler, "_get_setting", AsyncMock(return_value=None)),
  284. patch("backend.app.services.print_scheduler.printer_manager") as pm,
  285. ):
  286. pm.get_client.return_value = client
  287. pm.get_status.return_value = _make_state(trays=["PLA"])
  288. await scheduler._preheat_and_soak(db, item, _make_printer("H2D"), bare_archive)
  289. client.set_bed_temperature.assert_not_called()
  290. client.set_chamber_temperature.assert_not_called()
  291. @pytest.mark.asyncio
  292. async def test_x1c_skips_m141_but_waits_passively(scheduler, item, archive):
  293. """X1C has a chamber sensor but no active heater — M141 must NOT fire even
  294. when the filament map derives a non-zero target."""
  295. db = AsyncMock()
  296. client = _make_client()
  297. with (
  298. patch.object(scheduler, "_get_bool_setting", AsyncMock(return_value=True)),
  299. patch.object(scheduler, "_get_int_setting", _ints(preheat_soak_seconds=0)),
  300. patch.object(scheduler, "_get_setting", AsyncMock(return_value=None)),
  301. patch("backend.app.services.print_scheduler.printer_manager") as pm,
  302. patch("backend.app.services.print_scheduler.asyncio.sleep", AsyncMock()),
  303. ):
  304. pm.get_client.return_value = client
  305. # ABS loaded → derived target 45; sensor reads 46 (already there).
  306. pm.get_status.return_value = _make_state(60.0, 46.0, trays=["ABS"])
  307. await scheduler._preheat_and_soak(db, item, _make_printer("X1C"), archive)
  308. client.set_bed_temperature.assert_called_once_with(60)
  309. client.set_chamber_temperature.assert_not_called()
  310. @pytest.mark.asyncio
  311. async def test_p1s_no_chamber_sensor_uses_soak_timer_only(scheduler, item, archive):
  312. """P1S has no chamber sensor — derived target is ignored for the wait
  313. loop, only the soak timer applies."""
  314. db = AsyncMock()
  315. client = _make_client()
  316. with (
  317. patch.object(scheduler, "_get_bool_setting", AsyncMock(return_value=True)),
  318. patch.object(scheduler, "_get_int_setting", _ints(preheat_soak_seconds=600)),
  319. patch.object(scheduler, "_get_setting", AsyncMock(return_value=None)),
  320. patch("backend.app.services.print_scheduler.printer_manager") as pm,
  321. patch("backend.app.services.print_scheduler.asyncio.sleep", AsyncMock()) as sleep_mock,
  322. ):
  323. pm.get_client.return_value = client
  324. pm.get_status.return_value = _make_state(60.0, 0.0, trays=["ABS"])
  325. await scheduler._preheat_and_soak(db, item, _make_printer("P1S"), archive)
  326. client.set_bed_temperature.assert_called_once_with(60)
  327. client.set_chamber_temperature.assert_not_called()
  328. # The soak is slept in slices so a cancellation landing mid-hold is noticed
  329. # (a single 600s sleep could not see one), so assert the total rather than a
  330. # single call of the full duration.
  331. assert sum(call.args[0] for call in sleep_mock.call_args_list) == 600
  332. @pytest.mark.asyncio
  333. async def test_lost_client_skips_silently(scheduler, item, archive):
  334. """If the MQTT client drops, the helper returns without raising."""
  335. db = AsyncMock()
  336. with (
  337. patch.object(scheduler, "_get_bool_setting", AsyncMock(return_value=True)),
  338. patch.object(scheduler, "_get_int_setting", _ints()),
  339. patch.object(scheduler, "_get_setting", AsyncMock(return_value=None)),
  340. patch("backend.app.services.print_scheduler.printer_manager") as pm,
  341. ):
  342. pm.get_client.return_value = None
  343. await scheduler._preheat_and_soak(db, item, _make_printer("H2D"), archive)
  344. # No exception escaping — the disable path is silent.
  345. @pytest.mark.asyncio
  346. async def test_h2d_flips_airduct_to_heating_before_m141(scheduler, item, archive):
  347. """H-series + X2D have a cooling/heating airduct flap that DEFAULTS to
  348. cooling. If we energise M141 without first flipping to heating, the
  349. chamber fan actively extracts the heat we're trying to put in and the
  350. chamber never converges. Verify airduct=heating fires AND lands before
  351. the chamber-target call so the heater starts in the right airflow regime."""
  352. db = AsyncMock()
  353. client = _make_client()
  354. call_order = []
  355. client.set_airduct_mode.side_effect = lambda mode: call_order.append(("airduct", mode)) or True
  356. client.set_chamber_temperature.side_effect = lambda t: call_order.append(("chamber", t)) or True
  357. with (
  358. patch.object(scheduler, "_get_bool_setting", AsyncMock(return_value=True)),
  359. patch.object(scheduler, "_get_int_setting", _ints(preheat_soak_seconds=0)),
  360. patch.object(scheduler, "_get_setting", AsyncMock(return_value=None)),
  361. patch("backend.app.services.print_scheduler.printer_manager") as pm,
  362. patch("backend.app.services.print_scheduler.asyncio.sleep", AsyncMock()),
  363. ):
  364. pm.get_client.return_value = client
  365. pm.get_status.return_value = _make_state(60.0, 46.0, trays=["ABS"])
  366. await scheduler._preheat_and_soak(db, item, _make_printer("H2D"), archive)
  367. client.set_airduct_mode.assert_called_once_with("heating")
  368. client.set_chamber_temperature.assert_called_once_with(45)
  369. # Airduct heating must precede M141 — the heater enabling first while the
  370. # flap is still in cooling mode wastes minutes of fan-vs-heater tug-of-war.
  371. assert call_order == [("airduct", "heating"), ("chamber", 45)]
  372. @pytest.mark.asyncio
  373. async def test_x1c_skips_airduct_no_heater_no_call(scheduler, item, archive):
  374. """X1C has neither an active chamber heater nor an airduct flap (the
  375. frontend's airduct whitelist is P2S/X2D/H2D/H2C/H2S/H2D Pro — no X1
  376. series). The preheat stage's airduct call is gated on supports_airduct
  377. AND has_heater, so X1C gets neither call regardless. Important: a
  378. spurious set_airduct on X1C wouldn't just be wasted MQTT — there's no
  379. flap to set, so the firmware response would be undefined behaviour."""
  380. db = AsyncMock()
  381. client = _make_client()
  382. with (
  383. patch.object(scheduler, "_get_bool_setting", AsyncMock(return_value=True)),
  384. patch.object(scheduler, "_get_int_setting", _ints(preheat_soak_seconds=0)),
  385. patch.object(scheduler, "_get_setting", AsyncMock(return_value=None)),
  386. patch("backend.app.services.print_scheduler.printer_manager") as pm,
  387. patch("backend.app.services.print_scheduler.asyncio.sleep", AsyncMock()),
  388. ):
  389. pm.get_client.return_value = client
  390. pm.get_status.return_value = _make_state(60.0, 46.0, trays=["ABS"])
  391. await scheduler._preheat_and_soak(db, item, _make_printer("X1C"), archive)
  392. client.set_chamber_temperature.assert_not_called()
  393. client.set_airduct_mode.assert_not_called()
  394. @pytest.mark.asyncio
  395. async def test_normalize_filament_type_strips_at_space():
  396. """`PLA Basic` and `ABS Premium` should normalise to `PLA` and `ABS` so
  397. they match the map keys. `PA-CF` has no space and stays verbatim."""
  398. s = PrintScheduler
  399. assert s._normalize_filament_type("PLA Basic") == "PLA"
  400. assert s._normalize_filament_type("ABS Premium") == "ABS"
  401. assert s._normalize_filament_type("PA-CF") == "PA-CF"
  402. assert s._normalize_filament_type("") == ""
  403. assert s._normalize_filament_type("petg") == "PETG" # case-folded
  404. @pytest.mark.asyncio
  405. @pytest.mark.parametrize("stored", [None, "", "not json at all", "[1, 2, 3]"])
  406. async def test_get_preheat_filament_targets_defaults_when_missing(scheduler, stored):
  407. """Empty / null / malformed setting → bundled defaults are used.
  408. Every path out of this function must honour the one contract its docstring
  409. states: keys upper-cased, and DEFAULT present so the resolution loop can
  410. index it unconditionally. The fallback paths used to hand the bundled
  411. constant back as declared, with its lowercase `default`, so an install that
  412. had never opened the setting returned a dict the loop could not read its
  413. fallback out of. It happened to produce the right number only because that
  414. default is 0 -- this test is what stops the constant changing and taking
  415. every unconfigured install's chamber preheat down with it.
  416. """
  417. db = AsyncMock()
  418. with patch.object(scheduler, "_get_setting", AsyncMock(return_value=stored)):
  419. targets = await scheduler._get_preheat_filament_targets(db)
  420. assert targets["PLA"] == 0
  421. assert targets["ABS"] == 45
  422. assert targets["PA-CF"] == 55
  423. assert "DEFAULT" in targets, "the resolution loop looks the fallback up by this exact key"
  424. assert targets["DEFAULT"] == PrintScheduler.DEFAULT_PREHEAT_FILAMENT_TARGETS["default"]
  425. assert all(key == key.upper() for key in targets), targets
  426. @pytest.mark.asyncio
  427. async def test_a_configured_map_reaches_the_loop_under_the_same_contract(scheduler):
  428. """The editor writes the keys it displays, lowercase `default` included, so
  429. the parsed path has always upper-cased. Both paths agree now."""
  430. db = AsyncMock()
  431. stored = '{"PLA": 0, "abs": 60, "default": 15}'
  432. with patch.object(scheduler, "_get_setting", AsyncMock(return_value=stored)):
  433. targets = await scheduler._get_preheat_filament_targets(db)
  434. assert targets["ABS"] == 60
  435. assert targets["DEFAULT"] == 15
  436. assert all(key == key.upper() for key in targets), targets
  437. # ----------------------------------------------------------------------------
  438. # Airduct mode switch (#1468 follow-up)
  439. # ----------------------------------------------------------------------------
  440. @pytest.mark.asyncio
  441. async def test_h2d_chamber_heat_switches_airduct_to_heating(scheduler, item, archive):
  442. """H2D in cooling mode (the default; what you get after a PLA print)
  443. with chamber_target > 0 must switch the airduct to heating BEFORE the
  444. M141 dispatch — otherwise the open exhaust flap actively fights the
  445. chamber heater and the chamber never converges."""
  446. db = AsyncMock()
  447. client = _make_client()
  448. with (
  449. patch.object(scheduler, "_get_bool_setting", AsyncMock(return_value=True)),
  450. patch.object(scheduler, "_get_int_setting", _ints(preheat_soak_seconds=0)),
  451. patch.object(scheduler, "_get_setting", AsyncMock(return_value=None)),
  452. patch("backend.app.services.print_scheduler.printer_manager") as pm,
  453. patch("backend.app.services.print_scheduler.asyncio.sleep", AsyncMock()),
  454. ):
  455. pm.get_client.return_value = client
  456. # Currently in cooling (mode 0). ABS loaded → derived target 45.
  457. pm.get_status.return_value = _make_state(60.0, 46.0, trays=["ABS"], airduct_mode=0)
  458. await scheduler._preheat_and_soak(db, item, _make_printer("H2D"), archive)
  459. client.set_airduct_mode.assert_called_once_with("heating")
  460. client.set_chamber_temperature.assert_called_once_with(45)
  461. @pytest.mark.asyncio
  462. async def test_h2d_chamber_zero_switches_airduct_to_cooling(scheduler, item, archive):
  463. """H2D running a PLA print (chamber_target derives 0) on an airduct
  464. previously left in heating mode (from a prior ABS run) must switch
  465. back to cooling. Otherwise PLA prints inherit ABS's closed-flap recirc
  466. and run hot."""
  467. db = AsyncMock()
  468. client = _make_client()
  469. with (
  470. patch.object(scheduler, "_get_bool_setting", AsyncMock(return_value=True)),
  471. patch.object(scheduler, "_get_int_setting", _ints(preheat_soak_seconds=0)),
  472. patch.object(scheduler, "_get_setting", AsyncMock(return_value=None)),
  473. patch("backend.app.services.print_scheduler.printer_manager") as pm,
  474. patch("backend.app.services.print_scheduler.asyncio.sleep", AsyncMock()),
  475. ):
  476. pm.get_client.return_value = client
  477. # Currently in heating (mode 1). PLA loaded → derived target 0.
  478. pm.get_status.return_value = _make_state(60.0, 30.0, trays=["PLA"], airduct_mode=1)
  479. await scheduler._preheat_and_soak(db, item, _make_printer("H2D"), archive)
  480. client.set_airduct_mode.assert_called_once_with("cooling")
  481. client.set_chamber_temperature.assert_not_called()
  482. @pytest.mark.asyncio
  483. async def test_h2d_airduct_already_correct_idempotent(scheduler, item, archive):
  484. """If the airduct is already in the desired mode, don't re-send
  485. `set_airduct` — the firmware accepts it but it generates needless MQTT
  486. chatter and could thrash the flap motor on rapid repeats."""
  487. db = AsyncMock()
  488. client = _make_client()
  489. with (
  490. patch.object(scheduler, "_get_bool_setting", AsyncMock(return_value=True)),
  491. patch.object(scheduler, "_get_int_setting", _ints(preheat_soak_seconds=0)),
  492. patch.object(scheduler, "_get_setting", AsyncMock(return_value=None)),
  493. patch("backend.app.services.print_scheduler.printer_manager") as pm,
  494. patch("backend.app.services.print_scheduler.asyncio.sleep", AsyncMock()),
  495. ):
  496. pm.get_client.return_value = client
  497. # Already in heating (mode 1) and ABS → derived 45 wants heating.
  498. pm.get_status.return_value = _make_state(60.0, 46.0, trays=["ABS"], airduct_mode=1)
  499. await scheduler._preheat_and_soak(db, item, _make_printer("H2D"), archive)
  500. client.set_airduct_mode.assert_not_called()
  501. # But M141 still fires — the airduct decision is independent.
  502. client.set_chamber_temperature.assert_called_once_with(45)
  503. @pytest.mark.asyncio
  504. async def test_x1c_no_airduct_flap_never_fires_set_airduct(scheduler, item, archive):
  505. """X1C has a chamber sensor but no airduct flap — the firmware ignores
  506. `set_airduct`. We gate on `supports_airduct(model)` to avoid sending the
  507. no-op. Regression guard: wiring this to `supports_chamber_temp` or
  508. `supports_chamber_heater` alone would have leaked the command to
  509. X1C/X1E or P2S inappropriately."""
  510. db = AsyncMock()
  511. client = _make_client()
  512. with (
  513. patch.object(scheduler, "_get_bool_setting", AsyncMock(return_value=True)),
  514. patch.object(scheduler, "_get_int_setting", _ints(preheat_soak_seconds=0)),
  515. patch.object(scheduler, "_get_setting", AsyncMock(return_value=None)),
  516. patch("backend.app.services.print_scheduler.printer_manager") as pm,
  517. patch("backend.app.services.print_scheduler.asyncio.sleep", AsyncMock()),
  518. ):
  519. pm.get_client.return_value = client
  520. pm.get_status.return_value = _make_state(60.0, 46.0, trays=["ABS"], airduct_mode=0)
  521. await scheduler._preheat_and_soak(db, item, _make_printer("X1C"), archive)
  522. client.set_airduct_mode.assert_not_called()
  523. @pytest.mark.asyncio
  524. async def test_a_filled_variant_preheats_like_its_base_material(monkeypatch):
  525. """#2902 widened the type an AMS slot carries, so a slot that used to say
  526. "ASA" can now say "ASA-GF". The chamber map has no ASA-GF row, and an
  527. unknown type preheats to nothing -- so an ASA-GF print would have gone out
  528. with a cold chamber. The specific type is still tried first, so the rows
  529. that do exist for a variant (PETG-CF, PA-CF) are not traded down."""
  530. from backend.app.services.print_scheduler import PrintScheduler
  531. s = PrintScheduler()
  532. targets = PrintScheduler.DEFAULT_PREHEAT_FILAMENT_TARGETS
  533. def target_for(tray_type: str) -> int:
  534. normalised = s._normalize_filament_type(tray_type)
  535. value = targets.get(normalised)
  536. if value is None:
  537. value = targets.get(normalised.split("-")[0], targets.get("DEFAULT", 0))
  538. return value
  539. assert target_for("ASA-GF") == targets["ASA"]
  540. assert target_for("ASA-AERO") == targets["ASA"]
  541. assert target_for("ABS-GF") == targets["ABS"]
  542. # Variants listed in their own right keep their own row.
  543. assert target_for("PETG-CF") == 40
  544. assert target_for("PA-CF") == 55
  545. # And a plain type is untouched.
  546. assert target_for("PLA") == 0