test_library_slice_api.py 103 KB

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