test_threemf_tools.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  1. """Unit tests for 3MF parsing utilities (threemf_tools.py).
  2. Tests G-code parsing, filament length-to-weight conversion,
  3. and cumulative layer usage lookup.
  4. """
  5. import io
  6. import json
  7. import math
  8. import zipfile
  9. from backend.app.utils.threemf_tools import (
  10. extract_bed_type_from_3mf,
  11. extract_embedded_presets_from_3mf,
  12. extract_filament_usage_from_3mf,
  13. extract_plate_extruder_set_from_3mf,
  14. extract_project_filaments_from_3mf,
  15. get_cumulative_usage_at_layer,
  16. mm_to_grams,
  17. parse_gcode_layer_filament_usage,
  18. )
  19. def create_mock_3mf(slice_info_content: str) -> io.BytesIO:
  20. """Create a mock 3MF file (ZIP) with slice_info.config content."""
  21. buffer = io.BytesIO()
  22. with zipfile.ZipFile(buffer, "w") as zf:
  23. zf.writestr("Metadata/slice_info.config", slice_info_content)
  24. buffer.seek(0)
  25. return buffer
  26. class TestParseGcodeLayerFilamentUsage:
  27. """Tests for parse_gcode_layer_filament_usage()."""
  28. def test_single_filament_single_layer(self):
  29. """Single filament extruding on one layer."""
  30. gcode = """
  31. M620 S0
  32. G1 X10 Y10 E5.0
  33. G1 X20 Y20 E3.0
  34. """
  35. result = parse_gcode_layer_filament_usage(gcode)
  36. assert result == {0: {0: 8.0}}
  37. def test_multi_layer_single_filament(self):
  38. """Single filament across multiple layers."""
  39. gcode = """
  40. M620 S0
  41. G1 X10 Y10 E10.0
  42. M73 L1
  43. G1 X20 Y20 E5.0
  44. M73 L2
  45. G1 X30 Y30 E7.0
  46. """
  47. result = parse_gcode_layer_filament_usage(gcode)
  48. assert result[0] == {0: 10.0}
  49. assert result[1] == {0: 15.0}
  50. assert result[2] == {0: 22.0}
  51. def test_multi_material(self):
  52. """Multiple filaments switching via M620."""
  53. gcode = """
  54. M620 S0
  55. G1 E10.0
  56. M73 L1
  57. M620 S1
  58. G1 E5.0
  59. M620 S0
  60. G1 E3.0
  61. M73 L2
  62. G1 E2.0
  63. """
  64. result = parse_gcode_layer_filament_usage(gcode)
  65. # Layer 0: filament 0 = 10mm
  66. assert result[0] == {0: 10.0}
  67. # Layer 1: filament 0 = 13mm (10+3), filament 1 = 5mm
  68. assert result[1] == {0: 13.0, 1: 5.0}
  69. # Layer 2: filament 0 = 15mm (13+2)
  70. assert result[2] == {0: 15.0, 1: 5.0}
  71. def test_retractions_ignored(self):
  72. """Negative E values (retractions) should be ignored."""
  73. gcode = """
  74. M620 S0
  75. G1 E10.0
  76. G1 E-2.0
  77. G1 E5.0
  78. """
  79. result = parse_gcode_layer_filament_usage(gcode)
  80. assert result == {0: {0: 15.0}}
  81. def test_m620_s255_unloads(self):
  82. """M620 S255 means unload - extrusion after should be ignored."""
  83. gcode = """
  84. M620 S0
  85. G1 E10.0
  86. M620 S255
  87. G1 E5.0
  88. """
  89. result = parse_gcode_layer_filament_usage(gcode)
  90. assert result == {0: {0: 10.0}}
  91. def test_m620_with_suffix(self):
  92. """M620 S0A format (filament ID with suffix letter)."""
  93. gcode = """
  94. M620 S0A
  95. G1 E10.0
  96. M620 S1A
  97. G1 E5.0
  98. """
  99. result = parse_gcode_layer_filament_usage(gcode)
  100. assert result == {0: {0: 10.0, 1: 5.0}}
  101. def test_comments_ignored(self):
  102. """Comment lines and inline comments are ignored."""
  103. gcode = """
  104. ; This is a comment
  105. M620 S0
  106. G1 X10 E5.0 ; inline comment with E value
  107. G1 E3.0
  108. """
  109. result = parse_gcode_layer_filament_usage(gcode)
  110. assert result == {0: {0: 8.0}}
  111. def test_empty_gcode(self):
  112. """Empty G-code returns empty dict."""
  113. assert parse_gcode_layer_filament_usage("") == {}
  114. assert parse_gcode_layer_filament_usage("\n\n\n") == {}
  115. def test_no_extrusion(self):
  116. """G-code with moves but no extrusion."""
  117. gcode = """
  118. G1 X10 Y10
  119. G1 X20 Y20
  120. """
  121. assert parse_gcode_layer_filament_usage(gcode) == {}
  122. def test_no_active_filament_extrusion_ignored(self):
  123. """Extrusion before any M620 is ignored (no active filament)."""
  124. gcode = """
  125. G1 E10.0
  126. M620 S0
  127. G1 E5.0
  128. """
  129. result = parse_gcode_layer_filament_usage(gcode)
  130. assert result == {0: {0: 5.0}}
  131. def test_g0_g2_g3_extrusion(self):
  132. """G0, G2, G3 with E parameter are also tracked."""
  133. gcode = """
  134. M620 S0
  135. G0 E1.0
  136. G1 E2.0
  137. G2 E3.0
  138. G3 E4.0
  139. """
  140. result = parse_gcode_layer_filament_usage(gcode)
  141. assert result == {0: {0: 10.0}}
  142. def test_cumulative_across_layers(self):
  143. """Values are cumulative, not per-layer."""
  144. gcode = """
  145. M620 S0
  146. G1 E100.0
  147. M73 L1
  148. G1 E100.0
  149. M73 L2
  150. G1 E100.0
  151. """
  152. result = parse_gcode_layer_filament_usage(gcode)
  153. assert result[0] == {0: 100.0}
  154. assert result[1] == {0: 200.0}
  155. assert result[2] == {0: 300.0}
  156. class TestMmToGrams:
  157. """Tests for mm_to_grams()."""
  158. def test_default_pla_175(self):
  159. """Default PLA 1.75mm conversion."""
  160. # 1000mm of 1.75mm PLA at 1.24 g/cm³
  161. # Volume = π × (0.0875cm)² × 100cm = 2.405cm³
  162. # Weight = 2.405 × 1.24 = 2.982g
  163. result = mm_to_grams(1000.0)
  164. expected = math.pi * (0.0875**2) * 100 * 1.24
  165. assert abs(result - expected) < 0.001
  166. def test_zero_length(self):
  167. """Zero length returns zero weight."""
  168. assert mm_to_grams(0.0) == 0.0
  169. def test_custom_diameter(self):
  170. """Custom diameter (2.85mm) changes result."""
  171. result_175 = mm_to_grams(1000.0, diameter_mm=1.75)
  172. result_285 = mm_to_grams(1000.0, diameter_mm=2.85)
  173. # 2.85mm filament has more volume per mm
  174. assert result_285 > result_175
  175. ratio = (2.85 / 1.75) ** 2 # Volume scales with diameter²
  176. assert abs(result_285 / result_175 - ratio) < 0.001
  177. def test_custom_density(self):
  178. """Different density (ABS vs PLA)."""
  179. pla = mm_to_grams(1000.0, density_g_cm3=1.24)
  180. abs_ = mm_to_grams(1000.0, density_g_cm3=1.04)
  181. assert pla > abs_
  182. assert abs(pla / abs_ - 1.24 / 1.04) < 0.001
  183. def test_known_value(self):
  184. """Verify against a known calculation.
  185. 1m (1000mm) of 1.75mm PLA at 1.24 g/cm³:
  186. r = 0.0875 cm, L = 100 cm
  187. V = π × 0.0875² × 100 = 2.4053 cm³
  188. m = 2.4053 × 1.24 = 2.9826 g
  189. """
  190. result = mm_to_grams(1000.0, 1.75, 1.24)
  191. assert abs(result - 2.9826) < 0.01
  192. class TestGetCumulativeUsageAtLayer:
  193. """Tests for get_cumulative_usage_at_layer()."""
  194. def test_exact_layer_match(self):
  195. """Target layer exists exactly in the data."""
  196. data = {0: {0: 100.0}, 5: {0: 500.0}, 10: {0: 1000.0}}
  197. assert get_cumulative_usage_at_layer(data, 5) == {0: 500.0}
  198. def test_between_layers(self):
  199. """Target is between recorded layers - uses the closest lower one."""
  200. data = {0: {0: 100.0}, 5: {0: 500.0}, 10: {0: 1000.0}}
  201. # Layer 7 is between 5 and 10, should return layer 5's data
  202. assert get_cumulative_usage_at_layer(data, 7) == {0: 500.0}
  203. def test_beyond_last_layer(self):
  204. """Target is beyond the last recorded layer."""
  205. data = {0: {0: 100.0}, 5: {0: 500.0}}
  206. assert get_cumulative_usage_at_layer(data, 100) == {0: 500.0}
  207. def test_before_first_layer(self):
  208. """Target is before any recorded data."""
  209. data = {5: {0: 500.0}, 10: {0: 1000.0}}
  210. assert get_cumulative_usage_at_layer(data, 3) == {}
  211. def test_empty_data(self):
  212. """Empty layer_usage returns empty dict."""
  213. assert get_cumulative_usage_at_layer({}, 5) == {}
  214. def test_none_data(self):
  215. """None layer_usage returns empty dict."""
  216. assert get_cumulative_usage_at_layer(None, 5) == {}
  217. def test_multi_filament(self):
  218. """Multi-filament data at target layer."""
  219. data = {
  220. 0: {0: 50.0},
  221. 5: {0: 200.0, 1: 100.0},
  222. 10: {0: 400.0, 1: 250.0, 2: 50.0},
  223. }
  224. result = get_cumulative_usage_at_layer(data, 8)
  225. assert result == {0: 200.0, 1: 100.0}
  226. def test_layer_zero(self):
  227. """Target layer 0."""
  228. data = {0: {0: 10.0}, 1: {0: 20.0}}
  229. assert get_cumulative_usage_at_layer(data, 0) == {0: 10.0}
  230. class TestExtractFilamentUsageFrom3mf:
  231. """Tests for extract_filament_usage_from_3mf function."""
  232. def test_extract_single_filament(self, tmp_path):
  233. """Test extracting a single filament."""
  234. xml_content = """<?xml version="1.0" encoding="UTF-8"?>
  235. <config>
  236. <filament id="1" used_g="50.5" type="PLA" color="#FF0000"/>
  237. </config>
  238. """
  239. mock_3mf = create_mock_3mf(xml_content)
  240. file_path = tmp_path / "test.3mf"
  241. file_path.write_bytes(mock_3mf.read())
  242. result = extract_filament_usage_from_3mf(file_path)
  243. assert len(result) == 1
  244. assert result[0]["slot_id"] == 1
  245. assert result[0]["used_g"] == 50.5
  246. assert result[0]["type"] == "PLA"
  247. assert result[0]["color"] == "#FF0000"
  248. def test_extract_multiple_filaments(self, tmp_path):
  249. """Test extracting multiple filaments."""
  250. xml_content = """<?xml version="1.0" encoding="UTF-8"?>
  251. <config>
  252. <filament id="1" used_g="50.5" type="PLA" color="#FF0000"/>
  253. <filament id="2" used_g="30.2" type="PETG" color="#00FF00"/>
  254. <filament id="3" used_g="10.0" type="ABS" color="#0000FF"/>
  255. </config>
  256. """
  257. mock_3mf = create_mock_3mf(xml_content)
  258. file_path = tmp_path / "test.3mf"
  259. file_path.write_bytes(mock_3mf.read())
  260. result = extract_filament_usage_from_3mf(file_path)
  261. assert len(result) == 3
  262. assert result[0]["slot_id"] == 1
  263. assert result[1]["slot_id"] == 2
  264. assert result[2]["slot_id"] == 3
  265. def test_extract_filament_with_plate_id(self, tmp_path):
  266. """Test extracting filament for a specific plate."""
  267. xml_content = """<?xml version="1.0" encoding="UTF-8"?>
  268. <config>
  269. <plate>
  270. <metadata key="index" value="1"/>
  271. <filament id="1" used_g="25.0" type="PLA" color="#FF0000"/>
  272. </plate>
  273. <plate>
  274. <metadata key="index" value="2"/>
  275. <filament id="1" used_g="75.0" type="PETG" color="#00FF00"/>
  276. </plate>
  277. </config>
  278. """
  279. mock_3mf = create_mock_3mf(xml_content)
  280. file_path = tmp_path / "test.3mf"
  281. file_path.write_bytes(mock_3mf.read())
  282. result = extract_filament_usage_from_3mf(file_path, plate_id=2)
  283. assert len(result) == 1
  284. assert result[0]["used_g"] == 75.0
  285. assert result[0]["type"] == "PETG"
  286. def test_missing_slice_info_returns_empty(self, tmp_path):
  287. """Test that missing slice_info.config returns empty list."""
  288. buffer = io.BytesIO()
  289. with zipfile.ZipFile(buffer, "w") as zf:
  290. zf.writestr("other_file.txt", "content")
  291. buffer.seek(0)
  292. file_path = tmp_path / "test.3mf"
  293. file_path.write_bytes(buffer.read())
  294. result = extract_filament_usage_from_3mf(file_path)
  295. assert result == []
  296. def test_invalid_file_returns_empty(self, tmp_path):
  297. """Test that invalid file returns empty list."""
  298. file_path = tmp_path / "invalid.3mf"
  299. file_path.write_text("not a zip file")
  300. result = extract_filament_usage_from_3mf(file_path)
  301. assert result == []
  302. def test_nonexistent_file_returns_empty(self, tmp_path):
  303. """Test that nonexistent file returns empty list."""
  304. file_path = tmp_path / "nonexistent.3mf"
  305. result = extract_filament_usage_from_3mf(file_path)
  306. assert result == []
  307. def test_filament_without_id_is_skipped(self, tmp_path):
  308. """Test that filament without id is skipped."""
  309. xml_content = """<?xml version="1.0" encoding="UTF-8"?>
  310. <config>
  311. <filament used_g="50.5" type="PLA" color="#FF0000"/>
  312. <filament id="2" used_g="30.0" type="PETG" color="#00FF00"/>
  313. </config>
  314. """
  315. mock_3mf = create_mock_3mf(xml_content)
  316. file_path = tmp_path / "test.3mf"
  317. file_path.write_bytes(mock_3mf.read())
  318. result = extract_filament_usage_from_3mf(file_path)
  319. assert len(result) == 1
  320. assert result[0]["slot_id"] == 2
  321. def test_invalid_used_g_is_skipped(self, tmp_path):
  322. """Test that filament with invalid used_g is skipped."""
  323. xml_content = """<?xml version="1.0" encoding="UTF-8"?>
  324. <config>
  325. <filament id="1" used_g="invalid" type="PLA" color="#FF0000"/>
  326. <filament id="2" used_g="30.0" type="PETG" color="#00FF00"/>
  327. </config>
  328. """
  329. mock_3mf = create_mock_3mf(xml_content)
  330. file_path = tmp_path / "test.3mf"
  331. file_path.write_bytes(mock_3mf.read())
  332. result = extract_filament_usage_from_3mf(file_path)
  333. assert len(result) == 1
  334. assert result[0]["slot_id"] == 2
  335. def test_missing_optional_fields(self, tmp_path):
  336. """Test that missing type and color default to empty string."""
  337. xml_content = """<?xml version="1.0" encoding="UTF-8"?>
  338. <config>
  339. <filament id="1" used_g="50.5"/>
  340. </config>
  341. """
  342. mock_3mf = create_mock_3mf(xml_content)
  343. file_path = tmp_path / "test.3mf"
  344. file_path.write_bytes(mock_3mf.read())
  345. result = extract_filament_usage_from_3mf(file_path)
  346. assert len(result) == 1
  347. assert result[0]["type"] == ""
  348. assert result[0]["color"] == ""
  349. # ---------------------------------------------------------------------------
  350. # Tests for extract_project_filaments_from_3mf — used by the slice modal as
  351. # fallback when the sidecar can't run a preview slice.
  352. # ---------------------------------------------------------------------------
  353. def _make_3mf_with(files: dict[str, bytes | str]) -> zipfile.ZipFile:
  354. buf = io.BytesIO()
  355. with zipfile.ZipFile(buf, "w") as zf:
  356. for name, content in files.items():
  357. zf.writestr(name, content if isinstance(content, (bytes, str)) else str(content))
  358. buf.seek(0)
  359. return zipfile.ZipFile(buf, "r")
  360. class TestExtractProjectFilamentsFrom3mf:
  361. """The helper backfills the slice modal when slice_info.config is empty
  362. (raw project files) and the sidecar is unreachable."""
  363. def test_returns_empty_when_project_settings_missing(self):
  364. with _make_3mf_with({"placeholder.txt": "hi"}) as zf:
  365. assert extract_project_filaments_from_3mf(zf) == []
  366. def test_happy_path_returns_one_entry_per_slot(self):
  367. proj = {
  368. "filament_type": ["PLA", "PETG"],
  369. "filament_colour": ["#000000", "#FFFFFF"],
  370. }
  371. with _make_3mf_with({"Metadata/project_settings.config": json.dumps(proj)}) as zf:
  372. out = extract_project_filaments_from_3mf(zf)
  373. assert [(f["slot_id"], f["type"], f["color"]) for f in out] == [
  374. (1, "PLA", "#000000"),
  375. (2, "PETG", "#FFFFFF"),
  376. ]
  377. def test_mismatched_array_lengths_use_max_with_blanks(self):
  378. proj = {
  379. "filament_type": ["PLA", "PETG", "ABS"],
  380. "filament_colour": ["#000000"],
  381. }
  382. with _make_3mf_with({"Metadata/project_settings.config": json.dumps(proj)}) as zf:
  383. out = extract_project_filaments_from_3mf(zf)
  384. assert len(out) == 3
  385. assert out[0]["color"] == "#000000"
  386. assert out[1]["color"] == ""
  387. assert out[2]["color"] == ""
  388. def test_corrupt_json_returns_empty_no_exception(self):
  389. with _make_3mf_with({"Metadata/project_settings.config": b"{not json"}) as zf:
  390. assert extract_project_filaments_from_3mf(zf) == []
  391. def test_root_is_list_returns_empty(self):
  392. # Defensive: spec says it's a dict, but a file shipping a top-level
  393. # list (or anything non-dict) shouldn't crash the modal.
  394. with _make_3mf_with({"Metadata/project_settings.config": json.dumps([])}) as zf:
  395. assert extract_project_filaments_from_3mf(zf) == []
  396. def test_empty_arrays_returns_empty(self):
  397. proj = {"filament_type": [], "filament_colour": []}
  398. with _make_3mf_with({"Metadata/project_settings.config": json.dumps(proj)}) as zf:
  399. assert extract_project_filaments_from_3mf(zf) == []
  400. # ---------------------------------------------------------------------------
  401. # Tests for extract_plate_extruder_set_from_3mf — three sources unioned:
  402. # object top-level extruder, per-part extruder, painted-face quadtree leaves.
  403. # ---------------------------------------------------------------------------
  404. def _model_settings(plate_id: int, objects: list[dict]) -> str:
  405. """Build a minimal model_settings.config XML for tests. Each object dict
  406. can have: id, extruder (top-level), parts (list of {extruder}).
  407. The plate references all object ids."""
  408. parts_xml = []
  409. for obj in objects:
  410. oid = obj["id"]
  411. ext = obj.get("extruder")
  412. parts = obj.get("parts", [])
  413. ext_meta = f'<metadata key="extruder" value="{ext}"/>' if ext is not None else ""
  414. part_blocks = "".join(
  415. f'<part id="{i}" subtype="normal_part"><metadata key="extruder" value="{p["extruder"]}"/></part>'
  416. for i, p in enumerate(parts)
  417. if p.get("extruder") is not None
  418. )
  419. parts_xml.append(f'<object id="{oid}"><metadata key="name" value="o{oid}"/>{ext_meta}{part_blocks}</object>')
  420. instances = "".join(
  421. f'<model_instance><metadata key="object_id" value="{o["id"]}"/></model_instance>' for o in objects
  422. )
  423. plate = f'<plate><metadata key="plater_id" value="{plate_id}"/>{instances}</plate>'
  424. return f'<?xml version="1.0"?><config>{"".join(parts_xml)}{plate}</config>'
  425. class TestExtractPlateExtruderSetFrom3mf:
  426. def test_returns_empty_set_when_model_settings_missing(self):
  427. with _make_3mf_with({"placeholder.txt": "hi"}) as zf:
  428. assert extract_plate_extruder_set_from_3mf(zf, plate_id=1) == set()
  429. def test_object_top_level_extruder_only(self):
  430. xml = _model_settings(plate_id=1, objects=[{"id": "10", "extruder": 2}])
  431. with _make_3mf_with({"Metadata/model_settings.config": xml}) as zf:
  432. assert extract_plate_extruder_set_from_3mf(zf, plate_id=1) == {2}
  433. def test_per_part_extruder_unions_with_top_level(self):
  434. # Object's default is 1; one of its parts overrides to 3 (multi-color
  435. # via a sub-mesh). Union both — the slicer needs profiles for both.
  436. xml = _model_settings(
  437. plate_id=1,
  438. objects=[{"id": "10", "extruder": 1, "parts": [{"extruder": 3}]}],
  439. )
  440. with _make_3mf_with({"Metadata/model_settings.config": xml}) as zf:
  441. assert extract_plate_extruder_set_from_3mf(zf, plate_id=1) == {1, 3}
  442. def test_unknown_plate_id_returns_empty_set(self):
  443. xml = _model_settings(plate_id=1, objects=[{"id": "10", "extruder": 2}])
  444. with _make_3mf_with({"Metadata/model_settings.config": xml}) as zf:
  445. assert extract_plate_extruder_set_from_3mf(zf, plate_id=99) == set()
  446. def test_corrupt_xml_returns_empty_set_no_exception(self):
  447. with _make_3mf_with({"Metadata/model_settings.config": "<not valid xml"}) as zf:
  448. assert extract_plate_extruder_set_from_3mf(zf, plate_id=1) == set()
  449. def test_zero_extruder_value_ignored(self):
  450. # Bambu's 0 means "use object default" — not a real slot.
  451. xml = _model_settings(plate_id=1, objects=[{"id": "10", "extruder": 0}])
  452. with _make_3mf_with({"Metadata/model_settings.config": xml}) as zf:
  453. assert extract_plate_extruder_set_from_3mf(zf, plate_id=1) == set()
  454. def test_painted_face_above_threshold_kept(self):
  455. # 60/40 split: 60 triangles painted with extruder 1, 40 with ext 2.
  456. # Threshold is 5%; both above. The dominant ones are real colours.
  457. triangles = []
  458. for _ in range(60):
  459. triangles.append('<triangle v1="0" v2="1" v3="2" paint_color="1"/>')
  460. for _ in range(40):
  461. triangles.append('<triangle v1="0" v2="1" v3="2" paint_color="2"/>')
  462. per_obj = (
  463. '<?xml version="1.0"?>'
  464. '<model><resources><object id="100" type="model"><mesh>'
  465. "<triangles>" + "".join(triangles) + "</triangles>"
  466. "</mesh></object></resources><build/></model>"
  467. )
  468. ms = (
  469. '<?xml version="1.0"?><config>'
  470. '<object id="10"><metadata key="name" value="o"/></object>'
  471. '<plate><metadata key="plater_id" value="1"/>'
  472. '<model_instance><metadata key="object_id" value="10"/></model_instance>'
  473. "</plate></config>"
  474. )
  475. threed = (
  476. '<?xml version="1.0"?>'
  477. '<model xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02"'
  478. ' xmlns:p="http://schemas.microsoft.com/3dmanufacturing/production/2015/06">'
  479. "<resources>"
  480. '<object id="10" type="model"><components>'
  481. '<component p:path="/3D/Objects/o100.model" objectid="100"/>'
  482. "</components></object>"
  483. "</resources><build/></model>"
  484. )
  485. with _make_3mf_with(
  486. {
  487. "Metadata/model_settings.config": ms,
  488. "3D/3dmodel.model": threed,
  489. "3D/Objects/o100.model": per_obj,
  490. }
  491. ) as zf:
  492. result = extract_plate_extruder_set_from_3mf(zf, plate_id=1)
  493. # Both real colours kept (60/40 well above 5% threshold); the dropped
  494. # threshold case is the regression that motivates this test.
  495. assert result == {1, 2}
  496. def test_painted_face_below_threshold_dropped_as_noise(self):
  497. # 99 triangles at ext 1, 1 triangle at ext 9 (1% — below 5%
  498. # threshold). The 1% leaf is a single-leaf accident.
  499. triangles = []
  500. for _ in range(99):
  501. triangles.append('<triangle v1="0" v2="1" v3="2" paint_color="1"/>')
  502. triangles.append('<triangle v1="0" v2="1" v3="2" paint_color="9"/>')
  503. per_obj = (
  504. '<?xml version="1.0"?>'
  505. '<model><resources><object id="100" type="model"><mesh>'
  506. "<triangles>" + "".join(triangles) + "</triangles>"
  507. "</mesh></object></resources><build/></model>"
  508. )
  509. ms = (
  510. '<?xml version="1.0"?><config>'
  511. '<object id="10"><metadata key="name" value="o"/></object>'
  512. '<plate><metadata key="plater_id" value="1"/>'
  513. '<model_instance><metadata key="object_id" value="10"/></model_instance>'
  514. "</plate></config>"
  515. )
  516. threed = (
  517. '<?xml version="1.0"?>'
  518. '<model xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02"'
  519. ' xmlns:p="http://schemas.microsoft.com/3dmanufacturing/production/2015/06">'
  520. '<resources><object id="10" type="model"><components>'
  521. '<component p:path="/3D/Objects/o100.model" objectid="100"/>'
  522. "</components></object></resources><build/></model>"
  523. )
  524. with _make_3mf_with(
  525. {
  526. "Metadata/model_settings.config": ms,
  527. "3D/3dmodel.model": threed,
  528. "3D/Objects/o100.model": per_obj,
  529. }
  530. ) as zf:
  531. result = extract_plate_extruder_set_from_3mf(zf, plate_id=1)
  532. # Single-leaf accident at 1% filtered as noise; only the dominant
  533. # extruder survives.
  534. assert result == {1}
  535. def test_missing_per_object_model_file_silently_skipped(self):
  536. ms = (
  537. '<?xml version="1.0"?><config>'
  538. '<object id="10"><metadata key="extruder" value="2"/></object>'
  539. '<plate><metadata key="plater_id" value="1"/>'
  540. '<model_instance><metadata key="object_id" value="10"/></model_instance>'
  541. "</plate></config>"
  542. )
  543. threed = (
  544. '<?xml version="1.0"?>'
  545. '<model xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02"'
  546. ' xmlns:p="http://schemas.microsoft.com/3dmanufacturing/production/2015/06">'
  547. '<resources><object id="10" type="model"><components>'
  548. '<component p:path="/3D/Objects/missing.model" objectid="999"/>'
  549. "</components></object></resources><build/></model>"
  550. )
  551. with _make_3mf_with(
  552. {"Metadata/model_settings.config": ms, "3D/3dmodel.model": threed},
  553. ) as zf:
  554. # Top-level metadata still works; missing component model file
  555. # is silently skipped without crashing.
  556. assert extract_plate_extruder_set_from_3mf(zf, plate_id=1) == {2}
  557. class TestExtractEmbeddedPresetsFrom3mf:
  558. """Printer / process preset names read from project_settings.config so the
  559. SliceModal can default its dropdowns to the file's own config (#1325)."""
  560. def test_extracts_printer_and_process(self):
  561. config = json.dumps(
  562. {
  563. "printer_settings_id": "Bambu Lab X1 Carbon 0.4 nozzle",
  564. "print_settings_id": "0.20mm Standard @BBL X1C",
  565. "filament_settings_id": ["Bambu PLA Basic @BBL X1C"],
  566. }
  567. )
  568. with _make_3mf_with({"Metadata/project_settings.config": config}) as zf:
  569. assert extract_embedded_presets_from_3mf(zf) == {
  570. "printer": "Bambu Lab X1 Carbon 0.4 nozzle",
  571. "process": "0.20mm Standard @BBL X1C",
  572. }
  573. def test_settings_id_as_list_takes_first(self):
  574. # Some exports write *_settings_id as a per-extruder list.
  575. config = json.dumps(
  576. {
  577. "printer_settings_id": ["Bambu Lab A1 0.4 nozzle"],
  578. "print_settings_id": ["0.16mm Optimal @BBL A1", "0.20mm @BBL A1"],
  579. }
  580. )
  581. with _make_3mf_with({"Metadata/project_settings.config": config}) as zf:
  582. result = extract_embedded_presets_from_3mf(zf)
  583. assert result["printer"] == "Bambu Lab A1 0.4 nozzle"
  584. assert result["process"] == "0.16mm Optimal @BBL A1"
  585. def test_missing_config_returns_none_values(self):
  586. with _make_3mf_with({"3D/3dmodel.model": "<model/>"}) as zf:
  587. assert extract_embedded_presets_from_3mf(zf) == {
  588. "printer": None,
  589. "process": None,
  590. }
  591. def test_malformed_json_returns_none_values(self):
  592. with _make_3mf_with({"Metadata/project_settings.config": "not json"}) as zf:
  593. assert extract_embedded_presets_from_3mf(zf) == {
  594. "printer": None,
  595. "process": None,
  596. }
  597. def test_blank_and_absent_keys_yield_none(self):
  598. config = json.dumps({"printer_settings_id": " ", "other": "x"})
  599. with _make_3mf_with({"Metadata/project_settings.config": config}) as zf:
  600. assert extract_embedded_presets_from_3mf(zf) == {
  601. "printer": None,
  602. "process": None,
  603. }
  604. class TestExtractBedTypeFrom3mf:
  605. """extract_bed_type_from_3mf reads per-plate `curr_bed_type` from
  606. slice_info.config so the queue / print modal can show the right plate
  607. even on multi-plate 3MFs where different plates target different beds
  608. (#1281). archive.bed_type is one-value-per-archive (first plate's
  609. curr_bed_type — see services/archive.py:235), so for accurate
  610. per-plate surfacing we have to re-read the 3MF."""
  611. def test_single_plate_returns_bed_type(self, tmp_path):
  612. xml_content = """<?xml version="1.0" encoding="UTF-8"?>
  613. <config>
  614. <plate>
  615. <metadata key="index" value="1"/>
  616. <metadata key="curr_bed_type" value="Textured PEI Plate"/>
  617. </plate>
  618. </config>
  619. """
  620. file_path = tmp_path / "test.3mf"
  621. file_path.write_bytes(create_mock_3mf(xml_content).read())
  622. assert extract_bed_type_from_3mf(file_path) == "Textured PEI Plate"
  623. def test_multi_plate_returns_per_plate_value(self, tmp_path):
  624. # Reporter's case: a 3MF mixing PEI + Engineering across plates.
  625. # Looking up by plate_id must return THAT plate's value, not the
  626. # first plate's value the archive happens to cache.
  627. xml_content = """<?xml version="1.0" encoding="UTF-8"?>
  628. <config>
  629. <plate>
  630. <metadata key="index" value="1"/>
  631. <metadata key="curr_bed_type" value="Textured PEI Plate"/>
  632. </plate>
  633. <plate>
  634. <metadata key="index" value="2"/>
  635. <metadata key="curr_bed_type" value="Engineering Plate"/>
  636. </plate>
  637. <plate>
  638. <metadata key="index" value="3"/>
  639. <metadata key="curr_bed_type" value="Cool Plate"/>
  640. </plate>
  641. </config>
  642. """
  643. file_path = tmp_path / "test.3mf"
  644. file_path.write_bytes(create_mock_3mf(xml_content).read())
  645. assert extract_bed_type_from_3mf(file_path, plate_id=1) == "Textured PEI Plate"
  646. assert extract_bed_type_from_3mf(file_path, plate_id=2) == "Engineering Plate"
  647. assert extract_bed_type_from_3mf(file_path, plate_id=3) == "Cool Plate"
  648. def test_no_plate_id_returns_first_plate(self, tmp_path):
  649. # The plate_id=None branch must match the archive-level capture
  650. # convention (first plate wins) so callers that don't care about
  651. # plate selection see the same value the archive table holds.
  652. xml_content = """<?xml version="1.0" encoding="UTF-8"?>
  653. <config>
  654. <plate>
  655. <metadata key="index" value="1"/>
  656. <metadata key="curr_bed_type" value="Cool Plate SuperTack"/>
  657. </plate>
  658. <plate>
  659. <metadata key="index" value="2"/>
  660. <metadata key="curr_bed_type" value="Engineering Plate"/>
  661. </plate>
  662. </config>
  663. """
  664. file_path = tmp_path / "test.3mf"
  665. file_path.write_bytes(create_mock_3mf(xml_content).read())
  666. assert extract_bed_type_from_3mf(file_path) == "Cool Plate SuperTack"
  667. def test_unknown_plate_id_returns_none(self, tmp_path):
  668. xml_content = """<?xml version="1.0" encoding="UTF-8"?>
  669. <config>
  670. <plate>
  671. <metadata key="index" value="1"/>
  672. <metadata key="curr_bed_type" value="Textured PEI Plate"/>
  673. </plate>
  674. </config>
  675. """
  676. file_path = tmp_path / "test.3mf"
  677. file_path.write_bytes(create_mock_3mf(xml_content).read())
  678. assert extract_bed_type_from_3mf(file_path, plate_id=99) is None
  679. def test_plate_without_bed_type_returns_none(self, tmp_path):
  680. # Older slicers may export a plate without curr_bed_type. The
  681. # helper must return None rather than falling through to another
  682. # plate's value (which would silently lie).
  683. xml_content = """<?xml version="1.0" encoding="UTF-8"?>
  684. <config>
  685. <plate>
  686. <metadata key="index" value="1"/>
  687. </plate>
  688. <plate>
  689. <metadata key="index" value="2"/>
  690. <metadata key="curr_bed_type" value="Engineering Plate"/>
  691. </plate>
  692. </config>
  693. """
  694. file_path = tmp_path / "test.3mf"
  695. file_path.write_bytes(create_mock_3mf(xml_content).read())
  696. assert extract_bed_type_from_3mf(file_path, plate_id=1) is None
  697. assert extract_bed_type_from_3mf(file_path, plate_id=2) == "Engineering Plate"
  698. def test_missing_slice_info_returns_none(self, tmp_path):
  699. buffer = io.BytesIO()
  700. with zipfile.ZipFile(buffer, "w") as zf:
  701. zf.writestr("other_file.txt", "content")
  702. buffer.seek(0)
  703. file_path = tmp_path / "test.3mf"
  704. file_path.write_bytes(buffer.read())
  705. assert extract_bed_type_from_3mf(file_path) is None
  706. def test_invalid_file_returns_none(self, tmp_path):
  707. file_path = tmp_path / "invalid.3mf"
  708. file_path.write_text("not a zip file")
  709. assert extract_bed_type_from_3mf(file_path) is None
  710. def test_whitespace_trimmed(self, tmp_path):
  711. # 3MF values sometimes carry surrounding whitespace from manual
  712. # template tweaks; getBedTypeInfo() on the frontend is also
  713. # whitespace-tolerant, but the wire shape should be clean.
  714. xml_content = """<?xml version="1.0" encoding="UTF-8"?>
  715. <config>
  716. <plate>
  717. <metadata key="index" value="1"/>
  718. <metadata key="curr_bed_type" value=" Textured PEI Plate "/>
  719. </plate>
  720. </config>
  721. """
  722. file_path = tmp_path / "test.3mf"
  723. file_path.write_bytes(create_mock_3mf(xml_content).read())
  724. assert extract_bed_type_from_3mf(file_path) == "Textured PEI Plate"