test_scheduler_filament_scope_3522.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. """The scheduler holds a job to its creator's filament scope (#3522)."""
  2. from __future__ import annotations
  3. import json
  4. from contextlib import ExitStack
  5. from pathlib import Path
  6. from types import SimpleNamespace
  7. from unittest.mock import AsyncMock, MagicMock, patch
  8. import pytest
  9. import backend.app.services.print_scheduler as scheduler_module
  10. from backend.app.core.filament_scope import ALL_FILAMENTS, FilamentRule, FilamentScope, GroupFilamentPolicy
  11. from backend.app.models.print_queue import PrintQueueItem
  12. from backend.app.services.print_scheduler import FilamentScopeHold, PrintScheduler
  13. BLOCK_PETG_MATTE = FilamentScope((GroupFilamentPolicy("Friends", "block", (FilamentRule("filament_id", "GFG03"),)),))
  14. # A hold names who may not print it in the third person: an admin reads it too.
  15. FILE_NEEDS_PETG_MATTE = "This file needs a filament the job creator's group can't print with: PETG (GFG03)"
  16. SPOOL_IS_PETG_MATTE = "It would print from a loaded spool the job creator's group can't print with: PETG (GFG03)"
  17. def _tray(global_id: int, tray_info_idx: str, filament_type: str = "PETG") -> dict:
  18. return {
  19. "type": filament_type,
  20. "color": "#FFFFFF",
  21. "color_known": True,
  22. "tray_info_idx": tray_info_idx,
  23. "ams_id": 0,
  24. "tray_id": global_id,
  25. "is_ht": False,
  26. "is_external": False,
  27. "global_tray_id": global_id,
  28. "extruder_id": None,
  29. "remain": 80,
  30. }
  31. def _external(global_id: int, tray_info_idx: str, filament_type: str = "PETG") -> dict:
  32. return {**_tray(global_id, tray_info_idx, filament_type), "ams_id": -1, "tray_id": 0, "is_external": True}
  33. REQ_WHITE_PETG = {"slot_id": 1, "type": "PETG", "color": "#FFFFFF", "tray_info_idx": "", "used_grams": 10.0}
  34. REQ_PETG_MATTE = {"slot_id": 1, "type": "PETG", "color": "#FFFFFF", "tray_info_idx": "GFG03", "used_grams": 10.0}
  35. REQ_WHITE_PLA = {"slot_id": 1, "type": "PLA", "color": "#FFFFFF", "tray_info_idx": "", "used_grams": 10.0}
  36. def _item(**kwargs) -> PrintQueueItem:
  37. defaults = {"id": 1, "printer_id": 1, "archive_id": 1, "created_by_id": 7, "plate_id": None}
  38. defaults.update(kwargs)
  39. return PrintQueueItem(**defaults)
  40. async def _run(
  41. call,
  42. scope=BLOCK_PETG_MATTE,
  43. *,
  44. requirements=(REQ_WHITE_PETG,),
  45. loaded,
  46. printer_model="X1C",
  47. raw_data=None,
  48. source: Path | None = None,
  49. ):
  50. """Await ``call(scheduler)`` with the creator's scope, the file and the printer's spools stubbed."""
  51. status = SimpleNamespace(raw_data=raw_data or {}, fila_switch=None, ams_filament_backup=None)
  52. patches = [
  53. patch.object(PrintScheduler, "_get_printer", AsyncMock(return_value=SimpleNamespace(model=printer_model))),
  54. patch.object(scheduler_module, "resolve_user_id_filament_scope", AsyncMock(return_value=scope)),
  55. patch.object(scheduler_module.printer_manager, "get_status", MagicMock(return_value=status)),
  56. patch.object(
  57. PrintScheduler, "_get_filament_requirements", AsyncMock(return_value=[dict(r) for r in requirements])
  58. ),
  59. patch.object(PrintScheduler, "_build_loaded_filaments", MagicMock(return_value=loaded)),
  60. patch.object(PrintScheduler, "_get_bool_setting", AsyncMock(return_value=False)),
  61. # The job's file is on disk: this module stands in for it.
  62. patch.object(PrintScheduler, "_source_file_path", AsyncMock(return_value=source or Path(__file__))),
  63. ]
  64. with ExitStack() as stack:
  65. for p in patches:
  66. stack.enter_context(p)
  67. return await call(PrintScheduler())
  68. def _compute(item=None):
  69. return lambda sched: sched._compute_ams_mapping_for_printer(AsyncMock(), 1, item or _item())
  70. def _violation(item=None):
  71. return lambda sched: sched._filament_scope_violation(AsyncMock(), item or _item())
  72. def _ensure(item):
  73. return lambda sched: sched._ensure_ams_mapping(AsyncMock(), 1, item)
  74. @pytest.mark.asyncio
  75. class TestMappingSkipsBlockedTrays:
  76. @pytest.mark.parametrize(
  77. ("scope", "loaded", "mapping"),
  78. [
  79. pytest.param(BLOCK_PETG_MATTE, [_tray(0, "GFG03"), _tray(1, "GFG99")], [1], id="blocked_tray_never_chosen"),
  80. pytest.param(BLOCK_PETG_MATTE, [_tray(0, "GFG03")], None, id="only_blocked_trays_means_no_mapping"),
  81. pytest.param(ALL_FILAMENTS, [_tray(0, "GFG03")], [0], id="unrestricted_creator_may_use_any_tray"),
  82. ],
  83. )
  84. async def test_mapping(self, scope, loaded, mapping):
  85. assert await _run(_compute(), scope, loaded=loaded) == mapping
  86. @pytest.mark.asyncio
  87. class TestViolation:
  88. @pytest.mark.parametrize(
  89. ("scope", "requirements", "message"),
  90. [
  91. pytest.param(BLOCK_PETG_MATTE, [REQ_PETG_MATTE], FILE_NEEDS_PETG_MATTE, id="file_needs_a_blocked_filament"),
  92. pytest.param(BLOCK_PETG_MATTE, [REQ_WHITE_PETG], None, id="allowed_file"),
  93. pytest.param(ALL_FILAMENTS, [REQ_PETG_MATTE], None, id="unrestricted_skips_the_check"),
  94. ],
  95. )
  96. async def test_violation(self, scope, requirements, message):
  97. loaded = [_tray(0, "GFG03"), _tray(1, "GFG99")]
  98. assert await _run(_violation(), scope, requirements=requirements, loaded=loaded) == message
  99. @pytest.mark.asyncio
  100. class TestStoredMappingOnBlockedTray:
  101. @pytest.mark.parametrize("print_anyway", [False, True], ids=["checked", "print_anyway"])
  102. async def test_is_recomputed_onto_an_allowed_tray(self, print_anyway):
  103. # "Print anyway" skips the filament check, but never keeps a blocked tray.
  104. item = _item(ams_mapping=json.dumps([0]), skip_filament_check=print_anyway)
  105. result = await _run(_ensure(item), loaded=[_tray(0, "GFG03"), _tray(1, "GFG99")])
  106. assert result is None
  107. assert json.loads(item.ams_mapping)[0] == 1
  108. @pytest.mark.parametrize(("stored", "uses_blocked"), [([1], False), ([0], True)], ids=["allowed", "blocked"])
  109. async def test_mapping_uses_blocked_tray(self, stored, uses_blocked):
  110. uses = await _run(
  111. lambda sched: sched._mapping_uses_blocked_tray(AsyncMock(), 1, _item(), stored),
  112. loaded=[_tray(0, "GFG03"), _tray(1, "GFG99")],
  113. )
  114. assert uses is uses_blocked
  115. def _force_override(tray_info_idx: str) -> str:
  116. """A ``force_color_match`` override for slot 1, white PETG, as the print dialog stores it."""
  117. return json.dumps(
  118. [{"slot_id": 1, "type": "PETG", "color": "#FFFFFF", "tray_info_idx": tray_info_idx, "force_color_match": True}]
  119. )
  120. @pytest.mark.asyncio
  121. class TestForcedOverridesWithoutFileRequirements:
  122. """A 3MF without slice info falls back to its force-colour overrides (#3280); so does the scope."""
  123. async def test_a_forced_blocked_filament_is_a_violation(self):
  124. item = _item(filament_overrides=_force_override("GFG03"))
  125. message = await _run(_violation(item), requirements=[], loaded=[_tray(1, "GFG99")])
  126. assert message == FILE_NEEDS_PETG_MATTE
  127. async def test_the_direct_override_mapping_skips_blocked_trays(self):
  128. item = _item(filament_overrides=_force_override(""))
  129. mapping = await _run(_compute(item), requirements=[], loaded=[_tray(0, "GFG03"), _tray(1, "GFG99")])
  130. assert mapping is not None
  131. assert 0 not in mapping
  132. assert mapping[0] == 1
  133. PRINT_ANYWAY = {"skip_filament_check": True}
  134. PRINT_ANYWAY_LEAVES_PETG = (
  135. "Print anyway leaves PETG without a slot, and the printer could pick a loaded spool "
  136. "the job creator's group can't print with: PETG (GFG03)"
  137. )
  138. @pytest.mark.asyncio
  139. class TestHoldNotFail:
  140. """A permission finding holds the job, it doesn't fail it (#3522)."""
  141. @pytest.mark.parametrize(
  142. ("item_fields", "requirements", "loaded", "reason"),
  143. [
  144. pytest.param(
  145. {"ams_mapping": "[1]"},
  146. [REQ_PETG_MATTE],
  147. [_tray(1, "GFG99")],
  148. FILE_NEEDS_PETG_MATTE,
  149. id="file_needs_a_blocked_filament",
  150. ),
  151. pytest.param(
  152. {"ams_mapping": "[1]", **PRINT_ANYWAY},
  153. [REQ_PETG_MATTE],
  154. [_tray(1, "GFG99")],
  155. FILE_NEEDS_PETG_MATTE,
  156. id="file_needs_a_blocked_filament_even_with_print_anyway",
  157. ),
  158. pytest.param(
  159. {"ams_mapping": "[0]", **PRINT_ANYWAY},
  160. [REQ_WHITE_PETG],
  161. [_tray(0, "GFG03")],
  162. PRINT_ANYWAY_LEAVES_PETG,
  163. id="print_anyway_with_only_blocked_trays",
  164. ),
  165. pytest.param(
  166. {"ams_mapping": None, **PRINT_ANYWAY},
  167. [REQ_WHITE_PETG],
  168. [_tray(0, "GFG03")],
  169. PRINT_ANYWAY_LEAVES_PETG,
  170. id="print_anyway_with_no_mapping_and_only_blocked_trays",
  171. ),
  172. pytest.param(
  173. # No AMS tray matches, so nothing turns the AMS back on (#2595).
  174. {"use_ams": False},
  175. [REQ_WHITE_PETG],
  176. [_tray(1, "GFA00", "PLA"), _external(254, "GFG03")],
  177. SPOOL_IS_PETG_MATTE,
  178. id="external_spool_with_a_blocked_filament_without_the_ams",
  179. ),
  180. ],
  181. )
  182. async def test_is_held_with_the_reason(self, item_fields, requirements, loaded, reason):
  183. result = await _run(_ensure(_item(**item_fields)), requirements=requirements, loaded=loaded)
  184. assert isinstance(result, FilamentScopeHold)
  185. assert result.reason == reason
  186. @pytest.mark.parametrize(
  187. ("item_fields", "loaded"),
  188. [
  189. pytest.param(
  190. {"ams_mapping": "[1]", **PRINT_ANYWAY},
  191. [_tray(0, "GFG03"), _tray(1, "GFG99")],
  192. id="print_anyway_with_an_allowed_tray",
  193. ),
  194. pytest.param(
  195. {"use_ams": False},
  196. [_tray(1, "GFG03"), _external(254, "GFG99")],
  197. id="external_spool_with_an_allowed_filament_without_the_ams",
  198. ),
  199. ],
  200. )
  201. async def test_dispatches(self, item_fields, loaded):
  202. assert await _run(_ensure(_item(**item_fields)), loaded=loaded) is None
  203. async def test_unrestricted_print_anyway_still_short_circuits(self):
  204. item = _item(ams_mapping=json.dumps([0]), use_ams=False, **PRINT_ANYWAY)
  205. result = await _run(
  206. _ensure(item),
  207. ALL_FILAMENTS,
  208. requirements=[REQ_PETG_MATTE],
  209. loaded=[_tray(0, "GFG03"), _external(254, "GFG03")],
  210. )
  211. assert result is None
  212. assert json.loads(item.ams_mapping) == [0]
  213. @pytest.mark.asyncio
  214. class TestScopeIsResolvedOncePerPass:
  215. async def test_two_candidate_printers_resolve_the_scope_once(self):
  216. async def two_printers(sched):
  217. await sched._compute_ams_mapping_for_printer(AsyncMock(), 1, _item())
  218. await sched._compute_ams_mapping_for_printer(AsyncMock(), 2, _item())
  219. return scheduler_module.resolve_user_id_filament_scope.await_count
  220. assert await _run(two_printers, loaded=[_tray(1, "GFG99")]) == 1
  221. async def test_memo_answers_repeat_calls_and_is_cleared_each_pass(self):
  222. sched = PrintScheduler()
  223. resolve = AsyncMock(return_value=BLOCK_PETG_MATTE)
  224. with patch.object(scheduler_module, "resolve_user_id_filament_scope", resolve):
  225. for _ in range(3):
  226. assert await sched._creator_filament_scope(AsyncMock(), 7) is BLOCK_PETG_MATTE
  227. assert resolve.await_count == 1
  228. assert (await sched._creator_filament_scope(AsyncMock(), None)).is_unrestricted
  229. assert resolve.await_count == 1
  230. sched._filament_scope_memo.clear()
  231. await sched._creator_filament_scope(AsyncMock(), 7)
  232. assert resolve.await_count == 2
  233. @pytest.mark.asyncio
  234. class TestModelSelectionUnderPrintAnyway:
  235. async def _unmatched(self, scope):
  236. item = _item(printer_id=None, target_model="X1C", **PRINT_ANYWAY)
  237. return await _run(lambda sched: sched._unmatched_on(AsyncMock(), item, 1), scope, loaded=[_tray(0, "GFG03")])
  238. async def test_a_restricted_creator_does_not_skip_the_printer_match(self):
  239. assert await self._unmatched(BLOCK_PETG_MATTE)
  240. async def test_an_unrestricted_creator_still_skips_it(self):
  241. assert await self._unmatched(ALL_FILAMENTS) == []
  242. @pytest.mark.asyncio
  243. class TestWithoutTheAmsTheMappingDoesNotDecide:
  244. """With use_ams off and no tray mapped, a single-nozzle printer feeds its external spool (#3522)."""
  245. async def _judge(self, model: str):
  246. return await _run(
  247. _ensure(_item(use_ams=False, **PRINT_ANYWAY)),
  248. # "Print anyway" for PLA from an allowed PETG spool: no slot maps,
  249. # and a blocked tray is loaded the printer could pick.
  250. requirements=[REQ_WHITE_PLA],
  251. loaded=[_tray(0, "GFG03"), _external(254, "GFG99")],
  252. printer_model=model,
  253. )
  254. async def test_an_allowed_external_spool_is_enough_on_a_single_nozzle_printer(self):
  255. assert await self._judge("X1C") is None
  256. async def test_a_dual_nozzle_printer_still_has_its_mapping_judged(self):
  257. assert isinstance(await self._judge("H2D"), FilamentScopeHold)
  258. def _claimed(item):
  259. return lambda sched: sched._claimed_scope_violation(AsyncMock(), item)
  260. BLOCK_TPU = FilamentScope((GroupFilamentPolicy("Friends", "block", (FilamentRule("material", "TPU"),)),))
  261. ALLOW_ONLY_PETG_MATTE = FilamentScope(
  262. (GroupFilamentPolicy("Friends", "allow", (FilamentRule("filament_id", "GFG03"),)),)
  263. )
  264. # Slot 1 white PETG, slot 2 white PLA: two filaments the plate prints.
  265. TWO_SLOTS = (REQ_WHITE_PETG, {**REQ_WHITE_PLA, "slot_id": 2})
  266. @pytest.mark.asyncio
  267. class TestTheFeedThePrinterIsSent:
  268. """The feed is judged as the printer receives it (#3522).
  269. On a single-nozzle printer the command builder turns ``use_ams=False``
  270. back on when the mapping names a real tray (#2595), unless the plate
  271. prints only from the spool holder; and a printer that reported no AMS
  272. feeds the spool holder whatever ``use_ams`` says (#3356).
  273. """
  274. @pytest.mark.parametrize(
  275. ("item_fields", "requirements", "loaded", "raw_data", "reason"),
  276. [
  277. pytest.param(
  278. {"use_ams": False, "ams_mapping": "[0]"},
  279. (REQ_WHITE_PETG,),
  280. [_tray(0, "GFG03"), _external(254, "GFG99")],
  281. None,
  282. SPOOL_IS_PETG_MATTE,
  283. id="use_ams_off_but_the_mapping_names_a_blocked_tray",
  284. ),
  285. pytest.param(
  286. {"use_ams": False, "ams_mapping": "[1, -1]", **PRINT_ANYWAY},
  287. TWO_SLOTS,
  288. [_tray(0, "GFG03"), _tray(1, "GFG99"), _external(254, "GFG99")],
  289. None,
  290. "Print anyway leaves PLA without a slot, and the printer could pick a loaded spool "
  291. "the job creator's group can't print with: PETG (GFG03)",
  292. id="use_ams_off_print_anyway_with_an_unresolved_slot",
  293. ),
  294. pytest.param(
  295. {"ams_mapping": None},
  296. (REQ_WHITE_PETG,),
  297. [_external(254, "GFG03")],
  298. {"ams": []},
  299. SPOOL_IS_PETG_MATTE,
  300. id="no_ams_feeds_the_spool_holder_even_with_use_ams_on",
  301. ),
  302. ],
  303. )
  304. async def test_is_held(self, item_fields, requirements, loaded, raw_data, reason):
  305. result = await _run(_claimed(_item(**item_fields)), requirements=requirements, loaded=loaded, raw_data=raw_data)
  306. assert result == reason
  307. @pytest.mark.parametrize(
  308. ("item_fields", "requirements", "loaded"),
  309. [
  310. pytest.param(
  311. {"use_ams": False, "ams_mapping": "[1]"},
  312. (REQ_WHITE_PETG,),
  313. [_tray(1, "GFG99"), _external(254, "GFG03")],
  314. id="use_ams_off_but_the_mapping_names_an_allowed_tray",
  315. ),
  316. pytest.param(
  317. # Slot 2 is another plate's: this plate prints only from the
  318. # spool holder, so the AMS stays off (#3087) and tray 0 unused.
  319. {"use_ams": False, "ams_mapping": "[254, 0]"},
  320. (REQ_WHITE_PETG,),
  321. [_tray(0, "GFG03"), _external(254, "GFG99")],
  322. id="plate_prints_only_the_allowed_external_spool",
  323. ),
  324. ],
  325. )
  326. async def test_dispatches(self, item_fields, requirements, loaded):
  327. assert await _run(_claimed(_item(**item_fields)), requirements=requirements, loaded=loaded) is None
  328. async def test_a_blocked_external_spool_does_not_hold_a_job_the_ams_feeds(self):
  329. # use_ams=False as a Virtual Printer stamps it; the matcher picks the
  330. # allowed AMS tray, which turns the AMS back on (#2595).
  331. item = _item(use_ams=False)
  332. result = await _run(_ensure(item), loaded=[_tray(1, "GFG99"), _external(254, "GFG03")])
  333. assert result is None
  334. assert json.loads(item.ams_mapping) == [1]
  335. @pytest.mark.asyncio
  336. class TestOverriddenSlotsAndFilamentIdRules:
  337. """An overridden slot is left to the tray filter, not judged without its filament id (#3522)."""
  338. @staticmethod
  339. def _override(*, force: bool, tray_info_idx: str = "GFG03") -> str:
  340. return json.dumps(
  341. [
  342. {
  343. "slot_id": 1,
  344. "type": "PETG",
  345. "color": "#000000",
  346. "tray_info_idx": tray_info_idx,
  347. "force_color_match": force,
  348. }
  349. ]
  350. )
  351. @pytest.mark.parametrize(
  352. ("override", "message"),
  353. [
  354. # A colour swap to another allowed GFG03 spool clears the id.
  355. pytest.param({"force": False}, None, id="colour_swap"),
  356. pytest.param({"force": True, "tray_info_idx": ""}, None, id="forced_colour_naming_no_id"),
  357. pytest.param({"force": True}, None, id="forced_colour_of_the_allowed_id"),
  358. ],
  359. )
  360. async def test_allowed_override_is_not_held(self, override, message):
  361. item = _item(filament_overrides=self._override(**override))
  362. result = await _run(
  363. _violation(item), ALLOW_ONLY_PETG_MATTE, requirements=[REQ_PETG_MATTE], loaded=[_tray(0, "GFG03")]
  364. )
  365. assert result == message
  366. async def test_a_forced_override_naming_a_blocked_id_is_still_held(self):
  367. item = _item(filament_overrides=self._override(force=True))
  368. result = await _run(_violation(item), requirements=[REQ_WHITE_PETG], loaded=[_tray(1, "GFG99")])
  369. assert result == FILE_NEEDS_PETG_MATTE
  370. async def test_an_override_onto_a_blocked_tray_with_print_anyway_is_held_at_dispatch(self):
  371. # Skipped by the file check; the tray filter leaves the slot unmapped,
  372. # and "Print anyway" doesn't let the printer pick the blocked tray.
  373. item = _item(filament_overrides=self._override(force=False), **PRINT_ANYWAY)
  374. result = await _run(_ensure(item), requirements=[REQ_WHITE_PLA], loaded=[_tray(0, "GFG03")])
  375. assert isinstance(result, FilamentScopeHold)
  376. assert "PETG (GFG03)" in result.reason
  377. @pytest.mark.asyncio
  378. class TestPrintAnywayOnlyWhereABlockedTrayIsLoaded:
  379. """The unresolved-slot check needs a blocked tray on the printer (#3522)."""
  380. async def test_nothing_blocked_loaded_lets_print_anyway_through(self):
  381. item = _item(ams_mapping=None, **PRINT_ANYWAY)
  382. result = await _run(_claimed(item), BLOCK_TPU, requirements=[REQ_WHITE_PLA], loaded=[_tray(0, "GFG99")])
  383. assert result is None
  384. async def test_a_blocked_tray_holds_it_naming_only_the_blocked_filament(self):
  385. item = _item(ams_mapping=None, **PRINT_ANYWAY)
  386. result = await _run(
  387. _claimed(item),
  388. BLOCK_TPU,
  389. requirements=[REQ_WHITE_PLA],
  390. loaded=[_tray(0, "", "TPU"), _tray(1, "GFG99")],
  391. )
  392. assert result == (
  393. "Print anyway leaves PLA without a slot, and the printer could pick a loaded spool "
  394. "the job creator's group can't print with: TPU"
  395. )
  396. async def test_a_blocked_external_spool_the_ams_job_is_not_fed_from_holds_nothing(self):
  397. # Single nozzle, AMS on: a slot left without a tray never goes to the
  398. # spool holder, so the blocked spool there is not one it could pick.
  399. item = _item(ams_mapping=None, **PRINT_ANYWAY)
  400. loaded = [_tray(1, "GFG99"), _external(254, "GFG03")]
  401. assert await _run(_claimed(item), requirements=[REQ_WHITE_PLA], loaded=loaded) is None
  402. async def test_a_blocked_external_spool_the_job_is_fed_from_still_holds_it(self):
  403. item = _item(ams_mapping=None, use_ams=False, **PRINT_ANYWAY)
  404. loaded = [_tray(1, "GFG99"), _external(254, "GFG03")]
  405. assert await _run(_claimed(item), requirements=[REQ_WHITE_PLA], loaded=loaded) == SPOOL_IS_PETG_MATTE
  406. H2D_WITHOUT_AMS = {"ams": [], "vt_tray": [{"id": "254"}, {"id": "255"}]}
  407. @pytest.mark.asyncio
  408. class TestDualNozzleWithOnlyExternalSpools:
  409. """A blocked spool that would have matched holds the job, it doesn't fail it (#3522)."""
  410. @pytest.mark.parametrize(
  411. "loaded",
  412. [
  413. pytest.param([_external(254, "GFG03"), _external(255, "GFA00", "PLA")], id="next_to_an_allowed_spool"),
  414. pytest.param([_external(254, "GFG03")], id="alone"),
  415. ],
  416. )
  417. async def test_is_held_with_the_permission_reason(self, loaded):
  418. result = await _run(_ensure(_item()), loaded=loaded, raw_data=H2D_WITHOUT_AMS, printer_model="H2D")
  419. assert result == FilamentScopeHold(SPOOL_IS_PETG_MATTE)
  420. async def test_the_failure_does_not_list_a_blocked_spool_as_loaded(self):
  421. # Nothing loaded matches TPU, blocked or not: the job fails (#2771),
  422. # naming only the spools its creator may use.
  423. tpu = {**REQ_WHITE_PLA, "type": "TPU"}
  424. result = await _run(
  425. _ensure(_item()),
  426. requirements=[tpu],
  427. loaded=[_external(254, "GFG03"), _external(255, "GFA00", "PLA")],
  428. raw_data=H2D_WITHOUT_AMS,
  429. printer_model="H2D",
  430. )
  431. assert isinstance(result, str)
  432. assert "PLA" in result
  433. assert "PETG" not in result
  434. @pytest.mark.asyncio
  435. class TestModelSelectionUnderPrintAnywayWithNothingBlockedLoaded:
  436. async def test_print_anyway_is_honoured_where_no_blocked_tray_is_loaded(self):
  437. # Dispatch lets it through with nothing blocked loaded, so choosing a
  438. # printer does too.
  439. item = _item(printer_id=None, target_model="X1C", **PRINT_ANYWAY)
  440. unmatched = await _run(
  441. lambda sched: sched._unmatched_on(AsyncMock(), item, 1),
  442. BLOCK_TPU,
  443. requirements=[REQ_WHITE_PLA],
  444. loaded=[_tray(0, "GFG03")],
  445. )
  446. assert unmatched == []
  447. @pytest.mark.asyncio
  448. class TestAMappedTrayThePrinterDoesNotHave:
  449. """A tray id the printer doesn't report loaded settles nothing for a restricted creator (#3522).
  450. Only a hand-written payload carries one, and "Print anyway" keeps it past
  451. the fit check, so it is read as a slot left for the printer to fill.
  452. """
  453. async def test_on_a_printer_without_an_ams_the_blocked_external_spool_holds_it(self):
  454. # use_ams stays on, but the command builder turns it off for a printer
  455. # that reports no AMS, so the spool holder is what feeds.
  456. item = _item(ams_mapping="[0]", **PRINT_ANYWAY)
  457. result = await _run(
  458. _ensure(item), requirements=[REQ_WHITE_PLA], loaded=[_external(254, "GFG03")], raw_data={"ams": []}
  459. )
  460. assert result == FilamentScopeHold(SPOOL_IS_PETG_MATTE)
  461. async def test_on_a_printer_with_an_ams_it_is_left_for_the_printer_to_fill(self):
  462. item = _item(ams_mapping="[5]", **PRINT_ANYWAY)
  463. result = await _run(
  464. _ensure(item), requirements=[REQ_WHITE_PLA], loaded=[_tray(0, "GFG03"), _tray(1, "GFA00", "PLA")]
  465. )
  466. assert result == FilamentScopeHold(
  467. "Print anyway leaves PLA without a slot, and the printer could pick a loaded spool "
  468. "the job creator's group can't print with: PETG (GFG03)"
  469. )
  470. # An H3C has an external input per hotend, 247-255, and reports the ones in use.
  471. H3C_INPUTS = {"vt_tray": [{"id": "250"}, {"id": "251"}]}
  472. @pytest.mark.asyncio
  473. class TestARackPrintersExternalInputs:
  474. """On an H3C the mapping names the external input that feeds, so only that one is judged (#3522)."""
  475. @pytest.mark.parametrize(
  476. ("mapping", "raw_data", "reason"),
  477. [
  478. pytest.param("[250]", H3C_INPUTS, None, id="mapped_to_the_allowed_input"),
  479. pytest.param("[251]", H3C_INPUTS, SPOOL_IS_PETG_MATTE, id="mapped_to_the_blocked_input"),
  480. pytest.param("[250, 251]", H3C_INPUTS, SPOOL_IS_PETG_MATTE, id="mapped_to_both"),
  481. # No AMS and no input named: any of them may feed.
  482. pytest.param(None, {**H3C_INPUTS, "ams": []}, SPOOL_IS_PETG_MATTE, id="no_input_named"),
  483. ],
  484. )
  485. async def test_only_a_named_input_holds_the_job(self, mapping, raw_data, reason):
  486. result = await _run(
  487. _claimed(_item(ams_mapping=mapping)),
  488. loaded=[_external(250, "GFG99"), _external(251, "GFG03")],
  489. raw_data=raw_data,
  490. printer_model="H3C",
  491. )
  492. assert result == reason
  493. UNLISTED_NEXT_TO_PETG_MATTE = (
  494. "This file doesn't list its filaments, and the printer has a loaded spool "
  495. "the job creator's group can't print with: PETG (GFG03)"
  496. )
  497. @pytest.mark.asyncio
  498. class TestAFileThatListsNoFilaments:
  499. """A file without readable slice info can't be judged from the file, so the printer is (#3522)."""
  500. @pytest.mark.parametrize(
  501. ("scope", "loaded", "raw_data", "result"),
  502. [
  503. pytest.param(
  504. BLOCK_PETG_MATTE,
  505. [_external(254, "GFG03")],
  506. {"ams": []},
  507. FilamentScopeHold(SPOOL_IS_PETG_MATTE),
  508. id="no_ams_and_a_blocked_external_spool",
  509. ),
  510. pytest.param(BLOCK_PETG_MATTE, [_external(254, "GFG99")], {"ams": []}, None, id="allowed_external_spool"),
  511. pytest.param(
  512. BLOCK_PETG_MATTE,
  513. [_tray(0, "GFG03"), _tray(1, "GFG99")],
  514. None,
  515. FilamentScopeHold(UNLISTED_NEXT_TO_PETG_MATTE),
  516. id="a_blocked_ams_tray_the_printer_could_pick",
  517. ),
  518. pytest.param(
  519. # The AMS feeds, so the spool holder isn't one it could pick.
  520. BLOCK_PETG_MATTE,
  521. [_tray(1, "GFG99"), _external(254, "GFG03")],
  522. None,
  523. None,
  524. id="only_the_unfed_external_spool_is_blocked",
  525. ),
  526. pytest.param(ALL_FILAMENTS, [_tray(0, "GFG03")], None, None, id="unrestricted_creator_is_unaffected"),
  527. ],
  528. )
  529. async def test_the_spools_it_could_be_fed_from_decide(self, scope, loaded, raw_data, result):
  530. assert await _run(_ensure(_item()), scope, requirements=[], loaded=loaded, raw_data=raw_data) == result
  531. async def test_a_file_that_is_gone_is_left_to_the_missing_file_failure(self, tmp_path):
  532. result = await _run(_ensure(_item()), requirements=[], loaded=[_tray(0, "GFG03")], source=tmp_path / "gone.3mf")
  533. assert result is None
  534. @pytest.mark.parametrize("item_fields", [{}, {"ams_mapping": "[254]"}], ids=["no_mapping", "mapped_to_it"])
  535. async def test_a_dual_nozzle_printer_without_an_ams_may_feed_its_blocked_external_spool(self, item_fields):
  536. # use_ams picks the extruder there, not the AMS, so it stays on and
  537. # the external spools are all the printer has to feed from.
  538. result = await _run(
  539. _ensure(_item(**item_fields)),
  540. requirements=[],
  541. loaded=[_external(254, "GFG03"), _external(255, "GFA00", "PLA")],
  542. raw_data=H2D_WITHOUT_AMS,
  543. printer_model="H2D",
  544. )
  545. assert result == FilamentScopeHold(UNLISTED_NEXT_TO_PETG_MATTE)
  546. @pytest.mark.asyncio
  547. class TestTheCheckOnceClaimed:
  548. async def test_reads_the_creators_rules_afresh(self):
  549. # A pass can wait minutes on a smart plug; a rule tightened meanwhile
  550. # applies to the job it dispatches next.
  551. async def stale_then_claimed(sched):
  552. sched._filament_scope_memo[7] = ALL_FILAMENTS
  553. return await sched._claimed_scope_violation(AsyncMock(), _item())
  554. assert await _run(stale_then_claimed, requirements=[REQ_PETG_MATTE], loaded=[]) == FILE_NEEDS_PETG_MATTE
  555. @pytest.mark.asyncio
  556. class TestStartingAStagedJob:
  557. async def test_reads_the_creators_rules_afresh(self):
  558. # Start is a request, not a pass: a rule lifted since the last pass
  559. # lets the job map onto the tray it was held from.
  560. async def stale_then_start(sched):
  561. sched._filament_scope_memo[7] = BLOCK_PETG_MATTE
  562. return await sched.missing_filament_for_start(AsyncMock(), _item())
  563. assert await _run(stale_then_start, ALL_FILAMENTS, loaded=[_tray(0, "GFG03")]) is None