test_filament_deficit.py 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223
  1. """Unit tests for the filament-deficit pre-dispatch check (#1496).
  2. The check is the single source of truth that both ``POST /queue/{id}/start``
  3. and the dispatch scheduler call before sending a print to the printer. Pin
  4. the contract for the cases that matter:
  5. * Internal-inventory mode: shortfall + sufficient + no assignment.
  6. * AMS-mapping gating: a missing mapping means "not yet decided, skip".
  7. * Disabled-warnings setting + missing printer (model-based item) + no
  8. source 3MF all short-circuit to "no deficit".
  9. """
  10. from __future__ import annotations
  11. import json
  12. import logging
  13. import zipfile
  14. from pathlib import Path
  15. from unittest.mock import patch
  16. import pytest
  17. from backend.app.models.archive import PrintArchive
  18. from backend.app.models.print_queue import PrintQueueItem
  19. from backend.app.models.settings import Settings
  20. from backend.app.models.spool import Spool
  21. from backend.app.models.spool_assignment import SpoolAssignment
  22. from backend.app.services.filament_deficit import (
  23. FilamentDeficit,
  24. compute_deficit_for_queue_item,
  25. )
  26. def _write_3mf(file_path: Path, filaments: list[dict]) -> None:
  27. """Minimal 3MF that ``extract_filament_requirements`` can parse (flat shape)."""
  28. body = "".join(
  29. f'<filament id="{f["id"]}" type="{f["type"]}" color="{f["color"]}" '
  30. f'used_g="{f["used_g"]}" tray_info_idx="{f.get("tray_info_idx", "")}"/>'
  31. for f in filaments
  32. )
  33. config = f'<?xml version="1.0" encoding="utf-8"?><config>{body}</config>'
  34. with zipfile.ZipFile(file_path, "w") as zf:
  35. zf.writestr("Metadata/slice_info.config", config)
  36. async def _setup_archive_3mf(db_session, tmp_path: Path, filaments: list[dict]) -> PrintArchive:
  37. """Create a 3MF on disk and a PrintArchive row pointing at it."""
  38. file_name = "model.3mf"
  39. file_path = tmp_path / file_name
  40. _write_3mf(file_path, filaments)
  41. archive = PrintArchive(
  42. filename=file_name,
  43. print_name="Test",
  44. # The helper resolves via app_settings.base_dir / file_path, but
  45. # storing the absolute path on the model also works because
  46. # ``Path / abs`` collapses to the absolute side.
  47. file_path=str(file_path),
  48. file_size=file_path.stat().st_size,
  49. status="completed",
  50. )
  51. db_session.add(archive)
  52. await db_session.commit()
  53. await db_session.refresh(archive)
  54. return archive
  55. async def _setup_library_3mf(db_session, base_dir: Path, filaments: list[dict], *, absolute: bool = False):
  56. """Create a 3MF under ``base_dir`` and a LibraryFile row pointing at it.
  57. Mirrors production storage: the file lands in
  58. ``<base_dir>/archive/library/files/`` and the row stores the path
  59. *relative* to base_dir, exactly as ``library.py`` writes it (#2779).
  60. """
  61. from backend.app.models.library import LibraryFile
  62. rel_path = Path("archive/library/files/deficit_probe.gcode.3mf")
  63. abs_path = base_dir / rel_path
  64. abs_path.parent.mkdir(parents=True, exist_ok=True)
  65. _write_3mf(abs_path, filaments)
  66. lib_file = LibraryFile(
  67. filename="deficit_probe.gcode.3mf",
  68. file_path=str(abs_path) if absolute else str(rel_path),
  69. file_type="3mf",
  70. file_size=abs_path.stat().st_size,
  71. )
  72. db_session.add(lib_file)
  73. await db_session.commit()
  74. await db_session.refresh(lib_file)
  75. return lib_file
  76. async def _spool(
  77. db_session,
  78. *,
  79. label_weight: int,
  80. weight_used: float,
  81. color: str = "#000000",
  82. slicer_filament: str | None = None,
  83. ) -> Spool:
  84. spool = Spool(
  85. material="PLA",
  86. label_weight=label_weight,
  87. weight_used=weight_used,
  88. rgba=color,
  89. slicer_filament=slicer_filament,
  90. )
  91. db_session.add(spool)
  92. await db_session.commit()
  93. await db_session.refresh(spool)
  94. return spool
  95. async def _assign(db_session, *, printer_id: int, spool_id: int, ams_id: int = 0, tray_id: int = 0) -> None:
  96. db_session.add(
  97. SpoolAssignment(
  98. spool_id=spool_id,
  99. printer_id=printer_id,
  100. ams_id=ams_id,
  101. tray_id=tray_id,
  102. )
  103. )
  104. await db_session.commit()
  105. async def _queue_item(
  106. db_session,
  107. *,
  108. printer_id: int | None,
  109. archive: PrintArchive | None,
  110. ams_mapping: list[int] | None,
  111. plate_id: int | None = None,
  112. library_file=None,
  113. ) -> PrintQueueItem:
  114. item = PrintQueueItem(
  115. printer_id=printer_id,
  116. archive_id=archive.id if archive else None,
  117. library_file_id=library_file.id if library_file else None,
  118. ams_mapping=json.dumps(ams_mapping) if ams_mapping is not None else None,
  119. plate_id=plate_id,
  120. status="pending",
  121. manual_start=True,
  122. )
  123. db_session.add(item)
  124. await db_session.commit()
  125. await db_session.refresh(item, ["archive", "library_file"])
  126. return item
  127. class TestFilamentDeficit:
  128. @pytest.mark.asyncio
  129. async def test_returns_deficit_when_spool_too_light(self, db_session, printer_factory, tmp_path):
  130. """Spool with 30g remaining for a 100g print → one deficit row."""
  131. printer = await printer_factory()
  132. archive = await _setup_archive_3mf(
  133. db_session,
  134. tmp_path,
  135. [{"id": "1", "type": "PLA", "color": "#FFFFFF", "used_g": "100.0"}],
  136. )
  137. spool = await _spool(db_session, label_weight=1000, weight_used=970.0) # 30g left
  138. await _assign(db_session, printer_id=printer.id, spool_id=spool.id, ams_id=0, tray_id=0)
  139. item = await _queue_item(db_session, printer_id=printer.id, archive=archive, ams_mapping=[0])
  140. with patch("backend.app.services.filament_deficit.app_settings.base_dir", Path("/")):
  141. deficit = await compute_deficit_for_queue_item(db_session, item)
  142. assert len(deficit) == 1
  143. assert isinstance(deficit[0], FilamentDeficit)
  144. assert deficit[0].slot_id == 1
  145. assert deficit[0].required_grams == 100.0
  146. assert deficit[0].remaining_grams == 30.0
  147. assert deficit[0].filament_type == "PLA"
  148. @pytest.mark.asyncio
  149. async def test_returns_empty_when_spool_has_enough(self, db_session, printer_factory, tmp_path):
  150. printer = await printer_factory()
  151. archive = await _setup_archive_3mf(
  152. db_session,
  153. tmp_path,
  154. [{"id": "1", "type": "PLA", "color": "#FFFFFF", "used_g": "100.0"}],
  155. )
  156. spool = await _spool(db_session, label_weight=1000, weight_used=200.0) # 800g left
  157. await _assign(db_session, printer_id=printer.id, spool_id=spool.id, ams_id=0, tray_id=0)
  158. item = await _queue_item(db_session, printer_id=printer.id, archive=archive, ams_mapping=[0])
  159. with patch("backend.app.services.filament_deficit.app_settings.base_dir", Path("/")):
  160. deficit = await compute_deficit_for_queue_item(db_session, item)
  161. assert deficit == []
  162. @pytest.mark.asyncio
  163. async def test_returns_empty_when_ams_mapping_missing(self, db_session, printer_factory, tmp_path):
  164. """No mapping yet = scheduler hasn't decided which slot maps where."""
  165. printer = await printer_factory()
  166. archive = await _setup_archive_3mf(
  167. db_session,
  168. tmp_path,
  169. [{"id": "1", "type": "PLA", "color": "#FFFFFF", "used_g": "100.0"}],
  170. )
  171. item = await _queue_item(db_session, printer_id=printer.id, archive=archive, ams_mapping=None)
  172. with patch("backend.app.services.filament_deficit.app_settings.base_dir", Path("/")):
  173. deficit = await compute_deficit_for_queue_item(db_session, item)
  174. assert deficit == []
  175. @pytest.mark.asyncio
  176. async def test_returns_empty_when_no_printer_assigned(self, db_session, tmp_path):
  177. """Model-based queue items with no resolved printer_id can't be checked."""
  178. archive = await _setup_archive_3mf(
  179. db_session,
  180. tmp_path,
  181. [{"id": "1", "type": "PLA", "color": "#FFFFFF", "used_g": "100.0"}],
  182. )
  183. item = await _queue_item(db_session, printer_id=None, archive=archive, ams_mapping=[0])
  184. with patch("backend.app.services.filament_deficit.app_settings.base_dir", Path("/")):
  185. deficit = await compute_deficit_for_queue_item(db_session, item)
  186. assert deficit == []
  187. @pytest.mark.asyncio
  188. async def test_returns_empty_when_warnings_disabled(self, db_session, printer_factory, tmp_path):
  189. """Honour the disable_filament_warnings setting (#720 toggle)."""
  190. printer = await printer_factory()
  191. archive = await _setup_archive_3mf(
  192. db_session,
  193. tmp_path,
  194. [{"id": "1", "type": "PLA", "color": "#FFFFFF", "used_g": "100.0"}],
  195. )
  196. spool = await _spool(db_session, label_weight=1000, weight_used=970.0)
  197. await _assign(db_session, printer_id=printer.id, spool_id=spool.id)
  198. item = await _queue_item(db_session, printer_id=printer.id, archive=archive, ams_mapping=[0])
  199. db_session.add(Settings(key="disable_filament_warnings", value="true"))
  200. await db_session.commit()
  201. with patch("backend.app.services.filament_deficit.app_settings.base_dir", Path("/")):
  202. deficit = await compute_deficit_for_queue_item(db_session, item)
  203. assert deficit == []
  204. @pytest.mark.asyncio
  205. async def test_returns_empty_when_no_assignment(self, db_session, printer_factory, tmp_path):
  206. """Mapping points at a slot with no spool assigned → silent, not blocked."""
  207. printer = await printer_factory()
  208. archive = await _setup_archive_3mf(
  209. db_session,
  210. tmp_path,
  211. [{"id": "1", "type": "PLA", "color": "#FFFFFF", "used_g": "100.0"}],
  212. )
  213. item = await _queue_item(db_session, printer_id=printer.id, archive=archive, ams_mapping=[0])
  214. with patch("backend.app.services.filament_deficit.app_settings.base_dir", Path("/")):
  215. deficit = await compute_deficit_for_queue_item(db_session, item)
  216. assert deficit == []
  217. @pytest.mark.asyncio
  218. async def test_library_file_with_relative_path_is_checked(self, db_session, printer_factory, tmp_path):
  219. """#2779: a Library-backed item stores its path relative to base_dir.
  220. Resolving it against the process working directory finds nothing, and
  221. "no source" is treated as "nothing to verify" — so the check returned
  222. no deficit and the scheduler dispatched onto a spool that could not
  223. finish the print. Every Slicer Pipeline item and everything queued via
  224. the Library's Add to queue is library-backed, so the guard was absent
  225. for all of them. Numbers are the reporter's: 20.5 g needed, 9 g left.
  226. """
  227. printer = await printer_factory()
  228. lib_file = await _setup_library_3mf(
  229. db_session,
  230. tmp_path,
  231. [{"id": "1", "type": "PLA", "color": "#FFFFFF", "used_g": "20.5"}],
  232. )
  233. assert not Path(lib_file.file_path).is_absolute() # the shape that broke
  234. spool = await _spool(db_session, label_weight=1000, weight_used=991.0) # 9g left
  235. await _assign(db_session, printer_id=printer.id, spool_id=spool.id, ams_id=0, tray_id=0)
  236. item = await _queue_item(
  237. db_session, printer_id=printer.id, archive=None, library_file=lib_file, ams_mapping=[0]
  238. )
  239. with patch("backend.app.services.filament_deficit.app_settings.base_dir", tmp_path):
  240. deficit = await compute_deficit_for_queue_item(db_session, item)
  241. assert len(deficit) == 1
  242. assert deficit[0].required_grams == 20.5
  243. assert deficit[0].remaining_grams == 9.0
  244. @pytest.mark.asyncio
  245. async def test_library_file_with_absolute_path_is_checked(self, db_session, printer_factory, tmp_path):
  246. """The other half of the resolver: a row that already holds an absolute
  247. path must not be joined onto base_dir a second time."""
  248. printer = await printer_factory()
  249. lib_file = await _setup_library_3mf(
  250. db_session,
  251. tmp_path,
  252. [{"id": "1", "type": "PLA", "color": "#FFFFFF", "used_g": "100.0"}],
  253. absolute=True,
  254. )
  255. spool = await _spool(db_session, label_weight=1000, weight_used=970.0) # 30g left
  256. await _assign(db_session, printer_id=printer.id, spool_id=spool.id, ams_id=0, tray_id=0)
  257. item = await _queue_item(
  258. db_session, printer_id=printer.id, archive=None, library_file=lib_file, ams_mapping=[0]
  259. )
  260. # A base_dir the file is NOT under — joining it on would break the path.
  261. with patch("backend.app.services.filament_deficit.app_settings.base_dir", tmp_path / "elsewhere"):
  262. deficit = await compute_deficit_for_queue_item(db_session, item)
  263. assert len(deficit) == 1
  264. assert deficit[0].required_grams == 100.0
  265. @pytest.mark.asyncio
  266. async def test_missing_source_is_logged_not_just_skipped(self, db_session, printer_factory, caplog):
  267. """A source that is configured but absent still dispatches — the upload
  268. would fail seconds later anyway, and wedging the queue on a missing
  269. file is the worse trade. But it must not pass silently: skipping the
  270. check without a trace is what let #2779 go unnoticed for every
  271. library-backed item.
  272. """
  273. printer = await printer_factory()
  274. archive = PrintArchive(
  275. filename="ghost.3mf",
  276. file_path="/nonexistent/ghost.3mf",
  277. file_size=0,
  278. status="completed",
  279. )
  280. db_session.add(archive)
  281. await db_session.commit()
  282. await db_session.refresh(archive)
  283. item = await _queue_item(db_session, printer_id=printer.id, archive=archive, ams_mapping=[0])
  284. with caplog.at_level(logging.WARNING, logger="backend.app.services.filament_deficit"):
  285. deficit = await compute_deficit_for_queue_item(db_session, item)
  286. assert deficit == []
  287. assert any("ghost.3mf" in r.getMessage() for r in caplog.records)
  288. @pytest.mark.asyncio
  289. async def test_returns_empty_when_3mf_missing(self, db_session, printer_factory):
  290. printer = await printer_factory()
  291. archive = PrintArchive(
  292. filename="ghost.3mf",
  293. file_path="/nonexistent/ghost.3mf",
  294. file_size=0,
  295. status="completed",
  296. )
  297. db_session.add(archive)
  298. await db_session.commit()
  299. await db_session.refresh(archive)
  300. item = await _queue_item(db_session, printer_id=printer.id, archive=archive, ams_mapping=[0])
  301. deficit = await compute_deficit_for_queue_item(db_session, item)
  302. assert deficit == []
  303. @pytest.mark.asyncio
  304. async def test_multi_slot_only_shorted_slot_returned(self, db_session, printer_factory, tmp_path):
  305. """One slot fine, one short — only the short slot is in the result."""
  306. printer = await printer_factory()
  307. archive = await _setup_archive_3mf(
  308. db_session,
  309. tmp_path,
  310. [
  311. {"id": "1", "type": "PLA", "color": "#FFFFFF", "used_g": "100.0"},
  312. {"id": "2", "type": "PETG", "color": "#000000", "used_g": "80.0"},
  313. ],
  314. )
  315. plenty = await _spool(db_session, label_weight=1000, weight_used=100.0) # 900g
  316. shorted = await _spool(db_session, label_weight=1000, weight_used=950.0) # 50g
  317. await _assign(db_session, printer_id=printer.id, spool_id=plenty.id, ams_id=0, tray_id=0)
  318. await _assign(db_session, printer_id=printer.id, spool_id=shorted.id, ams_id=0, tray_id=1)
  319. item = await _queue_item(
  320. db_session,
  321. printer_id=printer.id,
  322. archive=archive,
  323. ams_mapping=[0, 1], # slot 1 -> tray 0, slot 2 -> tray 1
  324. )
  325. with patch("backend.app.services.filament_deficit.app_settings.base_dir", Path("/")):
  326. deficit = await compute_deficit_for_queue_item(db_session, item)
  327. assert [d.slot_id for d in deficit] == [2]
  328. assert deficit[0].remaining_grams == 50.0
  329. assert deficit[0].required_grams == 80.0
  330. class TestFilamentDeficitBackupAware:
  331. """#1762 — when AMS Filament Backup is ON, pool remaining grams across
  332. same-material spools on the printer (within the same extruder side on
  333. dual-nozzle models) before declaring a slot deficit.
  334. Reporter scenario: PLA Basic in AMS-1 slot 1 with 10 g left, same PLA
  335. Basic in AMS-2 slot 1 with 500 g left. Today's per-slot accounting
  336. blocks the print because slot 1 of AMS-1 is short. With backup ON,
  337. firmware switches mid-print, so the deficit shouldn't fire.
  338. """
  339. @staticmethod
  340. def _patch_status(
  341. *,
  342. printer_id: int,
  343. backup_on: bool,
  344. ams_extruder_map: dict | None = None,
  345. model: str | None = None,
  346. ):
  347. """Patch ``printer_manager.get_status`` + ``get_model`` for the test."""
  348. from types import SimpleNamespace
  349. from unittest.mock import patch as _patch
  350. fake_state = SimpleNamespace(
  351. ams_filament_backup=backup_on if backup_on is not None else None,
  352. ams_extruder_map=ams_extruder_map or {},
  353. )
  354. return [
  355. _patch(
  356. "backend.app.services.printer_manager.printer_manager.get_status",
  357. lambda pid: fake_state if pid == printer_id else None,
  358. ),
  359. _patch(
  360. "backend.app.services.printer_manager.printer_manager.get_model",
  361. lambda pid: model if pid == printer_id else None,
  362. ),
  363. ]
  364. @pytest.mark.asyncio
  365. async def test_backup_on_pool_covers_short_slot(self, db_session, printer_factory, tmp_path):
  366. """The reporter scenario: assigned slot is short, but the same
  367. material on a peer slot covers the print. With backup ON, no deficit."""
  368. printer = await printer_factory(model="X1C")
  369. archive = await _setup_archive_3mf(
  370. db_session,
  371. tmp_path,
  372. [{"id": "1", "type": "PLA", "color": "#000000", "used_g": "200.0"}],
  373. )
  374. # Mapped slot: 10 g remaining, same Bambu preset as peer.
  375. short = await _spool(db_session, label_weight=1000, weight_used=990.0, slicer_filament="GFA00")
  376. # Peer slot on AMS-2: same preset, 500 g remaining.
  377. peer = await _spool(db_session, label_weight=1000, weight_used=500.0, slicer_filament="GFA00")
  378. await _assign(db_session, printer_id=printer.id, spool_id=short.id, ams_id=0, tray_id=0)
  379. await _assign(db_session, printer_id=printer.id, spool_id=peer.id, ams_id=1, tray_id=0)
  380. item = await _queue_item(
  381. db_session,
  382. printer_id=printer.id,
  383. archive=archive,
  384. ams_mapping=[0],
  385. )
  386. patches = TestFilamentDeficitBackupAware._patch_status(printer_id=printer.id, backup_on=True, model="X1C")
  387. with patch("backend.app.services.filament_deficit.app_settings.base_dir", Path("/")):
  388. for p in patches:
  389. p.start()
  390. try:
  391. deficit = await compute_deficit_for_queue_item(db_session, item)
  392. finally:
  393. for p in patches:
  394. p.stop()
  395. # Pool (10 + 500 = 510 g) covers the 200 g print → no deficit.
  396. assert deficit == []
  397. @pytest.mark.asyncio
  398. async def test_backup_on_pool_insufficient_emits_deficit(self, db_session, printer_factory, tmp_path):
  399. """Backup ON but the same-material pool across all slots is still
  400. too small for the print → deficit emitted (real shortfall)."""
  401. printer = await printer_factory(model="X1C")
  402. archive = await _setup_archive_3mf(
  403. db_session,
  404. tmp_path,
  405. [{"id": "1", "type": "PLA", "color": "#000000", "used_g": "1500.0"}],
  406. )
  407. a = await _spool(db_session, label_weight=1000, weight_used=900.0, slicer_filament="GFA00") # 100g
  408. b = await _spool(db_session, label_weight=1000, weight_used=700.0, slicer_filament="GFA00") # 300g
  409. await _assign(db_session, printer_id=printer.id, spool_id=a.id, ams_id=0, tray_id=0)
  410. await _assign(db_session, printer_id=printer.id, spool_id=b.id, ams_id=1, tray_id=0)
  411. item = await _queue_item(
  412. db_session,
  413. printer_id=printer.id,
  414. archive=archive,
  415. ams_mapping=[0],
  416. )
  417. patches = TestFilamentDeficitBackupAware._patch_status(printer_id=printer.id, backup_on=True, model="X1C")
  418. with patch("backend.app.services.filament_deficit.app_settings.base_dir", Path("/")):
  419. for p in patches:
  420. p.start()
  421. try:
  422. deficit = await compute_deficit_for_queue_item(db_session, item)
  423. finally:
  424. for p in patches:
  425. p.stop()
  426. # Pool 400 g < required 1500 g → deficit fires.
  427. assert len(deficit) == 1
  428. assert deficit[0].slot_id == 1
  429. @pytest.mark.asyncio
  430. async def test_backup_on_different_materials_no_pool(self, db_session, printer_factory, tmp_path):
  431. """Backup ON, but the peer slot holds a DIFFERENT material — pool
  432. doesn't include it, deficit fires for the original short slot."""
  433. printer = await printer_factory(model="X1C")
  434. archive = await _setup_archive_3mf(
  435. db_session,
  436. tmp_path,
  437. [{"id": "1", "type": "PLA", "color": "#FFFFFF", "used_g": "200.0"}],
  438. )
  439. # Assigned slot: PLA White preset GFA01, 10 g.
  440. short = await _spool(db_session, label_weight=1000, weight_used=990.0, color="#FFFFFF", slicer_filament="GFA01")
  441. # Peer: PLA Black, different preset (GFA00) — NOT a backup peer under the strict rule.
  442. peer = await _spool(db_session, label_weight=1000, weight_used=500.0, color="#000000", slicer_filament="GFA00")
  443. await _assign(db_session, printer_id=printer.id, spool_id=short.id, ams_id=0, tray_id=0)
  444. await _assign(db_session, printer_id=printer.id, spool_id=peer.id, ams_id=1, tray_id=0)
  445. item = await _queue_item(
  446. db_session,
  447. printer_id=printer.id,
  448. archive=archive,
  449. ams_mapping=[0],
  450. )
  451. patches = TestFilamentDeficitBackupAware._patch_status(printer_id=printer.id, backup_on=True, model="X1C")
  452. with patch("backend.app.services.filament_deficit.app_settings.base_dir", Path("/")):
  453. for p in patches:
  454. p.start()
  455. try:
  456. deficit = await compute_deficit_for_queue_item(db_session, item)
  457. finally:
  458. for p in patches:
  459. p.stop()
  460. # Pool for white = 10 g, required = 200 g → deficit.
  461. assert len(deficit) == 1
  462. assert deficit[0].slot_id == 1
  463. assert deficit[0].remaining_grams == 10.0
  464. @pytest.mark.asyncio
  465. async def test_backup_off_falls_back_to_per_slot_accounting(self, db_session, printer_factory, tmp_path):
  466. """When backup is OFF the new code path must be a strict no-op vs.
  467. the pre-#1762 per-slot accounting. Identical inputs to the
  468. ``pool_covers_short_slot`` case but with backup OFF — deficit fires."""
  469. printer = await printer_factory(model="X1C")
  470. archive = await _setup_archive_3mf(
  471. db_session,
  472. tmp_path,
  473. [{"id": "1", "type": "PLA", "color": "#000000", "used_g": "200.0"}],
  474. )
  475. short = await _spool(db_session, label_weight=1000, weight_used=990.0, slicer_filament="GFA00")
  476. peer = await _spool(db_session, label_weight=1000, weight_used=500.0, slicer_filament="GFA00")
  477. await _assign(db_session, printer_id=printer.id, spool_id=short.id, ams_id=0, tray_id=0)
  478. await _assign(db_session, printer_id=printer.id, spool_id=peer.id, ams_id=1, tray_id=0)
  479. item = await _queue_item(
  480. db_session,
  481. printer_id=printer.id,
  482. archive=archive,
  483. ams_mapping=[0],
  484. )
  485. patches = TestFilamentDeficitBackupAware._patch_status(printer_id=printer.id, backup_on=False, model="X1C")
  486. with patch("backend.app.services.filament_deficit.app_settings.base_dir", Path("/")):
  487. for p in patches:
  488. p.start()
  489. try:
  490. deficit = await compute_deficit_for_queue_item(db_session, item)
  491. finally:
  492. for p in patches:
  493. p.stop()
  494. # Backup OFF → per-slot accounting → slot 1 has 10 g, needs 200 g.
  495. assert len(deficit) == 1
  496. assert deficit[0].remaining_grams == 10.0
  497. @pytest.mark.asyncio
  498. async def test_backup_on_dual_extruder_scopes_pool_per_side(self, db_session, printer_factory, tmp_path):
  499. """Dual-extruder printer (H2D): peer slot on the OPPOSITE extruder
  500. does NOT count toward the pool — firmware can't cross. Deficit fires."""
  501. printer = await printer_factory(model="O1D") # H2D internal code
  502. archive = await _setup_archive_3mf(
  503. db_session,
  504. tmp_path,
  505. [{"id": "1", "type": "PLA", "color": "#000000", "used_g": "200.0"}],
  506. )
  507. short = await _spool(db_session, label_weight=1000, weight_used=990.0, slicer_filament="GFA00")
  508. peer_other_side = await _spool(db_session, label_weight=1000, weight_used=500.0, slicer_filament="GFA00")
  509. # AMS 0 is on extruder 0 (right). AMS 1 is on extruder 1 (left).
  510. await _assign(db_session, printer_id=printer.id, spool_id=short.id, ams_id=0, tray_id=0)
  511. await _assign(db_session, printer_id=printer.id, spool_id=peer_other_side.id, ams_id=1, tray_id=0)
  512. item = await _queue_item(
  513. db_session,
  514. printer_id=printer.id,
  515. archive=archive,
  516. ams_mapping=[0],
  517. )
  518. patches = TestFilamentDeficitBackupAware._patch_status(
  519. printer_id=printer.id,
  520. backup_on=True,
  521. ams_extruder_map={"0": 0, "1": 1},
  522. model="O1D",
  523. )
  524. with patch("backend.app.services.filament_deficit.app_settings.base_dir", Path("/")):
  525. for p in patches:
  526. p.start()
  527. try:
  528. deficit = await compute_deficit_for_queue_item(db_session, item)
  529. finally:
  530. for p in patches:
  531. p.stop()
  532. # Pool for extruder 0 = 10 g (peer on extruder 1 is unreachable) <
  533. # required 200 g → deficit.
  534. assert len(deficit) == 1
  535. assert deficit[0].slot_id == 1
  536. @pytest.mark.asyncio
  537. async def test_backup_on_no_preset_never_pairs(self, db_session, printer_factory, tmp_path):
  538. """Strict rule: two user-tagged spools with no slicer_filament preset
  539. must NEVER pair, even when material + colour match. Mirrors Bambu
  540. firmware: the backup decision relies on the Bambu Lab preset ID, so
  541. generic spools without one can't be trusted to switch."""
  542. printer = await printer_factory(model="X1C")
  543. archive = await _setup_archive_3mf(
  544. db_session,
  545. tmp_path,
  546. [{"id": "1", "type": "PLA", "color": "#000000", "used_g": "200.0"}],
  547. )
  548. # Both spools: material PLA, colour black, NO preset → unique keys.
  549. short = await _spool(db_session, label_weight=1000, weight_used=990.0)
  550. peer_no_preset = await _spool(db_session, label_weight=1000, weight_used=500.0)
  551. await _assign(db_session, printer_id=printer.id, spool_id=short.id, ams_id=0, tray_id=0)
  552. await _assign(db_session, printer_id=printer.id, spool_id=peer_no_preset.id, ams_id=1, tray_id=0)
  553. item = await _queue_item(
  554. db_session,
  555. printer_id=printer.id,
  556. archive=archive,
  557. ams_mapping=[0],
  558. )
  559. patches = TestFilamentDeficitBackupAware._patch_status(printer_id=printer.id, backup_on=True, model="X1C")
  560. with patch("backend.app.services.filament_deficit.app_settings.base_dir", Path("/")):
  561. for p in patches:
  562. p.start()
  563. try:
  564. deficit = await compute_deficit_for_queue_item(db_session, item)
  565. finally:
  566. for p in patches:
  567. p.stop()
  568. # No preset means no pool — slot 1's 10 g vs 200 g required → deficit.
  569. assert len(deficit) == 1
  570. assert deficit[0].slot_id == 1
  571. assert deficit[0].remaining_grams == 10.0
  572. @pytest.mark.asyncio
  573. async def test_backup_on_same_preset_different_colors_does_not_pair(self, db_session, printer_factory, tmp_path):
  574. """STRICT colour rule: two spools sharing the same Bambu preset ID
  575. but DIFFERENT colours must NOT pool. Three PETG HF spools in
  576. different colours can't back each other up — the firmware would
  577. switch material correctly but the print would change colour
  578. mid-run. Pool is per-(preset, colour)."""
  579. printer = await printer_factory(model="X1C")
  580. archive = await _setup_archive_3mf(
  581. db_session,
  582. tmp_path,
  583. [{"id": "1", "type": "PLA", "color": "#000000", "used_g": "200.0"}],
  584. )
  585. # Assigned slot: PLA Basic + GFA00 + BLACK, only 10 g left.
  586. short = await _spool(db_session, label_weight=1000, weight_used=990.0, color="#000000", slicer_filament="GFA00")
  587. # Peer slot: same GFA00 profile but WHITE — must not pool.
  588. peer_diff_color = await _spool(
  589. db_session, label_weight=1000, weight_used=500.0, color="#FFFFFF", slicer_filament="GFA00"
  590. )
  591. await _assign(db_session, printer_id=printer.id, spool_id=short.id, ams_id=0, tray_id=0)
  592. await _assign(db_session, printer_id=printer.id, spool_id=peer_diff_color.id, ams_id=1, tray_id=0)
  593. item = await _queue_item(
  594. db_session,
  595. printer_id=printer.id,
  596. archive=archive,
  597. ams_mapping=[0],
  598. )
  599. patches = TestFilamentDeficitBackupAware._patch_status(printer_id=printer.id, backup_on=True, model="X1C")
  600. with patch("backend.app.services.filament_deficit.app_settings.base_dir", Path("/")):
  601. for p in patches:
  602. p.start()
  603. try:
  604. deficit = await compute_deficit_for_queue_item(db_session, item)
  605. finally:
  606. for p in patches:
  607. p.stop()
  608. # Pool for (GFA00, black) = 10 g; required = 200 g → deficit.
  609. assert len(deficit) == 1
  610. assert deficit[0].slot_id == 1
  611. assert deficit[0].remaining_grams == 10.0
  612. @pytest.mark.asyncio
  613. async def test_backup_on_color_alpha_normalized(self, db_session, printer_factory, tmp_path):
  614. """Colour normalisation: 6-char hex matches 8-char hex of the same
  615. RGB. ``000000`` and ``000000FF`` should both resolve to BLACK."""
  616. printer = await printer_factory(model="X1C")
  617. archive = await _setup_archive_3mf(
  618. db_session,
  619. tmp_path,
  620. [{"id": "1", "type": "PLA", "color": "#000000", "used_g": "200.0"}],
  621. )
  622. short = await _spool(db_session, label_weight=1000, weight_used=990.0, color="#000000", slicer_filament="GFA00")
  623. # Same colour but expressed with explicit alpha.
  624. peer = await _spool(
  625. db_session, label_weight=1000, weight_used=500.0, color="#000000FF", slicer_filament="GFA00"
  626. )
  627. await _assign(db_session, printer_id=printer.id, spool_id=short.id, ams_id=0, tray_id=0)
  628. await _assign(db_session, printer_id=printer.id, spool_id=peer.id, ams_id=1, tray_id=0)
  629. item = await _queue_item(
  630. db_session,
  631. printer_id=printer.id,
  632. archive=archive,
  633. ams_mapping=[0],
  634. )
  635. patches = TestFilamentDeficitBackupAware._patch_status(printer_id=printer.id, backup_on=True, model="X1C")
  636. with patch("backend.app.services.filament_deficit.app_settings.base_dir", Path("/")):
  637. for p in patches:
  638. p.start()
  639. try:
  640. deficit = await compute_deficit_for_queue_item(db_session, item)
  641. finally:
  642. for p in patches:
  643. p.stop()
  644. # Pool (10 + 500 = 510 g) covers 200 g → no deficit.
  645. assert deficit == []
  646. class TestBuildSlotMaterials:
  647. """``build_slot_materials`` is the pool the backup accounting draws on, and
  648. the payload ``GET /printers/{id}/inventory-remain`` hands the PrintModal.
  649. The modal used to resolve spools itself and knew nothing about AMS Filament
  650. Backup, so it blocked prints the dispatcher would have run — two full eSUN
  651. spools in A3/A4, 1441 g needed, "A3: needs 1441g, remaining 1000g". Both
  652. sides now group on the keys this builder emits, so the modal's warning and
  653. the dispatcher's 409 cannot disagree about what backs what up.
  654. """
  655. @pytest.mark.asyncio
  656. async def test_internal_mode_emits_shared_key_for_same_preset_and_colour(self, db_session, printer_factory):
  657. """The reporter's slots: same preset, same colour, adjacent trays."""
  658. from backend.app.services.filament_deficit import build_slot_materials
  659. printer = await printer_factory(model="H2D")
  660. a3 = await _spool(db_session, label_weight=1000, weight_used=0.0, color="#616777FF", slicer_filament="PFUS6488")
  661. a4 = await _spool(db_session, label_weight=1000, weight_used=0.0, color="#616777", slicer_filament="PFUS6488")
  662. await _assign(db_session, printer_id=printer.id, spool_id=a3.id, ams_id=0, tray_id=2)
  663. await _assign(db_session, printer_id=printer.id, spool_id=a4.id, ams_id=0, tray_id=3)
  664. patches = TestFilamentDeficitBackupAware._patch_status(printer_id=printer.id, backup_on=True, model="H2D")
  665. for p in patches:
  666. p.start()
  667. try:
  668. slots = await build_slot_materials(db_session, printer.id)
  669. finally:
  670. for p in patches:
  671. p.stop()
  672. by_tray = {s.global_tray_id: s for s in slots}
  673. assert set(by_tray) == {2, 3}
  674. assert by_tray[2].material_key == by_tray[3].material_key
  675. assert by_tray[2].remaining_grams == 1000.0
  676. # Pooled, the two cover the 1441 g the modal refused to start.
  677. assert sum(s.remaining_grams for s in slots) == 2000.0
  678. @pytest.mark.asyncio
  679. async def test_internal_mode_separates_colours_and_presetless_spools(self, db_session, printer_factory):
  680. """Different colour, and no preset at all, must never share a key."""
  681. from backend.app.services.filament_deficit import build_slot_materials
  682. printer = await printer_factory(model="X1C")
  683. black = await _spool(db_session, label_weight=1000, weight_used=0.0, color="#000000", slicer_filament="GFA00")
  684. white = await _spool(db_session, label_weight=1000, weight_used=0.0, color="#FFFFFF", slicer_filament="GFA00")
  685. untagged_a = await _spool(db_session, label_weight=1000, weight_used=0.0, color="#000000")
  686. untagged_b = await _spool(db_session, label_weight=1000, weight_used=0.0, color="#000000")
  687. for idx, spool in enumerate((black, white, untagged_a, untagged_b)):
  688. await _assign(db_session, printer_id=printer.id, spool_id=spool.id, ams_id=0, tray_id=idx)
  689. patches = TestFilamentDeficitBackupAware._patch_status(printer_id=printer.id, backup_on=True, model="X1C")
  690. for p in patches:
  691. p.start()
  692. try:
  693. slots = await build_slot_materials(db_session, printer.id)
  694. finally:
  695. for p in patches:
  696. p.stop()
  697. keys = [s.material_key for s in sorted(slots, key=lambda s: s.global_tray_id)]
  698. assert len(set(keys)) == 4, keys
  699. @pytest.mark.asyncio
  700. async def test_internal_mode_scopes_extruder_on_dual_nozzle(self, db_session, printer_factory):
  701. """Same material on opposite sides of an H2D can't back each other up."""
  702. from backend.app.services.filament_deficit import build_slot_materials
  703. printer = await printer_factory(model="H2D")
  704. right = await _spool(db_session, label_weight=1000, weight_used=0.0, slicer_filament="GFA00")
  705. left = await _spool(db_session, label_weight=1000, weight_used=0.0, slicer_filament="GFA00")
  706. await _assign(db_session, printer_id=printer.id, spool_id=right.id, ams_id=0, tray_id=0)
  707. await _assign(db_session, printer_id=printer.id, spool_id=left.id, ams_id=1, tray_id=0)
  708. patches = TestFilamentDeficitBackupAware._patch_status(
  709. printer_id=printer.id, backup_on=True, ams_extruder_map={"0": 0, "1": 1}, model="H2D"
  710. )
  711. for p in patches:
  712. p.start()
  713. try:
  714. slots = await build_slot_materials(db_session, printer.id)
  715. finally:
  716. for p in patches:
  717. p.stop()
  718. by_tray = {s.global_tray_id: s for s in slots}
  719. assert by_tray[0].material_key == by_tray[4].material_key # same material...
  720. assert {by_tray[0].extruder, by_tray[4].extruder} == {0, 1} # ...different side
  721. @pytest.mark.asyncio
  722. async def test_internal_mode_omits_slots_with_no_usable_weight(self, db_session, printer_factory):
  723. """A binding with no label weight is unknown, not empty — omit it so the
  724. client can't read a missing slot as a zero-gram one."""
  725. from backend.app.services.filament_deficit import build_slot_materials
  726. printer = await printer_factory(model="X1C")
  727. unweighed = await _spool(db_session, label_weight=0, weight_used=0.0, slicer_filament="GFA00")
  728. ok = await _spool(db_session, label_weight=1000, weight_used=250.0, slicer_filament="GFA00")
  729. await _assign(db_session, printer_id=printer.id, spool_id=unweighed.id, ams_id=0, tray_id=0)
  730. await _assign(db_session, printer_id=printer.id, spool_id=ok.id, ams_id=0, tray_id=1)
  731. patches = TestFilamentDeficitBackupAware._patch_status(printer_id=printer.id, backup_on=True, model="X1C")
  732. for p in patches:
  733. p.start()
  734. try:
  735. slots = await build_slot_materials(db_session, printer.id)
  736. finally:
  737. for p in patches:
  738. p.stop()
  739. assert [(s.global_tray_id, s.remaining_grams) for s in slots] == [(1, 750.0)]
  740. @pytest.mark.asyncio
  741. async def test_external_and_ht_slots_get_the_frontend_tray_numbering(self, db_session, printer_factory):
  742. """``global_tray_id`` must match the client's ``getGlobalTrayId`` or the
  743. modal looks up the wrong slot: 254+ for external, unit id for AMS-HT."""
  744. from backend.app.services.filament_deficit import build_slot_materials
  745. printer = await printer_factory(model="X1C")
  746. ht = await _spool(db_session, label_weight=1000, weight_used=0.0, slicer_filament="GFA00")
  747. ext = await _spool(db_session, label_weight=1000, weight_used=0.0, slicer_filament="GFA01")
  748. await _assign(db_session, printer_id=printer.id, spool_id=ht.id, ams_id=128, tray_id=0)
  749. await _assign(db_session, printer_id=printer.id, spool_id=ext.id, ams_id=255, tray_id=0)
  750. patches = TestFilamentDeficitBackupAware._patch_status(printer_id=printer.id, backup_on=True, model="X1C")
  751. for p in patches:
  752. p.start()
  753. try:
  754. slots = await build_slot_materials(db_session, printer.id)
  755. finally:
  756. for p in patches:
  757. p.stop()
  758. assert sorted(s.global_tray_id for s in slots) == [128, 254]
  759. @pytest.mark.asyncio
  760. async def test_spoolman_mode_pools_on_filament_id_and_colour(self, db_session, printer_factory):
  761. """Spoolman parity: same catalog filament + colour → one pool key."""
  762. from unittest.mock import AsyncMock
  763. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  764. from backend.app.services.filament_deficit import build_slot_materials
  765. printer = await printer_factory(model="H2D")
  766. db_session.add(Settings(key="spoolman_enabled", value="true"))
  767. for tray_id, spool_id in ((2, 68), (3, 69)):
  768. db_session.add(
  769. SpoolmanSlotAssignment(printer_id=printer.id, ams_id=0, tray_id=tray_id, spoolman_spool_id=spool_id)
  770. )
  771. await db_session.commit()
  772. spools = {
  773. 68: {"id": 68, "remaining_weight": 1000.0, "filament": {"id": 7, "color_hex": "616777"}},
  774. # Same catalog entry, colour spelled with alpha, weight via used_weight.
  775. 69: {"id": 69, "used_weight": 0.0, "filament": {"id": 7, "weight": 1000.0, "color_hex": "616777FF"}},
  776. }
  777. client = AsyncMock()
  778. client.get_spool = AsyncMock(side_effect=lambda sid: spools[sid])
  779. patches = TestFilamentDeficitBackupAware._patch_status(printer_id=printer.id, backup_on=True, model="H2D")
  780. for p in patches:
  781. p.start()
  782. try:
  783. with patch(
  784. "backend.app.services.spoolman.get_spoolman_client",
  785. AsyncMock(return_value=client),
  786. ):
  787. slots = await build_slot_materials(db_session, printer.id)
  788. finally:
  789. for p in patches:
  790. p.stop()
  791. assert len({s.material_key for s in slots}) == 1
  792. assert sum(s.remaining_grams for s in slots) == 2000.0
  793. @pytest.mark.asyncio
  794. async def test_spoolman_unreachable_returns_no_slots(self, db_session, printer_factory):
  795. """A Spoolman blip must read as "nothing to verify", never as an empty
  796. AMS — the modal would otherwise warn on every slot while it's down."""
  797. from unittest.mock import AsyncMock
  798. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  799. from backend.app.services.filament_deficit import build_slot_materials
  800. printer = await printer_factory(model="X1C")
  801. db_session.add(Settings(key="spoolman_enabled", value="true"))
  802. db_session.add(SpoolmanSlotAssignment(printer_id=printer.id, ams_id=0, tray_id=0, spoolman_spool_id=1))
  803. await db_session.commit()
  804. patches = TestFilamentDeficitBackupAware._patch_status(printer_id=printer.id, backup_on=True, model="X1C")
  805. for p in patches:
  806. p.start()
  807. try:
  808. with patch(
  809. "backend.app.services.spoolman.get_spoolman_client",
  810. AsyncMock(return_value=None),
  811. ):
  812. slots = await build_slot_materials(db_session, printer.id)
  813. finally:
  814. for p in patches:
  815. p.stop()
  816. assert slots == []
  817. class TestSlotSpoolIdentity:
  818. """The display half of ``build_slot_materials``.
  819. A tray record has no brand field, and ``tray_sub_brands`` stays empty for
  820. anything that isn't a Bambu spool, so a client naming a slot from telemetry
  821. alone has only the type and a colour hex — which it resolves against
  822. Bambu's own colour catalogue. The reporter's Devil Design PLA Basic Orange
  823. therefore read as "PLA (Sunflower Yellow)" in the print dialog while the
  824. printer card, which reads the assignment, named it correctly.
  825. Descriptive only: nothing here takes part in matching, which stays on the
  826. printer's telemetry so the dialog and the dispatcher cannot disagree.
  827. """
  828. @pytest.mark.asyncio
  829. async def test_internal_mode_carries_what_the_printer_cannot_say(self, db_session, printer_factory):
  830. """Brand and subtype exist nowhere in the telemetry for a third-party spool."""
  831. from backend.app.services.filament_deficit import build_slot_materials
  832. printer = await printer_factory(model="H2C")
  833. spool = Spool(
  834. brand="Devil Design",
  835. material="PLA",
  836. subtype="Basic",
  837. color_name="Orange",
  838. rgba="FEC600FF",
  839. label_weight=1000,
  840. weight_used=0.0,
  841. )
  842. db_session.add(spool)
  843. await db_session.commit()
  844. await db_session.refresh(spool)
  845. await _assign(db_session, printer_id=printer.id, spool_id=spool.id, ams_id=2, tray_id=0)
  846. patches = TestFilamentDeficitBackupAware._patch_status(printer_id=printer.id, backup_on=False, model="H2C")
  847. for p in patches:
  848. p.start()
  849. try:
  850. slots = await build_slot_materials(db_session, printer.id)
  851. finally:
  852. for p in patches:
  853. p.stop()
  854. assert len(slots) == 1
  855. identity = slots[0].spool
  856. assert identity is not None
  857. assert identity.to_dict() == {
  858. "brand": "Devil Design",
  859. "material": "PLA",
  860. "subtype": "Basic",
  861. # The hex is FEC600, which is also Bambu's "Sunflower Yellow" —
  862. # naming this slot from the hex is exactly the bug.
  863. "color_name": "Orange",
  864. "rgba": "FEC600FF",
  865. }
  866. @pytest.mark.asyncio
  867. async def test_blank_fields_become_null_so_the_client_can_fall_back(self, db_session, printer_factory):
  868. """Per-field, not all-or-nothing: an unnamed colour still falls back to
  869. the catalogue lookup while the brand and subtype come from the spool."""
  870. from backend.app.services.filament_deficit import build_slot_materials
  871. printer = await printer_factory(model="H2C")
  872. spool = Spool(
  873. brand=" ",
  874. material="PLA",
  875. subtype="Silk+",
  876. color_name=None,
  877. rgba="5F6367FF",
  878. label_weight=1000,
  879. weight_used=0.0,
  880. )
  881. db_session.add(spool)
  882. await db_session.commit()
  883. await db_session.refresh(spool)
  884. await _assign(db_session, printer_id=printer.id, spool_id=spool.id, ams_id=0, tray_id=2)
  885. patches = TestFilamentDeficitBackupAware._patch_status(printer_id=printer.id, backup_on=False, model="H2C")
  886. for p in patches:
  887. p.start()
  888. try:
  889. slots = await build_slot_materials(db_session, printer.id)
  890. finally:
  891. for p in patches:
  892. p.stop()
  893. identity = slots[0].spool
  894. assert identity is not None
  895. assert identity.brand is None
  896. assert identity.color_name is None
  897. assert identity.subtype == "Silk+"
  898. @pytest.mark.asyncio
  899. async def test_spoolman_mode_reaches_the_same_shape(self, db_session, printer_factory):
  900. """Parity (#1390): brand off the nested vendor, subtype from the
  901. filament name with its material prefix stripped. Derived through
  902. ``_map_spoolman_spool`` rather than re-read here, which is what stops
  903. the two inventory modes drifting apart."""
  904. from unittest.mock import AsyncMock
  905. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  906. from backend.app.services.filament_deficit import build_slot_materials
  907. printer = await printer_factory(model="H2C")
  908. db_session.add(Settings(key="spoolman_enabled", value="true"))
  909. db_session.add(SpoolmanSlotAssignment(printer_id=printer.id, ams_id=2, tray_id=0, spoolman_spool_id=42))
  910. await db_session.commit()
  911. client = AsyncMock()
  912. client.get_spool = AsyncMock(
  913. return_value={
  914. "id": 42,
  915. "remaining_weight": 800.0,
  916. "extra": {"bambu_color_name": '"Orange"'},
  917. "filament": {
  918. "id": 7,
  919. "name": "PLA Basic",
  920. "material": "PLA",
  921. "color_hex": "FEC600",
  922. "weight": 1000,
  923. "vendor": {"id": 3, "name": "Devil Design"},
  924. },
  925. }
  926. )
  927. patches = TestFilamentDeficitBackupAware._patch_status(printer_id=printer.id, backup_on=False, model="H2C")
  928. for p in patches:
  929. p.start()
  930. try:
  931. with patch(
  932. "backend.app.services.spoolman.get_spoolman_client",
  933. AsyncMock(return_value=client),
  934. ):
  935. slots = await build_slot_materials(db_session, printer.id)
  936. finally:
  937. for p in patches:
  938. p.stop()
  939. identity = slots[0].spool
  940. assert identity is not None
  941. assert identity.brand == "Devil Design"
  942. assert identity.material == "PLA"
  943. assert identity.subtype == "Basic"
  944. assert identity.color_name == "Orange"
  945. assert identity.rgba == "FEC600FF"
  946. @pytest.mark.asyncio
  947. async def test_spoolman_synthesised_colour_name_is_dropped(self, db_session, printer_factory):
  948. """Spoolman has no colour-name field, so `_map_spoolman_spool` falls
  949. back to the subtype when nothing is stored. That reads fine in an
  950. inventory list and badly as a colour — "Devil Design PLA Basic
  951. (Basic)". Withheld, so the client names the hex as it did before."""
  952. from unittest.mock import AsyncMock
  953. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  954. from backend.app.services.filament_deficit import build_slot_materials
  955. printer = await printer_factory(model="H2C")
  956. db_session.add(Settings(key="spoolman_enabled", value="true"))
  957. db_session.add(SpoolmanSlotAssignment(printer_id=printer.id, ams_id=0, tray_id=0, spoolman_spool_id=9))
  958. await db_session.commit()
  959. client = AsyncMock()
  960. # No extra.bambu_color_name and no filament.color_name — the two places
  961. # a real one can come from.
  962. client.get_spool = AsyncMock(
  963. return_value={
  964. "id": 9,
  965. "remaining_weight": 500.0,
  966. "filament": {
  967. "id": 2,
  968. "name": "PLA Basic",
  969. "material": "PLA",
  970. "color_hex": "FEC600",
  971. "vendor": {"id": 1, "name": "Devil Design"},
  972. },
  973. }
  974. )
  975. patches = TestFilamentDeficitBackupAware._patch_status(printer_id=printer.id, backup_on=False, model="H2C")
  976. for p in patches:
  977. p.start()
  978. try:
  979. with patch(
  980. "backend.app.services.spoolman.get_spoolman_client",
  981. AsyncMock(return_value=client),
  982. ):
  983. slots = await build_slot_materials(db_session, printer.id)
  984. finally:
  985. for p in patches:
  986. p.stop()
  987. identity = slots[0].spool
  988. assert identity is not None
  989. assert identity.subtype == "Basic"
  990. assert identity.color_name is None
  991. @pytest.mark.asyncio
  992. @pytest.mark.parametrize(
  993. "payload",
  994. [
  995. {"id": 1, "remaining_weight": 500.0, "filament": "PLA"},
  996. {"id": 1, "remaining_weight": 500.0, "filament": {"id": 2}, "extra": "nope"},
  997. {"id": 1, "remaining_weight": 500.0, "filament": {"id": 2}, "extra": {"tag": 12345}},
  998. {"id": 1, "remaining_weight": 500.0, "filament": {"id": 2, "color_hex": 255}},
  999. {"id": 1, "remaining_weight": 500.0, "filament": {"id": 2, "vendor": ["x"]}},
  1000. ],
  1001. ids=["filament-not-a-dict", "extra-not-a-dict", "tag-not-a-str", "hex-not-a-str", "vendor-not-a-dict"],
  1002. )
  1003. async def test_malformed_spoolman_payload_cannot_break_a_dispatch(self, db_session, printer_factory, payload):
  1004. """Naming a slot must never cost a queue start.
  1005. ``build_slot_materials`` is on the dispatch path — every queue start
  1006. runs it through ``compute_deficit_for_queue_item``. The mapper walks a
  1007. dozen nested wire fields, and each of these arrives as the wrong type
  1008. and raises AttributeError, not ValueError.
  1009. """
  1010. from unittest.mock import AsyncMock
  1011. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  1012. from backend.app.services.filament_deficit import build_slot_materials
  1013. printer = await printer_factory(model="X1C")
  1014. db_session.add(Settings(key="spoolman_enabled", value="true"))
  1015. db_session.add(SpoolmanSlotAssignment(printer_id=printer.id, ams_id=0, tray_id=0, spoolman_spool_id=1))
  1016. await db_session.commit()
  1017. client = AsyncMock()
  1018. client.get_spool = AsyncMock(return_value=payload)
  1019. patches = TestFilamentDeficitBackupAware._patch_status(printer_id=printer.id, backup_on=False, model="X1C")
  1020. for p in patches:
  1021. p.start()
  1022. try:
  1023. with patch(
  1024. "backend.app.services.spoolman.get_spoolman_client",
  1025. AsyncMock(return_value=client),
  1026. ):
  1027. slots = await build_slot_materials(db_session, printer.id)
  1028. finally:
  1029. for p in patches:
  1030. p.stop()
  1031. # The slot keeps its grams — only the name is lost.
  1032. assert len(slots) == 1
  1033. assert slots[0].remaining_grams == 500.0
  1034. assert slots[0].spool is None
  1035. @pytest.mark.asyncio
  1036. async def test_unreadable_spoolman_spool_keeps_the_slot_but_drops_the_name(self, db_session, printer_factory):
  1037. """A spool we cannot describe must not cost the slot its place in the
  1038. pool — the backup accounting still needs its grams. The client falls
  1039. back to telemetry for the name, exactly as before this existed."""
  1040. from unittest.mock import AsyncMock
  1041. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  1042. from backend.app.services.filament_deficit import build_slot_materials
  1043. printer = await printer_factory(model="X1C")
  1044. db_session.add(Settings(key="spoolman_enabled", value="true"))
  1045. db_session.add(SpoolmanSlotAssignment(printer_id=printer.id, ams_id=0, tray_id=0, spoolman_spool_id=5))
  1046. await db_session.commit()
  1047. client = AsyncMock()
  1048. # No id — `_map_spoolman_spool` raises, and only the naming is lost.
  1049. client.get_spool = AsyncMock(return_value={"remaining_weight": 500.0, "filament": {"id": 1}})
  1050. patches = TestFilamentDeficitBackupAware._patch_status(printer_id=printer.id, backup_on=False, model="X1C")
  1051. for p in patches:
  1052. p.start()
  1053. try:
  1054. with patch(
  1055. "backend.app.services.spoolman.get_spoolman_client",
  1056. AsyncMock(return_value=client),
  1057. ):
  1058. slots = await build_slot_materials(db_session, printer.id)
  1059. finally:
  1060. for p in patches:
  1061. p.stop()
  1062. assert len(slots) == 1
  1063. assert slots[0].remaining_grams == 500.0
  1064. assert slots[0].spool is None
  1065. assert slots[0].to_dict()["spool"] is None