test_library_slice_api.py 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356
  1. """Integration tests for the slice-via-API flow.
  2. Routes under test:
  3. - POST /library/files/{id}/slice (returns 202 + job_id; bg task does the work)
  4. - POST /archives/{id}/slice (same shape; result lands in archives table)
  5. - GET /slice-jobs/{id} (poll for terminal state)
  6. The synchronous validation paths (404 missing source, 400 wrong file type)
  7. are tested directly. The bg-task paths poll until the job finishes and then
  8. assert on the captured state.
  9. """
  10. from __future__ import annotations
  11. import asyncio
  12. import io
  13. import json
  14. import zipfile
  15. from collections.abc import Callable
  16. import httpx
  17. import pytest
  18. from httpx import AsyncClient
  19. from backend.app.api.routes.library import _slicer_rejection_message
  20. from backend.app.core.config import settings as app_settings
  21. from backend.app.models.library import LibraryFile
  22. from backend.app.models.local_preset import LocalPreset
  23. from backend.app.models.settings import Settings as SettingsModel
  24. from backend.app.services import slicer_api as slicer_api_module
  25. from backend.app.services.slice_dispatch import slice_dispatch
  26. # ---------------------------------------------------------------------------
  27. # Helpers
  28. # ---------------------------------------------------------------------------
  29. def _make_3mf_with_settings(settings_payload: dict | None = None) -> bytes:
  30. """Build a tiny in-memory 3MF zip with all the embedded-config files
  31. that real-world Bambu Studio / OrcaSlicer 3MFs ship with.
  32. The strip-before-forwarding helper has to remove ALL of these (not
  33. just `project_settings.config`) — leftover entries reference printer
  34. / filament IDs from the original slice and trip the CLI's input
  35. validation when a different `--load-settings` triplet is supplied.
  36. """
  37. buf = io.BytesIO()
  38. with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
  39. zf.writestr("3D/3dmodel.model", "<model/>")
  40. zf.writestr(
  41. "Metadata/project_settings.config",
  42. json.dumps(settings_payload or {"prime_tower_brim_width": "-1"}),
  43. )
  44. zf.writestr("Metadata/model_settings.config", "<config><object id='1'/></config>")
  45. zf.writestr(
  46. "Metadata/slice_info.config",
  47. "<config><plate><metadata key='filament' value='GFL00'/></plate></config>",
  48. )
  49. zf.writestr("Metadata/cut_information.xml", "<cut><part id='1'/></cut>")
  50. return buf.getvalue()
  51. def _install_mock_sidecar(handler: Callable[[httpx.Request], httpx.Response]) -> httpx.AsyncClient:
  52. """Pin a MockTransport-backed httpx client onto the slicer_api singleton
  53. so per-request `SlicerApiService` instances reuse it instead of opening
  54. a real connection."""
  55. client = httpx.AsyncClient(transport=httpx.MockTransport(handler), timeout=10.0)
  56. slicer_api_module.set_shared_http_client(client)
  57. return client
  58. def _is_slice_post(request: httpx.Request) -> bool:
  59. """True for the slice call itself, false for the progress polls beside it.
  60. Since #2730 a slice is supervised by a 1 Hz poll of
  61. ``GET /slice/progress/{id}``, which shares this mock transport. Tests that
  62. count *slice attempts* — primary vs embedded-settings fallback — have to
  63. exclude those, or the count becomes a measure of how long the test took.
  64. """
  65. return request.method == "POST" and request.url.path.endswith("/slice")
  66. async def _wait_for_job(client: AsyncClient, job_id: int, timeout: float = 5.0) -> dict:
  67. """Poll `/api/v1/slice-jobs/{id}` until the job hits a terminal state.
  68. The dispatcher runs work as an asyncio task on the same event loop, so
  69. poll-with-sleep here is enough — a few yields and the task finishes.
  70. """
  71. deadline = asyncio.get_event_loop().time() + timeout
  72. while asyncio.get_event_loop().time() < deadline:
  73. r = await client.get(f"/api/v1/slice-jobs/{job_id}")
  74. if r.status_code != 200:
  75. raise AssertionError(f"slice-jobs poll failed: {r.status_code} {r.text}")
  76. body = r.json()
  77. if body["status"] in ("completed", "failed"):
  78. return body
  79. await asyncio.sleep(0.05)
  80. raise AssertionError(f"slice job {job_id} did not finish in {timeout}s")
  81. # ---------------------------------------------------------------------------
  82. # Fixtures
  83. # ---------------------------------------------------------------------------
  84. @pytest.fixture
  85. async def slice_test_setup(db_session, tmp_path, monkeypatch):
  86. """Source LibraryFile + 3 LocalPresets + preferred_slicer=orcaslicer.
  87. ``base_dir`` is patched via ``monkeypatch`` rather than assigned and
  88. restored by hand. ``app_settings`` is a process-wide singleton, and the
  89. hand-rolled version only restored after the ``yield`` — so anything raising
  90. during setup (a commit, a refresh) left ``base_dir`` pointing at a
  91. ``tmp_path`` that pytest then deleted, and every later test in that xdist
  92. worker which reads it failed. That was the cause of intermittent failures
  93. in ``TestLibraryPathHelpers`` and ``TestArchivePlatesDesignOverrides``,
  94. which share nothing with this module but land in the same worker.
  95. """
  96. storage_dir = tmp_path / "library" / "files"
  97. storage_dir.mkdir(parents=True, exist_ok=True)
  98. src_path = storage_dir / "Cube.stl"
  99. src_path.write_bytes(b"solid Cube\nendsolid\n")
  100. monkeypatch.setattr(app_settings, "base_dir", tmp_path)
  101. src_file = LibraryFile(
  102. filename="Cube.stl",
  103. file_path=str(src_path.relative_to(tmp_path)),
  104. file_type="stl",
  105. file_size=src_path.stat().st_size,
  106. )
  107. db_session.add(src_file)
  108. presets = {}
  109. for kind in ("printer", "process", "filament"):
  110. p = LocalPreset(
  111. name=f"Test {kind}",
  112. preset_type=kind,
  113. source="orcaslicer",
  114. setting=json.dumps({"name": f"Test {kind}", "type": kind}),
  115. )
  116. db_session.add(p)
  117. presets[kind] = p
  118. db_session.add(SettingsModel(key="preferred_slicer", value="orcaslicer"))
  119. await db_session.commit()
  120. for p in presets.values():
  121. await db_session.refresh(p)
  122. await db_session.refresh(src_file)
  123. yield {
  124. "src_file_id": src_file.id,
  125. "printer_id": presets["printer"].id,
  126. "process_id": presets["process"].id,
  127. "filament_id": presets["filament"].id,
  128. "tmp_path": tmp_path,
  129. }
  130. slicer_api_module.set_shared_http_client(None)
  131. # ---------------------------------------------------------------------------
  132. # POST /library/files/{id}/slice — synchronous validation paths
  133. # ---------------------------------------------------------------------------
  134. class TestSliceValidation:
  135. @pytest.mark.asyncio
  136. @pytest.mark.integration
  137. async def test_returns_404_when_source_missing(self, async_client: AsyncClient, slice_test_setup):
  138. _install_mock_sidecar(lambda r: httpx.Response(200, content=b""))
  139. response = await async_client.post(
  140. "/api/v1/library/files/999999/slice",
  141. json={
  142. "printer_preset_id": slice_test_setup["printer_id"],
  143. "process_preset_id": slice_test_setup["process_id"],
  144. "filament_preset_id": slice_test_setup["filament_id"],
  145. },
  146. )
  147. assert response.status_code == 404
  148. @pytest.mark.asyncio
  149. @pytest.mark.integration
  150. async def test_returns_400_for_wrong_file_type(self, async_client: AsyncClient, db_session, slice_test_setup):
  151. gcode_path = slice_test_setup["tmp_path"] / "library" / "files" / "out.gcode"
  152. gcode_path.write_bytes(b"; gcode\n")
  153. gfile = LibraryFile(
  154. filename="out.gcode",
  155. file_path=str(gcode_path.relative_to(slice_test_setup["tmp_path"])),
  156. file_type="gcode",
  157. file_size=10,
  158. )
  159. db_session.add(gfile)
  160. await db_session.commit()
  161. await db_session.refresh(gfile)
  162. _install_mock_sidecar(lambda r: httpx.Response(200, content=b""))
  163. response = await async_client.post(
  164. f"/api/v1/library/files/{gfile.id}/slice",
  165. json={
  166. "printer_preset_id": slice_test_setup["printer_id"],
  167. "process_preset_id": slice_test_setup["process_id"],
  168. "filament_preset_id": slice_test_setup["filament_id"],
  169. },
  170. )
  171. assert response.status_code == 400
  172. assert "STL, 3MF, or STEP" in response.json()["detail"]
  173. # ---------------------------------------------------------------------------
  174. # POST /library/files/{id}/slice — async dispatch + bg job
  175. # ---------------------------------------------------------------------------
  176. class TestSliceLibraryFile:
  177. @pytest.mark.asyncio
  178. @pytest.mark.integration
  179. async def test_happy_path_returns_202_then_job_completes_with_library_file(
  180. self, async_client: AsyncClient, slice_test_setup
  181. ):
  182. captured: dict = {}
  183. def handler(request: httpx.Request) -> httpx.Response:
  184. captured["url"] = str(request.url)
  185. return httpx.Response(
  186. status_code=200,
  187. content=_make_3mf_with_settings(), # #2671: real zip; validation rejects non-3MF bodies
  188. headers={
  189. "x-print-time-seconds": "656",
  190. "x-filament-used-g": "0.94",
  191. "x-filament-used-mm": "302.5",
  192. },
  193. )
  194. _install_mock_sidecar(handler)
  195. response = await async_client.post(
  196. f"/api/v1/library/files/{slice_test_setup['src_file_id']}/slice",
  197. json={
  198. "printer_preset_id": slice_test_setup["printer_id"],
  199. "process_preset_id": slice_test_setup["process_id"],
  200. "filament_preset_id": slice_test_setup["filament_id"],
  201. },
  202. )
  203. assert response.status_code == 202, response.text
  204. body = response.json()
  205. assert body["status"] == "pending"
  206. assert body["status_url"].startswith("/api/v1/slice-jobs/")
  207. final = await _wait_for_job(async_client, body["job_id"])
  208. assert final["status"] == "completed", final
  209. assert final["result"]["library_file_id"] != slice_test_setup["src_file_id"]
  210. assert final["result"]["print_time_seconds"] == 656
  211. assert captured["url"].endswith("/slice")
  212. @pytest.mark.asyncio
  213. @pytest.mark.integration
  214. async def test_bed_type_override_patches_process_profile(self, async_client: AsyncClient, slice_test_setup):
  215. """#1337: when SliceRequest.bed_type is set, the process JSON sent to
  216. the sidecar must carry curr_bed_type with that exact value. Without
  217. the patch, slicing high-temp filaments on a "Cool Plate" process
  218. preset fails inside the slicer CLI with "does not support filament 1"
  219. and the user has no way to switch plates from the SliceModal."""
  220. captured: dict = {}
  221. def handler(request: httpx.Request) -> httpx.Response:
  222. captured["body"] = bytes(request.content)
  223. return httpx.Response(
  224. status_code=200,
  225. content=_make_3mf_with_settings(), # #2671: real zip; validation rejects non-3MF bodies
  226. headers={
  227. "x-print-time-seconds": "10",
  228. "x-filament-used-g": "0.1",
  229. "x-filament-used-mm": "1.0",
  230. },
  231. )
  232. _install_mock_sidecar(handler)
  233. response = await async_client.post(
  234. f"/api/v1/library/files/{slice_test_setup['src_file_id']}/slice",
  235. json={
  236. "printer_preset_id": slice_test_setup["printer_id"],
  237. "process_preset_id": slice_test_setup["process_id"],
  238. "filament_preset_id": slice_test_setup["filament_id"],
  239. "bed_type": "Textured PEI Plate",
  240. },
  241. )
  242. assert response.status_code == 202
  243. final = await _wait_for_job(async_client, response.json()["job_id"])
  244. assert final["status"] == "completed", final
  245. # The presetProfile part of the multipart upload now carries the
  246. # override. Searching the raw body avoids parsing the multipart by
  247. # hand — the substring is unique enough since we control the JSON
  248. # being patched.
  249. assert b'"curr_bed_type": "Textured PEI Plate"' in captured["body"], (
  250. "bed_type override must appear in the process JSON sent to the sidecar"
  251. )
  252. @pytest.mark.asyncio
  253. @pytest.mark.integration
  254. async def test_bed_type_omitted_leaves_process_profile_untouched(self, async_client: AsyncClient, slice_test_setup):
  255. """Companion to the override test: the patch must NOT fire when the
  256. client omits bed_type, so the process preset's own curr_bed_type
  257. (or absence thereof) is forwarded to the sidecar unchanged."""
  258. captured: dict = {}
  259. def handler(request: httpx.Request) -> httpx.Response:
  260. captured["body"] = bytes(request.content)
  261. return httpx.Response(
  262. status_code=200,
  263. content=_make_3mf_with_settings(), # #2671: real zip; validation rejects non-3MF bodies
  264. headers={
  265. "x-print-time-seconds": "10",
  266. "x-filament-used-g": "0.1",
  267. "x-filament-used-mm": "1.0",
  268. },
  269. )
  270. _install_mock_sidecar(handler)
  271. response = await async_client.post(
  272. f"/api/v1/library/files/{slice_test_setup['src_file_id']}/slice",
  273. json={
  274. "printer_preset_id": slice_test_setup["printer_id"],
  275. "process_preset_id": slice_test_setup["process_id"],
  276. "filament_preset_id": slice_test_setup["filament_id"],
  277. },
  278. )
  279. assert response.status_code == 202
  280. final = await _wait_for_job(async_client, response.json()["job_id"])
  281. assert final["status"] == "completed", final
  282. assert b"curr_bed_type" not in captured["body"], (
  283. "bed_type must stay out of the process JSON when no override is set"
  284. )
  285. @pytest.mark.asyncio
  286. @pytest.mark.integration
  287. async def test_auto_orient_and_arrange_reach_the_sidecar(self, async_client: AsyncClient, slice_test_setup):
  288. """#2548: the two layout passes are per-slice options, so ticking
  289. them in the SliceModal has to come out the other end as the
  290. sidecar's ``orient`` / ``arrange`` form fields. Before this the
  291. flags existed on the wire but only #1493's cross-class detector
  292. could set arrange, and nothing at all could set orient."""
  293. captured: dict = {}
  294. def handler(request: httpx.Request) -> httpx.Response:
  295. captured["body"] = bytes(request.content)
  296. return httpx.Response(
  297. status_code=200,
  298. content=_make_3mf_with_settings(),
  299. headers={
  300. "x-print-time-seconds": "10",
  301. "x-filament-used-g": "0.1",
  302. "x-filament-used-mm": "1.0",
  303. },
  304. )
  305. _install_mock_sidecar(handler)
  306. response = await async_client.post(
  307. f"/api/v1/library/files/{slice_test_setup['src_file_id']}/slice",
  308. json={
  309. "printer_preset_id": slice_test_setup["printer_id"],
  310. "process_preset_id": slice_test_setup["process_id"],
  311. "filament_preset_id": slice_test_setup["filament_id"],
  312. "auto_orient": True,
  313. "auto_arrange": True,
  314. },
  315. )
  316. assert response.status_code == 202
  317. final = await _wait_for_job(async_client, response.json()["job_id"])
  318. assert final["status"] == "completed", final
  319. assert b'name="orient"' in captured["body"]
  320. assert b'name="arrange"' in captured["body"]
  321. @pytest.mark.asyncio
  322. @pytest.mark.integration
  323. async def test_layout_flags_absent_by_default(self, async_client: AsyncClient, slice_test_setup):
  324. """Companion to the above. Both default to off, and off is expressed
  325. by omitting the field — the sidecar reads any present value as
  326. truthy, so a "false" on the wire would auto-arrange every slice."""
  327. captured: dict = {}
  328. def handler(request: httpx.Request) -> httpx.Response:
  329. captured["body"] = bytes(request.content)
  330. return httpx.Response(
  331. status_code=200,
  332. content=_make_3mf_with_settings(),
  333. headers={
  334. "x-print-time-seconds": "10",
  335. "x-filament-used-g": "0.1",
  336. "x-filament-used-mm": "1.0",
  337. },
  338. )
  339. _install_mock_sidecar(handler)
  340. response = await async_client.post(
  341. f"/api/v1/library/files/{slice_test_setup['src_file_id']}/slice",
  342. json={
  343. "printer_preset_id": slice_test_setup["printer_id"],
  344. "process_preset_id": slice_test_setup["process_id"],
  345. "filament_preset_id": slice_test_setup["filament_id"],
  346. },
  347. )
  348. assert response.status_code == 202
  349. final = await _wait_for_job(async_client, response.json()["job_id"])
  350. assert final["status"] == "completed", final
  351. assert b'name="orient"' not in captured["body"]
  352. assert b'name="arrange"' not in captured["body"]
  353. @pytest.mark.asyncio
  354. @pytest.mark.integration
  355. async def test_invalid_preset_id_surfaces_as_failed_job_with_status_400(
  356. self, async_client: AsyncClient, slice_test_setup
  357. ):
  358. _install_mock_sidecar(lambda r: httpx.Response(200, content=b""))
  359. response = await async_client.post(
  360. f"/api/v1/library/files/{slice_test_setup['src_file_id']}/slice",
  361. json={
  362. # Swap printer/filament — both exist but wrong preset_type.
  363. "printer_preset_id": slice_test_setup["filament_id"],
  364. "process_preset_id": slice_test_setup["process_id"],
  365. "filament_preset_id": slice_test_setup["printer_id"],
  366. },
  367. )
  368. assert response.status_code == 202
  369. final = await _wait_for_job(async_client, response.json()["job_id"])
  370. assert final["status"] == "failed"
  371. assert final["error_status"] == 400
  372. assert "preset_type" in (final["error_detail"] or "")
  373. @pytest.mark.asyncio
  374. @pytest.mark.integration
  375. async def test_unknown_preferred_slicer_fails_with_400(
  376. self, async_client: AsyncClient, db_session, slice_test_setup
  377. ):
  378. await db_session.execute(
  379. SettingsModel.__table__.update().where(SettingsModel.key == "preferred_slicer").values(value="prusaslicer")
  380. )
  381. await db_session.commit()
  382. _install_mock_sidecar(lambda r: httpx.Response(200, content=b""))
  383. response = await async_client.post(
  384. f"/api/v1/library/files/{slice_test_setup['src_file_id']}/slice",
  385. json={
  386. "printer_preset_id": slice_test_setup["printer_id"],
  387. "process_preset_id": slice_test_setup["process_id"],
  388. "filament_preset_id": slice_test_setup["filament_id"],
  389. },
  390. )
  391. assert response.status_code == 202
  392. final = await _wait_for_job(async_client, response.json()["job_id"])
  393. assert final["status"] == "failed"
  394. assert final["error_status"] == 400
  395. assert "preferred_slicer" in (final["error_detail"] or "")
  396. @pytest.mark.asyncio
  397. @pytest.mark.integration
  398. async def test_sidecar_unreachable_fails_with_502(self, async_client: AsyncClient, slice_test_setup):
  399. def handler(_: httpx.Request) -> httpx.Response:
  400. raise httpx.ConnectError("connection refused")
  401. _install_mock_sidecar(handler)
  402. response = await async_client.post(
  403. f"/api/v1/library/files/{slice_test_setup['src_file_id']}/slice",
  404. json={
  405. "printer_preset_id": slice_test_setup["printer_id"],
  406. "process_preset_id": slice_test_setup["process_id"],
  407. "filament_preset_id": slice_test_setup["filament_id"],
  408. },
  409. )
  410. assert response.status_code == 202
  411. final = await _wait_for_job(async_client, response.json()["job_id"])
  412. assert final["status"] == "failed"
  413. assert final["error_status"] == 502
  414. assert "unreachable" in (final["error_detail"] or "").lower()
  415. @pytest.mark.asyncio
  416. @pytest.mark.integration
  417. async def test_3mf_falls_back_to_embedded_settings_on_cli_failure(
  418. self, async_client: AsyncClient, db_session, slice_test_setup
  419. ):
  420. # When the slicer CLI fails on the --load-settings path (segfault
  421. # on complex H2D models), Bambuddy retries with no profile triplet
  422. # so the CLI uses the file's embedded settings.
  423. src_3mf_path = slice_test_setup["tmp_path"] / "library" / "files" / "complex.3mf"
  424. src_3mf_path.write_bytes(_make_3mf_with_settings({"prime_tower_brim_width": "-1"}))
  425. threemf = LibraryFile(
  426. filename="complex.3mf",
  427. file_path=str(src_3mf_path.relative_to(slice_test_setup["tmp_path"])),
  428. file_type="3mf",
  429. file_size=src_3mf_path.stat().st_size,
  430. )
  431. db_session.add(threemf)
  432. await db_session.commit()
  433. await db_session.refresh(threemf)
  434. call_count = {"n": 0}
  435. def handler(request: httpx.Request) -> httpx.Response:
  436. if not _is_slice_post(request):
  437. return httpx.Response(404)
  438. call_count["n"] += 1
  439. # First call: profile triplet present → simulate CLI 5xx
  440. if call_count["n"] == 1:
  441. return httpx.Response(
  442. status_code=500,
  443. json={"message": "Failed to slice the model"},
  444. )
  445. # Retry: no profile triplet → succeed with embedded settings
  446. return httpx.Response(
  447. status_code=200,
  448. content=_make_3mf_with_settings(), # #2671: real zip; validation rejects non-3MF bodies
  449. headers={
  450. "x-print-time-seconds": "100",
  451. "x-filament-used-g": "1.0",
  452. "x-filament-used-mm": "100",
  453. },
  454. )
  455. _install_mock_sidecar(handler)
  456. response = await async_client.post(
  457. f"/api/v1/library/files/{threemf.id}/slice",
  458. json={
  459. "printer_preset_id": slice_test_setup["printer_id"],
  460. "process_preset_id": slice_test_setup["process_id"],
  461. "filament_preset_id": slice_test_setup["filament_id"],
  462. },
  463. )
  464. assert response.status_code == 202
  465. final = await _wait_for_job(async_client, response.json()["job_id"])
  466. assert final["status"] == "completed", final
  467. assert final["result"]["used_embedded_settings"] is True
  468. assert call_count["n"] == 2 # primary + fallback retry
  469. @pytest.mark.asyncio
  470. @pytest.mark.integration
  471. async def test_stl_does_not_fall_back_on_cli_failure(self, async_client: AsyncClient, slice_test_setup):
  472. # STL has no embedded settings — the CLI 5xx is terminal.
  473. call_count = {"n": 0}
  474. def handler(request: httpx.Request) -> httpx.Response:
  475. if not _is_slice_post(request):
  476. return httpx.Response(404)
  477. call_count["n"] += 1
  478. return httpx.Response(
  479. status_code=500,
  480. json={"message": "Failed to slice the model"},
  481. )
  482. _install_mock_sidecar(handler)
  483. response = await async_client.post(
  484. f"/api/v1/library/files/{slice_test_setup['src_file_id']}/slice",
  485. json={
  486. "printer_preset_id": slice_test_setup["printer_id"],
  487. "process_preset_id": slice_test_setup["process_id"],
  488. "filament_preset_id": slice_test_setup["filament_id"],
  489. },
  490. )
  491. assert response.status_code == 202
  492. final = await _wait_for_job(async_client, response.json()["job_id"])
  493. assert final["status"] == "failed"
  494. assert final["error_status"] == 502
  495. assert call_count["n"] == 1 # No retry for STL
  496. @pytest.mark.asyncio
  497. @pytest.mark.integration
  498. async def test_3mf_input_forwarded_unmodified_to_sidecar(
  499. self, async_client: AsyncClient, db_session, slice_test_setup
  500. ):
  501. # 3MF input must be forwarded to the sidecar verbatim — every
  502. # Metadata/*.config the source carries (project_settings,
  503. # model_settings, slice_info, cut_information) is needed by the
  504. # CLI to find plate definitions and baseline config; an earlier
  505. # version of this code stripped them and caused the CLI to
  506. # silently exit immediately after "Initializing StaticPrintConfigs"
  507. # for every 3MF slice. --load-settings overrides the specific
  508. # fields the user changed; the rest comes from the embedded data.
  509. src_3mf_path = slice_test_setup["tmp_path"] / "library" / "files" / "real.3mf"
  510. src_3mf_path.write_bytes(_make_3mf_with_settings({"prime_tower_brim_width": "-1"}))
  511. threemf = LibraryFile(
  512. filename="real.3mf",
  513. file_path=str(src_3mf_path.relative_to(slice_test_setup["tmp_path"])),
  514. file_type="3mf",
  515. file_size=src_3mf_path.stat().st_size,
  516. )
  517. db_session.add(threemf)
  518. await db_session.commit()
  519. await db_session.refresh(threemf)
  520. captured: dict = {}
  521. def handler(request: httpx.Request) -> httpx.Response:
  522. captured["body"] = request.content
  523. return httpx.Response(
  524. status_code=200,
  525. content=_make_3mf_with_settings(), # #2671: real zip; validation rejects non-3MF bodies
  526. headers={
  527. "x-print-time-seconds": "1",
  528. "x-filament-used-g": "0",
  529. "x-filament-used-mm": "0",
  530. },
  531. )
  532. _install_mock_sidecar(handler)
  533. response = await async_client.post(
  534. f"/api/v1/library/files/{threemf.id}/slice",
  535. json={
  536. "printer_preset_id": slice_test_setup["printer_id"],
  537. "process_preset_id": slice_test_setup["process_id"],
  538. "filament_preset_id": slice_test_setup["filament_id"],
  539. },
  540. )
  541. assert response.status_code == 202
  542. final = await _wait_for_job(async_client, response.json()["job_id"])
  543. assert final["status"] == "completed", final
  544. # Recover the embedded zip from the multipart body and assert ALL
  545. # the source's Metadata/*.config files are still present — the
  546. # opposite of the previous (broken) "strip everything" test.
  547. body = captured["body"]
  548. pk = body.find(b"PK\x03\x04")
  549. assert pk >= 0, "3MF body not found in multipart payload"
  550. with zipfile.ZipFile(io.BytesIO(body[pk:]), "r") as zin:
  551. names = set(zin.namelist())
  552. assert "Metadata/project_settings.config" in names
  553. assert "Metadata/model_settings.config" in names
  554. assert "Metadata/slice_info.config" in names
  555. assert "Metadata/cut_information.xml" in names
  556. assert "3D/3dmodel.model" in names
  557. @pytest.mark.asyncio
  558. @pytest.mark.integration
  559. async def test_use_embedded_settings_skips_profile_triplet(
  560. self, async_client: AsyncClient, db_session, slice_test_setup
  561. ):
  562. # "Slice as designed" (#2611): with use_embedded_settings the 3MF is
  563. # sliced on its own project_settings.config — no --load-settings — so
  564. # the sidecar request carries ONLY the model file, never the
  565. # printer/process/filament profile parts. Succeeds on the first call
  566. # (no crash-fallback), and the result is flagged used_embedded_settings.
  567. src_3mf_path = slice_test_setup["tmp_path"] / "library" / "files" / "designed.3mf"
  568. src_3mf_path.write_bytes(_make_3mf_with_settings({"wall_loops": "5"}))
  569. threemf = LibraryFile(
  570. filename="designed.3mf",
  571. file_path=str(src_3mf_path.relative_to(slice_test_setup["tmp_path"])),
  572. file_type="3mf",
  573. file_size=src_3mf_path.stat().st_size,
  574. )
  575. db_session.add(threemf)
  576. await db_session.commit()
  577. await db_session.refresh(threemf)
  578. captured: dict = {}
  579. call_count = {"n": 0}
  580. def handler(request: httpx.Request) -> httpx.Response:
  581. if not _is_slice_post(request):
  582. return httpx.Response(404)
  583. call_count["n"] += 1
  584. captured["body"] = request.content
  585. return httpx.Response(
  586. status_code=200,
  587. content=_make_3mf_with_settings(), # #2671: real zip; validation rejects non-3MF bodies
  588. headers={
  589. "x-print-time-seconds": "100",
  590. "x-filament-used-g": "1.0",
  591. "x-filament-used-mm": "100",
  592. },
  593. )
  594. _install_mock_sidecar(handler)
  595. response = await async_client.post(
  596. f"/api/v1/library/files/{threemf.id}/slice",
  597. json={
  598. "printer_preset_id": slice_test_setup["printer_id"],
  599. "process_preset_id": slice_test_setup["process_id"],
  600. "filament_preset_id": slice_test_setup["filament_id"],
  601. "use_embedded_settings": True,
  602. },
  603. )
  604. assert response.status_code == 202
  605. final = await _wait_for_job(async_client, response.json()["job_id"])
  606. assert final["status"] == "completed", final
  607. assert final["result"]["used_embedded_settings"] is True
  608. assert call_count["n"] == 1 # embedded path taken directly, no fallback retry
  609. # The multipart body must NOT carry any profile part — that is the
  610. # whole point of the mode. Their presence would mean --load-settings
  611. # ran and overrode the designer's embedded settings.
  612. body = captured["body"]
  613. assert b"printerProfile" not in body
  614. assert b"presetProfile" not in body
  615. assert b"filamentProfile" not in body
  616. @pytest.mark.asyncio
  617. @pytest.mark.integration
  618. async def test_use_embedded_settings_ignored_for_stl(self, async_client: AsyncClient, slice_test_setup):
  619. # An STL has no embedded project settings to honour, so the flag is a
  620. # no-op: the normal profile path runs and the triplet is forwarded.
  621. captured: dict = {}
  622. def handler(request: httpx.Request) -> httpx.Response:
  623. captured["body"] = request.content
  624. return httpx.Response(
  625. status_code=200,
  626. content=_make_3mf_with_settings(), # #2671: real zip; validation rejects non-3MF bodies
  627. headers={
  628. "x-print-time-seconds": "1",
  629. "x-filament-used-g": "0",
  630. "x-filament-used-mm": "0",
  631. },
  632. )
  633. _install_mock_sidecar(handler)
  634. response = await async_client.post(
  635. f"/api/v1/library/files/{slice_test_setup['src_file_id']}/slice",
  636. json={
  637. "printer_preset_id": slice_test_setup["printer_id"],
  638. "process_preset_id": slice_test_setup["process_id"],
  639. "filament_preset_id": slice_test_setup["filament_id"],
  640. "use_embedded_settings": True,
  641. },
  642. )
  643. assert response.status_code == 202
  644. final = await _wait_for_job(async_client, response.json()["job_id"])
  645. assert final["status"] == "completed", final
  646. assert final["result"]["used_embedded_settings"] is False
  647. assert b"printerProfile" in captured["body"] # profile path still ran
  648. # ---------------------------------------------------------------------------
  649. # GET /slice-jobs/{id}
  650. # ---------------------------------------------------------------------------
  651. class TestSliceJobs:
  652. @pytest.mark.asyncio
  653. @pytest.mark.integration
  654. async def test_unknown_job_returns_404(self, async_client: AsyncClient):
  655. # Sweep dispatcher state so a fresh ID is unknown.
  656. slice_dispatch._jobs.clear()
  657. r = await async_client.get("/api/v1/slice-jobs/999999")
  658. assert r.status_code == 404
  659. # ---------------------------------------------------------------------------
  660. # POST /archives/{id}/slice — re-sliced archive reflects the target printer
  661. # ---------------------------------------------------------------------------
  662. def _make_sliced_3mf(printer_model_id: str, bed_type: str | None = None) -> bytes:
  663. """A minimal sliced-output 3MF that embeds a printer_model_id in
  664. slice_info.config, the way a real Bambu Studio / OrcaSlicer export does.
  665. ThreeMFParser reads this into metadata['sliced_for_model']. When
  666. ``bed_type`` is set, also embed ``curr_bed_type`` so the parser surfaces
  667. ``metadata['bed_type']`` — needed for the bed-type lift assertion in
  668. TestSliceArchiveReslicedBedType."""
  669. extra_meta = f"<metadata key='curr_bed_type' value='{bed_type}'/>" if bed_type else ""
  670. buf = io.BytesIO()
  671. with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
  672. zf.writestr("3D/3dmodel.model", "<model/>")
  673. zf.writestr(
  674. "Metadata/slice_info.config",
  675. (
  676. "<config><plate>"
  677. f"<metadata key='printer_model_id' value='{printer_model_id}'/>"
  678. f"{extra_meta}"
  679. "</plate></config>"
  680. ),
  681. )
  682. return buf.getvalue()
  683. class TestCrossClassSliceAllLoop:
  684. """#1493: when the user picks "Slice all plates" on a cross-class source
  685. (X1C → H2D), Bambuddy must NOT send a single ``--slice 0 --arrange 1``
  686. call — that consolidates every plate's objects onto one bed via BS's
  687. project-wide arrange. Instead it loops per plate (``plate=N, arrange=true``)
  688. and merges the N single-plate outputs into one multi-plate 3MF locally.
  689. This test mocks the sidecar to assert (a) N calls happen, one per plate,
  690. each with arrange=true, and (b) the resulting archive's stored 3MF
  691. contains plate_1..plate_N.gcode entries."""
  692. @staticmethod
  693. def _make_multi_plate_x1c_source(plate_count: int = 3) -> bytes:
  694. """Source 3MF: X1C-stamped, N plates declared via model_settings."""
  695. plate_blocks = "\n".join(
  696. f'<plate><metadata key="plater_id" value="{i}"/></plate>' for i in range(1, plate_count + 1)
  697. )
  698. buf = io.BytesIO()
  699. with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
  700. zf.writestr("3D/3dmodel.model", "<model/>")
  701. zf.writestr(
  702. "Metadata/project_settings.config",
  703. json.dumps({"printer_model": "Bambu Lab X1 Carbon"}),
  704. )
  705. zf.writestr(
  706. "Metadata/model_settings.config",
  707. f"<?xml version='1.0'?>\n<config>\n{plate_blocks}\n</config>\n",
  708. )
  709. return buf.getvalue()
  710. @staticmethod
  711. def _make_single_plate_sliced_output(plate_num: int) -> bytes:
  712. """Mock per-plate output: looks like what BS CLI returns for
  713. --slice N. Carries an H2D project_settings (target), a one-line
  714. slice_info <plate> block, and a per-plate gcode + thumbnail."""
  715. buf = io.BytesIO()
  716. with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
  717. zf.writestr("3D/3dmodel.model", "<model/>")
  718. zf.writestr(
  719. "Metadata/project_settings.config",
  720. json.dumps({"printer_model": "Bambu Lab H2D"}),
  721. )
  722. zf.writestr("Metadata/model_settings.config", "<config/>")
  723. zf.writestr(
  724. "Metadata/slice_info.config",
  725. f"<config><plate><metadata key='index' value='{plate_num}'/>"
  726. f"<metadata key='printer_model_id' value='O1D'/></plate></config>",
  727. )
  728. zf.writestr(f"Metadata/plate_{plate_num}.gcode", f"G{plate_num}".encode())
  729. zf.writestr(f"Metadata/plate_{plate_num}.gcode.md5", b"deadbeef")
  730. zf.writestr(f"Metadata/plate_{plate_num}.json", b"{}")
  731. zf.writestr(f"Metadata/plate_{plate_num}.png", f"P{plate_num}".encode())
  732. return buf.getvalue()
  733. @pytest.mark.asyncio
  734. @pytest.mark.integration
  735. async def test_loops_per_plate_when_cross_class_with_plate_zero(
  736. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  737. ):
  738. from backend.app.models.archive import PrintArchive
  739. tmp_path = slice_test_setup["tmp_path"]
  740. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  741. src_dir = tmp_path / "archives" / "src"
  742. src_dir.mkdir(parents=True, exist_ok=True)
  743. src_3mf = src_dir / "mewtwo.3mf"
  744. src_3mf.write_bytes(self._make_multi_plate_x1c_source(plate_count=3))
  745. printer = await printer_factory()
  746. source = await archive_factory(
  747. printer.id,
  748. filename="mewtwo.3mf",
  749. file_path=str(src_3mf.relative_to(tmp_path)),
  750. sliced_for_model="X1C",
  751. with_run=False,
  752. )
  753. # H2D target preset — the cross-class detector reads the
  754. # ``printer_model`` field off the resolved JSON.
  755. h2d = LocalPreset(
  756. name="# Bambu Lab H2D 0.4 nozzle",
  757. preset_type="printer",
  758. source="orcaslicer",
  759. setting=json.dumps({"name": "Bambu Lab H2D 0.4 nozzle", "printer_model": "Bambu Lab H2D"}),
  760. )
  761. db_session.add(h2d)
  762. await db_session.commit()
  763. await db_session.refresh(h2d)
  764. # Mock sidecar: capture every request and respond with that
  765. # plate's single-plate output. We expect one request per plate
  766. # in the source (3 here).
  767. captured_requests: list[dict] = []
  768. def handler(request: httpx.Request) -> httpx.Response:
  769. if not _is_slice_post(request):
  770. return httpx.Response(404)
  771. # Multipart bodies aren't trivially parseable here; pull
  772. # the plate field by string search since the helper sends
  773. # ``name="plate"`` immediately followed by the value.
  774. body = request.content
  775. plate = None
  776. marker = b'name="plate"\r\n\r\n'
  777. idx = body.find(marker)
  778. if idx != -1:
  779. # Find the next CRLF after the value start.
  780. start = idx + len(marker)
  781. end = body.find(b"\r\n", start)
  782. try:
  783. plate = int(body[start:end].decode("utf-8"))
  784. except (UnicodeDecodeError, ValueError):
  785. plate = None
  786. arrange_in_body = b'name="arrange"' in body
  787. captured_requests.append({"plate": plate, "arrange": arrange_in_body})
  788. return httpx.Response(
  789. status_code=200,
  790. content=self._make_single_plate_sliced_output(plate or 1),
  791. headers={
  792. "x-print-time-seconds": "600",
  793. "x-filament-used-g": "5.0",
  794. "x-filament-used-mm": "1600.0",
  795. },
  796. )
  797. _install_mock_sidecar(handler)
  798. # plate=0 + cross-class triplet → backend should enter the
  799. # per-plate loop, slice each of the 3 plates with arrange=True,
  800. # and merge into one archive.
  801. resp = await async_client.post(
  802. f"/api/v1/archives/{source.id}/slice",
  803. json={
  804. "printer_preset": {"source": "local", "id": str(h2d.id)},
  805. "process_preset": {"source": "local", "id": str(slice_test_setup["process_id"])},
  806. "filament_presets": [{"source": "local", "id": str(slice_test_setup["filament_id"])}],
  807. "plate": 0,
  808. },
  809. )
  810. assert resp.status_code == 202, resp.text
  811. final = await _wait_for_job(async_client, resp.json()["job_id"], timeout=15.0)
  812. assert final["status"] == "completed", final
  813. # Exactly one sidecar call per plate, in plate order. The
  814. # ``--arrange 1`` flag travels with every per-plate sub-slice
  815. # (it's what fixes the cross-class boundary error).
  816. plates_called = [c["plate"] for c in captured_requests]
  817. arrange_used = [c["arrange"] for c in captured_requests]
  818. assert plates_called == [1, 2, 3], plates_called
  819. assert all(arrange_used), arrange_used
  820. # The merged archive has plate_1..plate_3.gcode inside its one
  821. # output 3MF (single Bambuddy archive, three plates).
  822. new_archive = await db_session.get(PrintArchive, final["result"]["archive_id"])
  823. archive_path = tmp_path / new_archive.file_path
  824. with zipfile.ZipFile(archive_path, "r") as zf:
  825. entries = set(zf.namelist())
  826. assert "Metadata/plate_1.gcode" in entries
  827. assert "Metadata/plate_2.gcode" in entries
  828. assert "Metadata/plate_3.gcode" in entries
  829. # Per-plate-result totals are summed onto the merged archive.
  830. assert new_archive.print_time_seconds == 600 * 3
  831. assert new_archive.filament_used_grams == pytest.approx(5.0 * 3)
  832. @pytest.mark.asyncio
  833. @pytest.mark.integration
  834. async def test_user_requested_arrange_also_loops_per_plate(
  835. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  836. ):
  837. """#2548 inherits #1493's hazard. The per-plate loop exists because
  838. ``--arrange`` is project-wide: a single ``--slice 0 --arrange 1``
  839. collapses every plate's objects onto one bed. That is a property of
  840. the flag, not of the cross-class detour that first needed it — so a
  841. user ticking auto-arrange over "all plates" on a SAME-class source
  842. must take the same loop. Keying the loop on the cross-class decision
  843. alone would send one call and silently return a one-plate result.
  844. """
  845. from backend.app.models.archive import PrintArchive
  846. tmp_path = slice_test_setup["tmp_path"]
  847. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  848. src_dir = tmp_path / "archives" / "src_same_class"
  849. src_dir.mkdir(parents=True, exist_ok=True)
  850. src_3mf = src_dir / "tray.3mf"
  851. src_3mf.write_bytes(self._make_multi_plate_x1c_source(plate_count=2))
  852. printer = await printer_factory()
  853. source = await archive_factory(
  854. printer.id,
  855. filename="tray.3mf",
  856. file_path=str(src_3mf.relative_to(tmp_path)),
  857. sliced_for_model="X1C",
  858. with_run=False,
  859. )
  860. # X1C target: same nozzle class as the X1C source, so #1493's
  861. # detector stays off and only the user's flag is in play.
  862. x1c = LocalPreset(
  863. name="# Bambu Lab X1 Carbon 0.4 nozzle",
  864. preset_type="printer",
  865. source="orcaslicer",
  866. setting=json.dumps({"name": "Bambu Lab X1 Carbon 0.4 nozzle", "printer_model": "Bambu Lab X1 Carbon"}),
  867. )
  868. db_session.add(x1c)
  869. await db_session.commit()
  870. await db_session.refresh(x1c)
  871. captured_requests: list[dict] = []
  872. def handler(request: httpx.Request) -> httpx.Response:
  873. if not _is_slice_post(request):
  874. return httpx.Response(404)
  875. body = request.content
  876. plate = None
  877. marker = b'name="plate"\r\n\r\n'
  878. idx = body.find(marker)
  879. if idx != -1:
  880. start = idx + len(marker)
  881. end = body.find(b"\r\n", start)
  882. try:
  883. plate = int(body[start:end].decode("utf-8"))
  884. except (UnicodeDecodeError, ValueError):
  885. plate = None
  886. captured_requests.append(
  887. {
  888. "plate": plate,
  889. "arrange": b'name="arrange"' in body,
  890. "orient": b'name="orient"' in body,
  891. }
  892. )
  893. return httpx.Response(
  894. status_code=200,
  895. content=self._make_single_plate_sliced_output(plate or 1),
  896. headers={
  897. "x-print-time-seconds": "300",
  898. "x-filament-used-g": "2.0",
  899. "x-filament-used-mm": "800.0",
  900. },
  901. )
  902. _install_mock_sidecar(handler)
  903. resp = await async_client.post(
  904. f"/api/v1/archives/{source.id}/slice",
  905. json={
  906. "printer_preset": {"source": "local", "id": str(x1c.id)},
  907. "process_preset": {"source": "local", "id": str(slice_test_setup["process_id"])},
  908. "filament_presets": [{"source": "local", "id": str(slice_test_setup["filament_id"])}],
  909. "plate": 0,
  910. "auto_arrange": True,
  911. "auto_orient": True,
  912. },
  913. )
  914. assert resp.status_code == 202, resp.text
  915. final = await _wait_for_job(async_client, resp.json()["job_id"], timeout=15.0)
  916. assert final["status"] == "completed", final
  917. assert [c["plate"] for c in captured_requests] == [1, 2]
  918. assert all(c["arrange"] for c in captured_requests)
  919. # Orient rides along on every sub-slice too — it is per-object, so
  920. # dropping it on the loop path would quietly ignore the user's tick.
  921. assert all(c["orient"] for c in captured_requests)
  922. new_archive = await db_session.get(PrintArchive, final["result"]["archive_id"])
  923. with zipfile.ZipFile(tmp_path / new_archive.file_path, "r") as zf:
  924. entries = set(zf.namelist())
  925. assert "Metadata/plate_1.gcode" in entries
  926. assert "Metadata/plate_2.gcode" in entries
  927. @pytest.mark.asyncio
  928. @pytest.mark.integration
  929. async def test_embedded_settings_slice_all_with_arrange_still_loops(
  930. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  931. ):
  932. """ "Slice as designed" must not skip the loop. The project-wide
  933. collapse comes from ``--arrange``; where the print config came from
  934. has no bearing on it. Taking the single-call embedded branch here
  935. would return one consolidated plate for a job the user asked to
  936. slice as N — and the per-plate calls must still omit the profile
  937. triplet, or "as designed" would silently stop meaning that.
  938. """
  939. from backend.app.models.archive import PrintArchive
  940. tmp_path = slice_test_setup["tmp_path"]
  941. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  942. src_dir = tmp_path / "archives" / "src_embedded"
  943. src_dir.mkdir(parents=True, exist_ok=True)
  944. src_3mf = src_dir / "kit.3mf"
  945. src_3mf.write_bytes(self._make_multi_plate_x1c_source(plate_count=2))
  946. printer = await printer_factory()
  947. source = await archive_factory(
  948. printer.id,
  949. filename="kit.3mf",
  950. file_path=str(src_3mf.relative_to(tmp_path)),
  951. sliced_for_model="X1C",
  952. with_run=False,
  953. )
  954. x1c = LocalPreset(
  955. name="# Bambu Lab X1 Carbon 0.4 nozzle",
  956. preset_type="printer",
  957. source="orcaslicer",
  958. setting=json.dumps({"name": "Bambu Lab X1 Carbon 0.4 nozzle", "printer_model": "Bambu Lab X1 Carbon"}),
  959. )
  960. db_session.add(x1c)
  961. await db_session.commit()
  962. await db_session.refresh(x1c)
  963. captured_requests: list[dict] = []
  964. def handler(request: httpx.Request) -> httpx.Response:
  965. if not _is_slice_post(request):
  966. return httpx.Response(404)
  967. body = request.content
  968. plate = None
  969. marker = b'name="plate"\r\n\r\n'
  970. idx = body.find(marker)
  971. if idx != -1:
  972. start = idx + len(marker)
  973. end = body.find(b"\r\n", start)
  974. try:
  975. plate = int(body[start:end].decode("utf-8"))
  976. except (UnicodeDecodeError, ValueError):
  977. plate = None
  978. captured_requests.append(
  979. {
  980. "plate": plate,
  981. "arrange": b'name="arrange"' in body,
  982. "has_profiles": b'name="printerProfile"' in body,
  983. }
  984. )
  985. return httpx.Response(
  986. status_code=200,
  987. content=self._make_single_plate_sliced_output(plate or 1),
  988. headers={
  989. "x-print-time-seconds": "300",
  990. "x-filament-used-g": "2.0",
  991. "x-filament-used-mm": "800.0",
  992. },
  993. )
  994. _install_mock_sidecar(handler)
  995. resp = await async_client.post(
  996. f"/api/v1/archives/{source.id}/slice",
  997. json={
  998. "printer_preset": {"source": "local", "id": str(x1c.id)},
  999. "process_preset": {"source": "local", "id": str(slice_test_setup["process_id"])},
  1000. "filament_presets": [{"source": "local", "id": str(slice_test_setup["filament_id"])}],
  1001. "plate": 0,
  1002. "use_embedded_settings": True,
  1003. "auto_arrange": True,
  1004. },
  1005. )
  1006. assert resp.status_code == 202, resp.text
  1007. final = await _wait_for_job(async_client, resp.json()["job_id"], timeout=15.0)
  1008. assert final["status"] == "completed", final
  1009. assert [c["plate"] for c in captured_requests] == [1, 2]
  1010. assert all(c["arrange"] for c in captured_requests)
  1011. # No --load-settings on any sub-call: the file's own settings drive
  1012. # each plate, which is what "slice as designed" promises.
  1013. assert not any(c["has_profiles"] for c in captured_requests)
  1014. assert final["result"]["used_embedded_settings"] is True
  1015. new_archive = await db_session.get(PrintArchive, final["result"]["archive_id"])
  1016. with zipfile.ZipFile(tmp_path / new_archive.file_path, "r") as zf:
  1017. entries = set(zf.namelist())
  1018. assert "Metadata/plate_1.gcode" in entries
  1019. assert "Metadata/plate_2.gcode" in entries
  1020. @pytest.mark.asyncio
  1021. @pytest.mark.integration
  1022. async def test_cross_class_arrange_survives_user_leaving_the_box_unticked(
  1023. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  1024. ):
  1025. """The user's per-slice choice is a union with #1493's decision, not
  1026. a replacement for it. Arrange is what keeps a class-crossing slice
  1027. from landing in the target's dead zone or segfaulting ZFiller — so
  1028. the default-false ``auto_arrange`` must not be able to turn it off.
  1029. """
  1030. tmp_path = slice_test_setup["tmp_path"]
  1031. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  1032. src_dir = tmp_path / "archives" / "src_cross_single"
  1033. src_dir.mkdir(parents=True, exist_ok=True)
  1034. src_3mf = src_dir / "clip.3mf"
  1035. src_3mf.write_bytes(self._make_multi_plate_x1c_source(plate_count=1))
  1036. printer = await printer_factory()
  1037. source = await archive_factory(
  1038. printer.id,
  1039. filename="clip.3mf",
  1040. file_path=str(src_3mf.relative_to(tmp_path)),
  1041. sliced_for_model="X1C",
  1042. with_run=False,
  1043. )
  1044. h2d = LocalPreset(
  1045. name="# Bambu Lab H2D 0.4 nozzle",
  1046. preset_type="printer",
  1047. source="orcaslicer",
  1048. setting=json.dumps({"name": "Bambu Lab H2D 0.4 nozzle", "printer_model": "Bambu Lab H2D"}),
  1049. )
  1050. db_session.add(h2d)
  1051. await db_session.commit()
  1052. await db_session.refresh(h2d)
  1053. captured: dict = {}
  1054. def handler(request: httpx.Request) -> httpx.Response:
  1055. if not _is_slice_post(request):
  1056. return httpx.Response(404)
  1057. captured["body"] = bytes(request.content)
  1058. return httpx.Response(
  1059. status_code=200,
  1060. content=self._make_single_plate_sliced_output(1),
  1061. headers={
  1062. "x-print-time-seconds": "300",
  1063. "x-filament-used-g": "2.0",
  1064. "x-filament-used-mm": "800.0",
  1065. },
  1066. )
  1067. _install_mock_sidecar(handler)
  1068. resp = await async_client.post(
  1069. f"/api/v1/archives/{source.id}/slice",
  1070. json={
  1071. "printer_preset": {"source": "local", "id": str(h2d.id)},
  1072. "process_preset": {"source": "local", "id": str(slice_test_setup["process_id"])},
  1073. "filament_presets": [{"source": "local", "id": str(slice_test_setup["filament_id"])}],
  1074. "plate": 1,
  1075. "auto_arrange": False,
  1076. },
  1077. )
  1078. assert resp.status_code == 202, resp.text
  1079. final = await _wait_for_job(async_client, resp.json()["job_id"], timeout=15.0)
  1080. assert final["status"] == "completed", final
  1081. assert b'name="arrange"' in captured["body"], "cross-class arrange must survive an explicit auto_arrange=false"
  1082. class TestSliceArchiveResliceModel:
  1083. """Re-slicing an archive for a different printer must stamp the new
  1084. archive with the printer it was sliced FOR, not the source's printer."""
  1085. @pytest.mark.asyncio
  1086. @pytest.mark.integration
  1087. async def test_reslice_uses_target_model_not_source_model(
  1088. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  1089. ):
  1090. from backend.app.models.archive import PrintArchive
  1091. tmp_path = slice_test_setup["tmp_path"]
  1092. # archive_dir is a static path off the real data dir; point it under
  1093. # base_dir (= tmp_path) so the new archive's file resolves there.
  1094. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  1095. # Source archive: a 3MF that was sliced for an X1C.
  1096. src_dir = tmp_path / "archives" / "src"
  1097. src_dir.mkdir(parents=True, exist_ok=True)
  1098. src_3mf = src_dir / "cube.3mf"
  1099. src_3mf.write_bytes(_make_3mf_with_settings())
  1100. printer = await printer_factory()
  1101. source = await archive_factory(
  1102. printer.id,
  1103. filename="cube.3mf",
  1104. file_path=str(src_3mf.relative_to(tmp_path)),
  1105. sliced_for_model="X1C",
  1106. with_run=False,
  1107. )
  1108. source_id = source.id
  1109. # The slicer returns a 3MF whose embedded printer_model_id is O1D (H2D).
  1110. def handler(request: httpx.Request) -> httpx.Response:
  1111. return httpx.Response(
  1112. status_code=200,
  1113. content=_make_sliced_3mf("O1D"),
  1114. headers={
  1115. "x-print-time-seconds": "600",
  1116. "x-filament-used-g": "5.0",
  1117. "x-filament-used-mm": "1600.0",
  1118. },
  1119. )
  1120. _install_mock_sidecar(handler)
  1121. resp = await async_client.post(
  1122. f"/api/v1/archives/{source_id}/slice",
  1123. json={
  1124. "printer_preset_id": slice_test_setup["printer_id"],
  1125. "process_preset_id": slice_test_setup["process_id"],
  1126. "filament_preset_id": slice_test_setup["filament_id"],
  1127. },
  1128. )
  1129. assert resp.status_code == 202, resp.text
  1130. final = await _wait_for_job(async_client, resp.json()["job_id"])
  1131. assert final["status"] == "completed", final
  1132. new_id = final["result"]["archive_id"]
  1133. assert new_id != source_id
  1134. new_archive = await db_session.get(PrintArchive, new_id)
  1135. # The fix: the re-sliced archive reflects H2D — the printer it was
  1136. # sliced for — instead of inheriting X1C from the source archive.
  1137. assert new_archive.sliced_for_model == "H2D"
  1138. # Source archive is untouched.
  1139. source_reloaded = await db_session.get(PrintArchive, source_id)
  1140. assert source_reloaded.sliced_for_model == "X1C"
  1141. @pytest.mark.asyncio
  1142. @pytest.mark.integration
  1143. async def test_cross_model_reslice_drops_source_printer_id(
  1144. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  1145. ):
  1146. """A cross-model re-slice (source's X1C → target's H2D) must not carry
  1147. over ``source.printer_id``. The archive card and reprint modal both
  1148. read ``printer_id`` first and only fall back to ``sliced_for_model``
  1149. when it's None, so leaving the inherited id makes the H2D-sliced card
  1150. display the source's X1C printer name (the "Workshop H2C" bug)."""
  1151. from backend.app.models.archive import PrintArchive
  1152. tmp_path = slice_test_setup["tmp_path"]
  1153. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  1154. src_dir = tmp_path / "archives" / "src"
  1155. src_dir.mkdir(parents=True, exist_ok=True)
  1156. src_3mf = src_dir / "cube.3mf"
  1157. src_3mf.write_bytes(_make_3mf_with_settings())
  1158. source_printer = await printer_factory()
  1159. source = await archive_factory(
  1160. source_printer.id,
  1161. filename="cube.3mf",
  1162. file_path=str(src_3mf.relative_to(tmp_path)),
  1163. sliced_for_model="X1C",
  1164. with_run=False,
  1165. )
  1166. source_id = source.id
  1167. source_printer_id = source_printer.id
  1168. def handler(request: httpx.Request) -> httpx.Response:
  1169. return httpx.Response(
  1170. status_code=200,
  1171. content=_make_sliced_3mf("O1D"), # H2D
  1172. headers={
  1173. "x-print-time-seconds": "600",
  1174. "x-filament-used-g": "5.0",
  1175. "x-filament-used-mm": "1600.0",
  1176. },
  1177. )
  1178. _install_mock_sidecar(handler)
  1179. resp = await async_client.post(
  1180. f"/api/v1/archives/{source_id}/slice",
  1181. json={
  1182. "printer_preset_id": slice_test_setup["printer_id"],
  1183. "process_preset_id": slice_test_setup["process_id"],
  1184. "filament_preset_id": slice_test_setup["filament_id"],
  1185. },
  1186. )
  1187. assert resp.status_code == 202, resp.text
  1188. final = await _wait_for_job(async_client, resp.json()["job_id"])
  1189. assert final["status"] == "completed", final
  1190. new_archive = await db_session.get(PrintArchive, final["result"]["archive_id"])
  1191. assert new_archive.sliced_for_model == "H2D"
  1192. # Card / reprint modal will now fall back to the sliced_for_model
  1193. # badge instead of showing the source printer's name.
  1194. assert new_archive.printer_id is None
  1195. # Source untouched: still bound to its original printer.
  1196. source_reloaded = await db_session.get(PrintArchive, source_id)
  1197. assert source_reloaded.printer_id == source_printer_id
  1198. @pytest.mark.asyncio
  1199. @pytest.mark.integration
  1200. async def test_same_model_reslice_preserves_source_printer_id(
  1201. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  1202. ):
  1203. """Same-model re-slice (X1C → X1C, e.g. just swapped a process preset)
  1204. keeps ``printer_id`` so the reprint modal pre-selects the original
  1205. printer. Only cross-model re-slices null it out."""
  1206. from backend.app.models.archive import PrintArchive
  1207. tmp_path = slice_test_setup["tmp_path"]
  1208. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  1209. src_dir = tmp_path / "archives" / "src"
  1210. src_dir.mkdir(parents=True, exist_ok=True)
  1211. src_3mf = src_dir / "cube.3mf"
  1212. src_3mf.write_bytes(_make_3mf_with_settings())
  1213. source_printer = await printer_factory()
  1214. source = await archive_factory(
  1215. source_printer.id,
  1216. filename="cube.3mf",
  1217. file_path=str(src_3mf.relative_to(tmp_path)),
  1218. sliced_for_model="X1C",
  1219. with_run=False,
  1220. )
  1221. def handler(request: httpx.Request) -> httpx.Response:
  1222. return httpx.Response(
  1223. status_code=200,
  1224. content=_make_sliced_3mf("C11"), # X1C — same model as source
  1225. headers={
  1226. "x-print-time-seconds": "600",
  1227. "x-filament-used-g": "5.0",
  1228. "x-filament-used-mm": "1600.0",
  1229. },
  1230. )
  1231. _install_mock_sidecar(handler)
  1232. resp = await async_client.post(
  1233. f"/api/v1/archives/{source.id}/slice",
  1234. json={
  1235. "printer_preset_id": slice_test_setup["printer_id"],
  1236. "process_preset_id": slice_test_setup["process_id"],
  1237. "filament_preset_id": slice_test_setup["filament_id"],
  1238. },
  1239. )
  1240. assert resp.status_code == 202, resp.text
  1241. final = await _wait_for_job(async_client, resp.json()["job_id"])
  1242. assert final["status"] == "completed", final
  1243. new_archive = await db_session.get(PrintArchive, final["result"]["archive_id"])
  1244. assert new_archive.sliced_for_model == "X1C"
  1245. # Same-model: keep the source's printer assignment so reprint pre-selects it.
  1246. assert new_archive.printer_id == source_printer.id
  1247. @pytest.mark.asyncio
  1248. @pytest.mark.integration
  1249. async def test_reslice_with_unknown_source_model_preserves_printer_id(
  1250. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  1251. ):
  1252. """When ``source.sliced_for_model`` is None (older archive that
  1253. predates that column being populated), the backend can't tell whether
  1254. this is a cross-model re-slice. Fail open and preserve ``printer_id``
  1255. rather than spuriously nulling it — current pre-fix behaviour, kept
  1256. as a deliberate edge case."""
  1257. from backend.app.models.archive import PrintArchive
  1258. tmp_path = slice_test_setup["tmp_path"]
  1259. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  1260. src_dir = tmp_path / "archives" / "src"
  1261. src_dir.mkdir(parents=True, exist_ok=True)
  1262. src_3mf = src_dir / "cube.3mf"
  1263. src_3mf.write_bytes(_make_3mf_with_settings())
  1264. source_printer = await printer_factory()
  1265. source = await archive_factory(
  1266. source_printer.id,
  1267. filename="cube.3mf",
  1268. file_path=str(src_3mf.relative_to(tmp_path)),
  1269. sliced_for_model=None,
  1270. with_run=False,
  1271. )
  1272. def handler(request: httpx.Request) -> httpx.Response:
  1273. return httpx.Response(
  1274. status_code=200,
  1275. content=_make_sliced_3mf("O1D"),
  1276. headers={
  1277. "x-print-time-seconds": "600",
  1278. "x-filament-used-g": "5.0",
  1279. "x-filament-used-mm": "1600.0",
  1280. },
  1281. )
  1282. _install_mock_sidecar(handler)
  1283. resp = await async_client.post(
  1284. f"/api/v1/archives/{source.id}/slice",
  1285. json={
  1286. "printer_preset_id": slice_test_setup["printer_id"],
  1287. "process_preset_id": slice_test_setup["process_id"],
  1288. "filament_preset_id": slice_test_setup["filament_id"],
  1289. },
  1290. )
  1291. assert resp.status_code == 202, resp.text
  1292. final = await _wait_for_job(async_client, resp.json()["job_id"])
  1293. assert final["status"] == "completed", final
  1294. new_archive = await db_session.get(PrintArchive, final["result"]["archive_id"])
  1295. # Insufficient info to decide cross-model → preserve printer_id.
  1296. assert new_archive.printer_id == source_printer.id
  1297. class TestSliceArchiveReslicedThumbnail:
  1298. """#1493 follow-up: the re-sliced archive's cover image preference order is
  1299. source's per-plate render > sliced output's per-plate render >
  1300. Auxiliaries marketing thumbnail. BS CLI rarely writes a fresh
  1301. ``Metadata/plate_N.png`` on the sliced output, so the source's render
  1302. of the same plate (closer to what's actually printing) wins over the
  1303. project-wide marketing image."""
  1304. @staticmethod
  1305. def _make_source_with_plate_png(plate_png_bytes: bytes) -> bytes:
  1306. buf = io.BytesIO()
  1307. with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
  1308. zf.writestr("3D/3dmodel.model", "<model/>")
  1309. zf.writestr("Metadata/plate_1.png", plate_png_bytes)
  1310. # Project-wide marketing image — the unwanted fallback target.
  1311. zf.writestr("Auxiliaries/.thumbnails/thumbnail_middle.png", b"COVER_ART")
  1312. return buf.getvalue()
  1313. @pytest.mark.asyncio
  1314. @pytest.mark.integration
  1315. async def test_uses_source_plate_png_when_sliced_output_lacks_one(
  1316. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  1317. ):
  1318. """Sliced output has no per-plate PNG (typical of BS CLI output
  1319. with --arrange). The source's plate_1.png must win over the
  1320. sliced output's Auxiliaries fallback."""
  1321. from backend.app.models.archive import PrintArchive
  1322. tmp_path = slice_test_setup["tmp_path"]
  1323. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  1324. # Source has its own plate_1.png AND a project-wide cover.
  1325. source_plate_marker = b"SOURCE_PLATE_RENDER"
  1326. src_dir = tmp_path / "archives" / "src"
  1327. src_dir.mkdir(parents=True, exist_ok=True)
  1328. src_3mf = src_dir / "cube.3mf"
  1329. src_3mf.write_bytes(self._make_source_with_plate_png(source_plate_marker))
  1330. printer = await printer_factory()
  1331. source = await archive_factory(
  1332. printer.id,
  1333. filename="cube.3mf",
  1334. file_path=str(src_3mf.relative_to(tmp_path)),
  1335. sliced_for_model="X1C",
  1336. with_run=False,
  1337. )
  1338. # Mock slicer returns a 3MF with NO Metadata/plate_1.png — only
  1339. # the Auxiliaries cover, mimicking BS CLI output with --arrange.
  1340. def handler(request: httpx.Request) -> httpx.Response:
  1341. sliced_buf = io.BytesIO()
  1342. with zipfile.ZipFile(sliced_buf, "w") as zf:
  1343. zf.writestr("3D/3dmodel.model", "<model/>")
  1344. zf.writestr("Metadata/slice_info.config", "<config/>")
  1345. zf.writestr("Auxiliaries/.thumbnails/thumbnail_middle.png", b"SLICED_COVER_ART")
  1346. return httpx.Response(
  1347. status_code=200,
  1348. content=sliced_buf.getvalue(),
  1349. headers={"x-print-time-seconds": "60", "x-filament-used-g": "1", "x-filament-used-mm": "100"},
  1350. )
  1351. _install_mock_sidecar(handler)
  1352. resp = await async_client.post(
  1353. f"/api/v1/archives/{source.id}/slice",
  1354. json={
  1355. "printer_preset_id": slice_test_setup["printer_id"],
  1356. "process_preset_id": slice_test_setup["process_id"],
  1357. "filament_preset_id": slice_test_setup["filament_id"],
  1358. },
  1359. )
  1360. assert resp.status_code == 202, resp.text
  1361. final = await _wait_for_job(async_client, resp.json()["job_id"])
  1362. assert final["status"] == "completed", final
  1363. new = await db_session.get(PrintArchive, final["result"]["archive_id"])
  1364. assert new.thumbnail_path is not None
  1365. thumb_full = tmp_path / new.thumbnail_path
  1366. assert thumb_full.read_bytes() == source_plate_marker, (
  1367. "Re-sliced archive's thumbnail should be the source's per-plate render, not the Auxiliaries cover art."
  1368. )
  1369. @pytest.mark.asyncio
  1370. @pytest.mark.integration
  1371. async def test_falls_back_to_auxiliaries_when_source_lacks_plate_png(
  1372. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  1373. ):
  1374. """When the source has no per-plate render (unsliced library upload),
  1375. the Auxiliaries marketing image from the sliced output is the
  1376. next-best preview — better than no card thumbnail at all."""
  1377. from backend.app.models.archive import PrintArchive
  1378. tmp_path = slice_test_setup["tmp_path"]
  1379. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  1380. # Source has no Metadata/plate_1.png at all.
  1381. bare_buf = io.BytesIO()
  1382. with zipfile.ZipFile(bare_buf, "w") as zf:
  1383. zf.writestr("3D/3dmodel.model", "<model/>")
  1384. src_dir = tmp_path / "archives" / "src"
  1385. src_dir.mkdir(parents=True, exist_ok=True)
  1386. src_3mf = src_dir / "bare.3mf"
  1387. src_3mf.write_bytes(bare_buf.getvalue())
  1388. printer = await printer_factory()
  1389. source = await archive_factory(
  1390. printer.id,
  1391. filename="bare.3mf",
  1392. file_path=str(src_3mf.relative_to(tmp_path)),
  1393. sliced_for_model="X1C",
  1394. with_run=False,
  1395. )
  1396. def handler(request: httpx.Request) -> httpx.Response:
  1397. sliced_buf = io.BytesIO()
  1398. with zipfile.ZipFile(sliced_buf, "w") as zf:
  1399. zf.writestr("3D/3dmodel.model", "<model/>")
  1400. zf.writestr("Metadata/slice_info.config", "<config/>")
  1401. zf.writestr("Auxiliaries/.thumbnails/thumbnail_middle.png", b"COVER_ART_FALLBACK")
  1402. return httpx.Response(
  1403. status_code=200,
  1404. content=sliced_buf.getvalue(),
  1405. headers={"x-print-time-seconds": "60", "x-filament-used-g": "1", "x-filament-used-mm": "100"},
  1406. )
  1407. _install_mock_sidecar(handler)
  1408. resp = await async_client.post(
  1409. f"/api/v1/archives/{source.id}/slice",
  1410. json={
  1411. "printer_preset_id": slice_test_setup["printer_id"],
  1412. "process_preset_id": slice_test_setup["process_id"],
  1413. "filament_preset_id": slice_test_setup["filament_id"],
  1414. },
  1415. )
  1416. assert resp.status_code == 202, resp.text
  1417. final = await _wait_for_job(async_client, resp.json()["job_id"])
  1418. assert final["status"] == "completed", final
  1419. new = await db_session.get(PrintArchive, final["result"]["archive_id"])
  1420. assert new.thumbnail_path is not None
  1421. thumb_full = tmp_path / new.thumbnail_path
  1422. assert thumb_full.read_bytes() == b"COVER_ART_FALLBACK"
  1423. class TestSliceArchiveReslicedBedType:
  1424. """#1493 follow-up: the re-sliced archive's ``bed_type`` column must be
  1425. set from the produced 3MF's ``curr_bed_type`` so the frontend's archive
  1426. card shows the right build-plate badge (the card reads the column, not
  1427. extra_data, so the value was previously invisible after a re-slice)."""
  1428. @pytest.mark.asyncio
  1429. @pytest.mark.integration
  1430. async def test_bed_type_lifted_from_sliced_output(
  1431. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  1432. ):
  1433. from backend.app.models.archive import PrintArchive
  1434. tmp_path = slice_test_setup["tmp_path"]
  1435. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  1436. src_dir = tmp_path / "archives" / "src"
  1437. src_dir.mkdir(parents=True, exist_ok=True)
  1438. src_3mf = src_dir / "cube.3mf"
  1439. src_3mf.write_bytes(_make_3mf_with_settings())
  1440. printer = await printer_factory()
  1441. source = await archive_factory(
  1442. printer.id,
  1443. filename="cube.3mf",
  1444. file_path=str(src_3mf.relative_to(tmp_path)),
  1445. sliced_for_model="X1C",
  1446. bed_type="Cool Plate",
  1447. with_run=False,
  1448. )
  1449. # Mock slicer: produced 3MF declares a different plate type than
  1450. # the source archive's ``Cool Plate``. The new column must reflect
  1451. # the slicer's value (the user picked a different plate in the
  1452. # SliceModal) instead of inheriting the source's.
  1453. def handler(request: httpx.Request) -> httpx.Response:
  1454. return httpx.Response(
  1455. status_code=200,
  1456. content=_make_sliced_3mf("O1D", bed_type="Textured PEI Plate"),
  1457. headers={
  1458. "x-print-time-seconds": "600",
  1459. "x-filament-used-g": "5.0",
  1460. "x-filament-used-mm": "1600.0",
  1461. },
  1462. )
  1463. _install_mock_sidecar(handler)
  1464. resp = await async_client.post(
  1465. f"/api/v1/archives/{source.id}/slice",
  1466. json={
  1467. "printer_preset_id": slice_test_setup["printer_id"],
  1468. "process_preset_id": slice_test_setup["process_id"],
  1469. "filament_preset_id": slice_test_setup["filament_id"],
  1470. },
  1471. )
  1472. assert resp.status_code == 202, resp.text
  1473. final = await _wait_for_job(async_client, resp.json()["job_id"])
  1474. assert final["status"] == "completed", final
  1475. new = await db_session.get(PrintArchive, final["result"]["archive_id"])
  1476. assert new.bed_type == "Textured PEI Plate"
  1477. @pytest.mark.asyncio
  1478. @pytest.mark.integration
  1479. async def test_bed_type_falls_back_to_source_when_missing_from_output(
  1480. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  1481. ):
  1482. """An older sidecar or sparse slice profile may produce a 3MF without
  1483. ``curr_bed_type``. The source archive's ``bed_type`` is the right
  1484. default in that case — better than leaving the badge blank."""
  1485. from backend.app.models.archive import PrintArchive
  1486. tmp_path = slice_test_setup["tmp_path"]
  1487. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  1488. src_dir = tmp_path / "archives" / "src"
  1489. src_dir.mkdir(parents=True, exist_ok=True)
  1490. src_3mf = src_dir / "cube.3mf"
  1491. src_3mf.write_bytes(_make_3mf_with_settings())
  1492. printer = await printer_factory()
  1493. source = await archive_factory(
  1494. printer.id,
  1495. filename="cube.3mf",
  1496. file_path=str(src_3mf.relative_to(tmp_path)),
  1497. sliced_for_model="X1C",
  1498. bed_type="Cool Plate",
  1499. with_run=False,
  1500. )
  1501. def handler(request: httpx.Request) -> httpx.Response:
  1502. return httpx.Response(
  1503. status_code=200,
  1504. # No bed_type embedded — simulates a sidecar that drops it.
  1505. content=_make_sliced_3mf("O1D"),
  1506. headers={
  1507. "x-print-time-seconds": "600",
  1508. "x-filament-used-g": "5.0",
  1509. "x-filament-used-mm": "1600.0",
  1510. },
  1511. )
  1512. _install_mock_sidecar(handler)
  1513. resp = await async_client.post(
  1514. f"/api/v1/archives/{source.id}/slice",
  1515. json={
  1516. "printer_preset_id": slice_test_setup["printer_id"],
  1517. "process_preset_id": slice_test_setup["process_id"],
  1518. "filament_preset_id": slice_test_setup["filament_id"],
  1519. },
  1520. )
  1521. assert resp.status_code == 202, resp.text
  1522. final = await _wait_for_job(async_client, resp.json()["job_id"])
  1523. assert final["status"] == "completed", final
  1524. new = await db_session.get(PrintArchive, final["result"]["archive_id"])
  1525. assert new.bed_type == "Cool Plate"
  1526. # ---------------------------------------------------------------------------
  1527. # Slicer content rejections surface instead of silently falling back
  1528. # ---------------------------------------------------------------------------
  1529. class TestSlicerRejectionMessage:
  1530. """_slicer_rejection_message distinguishes a real slicer content rejection
  1531. (surface it to the user) from a CLI crash (fall back to embedded)."""
  1532. def test_extracts_bed_boundary_reason(self):
  1533. text = (
  1534. "Slicer CLI failed (500): Slicing failed with error from slicer: "
  1535. "Some objects are located over the boundary of the heated bed.: "
  1536. "Slicer process failed (exit code 204)\nstdout: trace ..."
  1537. )
  1538. assert _slicer_rejection_message(text) == "Some objects are located over the boundary of the heated bed."
  1539. def test_extracts_filament_temp_reason(self):
  1540. text = (
  1541. "Slicer CLI failed (500): Slicing failed with error from slicer: "
  1542. "The temperature difference of the filaments used is too large.: "
  1543. "Slicer process failed (exit code 194)"
  1544. )
  1545. assert _slicer_rejection_message(text) == "The temperature difference of the filaments used is too large."
  1546. def test_generic_cli_failure_is_not_a_rejection(self):
  1547. # The #1201 CLI-crash signature carries no slicer error_string, so it
  1548. # must still fall through to the embedded-settings fallback.
  1549. assert _slicer_rejection_message("Slicer CLI failed (500): Failed to slice the model") is None
  1550. def test_empty_or_unrelated_text(self):
  1551. assert _slicer_rejection_message("") is None
  1552. assert _slicer_rejection_message("Slicer sidecar unreachable: connection reset") is None
  1553. def test_replaces_input_preset_invalid_placeholder_with_cli_error_line(self):
  1554. # #1851: the CLI emits its catch-all "input preset file is invalid"
  1555. # placeholder for every -5 exit, including real preset-vs-printer
  1556. # compatibility rejections. The actual diagnostic only appears in the
  1557. # stdout `[error] run NNNN:` line; the function must prefer that.
  1558. text = (
  1559. "Slicer CLI failed (500): Slicing failed with error from slicer: "
  1560. "The input preset file is invalid and can not be parsed.: "
  1561. "Slicer process failed (exit code 251)\n"
  1562. "stdout: [2026-06-29 04:12:11.952784] [trace] Initializing StaticPrintConfigs\n"
  1563. "[2026-06-29 04:12:12.175810] [error] run 3008: filament preset "
  1564. "Generic PLA @BBL H2C (slot 1) is not compatible with printer "
  1565. "Bambu Lab A1 0.4 nozzle.\n"
  1566. "run found error, return -5, exit..."
  1567. )
  1568. assert (
  1569. _slicer_rejection_message(text) == "filament preset Generic PLA @BBL H2C (slot 1) is not compatible with "
  1570. "printer Bambu Lab A1 0.4 nozzle."
  1571. )
  1572. def test_keeps_meaningful_reason_even_when_cli_error_line_present(self):
  1573. # When the headline error_string is already a useful reason (here:
  1574. # the bed-boundary rejection), don't override it with a generic
  1575. # `[error]` line that may just be the same message restated. Avoids
  1576. # double-text duplication in the user-facing detail.
  1577. text = (
  1578. "Slicer CLI failed (500): Slicing failed with error from slicer: "
  1579. "Some objects are located over the boundary of the heated bed.: "
  1580. "Slicer process failed (exit code 204)\n"
  1581. "stdout: [error] some unrelated stdout chatter"
  1582. )
  1583. assert _slicer_rejection_message(text) == "Some objects are located over the boundary of the heated bed."
  1584. def test_cli_error_line_without_run_prefix(self):
  1585. # The CLI sometimes logs `[error] <msg>` without the `run NNNN:`
  1586. # prefix (different code paths). The regex must still pick it up.
  1587. text = (
  1588. "Slicer CLI failed (500): Slicing failed with error from slicer: "
  1589. "The input preset file is invalid and can not be parsed.: "
  1590. "Slicer process failed (exit code 251)\n"
  1591. "stdout: [2026-06-29 12:00:00.000000] [error] Configuration parse failed: missing key 'printer_settings_id'"
  1592. )
  1593. assert _slicer_rejection_message(text) == "Configuration parse failed: missing key 'printer_settings_id'"
  1594. class TestSliceSlicerRejection:
  1595. @pytest.mark.asyncio
  1596. @pytest.mark.integration
  1597. async def test_3mf_surfaces_slicer_rejection_instead_of_falling_back(
  1598. self, async_client: AsyncClient, db_session, slice_test_setup
  1599. ):
  1600. """A real slicer content rejection (e.g. re-slicing for a printer with
  1601. a smaller bed) must surface as a 400 — not silently fall back to the
  1602. source 3MF's embedded settings, which would re-slice for the original
  1603. printer and hide the problem."""
  1604. src_3mf_path = slice_test_setup["tmp_path"] / "library" / "files" / "toobig.3mf"
  1605. src_3mf_path.write_bytes(_make_3mf_with_settings())
  1606. threemf = LibraryFile(
  1607. filename="toobig.3mf",
  1608. file_path=str(src_3mf_path.relative_to(slice_test_setup["tmp_path"])),
  1609. file_type="3mf",
  1610. file_size=src_3mf_path.stat().st_size,
  1611. )
  1612. db_session.add(threemf)
  1613. await db_session.commit()
  1614. await db_session.refresh(threemf)
  1615. call_count = {"n": 0}
  1616. def handler(request: httpx.Request) -> httpx.Response:
  1617. if not _is_slice_post(request):
  1618. return httpx.Response(404)
  1619. call_count["n"] += 1
  1620. return httpx.Response(
  1621. status_code=500,
  1622. json={
  1623. "message": (
  1624. "Slicing failed with error from slicer: Some objects are "
  1625. "located over the boundary of the heated bed."
  1626. ),
  1627. "details": "Slicer process failed (exit code 204)",
  1628. },
  1629. )
  1630. _install_mock_sidecar(handler)
  1631. response = await async_client.post(
  1632. f"/api/v1/library/files/{threemf.id}/slice",
  1633. json={
  1634. "printer_preset_id": slice_test_setup["printer_id"],
  1635. "process_preset_id": slice_test_setup["process_id"],
  1636. "filament_preset_id": slice_test_setup["filament_id"],
  1637. },
  1638. )
  1639. assert response.status_code == 202
  1640. final = await _wait_for_job(async_client, response.json()["job_id"])
  1641. assert final["status"] == "failed", final
  1642. assert final["error_status"] == 400
  1643. assert "boundary of the heated bed" in (final["error_detail"] or "")
  1644. # The slicer rejection must NOT trigger the embedded-settings retry.
  1645. assert call_count["n"] == 1
  1646. # ---------------------------------------------------------------------------
  1647. # Nozzle-class re-slice guard — single-nozzle <-> dual-nozzle (H2D) is blocked
  1648. # ---------------------------------------------------------------------------
  1649. from fastapi import HTTPException # noqa: E402
  1650. from backend.app.api.routes.library import ( # noqa: E402
  1651. _canonical_printer_model,
  1652. guard_nozzle_class_reslice,
  1653. )
  1654. class TestCanonicalPrinterModel:
  1655. """_canonical_printer_model strips the '# ' clone prefix and the
  1656. ' 0.4 nozzle' variant suffix so preset names resolve to a model code."""
  1657. def test_strips_nozzle_suffix(self):
  1658. assert _canonical_printer_model("Bambu Lab H2D 0.4 nozzle") == "H2D"
  1659. def test_strips_clone_prefix_and_suffix(self):
  1660. assert _canonical_printer_model("# Bambu Lab X1 Carbon 0.4 nozzle") == "X1C"
  1661. def test_bare_model_and_empty(self):
  1662. assert _canonical_printer_model("Bambu Lab H2D") == "H2D"
  1663. assert _canonical_printer_model(None) is None
  1664. assert _canonical_printer_model("") is None
  1665. class TestNozzleClassGuard:
  1666. """guard_nozzle_class_reslice is now a no-op (#1493). Cross-class re-slicing
  1667. is handled by the two-pass conversion in _run_slicer_with_fallback — so the
  1668. guard never blocks. The function is kept (and these tests with it) so
  1669. external forks / pinned versions that call it still link, and so a future
  1670. regression that re-introduces a raise inside the helper gets caught here."""
  1671. @staticmethod
  1672. def _request() -> object:
  1673. return type("_Req", (), {})()
  1674. @pytest.mark.asyncio
  1675. async def test_single_to_dual_is_allowed(self, monkeypatch):
  1676. """Cross-class re-slice: handled by the two-pass converter, so the
  1677. guard does NOT raise."""
  1678. import backend.app.api.routes.library as lib
  1679. async def _target(_db, _user, _request):
  1680. return "H2D"
  1681. monkeypatch.setattr(lib, "_resolve_target_printer_model", _target)
  1682. # No raise — the converter handles this case now.
  1683. await guard_nozzle_class_reslice(None, None, self._request(), "X1C")
  1684. @pytest.mark.asyncio
  1685. async def test_dual_to_single_is_allowed(self, monkeypatch):
  1686. import backend.app.api.routes.library as lib
  1687. async def _target(_db, _user, _request):
  1688. return "X1C"
  1689. monkeypatch.setattr(lib, "_resolve_target_printer_model", _target)
  1690. await guard_nozzle_class_reslice(None, None, self._request(), "H2D")
  1691. @pytest.mark.asyncio
  1692. async def test_same_nozzle_class_is_allowed(self, monkeypatch):
  1693. import backend.app.api.routes.library as lib
  1694. async def _target(_db, _user, _request):
  1695. return "P1S"
  1696. monkeypatch.setattr(lib, "_resolve_target_printer_model", _target)
  1697. await guard_nozzle_class_reslice(None, None, self._request(), "X1C")
  1698. @pytest.mark.asyncio
  1699. async def test_no_source_model_is_a_noop(self, monkeypatch):
  1700. import backend.app.api.routes.library as lib
  1701. async def _target(_db, _user, _request):
  1702. return "H2D"
  1703. monkeypatch.setattr(lib, "_resolve_target_printer_model", _target)
  1704. await guard_nozzle_class_reslice(None, None, self._request(), None)
  1705. @pytest.mark.asyncio
  1706. async def test_null_request_is_a_noop(self):
  1707. await guard_nozzle_class_reslice(None, None, None, "X1C")
  1708. @pytest.mark.asyncio
  1709. @pytest.mark.integration
  1710. async def test_archive_reslice_x1c_to_h2d_preset_path_is_not_400(
  1711. self, async_client: AsyncClient, db_session, slice_test_setup, printer_factory, archive_factory, monkeypatch
  1712. ):
  1713. """End to end: the preset-driven archive re-slice from X1C to H2D no
  1714. longer gets a synchronous 400 from the guard. It may still fail
  1715. downstream (no sidecar in test env), but it must not be rejected by
  1716. the nozzle-class guard's old "isn't supported yet" message."""
  1717. tmp_path = slice_test_setup["tmp_path"]
  1718. monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
  1719. src_dir = tmp_path / "archives" / "src"
  1720. src_dir.mkdir(parents=True, exist_ok=True)
  1721. src_3mf = src_dir / "cube.3mf"
  1722. src_3mf.write_bytes(_make_3mf_with_settings())
  1723. printer = await printer_factory()
  1724. source = await archive_factory(
  1725. printer.id,
  1726. filename="cube.3mf",
  1727. file_path=str(src_3mf.relative_to(tmp_path)),
  1728. sliced_for_model="X1C",
  1729. with_run=False,
  1730. )
  1731. h2d = LocalPreset(
  1732. name="# Bambu Lab H2D 0.4 nozzle",
  1733. preset_type="printer",
  1734. source="orcaslicer",
  1735. setting=json.dumps({"name": "Bambu Lab H2D 0.4 nozzle", "printer_model": "Bambu Lab H2D"}),
  1736. )
  1737. db_session.add(h2d)
  1738. await db_session.commit()
  1739. await db_session.refresh(h2d)
  1740. resp = await async_client.post(
  1741. f"/api/v1/archives/{source.id}/slice",
  1742. json={
  1743. "printer_preset": {"source": "local", "id": str(h2d.id)},
  1744. "process_preset": {"source": "local", "id": str(slice_test_setup["process_id"])},
  1745. "filament_presets": [{"source": "local", "id": str(slice_test_setup["filament_id"])}],
  1746. },
  1747. )
  1748. if resp.status_code == 400:
  1749. detail = resp.json().get("detail", "")
  1750. assert "isn't supported" not in detail, f"guard still firing on preset path: {detail!r}"
  1751. class TestUnusedSlotSubstitutionOnSinglePlateSource:
  1752. """#2711: a single-plate 3MF must still get its unused slots substituted.
  1753. The SliceModal omits ``plate`` entirely for single-plate and STL sources —
  1754. it skips the plate picker, so ``selectedPlate`` stays null and the field
  1755. never reaches the body. The schema documents an absent plate as "plate 1",
  1756. but the substitution used to read it as "unknown plate" and skip, so every
  1757. single-plate project reached the CLI with the dropdown values of slots the
  1758. plate never paints with.
  1759. In the reported case that was a MakerWorld project declaring four filaments
  1760. while plate 1 paints with one, the other three carrying presets baked into
  1761. the source for a different printer. The CLI rejected the whole slice with
  1762. "filament preset ... (slot 1) is not compatible with printer ...", and the
  1763. modal disables unused rows so there was no way to correct it by hand.
  1764. """
  1765. @staticmethod
  1766. def _single_plate_using_only_slot_3() -> bytes:
  1767. """One plate, one object, painted with slot 3 — slots 1, 2 and 4 are
  1768. declared by the project but unused. Mirrors the reported file."""
  1769. buf = io.BytesIO()
  1770. with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
  1771. zf.writestr("3D/3dmodel.model", "<model/>")
  1772. zf.writestr(
  1773. "Metadata/project_settings.config",
  1774. json.dumps({"filament_type": ["PLA", "PLA", "PLA", "TPU"]}),
  1775. )
  1776. zf.writestr(
  1777. "Metadata/model_settings.config",
  1778. "<?xml version='1.0'?>\n<config>"
  1779. '<object id="1"><metadata key="extruder" value="3"/></object>'
  1780. '<plate><metadata key="plater_id" value="1"/>'
  1781. '<model_instance><metadata key="object_id" value="1"/>'
  1782. '<metadata key="instance_id" value="0"/></model_instance>'
  1783. "</plate></config>",
  1784. )
  1785. return buf.getvalue()
  1786. @staticmethod
  1787. def _filament_names_sent(body: bytes) -> list[str]:
  1788. """Pull the ``name`` of each ``filamentProfile`` part, in slot order.
  1789. ``slice_model`` sends one repeated ``filamentProfile`` part per slot as
  1790. ``filament_N.json``; the parts stay in submission order, so a plain
  1791. scan preserves the slot mapping.
  1792. """
  1793. names: list[str] = []
  1794. marker = b'name="filamentProfile"; filename="filament_'
  1795. pos = body.find(marker)
  1796. while pos != -1:
  1797. start = body.find(b"{", pos)
  1798. end = body.find(b"\r\n", start)
  1799. names.append(json.loads(body[start:end].decode("utf-8"))["name"])
  1800. pos = body.find(marker, end)
  1801. return names
  1802. @pytest.mark.asyncio
  1803. @pytest.mark.integration
  1804. async def test_unused_slots_are_substituted_when_the_body_omits_plate(
  1805. self, async_client: AsyncClient, db_session, slice_test_setup
  1806. ):
  1807. tmp_path = slice_test_setup["tmp_path"]
  1808. src = tmp_path / "library" / "files" / "train.3mf"
  1809. src.write_bytes(self._single_plate_using_only_slot_3())
  1810. threemf = LibraryFile(
  1811. filename="train.3mf",
  1812. file_path=str(src.relative_to(tmp_path)),
  1813. file_type="3mf",
  1814. file_size=src.stat().st_size,
  1815. )
  1816. db_session.add(threemf)
  1817. # Four distinguishable filament presets, one per project slot. Only
  1818. # slot 3's is compatible with the target in the reported scenario.
  1819. slots = []
  1820. for i in range(1, 5):
  1821. p = LocalPreset(
  1822. name=f"slot{i}",
  1823. preset_type="filament",
  1824. source="orcaslicer",
  1825. setting=json.dumps({"name": f"slot{i}", "type": "filament"}),
  1826. )
  1827. db_session.add(p)
  1828. slots.append(p)
  1829. await db_session.commit()
  1830. await db_session.refresh(threemf)
  1831. for p in slots:
  1832. await db_session.refresh(p)
  1833. captured: list[list[str]] = []
  1834. def handler(request: httpx.Request) -> httpx.Response:
  1835. if not _is_slice_post(request):
  1836. return httpx.Response(404)
  1837. captured.append(self._filament_names_sent(request.content))
  1838. return httpx.Response(
  1839. status_code=200,
  1840. content=_make_3mf_with_settings(),
  1841. headers={
  1842. "x-print-time-seconds": "100",
  1843. "x-filament-used-g": "1.0",
  1844. "x-filament-used-mm": "100",
  1845. },
  1846. )
  1847. _install_mock_sidecar(handler)
  1848. response = await async_client.post(
  1849. f"/api/v1/library/files/{threemf.id}/slice",
  1850. json={
  1851. "printer_preset": {"source": "local", "id": str(slice_test_setup["printer_id"])},
  1852. "process_preset": {"source": "local", "id": str(slice_test_setup["process_id"])},
  1853. "filament_presets": [{"source": "local", "id": str(p.id)} for p in slots],
  1854. # No "plate" — exactly what the modal sends for a single-plate
  1855. # source. This is the whole point of the test.
  1856. },
  1857. )
  1858. assert response.status_code == 202, response.text
  1859. final = await _wait_for_job(async_client, response.json()["job_id"])
  1860. assert final["status"] == "completed", final
  1861. assert captured, "sidecar was never called"
  1862. # Every slot carries slot 3's profile: the array length stays intact
  1863. # (the source's per-slot references depend on it) while nothing the
  1864. # plate doesn't print with can fail the CLI's validators.
  1865. assert captured[0] == ["slot3", "slot3", "slot3", "slot3"], captured[0]
  1866. @pytest.mark.asyncio
  1867. @pytest.mark.integration
  1868. async def test_slice_all_keeps_every_slot(self, async_client: AsyncClient, db_session, slice_test_setup):
  1869. """``plate=0`` is the all-plates sentinel, so nothing is unused.
  1870. It reaches the same call site, and plate ids are 1-indexed — the
  1871. geometry lookup for plate 0 matches nothing. Without an explicit
  1872. exclusion the project's support-filament slot would be the only
  1873. member of the used set and would be copied over every colour.
  1874. """
  1875. tmp_path = slice_test_setup["tmp_path"]
  1876. buf = io.BytesIO()
  1877. with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
  1878. zf.writestr("3D/3dmodel.model", "<model/>")
  1879. zf.writestr(
  1880. "Metadata/project_settings.config",
  1881. json.dumps(
  1882. {
  1883. "enable_support": "1",
  1884. "support_filament": "4",
  1885. "support_interface_filament": "4",
  1886. "filament_type": ["PLA", "PLA", "PLA", "PVA"],
  1887. }
  1888. ),
  1889. )
  1890. zf.writestr(
  1891. "Metadata/model_settings.config",
  1892. "<?xml version='1.0'?>\n<config>"
  1893. '<object id="1"><metadata key="extruder" value="1"/></object>'
  1894. '<object id="2"><metadata key="extruder" value="2"/></object>'
  1895. '<plate><metadata key="plater_id" value="1"/>'
  1896. '<model_instance><metadata key="object_id" value="1"/></model_instance></plate>'
  1897. '<plate><metadata key="plater_id" value="2"/>'
  1898. '<model_instance><metadata key="object_id" value="2"/></model_instance></plate>'
  1899. "</config>",
  1900. )
  1901. src = tmp_path / "library" / "files" / "multi.3mf"
  1902. src.write_bytes(buf.getvalue())
  1903. threemf = LibraryFile(
  1904. filename="multi.3mf",
  1905. file_path=str(src.relative_to(tmp_path)),
  1906. file_type="3mf",
  1907. file_size=src.stat().st_size,
  1908. )
  1909. db_session.add(threemf)
  1910. slots = []
  1911. for i in range(1, 5):
  1912. p = LocalPreset(
  1913. name=f"slot{i}",
  1914. preset_type="filament",
  1915. source="orcaslicer",
  1916. setting=json.dumps({"name": f"slot{i}", "type": "filament"}),
  1917. )
  1918. db_session.add(p)
  1919. slots.append(p)
  1920. await db_session.commit()
  1921. await db_session.refresh(threemf)
  1922. for p in slots:
  1923. await db_session.refresh(p)
  1924. captured: list[list[str]] = []
  1925. def handler(request: httpx.Request) -> httpx.Response:
  1926. if not _is_slice_post(request):
  1927. return httpx.Response(404)
  1928. captured.append(self._filament_names_sent(request.content))
  1929. return httpx.Response(
  1930. status_code=200,
  1931. content=_make_3mf_with_settings(),
  1932. headers={
  1933. "x-print-time-seconds": "100",
  1934. "x-filament-used-g": "1.0",
  1935. "x-filament-used-mm": "100",
  1936. },
  1937. )
  1938. _install_mock_sidecar(handler)
  1939. response = await async_client.post(
  1940. f"/api/v1/library/files/{threemf.id}/slice",
  1941. json={
  1942. "printer_preset": {"source": "local", "id": str(slice_test_setup["printer_id"])},
  1943. "process_preset": {"source": "local", "id": str(slice_test_setup["process_id"])},
  1944. "filament_presets": [{"source": "local", "id": str(p.id)} for p in slots],
  1945. "plate": 0,
  1946. },
  1947. )
  1948. assert response.status_code == 202, response.text
  1949. final = await _wait_for_job(async_client, response.json()["job_id"])
  1950. assert final["status"] == "completed", final
  1951. assert captured, "sidecar was never called"
  1952. assert captured[0] == ["slot1", "slot2", "slot3", "slot4"], captured[0]
  1953. class TestFilamentRequirementsFullSlots:
  1954. """#2712: what the slice modal is handed must be positional.
  1955. The modal's filament list maps index 0 to slot 1, and the backend forwards
  1956. it in that order as ``filament_1.json``..``filament_N.json``. A MakerWorld
  1957. source that ships slice_info and paints with slot 4 alone therefore has to
  1958. present four rows — a one-row list binds the user's pick to slot 1, and
  1959. slot 4 slices with whatever the source had baked in. Picking PETG produced
  1960. a PLA print, and the print dialog then correctly refused to match PETG.
  1961. Print-time AMS matching shares this endpoint and needs the opposite: only
  1962. the slots the plate consumes, so it doesn't demand spools for slots the
  1963. G-code never touches. Hence the opt-in flag rather than a shape change.
  1964. """
  1965. @staticmethod
  1966. def _sliced_source_using_only_slot_4() -> bytes:
  1967. buf = io.BytesIO()
  1968. with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
  1969. zf.writestr("3D/3dmodel.model", "<model/>")
  1970. zf.writestr(
  1971. "Metadata/project_settings.config",
  1972. json.dumps(
  1973. {
  1974. "filament_type": ["PLA", "PLA", "PLA", "PLA"],
  1975. "filament_colour": ["#38CC0A", "#161616", "#898989", "#898989"],
  1976. }
  1977. ),
  1978. )
  1979. # MakerWorld ships slice_info without plate G-code, which is what
  1980. # sends this file down the "already sliced" branch.
  1981. zf.writestr(
  1982. "Metadata/slice_info.config",
  1983. "<?xml version='1.0'?>\n<config><plate>"
  1984. "<metadata key='index' value='1'/>"
  1985. "<filament id='4' tray_info_idx='GFL99' type='PLA' color='#898989'"
  1986. " used_m='35.51' used_g='105.92'/>"
  1987. "</plate></config>",
  1988. )
  1989. return buf.getvalue()
  1990. async def _make_file(self, db_session, tmp_path) -> int:
  1991. src = tmp_path / "library" / "files" / "tunnel.3mf"
  1992. src.write_bytes(self._sliced_source_using_only_slot_4())
  1993. lib = LibraryFile(
  1994. filename="tunnel.3mf",
  1995. file_path=str(src.relative_to(tmp_path)),
  1996. file_type="3mf",
  1997. file_size=src.stat().st_size,
  1998. )
  1999. db_session.add(lib)
  2000. await db_session.commit()
  2001. await db_session.refresh(lib)
  2002. return lib.id
  2003. @pytest.mark.asyncio
  2004. @pytest.mark.integration
  2005. async def test_full_slots_returns_one_row_per_project_slot(
  2006. self, async_client: AsyncClient, db_session, slice_test_setup
  2007. ):
  2008. file_id = await self._make_file(db_session, slice_test_setup["tmp_path"])
  2009. r = await async_client.get(f"/api/v1/library/files/{file_id}/filament-requirements?plate_id=1&full_slots=true")
  2010. assert r.status_code == 200, r.text
  2011. filaments = r.json()["filaments"]
  2012. assert [f["slot_id"] for f in filaments] == [1, 2, 3, 4]
  2013. # Only slot 4 prints, so only its row is selectable in the modal.
  2014. assert [f["used_in_plate"] for f in filaments] == [False, False, False, True]
  2015. # The used row keeps what the slice actually reported.
  2016. assert filaments[3]["used_grams"] == 105.9
  2017. assert filaments[3]["tray_info_idx"] == "GFL99"
  2018. @pytest.mark.asyncio
  2019. @pytest.mark.integration
  2020. async def test_the_print_path_still_gets_only_the_used_slot(
  2021. self, async_client: AsyncClient, db_session, slice_test_setup
  2022. ):
  2023. """Without the flag the response must be byte-for-byte what it was.
  2024. PrintModal drives AMS matching off this; widening it would ask the
  2025. user to load three spools the print never touches.
  2026. """
  2027. file_id = await self._make_file(db_session, slice_test_setup["tmp_path"])
  2028. r = await async_client.get(f"/api/v1/library/files/{file_id}/filament-requirements?plate_id=1")
  2029. assert r.status_code == 200, r.text
  2030. filaments = r.json()["filaments"]
  2031. assert [f["slot_id"] for f in filaments] == [4]
  2032. assert filaments[0]["used_in_plate"] is True
  2033. @pytest.mark.asyncio
  2034. @pytest.mark.integration
  2035. async def test_unsliced_sources_are_unaffected_by_the_flag(
  2036. self, async_client: AsyncClient, db_session, slice_test_setup
  2037. ):
  2038. """Those already returned the full project list; the flag must not
  2039. double-handle them or change what the modal has been getting."""
  2040. tmp_path = slice_test_setup["tmp_path"]
  2041. buf = io.BytesIO()
  2042. with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
  2043. zf.writestr("3D/3dmodel.model", "<model/>")
  2044. zf.writestr(
  2045. "Metadata/project_settings.config",
  2046. json.dumps({"filament_type": ["PLA", "PETG"], "filament_colour": ["#000000", "#FFFFFF"]}),
  2047. )
  2048. src = tmp_path / "library" / "files" / "raw.3mf"
  2049. src.write_bytes(buf.getvalue())
  2050. lib = LibraryFile(
  2051. filename="raw.3mf",
  2052. file_path=str(src.relative_to(tmp_path)),
  2053. file_type="3mf",
  2054. file_size=src.stat().st_size,
  2055. )
  2056. db_session.add(lib)
  2057. await db_session.commit()
  2058. await db_session.refresh(lib)
  2059. with_flag = await async_client.get(
  2060. f"/api/v1/library/files/{lib.id}/filament-requirements?plate_id=1&full_slots=true"
  2061. )
  2062. without = await async_client.get(f"/api/v1/library/files/{lib.id}/filament-requirements?plate_id=1")
  2063. assert with_flag.status_code == 200 and without.status_code == 200
  2064. assert with_flag.json()["filaments"] == without.json()["filaments"]
  2065. assert [f["slot_id"] for f in with_flag.json()["filaments"]] == [1, 2]