test_threemf_tools.py 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394
  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. expand_to_project_slots,
  11. extract_bed_type_from_3mf,
  12. extract_embedded_presets_from_3mf,
  13. extract_filament_usage_from_3mf,
  14. extract_max_z_height_from_3mf,
  15. extract_plate_extruder_set_from_3mf,
  16. extract_print_time_from_3mf,
  17. extract_project_filaments_from_3mf,
  18. extract_support_filament_slots_from_3mf,
  19. get_cumulative_usage_at_layer,
  20. mm_to_grams,
  21. parse_gcode_layer_filament_usage,
  22. )
  23. def create_mock_3mf(slice_info_content: str) -> io.BytesIO:
  24. """Create a mock 3MF file (ZIP) with slice_info.config content."""
  25. buffer = io.BytesIO()
  26. with zipfile.ZipFile(buffer, "w") as zf:
  27. zf.writestr("Metadata/slice_info.config", slice_info_content)
  28. buffer.seek(0)
  29. return buffer
  30. class TestParseGcodeLayerFilamentUsage:
  31. """Tests for parse_gcode_layer_filament_usage()."""
  32. def test_single_filament_single_layer(self):
  33. """Single filament extruding on one layer."""
  34. gcode = """
  35. M620 S0
  36. G1 X10 Y10 E5.0
  37. G1 X20 Y20 E3.0
  38. """
  39. result = parse_gcode_layer_filament_usage(gcode)
  40. assert result == {0: {0: 8.0}}
  41. def test_multi_layer_single_filament(self):
  42. """Single filament across multiple layers."""
  43. gcode = """
  44. M620 S0
  45. G1 X10 Y10 E10.0
  46. M73 L1
  47. G1 X20 Y20 E5.0
  48. M73 L2
  49. G1 X30 Y30 E7.0
  50. """
  51. result = parse_gcode_layer_filament_usage(gcode)
  52. assert result[0] == {0: 10.0}
  53. assert result[1] == {0: 15.0}
  54. assert result[2] == {0: 22.0}
  55. def test_multi_material(self):
  56. """Multiple filaments switching via M620."""
  57. gcode = """
  58. M620 S0
  59. G1 E10.0
  60. M73 L1
  61. M620 S1
  62. G1 E5.0
  63. M620 S0
  64. G1 E3.0
  65. M73 L2
  66. G1 E2.0
  67. """
  68. result = parse_gcode_layer_filament_usage(gcode)
  69. # Layer 0: filament 0 = 10mm
  70. assert result[0] == {0: 10.0}
  71. # Layer 1: filament 0 = 13mm (10+3), filament 1 = 5mm
  72. assert result[1] == {0: 13.0, 1: 5.0}
  73. # Layer 2: filament 0 = 15mm (13+2)
  74. assert result[2] == {0: 15.0, 1: 5.0}
  75. def test_retractions_ignored(self):
  76. """Negative E values (retractions) should be ignored."""
  77. gcode = """
  78. M620 S0
  79. G1 E10.0
  80. G1 E-2.0
  81. G1 E5.0
  82. """
  83. result = parse_gcode_layer_filament_usage(gcode)
  84. assert result == {0: {0: 15.0}}
  85. def test_m620_s255_unloads(self):
  86. """M620 S255 means unload - extrusion after should be ignored."""
  87. gcode = """
  88. M620 S0
  89. G1 E10.0
  90. M620 S255
  91. G1 E5.0
  92. """
  93. result = parse_gcode_layer_filament_usage(gcode)
  94. assert result == {0: {0: 10.0}}
  95. def test_m620_with_suffix(self):
  96. """M620 S0A format (filament ID with suffix letter)."""
  97. gcode = """
  98. M620 S0A
  99. G1 E10.0
  100. M620 S1A
  101. G1 E5.0
  102. """
  103. result = parse_gcode_layer_filament_usage(gcode)
  104. assert result == {0: {0: 10.0, 1: 5.0}}
  105. def test_comments_ignored(self):
  106. """Comment lines and inline comments are ignored."""
  107. gcode = """
  108. ; This is a comment
  109. M620 S0
  110. G1 X10 E5.0 ; inline comment with E value
  111. G1 E3.0
  112. """
  113. result = parse_gcode_layer_filament_usage(gcode)
  114. assert result == {0: {0: 8.0}}
  115. def test_empty_gcode(self):
  116. """Empty G-code returns empty dict."""
  117. assert parse_gcode_layer_filament_usage("") == {}
  118. assert parse_gcode_layer_filament_usage("\n\n\n") == {}
  119. def test_no_extrusion(self):
  120. """G-code with moves but no extrusion."""
  121. gcode = """
  122. G1 X10 Y10
  123. G1 X20 Y20
  124. """
  125. assert parse_gcode_layer_filament_usage(gcode) == {}
  126. def test_no_active_filament_extrusion_ignored(self):
  127. """Extrusion before any M620 is ignored (no active filament)."""
  128. gcode = """
  129. G1 E10.0
  130. M620 S0
  131. G1 E5.0
  132. """
  133. result = parse_gcode_layer_filament_usage(gcode)
  134. assert result == {0: {0: 5.0}}
  135. def test_g0_g2_g3_extrusion(self):
  136. """G0, G2, G3 with E parameter are also tracked."""
  137. gcode = """
  138. M620 S0
  139. G0 E1.0
  140. G1 E2.0
  141. G2 E3.0
  142. G3 E4.0
  143. """
  144. result = parse_gcode_layer_filament_usage(gcode)
  145. assert result == {0: {0: 10.0}}
  146. def test_cumulative_across_layers(self):
  147. """Values are cumulative, not per-layer."""
  148. gcode = """
  149. M620 S0
  150. G1 E100.0
  151. M73 L1
  152. G1 E100.0
  153. M73 L2
  154. G1 E100.0
  155. """
  156. result = parse_gcode_layer_filament_usage(gcode)
  157. assert result[0] == {0: 100.0}
  158. assert result[1] == {0: 200.0}
  159. assert result[2] == {0: 300.0}
  160. class TestMmToGrams:
  161. """Tests for mm_to_grams()."""
  162. def test_default_pla_175(self):
  163. """Default PLA 1.75mm conversion."""
  164. # 1000mm of 1.75mm PLA at 1.24 g/cm³
  165. # Volume = π × (0.0875cm)² × 100cm = 2.405cm³
  166. # Weight = 2.405 × 1.24 = 2.982g
  167. result = mm_to_grams(1000.0)
  168. expected = math.pi * (0.0875**2) * 100 * 1.24
  169. assert abs(result - expected) < 0.001
  170. def test_zero_length(self):
  171. """Zero length returns zero weight."""
  172. assert mm_to_grams(0.0) == 0.0
  173. def test_custom_diameter(self):
  174. """Custom diameter (2.85mm) changes result."""
  175. result_175 = mm_to_grams(1000.0, diameter_mm=1.75)
  176. result_285 = mm_to_grams(1000.0, diameter_mm=2.85)
  177. # 2.85mm filament has more volume per mm
  178. assert result_285 > result_175
  179. ratio = (2.85 / 1.75) ** 2 # Volume scales with diameter²
  180. assert abs(result_285 / result_175 - ratio) < 0.001
  181. def test_custom_density(self):
  182. """Different density (ABS vs PLA)."""
  183. pla = mm_to_grams(1000.0, density_g_cm3=1.24)
  184. abs_ = mm_to_grams(1000.0, density_g_cm3=1.04)
  185. assert pla > abs_
  186. assert abs(pla / abs_ - 1.24 / 1.04) < 0.001
  187. def test_known_value(self):
  188. """Verify against a known calculation.
  189. 1m (1000mm) of 1.75mm PLA at 1.24 g/cm³:
  190. r = 0.0875 cm, L = 100 cm
  191. V = π × 0.0875² × 100 = 2.4053 cm³
  192. m = 2.4053 × 1.24 = 2.9826 g
  193. """
  194. result = mm_to_grams(1000.0, 1.75, 1.24)
  195. assert abs(result - 2.9826) < 0.01
  196. class TestGetCumulativeUsageAtLayer:
  197. """Tests for get_cumulative_usage_at_layer()."""
  198. def test_exact_layer_match(self):
  199. """Target layer exists exactly in the data."""
  200. data = {0: {0: 100.0}, 5: {0: 500.0}, 10: {0: 1000.0}}
  201. assert get_cumulative_usage_at_layer(data, 5) == {0: 500.0}
  202. def test_between_layers(self):
  203. """Target is between recorded layers - uses the closest lower one."""
  204. data = {0: {0: 100.0}, 5: {0: 500.0}, 10: {0: 1000.0}}
  205. # Layer 7 is between 5 and 10, should return layer 5's data
  206. assert get_cumulative_usage_at_layer(data, 7) == {0: 500.0}
  207. def test_beyond_last_layer(self):
  208. """Target is beyond the last recorded layer."""
  209. data = {0: {0: 100.0}, 5: {0: 500.0}}
  210. assert get_cumulative_usage_at_layer(data, 100) == {0: 500.0}
  211. def test_before_first_layer(self):
  212. """Target is before any recorded data."""
  213. data = {5: {0: 500.0}, 10: {0: 1000.0}}
  214. assert get_cumulative_usage_at_layer(data, 3) == {}
  215. def test_empty_data(self):
  216. """Empty layer_usage returns empty dict."""
  217. assert get_cumulative_usage_at_layer({}, 5) == {}
  218. def test_none_data(self):
  219. """None layer_usage returns empty dict."""
  220. assert get_cumulative_usage_at_layer(None, 5) == {}
  221. def test_multi_filament(self):
  222. """Multi-filament data at target layer."""
  223. data = {
  224. 0: {0: 50.0},
  225. 5: {0: 200.0, 1: 100.0},
  226. 10: {0: 400.0, 1: 250.0, 2: 50.0},
  227. }
  228. result = get_cumulative_usage_at_layer(data, 8)
  229. assert result == {0: 200.0, 1: 100.0}
  230. def test_layer_zero(self):
  231. """Target layer 0."""
  232. data = {0: {0: 10.0}, 1: {0: 20.0}}
  233. assert get_cumulative_usage_at_layer(data, 0) == {0: 10.0}
  234. class TestExtractFilamentUsageFrom3mf:
  235. """Tests for extract_filament_usage_from_3mf function."""
  236. def test_extract_single_filament(self, tmp_path):
  237. """Test extracting a single filament."""
  238. xml_content = """<?xml version="1.0" encoding="UTF-8"?>
  239. <config>
  240. <filament id="1" used_g="50.5" type="PLA" color="#FF0000"/>
  241. </config>
  242. """
  243. mock_3mf = create_mock_3mf(xml_content)
  244. file_path = tmp_path / "test.3mf"
  245. file_path.write_bytes(mock_3mf.read())
  246. result = extract_filament_usage_from_3mf(file_path)
  247. assert len(result) == 1
  248. assert result[0]["slot_id"] == 1
  249. assert result[0]["used_g"] == 50.5
  250. assert result[0]["type"] == "PLA"
  251. assert result[0]["color"] == "#FF0000"
  252. def test_extract_multiple_filaments(self, tmp_path):
  253. """Test extracting multiple filaments."""
  254. xml_content = """<?xml version="1.0" encoding="UTF-8"?>
  255. <config>
  256. <filament id="1" used_g="50.5" type="PLA" color="#FF0000"/>
  257. <filament id="2" used_g="30.2" type="PETG" color="#00FF00"/>
  258. <filament id="3" used_g="10.0" type="ABS" color="#0000FF"/>
  259. </config>
  260. """
  261. mock_3mf = create_mock_3mf(xml_content)
  262. file_path = tmp_path / "test.3mf"
  263. file_path.write_bytes(mock_3mf.read())
  264. result = extract_filament_usage_from_3mf(file_path)
  265. assert len(result) == 3
  266. assert result[0]["slot_id"] == 1
  267. assert result[1]["slot_id"] == 2
  268. assert result[2]["slot_id"] == 3
  269. def test_extract_filament_with_plate_id(self, tmp_path):
  270. """Test extracting filament for a specific plate."""
  271. xml_content = """<?xml version="1.0" encoding="UTF-8"?>
  272. <config>
  273. <plate>
  274. <metadata key="index" value="1"/>
  275. <filament id="1" used_g="25.0" type="PLA" color="#FF0000"/>
  276. </plate>
  277. <plate>
  278. <metadata key="index" value="2"/>
  279. <filament id="1" used_g="75.0" type="PETG" color="#00FF00"/>
  280. </plate>
  281. </config>
  282. """
  283. mock_3mf = create_mock_3mf(xml_content)
  284. file_path = tmp_path / "test.3mf"
  285. file_path.write_bytes(mock_3mf.read())
  286. result = extract_filament_usage_from_3mf(file_path, plate_id=2)
  287. assert len(result) == 1
  288. assert result[0]["used_g"] == 75.0
  289. assert result[0]["type"] == "PETG"
  290. def test_missing_slice_info_returns_empty(self, tmp_path):
  291. """Test that missing slice_info.config returns empty list."""
  292. buffer = io.BytesIO()
  293. with zipfile.ZipFile(buffer, "w") as zf:
  294. zf.writestr("other_file.txt", "content")
  295. buffer.seek(0)
  296. file_path = tmp_path / "test.3mf"
  297. file_path.write_bytes(buffer.read())
  298. result = extract_filament_usage_from_3mf(file_path)
  299. assert result == []
  300. def test_invalid_file_returns_empty(self, tmp_path):
  301. """Test that invalid file returns empty list."""
  302. file_path = tmp_path / "invalid.3mf"
  303. file_path.write_text("not a zip file")
  304. result = extract_filament_usage_from_3mf(file_path)
  305. assert result == []
  306. def test_nonexistent_file_returns_empty(self, tmp_path):
  307. """Test that nonexistent file returns empty list."""
  308. file_path = tmp_path / "nonexistent.3mf"
  309. result = extract_filament_usage_from_3mf(file_path)
  310. assert result == []
  311. def test_filament_without_id_is_skipped(self, tmp_path):
  312. """Test that filament without id is skipped."""
  313. xml_content = """<?xml version="1.0" encoding="UTF-8"?>
  314. <config>
  315. <filament used_g="50.5" type="PLA" color="#FF0000"/>
  316. <filament id="2" used_g="30.0" type="PETG" color="#00FF00"/>
  317. </config>
  318. """
  319. mock_3mf = create_mock_3mf(xml_content)
  320. file_path = tmp_path / "test.3mf"
  321. file_path.write_bytes(mock_3mf.read())
  322. result = extract_filament_usage_from_3mf(file_path)
  323. assert len(result) == 1
  324. assert result[0]["slot_id"] == 2
  325. def test_invalid_used_g_is_skipped(self, tmp_path):
  326. """Test that filament with invalid used_g is skipped."""
  327. xml_content = """<?xml version="1.0" encoding="UTF-8"?>
  328. <config>
  329. <filament id="1" used_g="invalid" type="PLA" color="#FF0000"/>
  330. <filament id="2" used_g="30.0" type="PETG" color="#00FF00"/>
  331. </config>
  332. """
  333. mock_3mf = create_mock_3mf(xml_content)
  334. file_path = tmp_path / "test.3mf"
  335. file_path.write_bytes(mock_3mf.read())
  336. result = extract_filament_usage_from_3mf(file_path)
  337. assert len(result) == 1
  338. assert result[0]["slot_id"] == 2
  339. def test_missing_optional_fields(self, tmp_path):
  340. """Test that missing type and color default to empty string."""
  341. xml_content = """<?xml version="1.0" encoding="UTF-8"?>
  342. <config>
  343. <filament id="1" used_g="50.5"/>
  344. </config>
  345. """
  346. mock_3mf = create_mock_3mf(xml_content)
  347. file_path = tmp_path / "test.3mf"
  348. file_path.write_bytes(mock_3mf.read())
  349. result = extract_filament_usage_from_3mf(file_path)
  350. assert len(result) == 1
  351. assert result[0]["type"] == ""
  352. assert result[0]["color"] == ""
  353. # ---------------------------------------------------------------------------
  354. # Tests for extract_project_filaments_from_3mf — used by the slice modal as
  355. # fallback when the sidecar can't run a preview slice.
  356. # ---------------------------------------------------------------------------
  357. def _make_3mf_with(files: dict[str, bytes | str]) -> zipfile.ZipFile:
  358. buf = io.BytesIO()
  359. with zipfile.ZipFile(buf, "w") as zf:
  360. for name, content in files.items():
  361. zf.writestr(name, content if isinstance(content, (bytes, str)) else str(content))
  362. buf.seek(0)
  363. return zipfile.ZipFile(buf, "r")
  364. class TestExtractProjectFilamentsFrom3mf:
  365. """The helper backfills the slice modal when slice_info.config is empty
  366. (raw project files) and the sidecar is unreachable."""
  367. def test_returns_empty_when_project_settings_missing(self):
  368. with _make_3mf_with({"placeholder.txt": "hi"}) as zf:
  369. assert extract_project_filaments_from_3mf(zf) == []
  370. def test_happy_path_returns_one_entry_per_slot(self):
  371. proj = {
  372. "filament_type": ["PLA", "PETG"],
  373. "filament_colour": ["#000000", "#FFFFFF"],
  374. }
  375. with _make_3mf_with({"Metadata/project_settings.config": json.dumps(proj)}) as zf:
  376. out = extract_project_filaments_from_3mf(zf)
  377. assert [(f["slot_id"], f["type"], f["color"]) for f in out] == [
  378. (1, "PLA", "#000000"),
  379. (2, "PETG", "#FFFFFF"),
  380. ]
  381. def test_mismatched_array_lengths_use_max_with_blanks(self):
  382. proj = {
  383. "filament_type": ["PLA", "PETG", "ABS"],
  384. "filament_colour": ["#000000"],
  385. }
  386. with _make_3mf_with({"Metadata/project_settings.config": json.dumps(proj)}) as zf:
  387. out = extract_project_filaments_from_3mf(zf)
  388. assert len(out) == 3
  389. assert out[0]["color"] == "#000000"
  390. assert out[1]["color"] == ""
  391. assert out[2]["color"] == ""
  392. def test_corrupt_json_returns_empty_no_exception(self):
  393. with _make_3mf_with({"Metadata/project_settings.config": b"{not json"}) as zf:
  394. assert extract_project_filaments_from_3mf(zf) == []
  395. def test_root_is_list_returns_empty(self):
  396. # Defensive: spec says it's a dict, but a file shipping a top-level
  397. # list (or anything non-dict) shouldn't crash the modal.
  398. with _make_3mf_with({"Metadata/project_settings.config": json.dumps([])}) as zf:
  399. assert extract_project_filaments_from_3mf(zf) == []
  400. def test_empty_arrays_returns_empty(self):
  401. proj = {"filament_type": [], "filament_colour": []}
  402. with _make_3mf_with({"Metadata/project_settings.config": json.dumps(proj)}) as zf:
  403. assert extract_project_filaments_from_3mf(zf) == []
  404. # ---------------------------------------------------------------------------
  405. # Tests for expand_to_project_slots — #2712
  406. # ---------------------------------------------------------------------------
  407. class TestExpandToProjectSlots:
  408. """The slice modal's filament list is positional: index 0 is slot 1, all
  409. the way through to the ``filament_N.json`` parts handed to the slicer.
  410. A MakerWorld source that carries slice_info but paints with slot 4 alone
  411. used to yield a one-row list, so the user's single pick was bound to slot
  412. 1 and slot 4 — the slot that actually prints — kept the source's embedded
  413. default. Picking PETG produced a PLA print.
  414. """
  415. PROJECT = json.dumps(
  416. {
  417. "filament_type": ["PLA", "PLA", "PLA", "PLA"],
  418. "filament_colour": ["#38CC0A", "#161616", "#898989", "#898989"],
  419. }
  420. )
  421. def test_a_single_used_slot_still_produces_a_full_positional_list(self):
  422. """The reported file: four project slots, only slot 4 printed."""
  423. used = [
  424. {
  425. "slot_id": 4,
  426. "type": "PLA",
  427. "color": "#898989",
  428. "used_grams": 105.9,
  429. "used_meters": 35.51,
  430. "tray_info_idx": "GFL99",
  431. "used_in_plate": True,
  432. }
  433. ]
  434. with _make_3mf_with({"Metadata/project_settings.config": self.PROJECT}) as zf:
  435. out = expand_to_project_slots(zf, used)
  436. assert [f["slot_id"] for f in out] == [1, 2, 3, 4]
  437. assert [f["used_in_plate"] for f in out] == [False, False, False, True]
  438. def test_the_used_row_keeps_its_usage_figures(self):
  439. """The modal shows the real weight and colour, and the print path
  440. downstream reads ``tray_info_idx`` — none of it may be flattened into
  441. a zeroed project row."""
  442. used = [
  443. {
  444. "slot_id": 4,
  445. "type": "PETG",
  446. "color": "#FF0000",
  447. "used_grams": 105.9,
  448. "used_meters": 35.51,
  449. "tray_info_idx": "GFL99",
  450. "used_in_plate": True,
  451. }
  452. ]
  453. with _make_3mf_with({"Metadata/project_settings.config": self.PROJECT}) as zf:
  454. out = expand_to_project_slots(zf, used)
  455. slot4 = out[3]
  456. assert slot4["used_grams"] == 105.9
  457. assert slot4["tray_info_idx"] == "GFL99"
  458. # Resolved from the slice, not the project's stale PLA/#898989.
  459. assert (slot4["type"], slot4["color"]) == ("PETG", "#FF0000")
  460. def test_padding_rows_carry_the_project_type_and_colour(self):
  461. """They drive the modal's pre-pick for the disabled rows."""
  462. used = [{"slot_id": 4, "type": "PLA", "color": "#898989", "used_grams": 1.0, "used_meters": 1.0}]
  463. with _make_3mf_with({"Metadata/project_settings.config": self.PROJECT}) as zf:
  464. out = expand_to_project_slots(zf, used)
  465. assert (out[0]["type"], out[0]["color"]) == ("PLA", "#38CC0A")
  466. assert out[0]["used_grams"] == 0
  467. def test_every_slot_used_is_a_shape_change_only(self):
  468. used = [
  469. {"slot_id": i, "type": "PLA", "color": "", "used_grams": 5.0, "used_meters": 1.0, "used_in_plate": True}
  470. for i in (1, 2, 3, 4)
  471. ]
  472. with _make_3mf_with({"Metadata/project_settings.config": self.PROJECT}) as zf:
  473. out = expand_to_project_slots(zf, used)
  474. assert len(out) == 4
  475. assert all(f["used_in_plate"] for f in out)
  476. assert all(f["used_grams"] == 5.0 for f in out)
  477. def test_a_used_slot_beyond_the_project_list_is_kept(self):
  478. """Dropping it would recreate the original bug on a file whose
  479. project settings and slice_info disagree — the one slot that prints
  480. would vanish from the list entirely."""
  481. used = [{"slot_id": 9, "type": "PLA", "color": "", "used_grams": 5.0, "used_meters": 1.0}]
  482. with _make_3mf_with({"Metadata/project_settings.config": self.PROJECT}) as zf:
  483. out = expand_to_project_slots(zf, used)
  484. assert [f["slot_id"] for f in out] == [1, 2, 3, 4, 9]
  485. assert out[-1]["used_in_plate"] is True
  486. def test_returns_the_input_unchanged_without_project_settings(self):
  487. """Nothing to widen against — a narrow list still prints correctly,
  488. an invented one might not."""
  489. used = [{"slot_id": 4, "type": "PLA", "color": "", "used_grams": 5.0, "used_meters": 1.0}]
  490. with _make_3mf_with({"placeholder.txt": "hi"}) as zf:
  491. assert expand_to_project_slots(zf, used) == used
  492. # ---------------------------------------------------------------------------
  493. # Tests for extract_plate_extruder_set_from_3mf — three sources unioned:
  494. # object top-level extruder, per-part extruder, painted-face quadtree leaves.
  495. # ---------------------------------------------------------------------------
  496. def _model_settings(plate_id: int, objects: list[dict]) -> str:
  497. """Build a minimal model_settings.config XML for tests. Each object dict
  498. can have: id, extruder (top-level), parts (list of {extruder}).
  499. The plate references all object ids."""
  500. parts_xml = []
  501. for obj in objects:
  502. oid = obj["id"]
  503. ext = obj.get("extruder")
  504. parts = obj.get("parts", [])
  505. ext_meta = f'<metadata key="extruder" value="{ext}"/>' if ext is not None else ""
  506. part_blocks = "".join(
  507. f'<part id="{i}" subtype="normal_part"><metadata key="extruder" value="{p["extruder"]}"/></part>'
  508. for i, p in enumerate(parts)
  509. if p.get("extruder") is not None
  510. )
  511. parts_xml.append(f'<object id="{oid}"><metadata key="name" value="o{oid}"/>{ext_meta}{part_blocks}</object>')
  512. instances = "".join(
  513. f'<model_instance><metadata key="object_id" value="{o["id"]}"/></model_instance>' for o in objects
  514. )
  515. plate = f'<plate><metadata key="plater_id" value="{plate_id}"/>{instances}</plate>'
  516. return f'<?xml version="1.0"?><config>{"".join(parts_xml)}{plate}</config>'
  517. class TestExtractPlateExtruderSetFrom3mf:
  518. def test_returns_empty_set_when_model_settings_missing(self):
  519. with _make_3mf_with({"placeholder.txt": "hi"}) as zf:
  520. assert extract_plate_extruder_set_from_3mf(zf, plate_id=1) == set()
  521. def test_object_top_level_extruder_only(self):
  522. xml = _model_settings(plate_id=1, objects=[{"id": "10", "extruder": 2}])
  523. with _make_3mf_with({"Metadata/model_settings.config": xml}) as zf:
  524. assert extract_plate_extruder_set_from_3mf(zf, plate_id=1) == {2}
  525. def test_per_part_extruder_unions_with_top_level(self):
  526. # Object's default is 1; one of its parts overrides to 3 (multi-color
  527. # via a sub-mesh). Union both — the slicer needs profiles for both.
  528. xml = _model_settings(
  529. plate_id=1,
  530. objects=[{"id": "10", "extruder": 1, "parts": [{"extruder": 3}]}],
  531. )
  532. with _make_3mf_with({"Metadata/model_settings.config": xml}) as zf:
  533. assert extract_plate_extruder_set_from_3mf(zf, plate_id=1) == {1, 3}
  534. def test_unknown_plate_id_returns_empty_set(self):
  535. xml = _model_settings(plate_id=1, objects=[{"id": "10", "extruder": 2}])
  536. with _make_3mf_with({"Metadata/model_settings.config": xml}) as zf:
  537. assert extract_plate_extruder_set_from_3mf(zf, plate_id=99) == set()
  538. def test_corrupt_xml_returns_empty_set_no_exception(self):
  539. with _make_3mf_with({"Metadata/model_settings.config": "<not valid xml"}) as zf:
  540. assert extract_plate_extruder_set_from_3mf(zf, plate_id=1) == set()
  541. def test_zero_extruder_value_ignored(self):
  542. # Bambu's 0 means "use object default" — not a real slot.
  543. xml = _model_settings(plate_id=1, objects=[{"id": "10", "extruder": 0}])
  544. with _make_3mf_with({"Metadata/model_settings.config": xml}) as zf:
  545. assert extract_plate_extruder_set_from_3mf(zf, plate_id=1) == set()
  546. def test_painted_face_above_threshold_kept(self):
  547. # 60/40 split: 60 triangles painted with extruder 1, 40 with ext 2.
  548. # Threshold is 5%; both above. The dominant ones are real colours.
  549. triangles = []
  550. for _ in range(60):
  551. triangles.append('<triangle v1="0" v2="1" v3="2" paint_color="1"/>')
  552. for _ in range(40):
  553. triangles.append('<triangle v1="0" v2="1" v3="2" paint_color="2"/>')
  554. per_obj = (
  555. '<?xml version="1.0"?>'
  556. '<model><resources><object id="100" type="model"><mesh>'
  557. "<triangles>" + "".join(triangles) + "</triangles>"
  558. "</mesh></object></resources><build/></model>"
  559. )
  560. ms = (
  561. '<?xml version="1.0"?><config>'
  562. '<object id="10"><metadata key="name" value="o"/></object>'
  563. '<plate><metadata key="plater_id" value="1"/>'
  564. '<model_instance><metadata key="object_id" value="10"/></model_instance>'
  565. "</plate></config>"
  566. )
  567. threed = (
  568. '<?xml version="1.0"?>'
  569. '<model xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02"'
  570. ' xmlns:p="http://schemas.microsoft.com/3dmanufacturing/production/2015/06">'
  571. "<resources>"
  572. '<object id="10" type="model"><components>'
  573. '<component p:path="/3D/Objects/o100.model" objectid="100"/>'
  574. "</components></object>"
  575. "</resources><build/></model>"
  576. )
  577. with _make_3mf_with(
  578. {
  579. "Metadata/model_settings.config": ms,
  580. "3D/3dmodel.model": threed,
  581. "3D/Objects/o100.model": per_obj,
  582. }
  583. ) as zf:
  584. result = extract_plate_extruder_set_from_3mf(zf, plate_id=1)
  585. # Both real colours kept (60/40 well above 5% threshold); the dropped
  586. # threshold case is the regression that motivates this test.
  587. assert result == {1, 2}
  588. def test_painted_face_below_threshold_dropped_as_noise(self):
  589. # 99 triangles at ext 1, 1 triangle at ext 9 (1% — below 5%
  590. # threshold). The 1% leaf is a single-leaf accident.
  591. triangles = []
  592. for _ in range(99):
  593. triangles.append('<triangle v1="0" v2="1" v3="2" paint_color="1"/>')
  594. triangles.append('<triangle v1="0" v2="1" v3="2" paint_color="9"/>')
  595. per_obj = (
  596. '<?xml version="1.0"?>'
  597. '<model><resources><object id="100" type="model"><mesh>'
  598. "<triangles>" + "".join(triangles) + "</triangles>"
  599. "</mesh></object></resources><build/></model>"
  600. )
  601. ms = (
  602. '<?xml version="1.0"?><config>'
  603. '<object id="10"><metadata key="name" value="o"/></object>'
  604. '<plate><metadata key="plater_id" value="1"/>'
  605. '<model_instance><metadata key="object_id" value="10"/></model_instance>'
  606. "</plate></config>"
  607. )
  608. threed = (
  609. '<?xml version="1.0"?>'
  610. '<model xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02"'
  611. ' xmlns:p="http://schemas.microsoft.com/3dmanufacturing/production/2015/06">'
  612. '<resources><object id="10" type="model"><components>'
  613. '<component p:path="/3D/Objects/o100.model" objectid="100"/>'
  614. "</components></object></resources><build/></model>"
  615. )
  616. with _make_3mf_with(
  617. {
  618. "Metadata/model_settings.config": ms,
  619. "3D/3dmodel.model": threed,
  620. "3D/Objects/o100.model": per_obj,
  621. }
  622. ) as zf:
  623. result = extract_plate_extruder_set_from_3mf(zf, plate_id=1)
  624. # Single-leaf accident at 1% filtered as noise; only the dominant
  625. # extruder survives.
  626. assert result == {1}
  627. def test_missing_per_object_model_file_silently_skipped(self):
  628. ms = (
  629. '<?xml version="1.0"?><config>'
  630. '<object id="10"><metadata key="extruder" value="2"/></object>'
  631. '<plate><metadata key="plater_id" value="1"/>'
  632. '<model_instance><metadata key="object_id" value="10"/></model_instance>'
  633. "</plate></config>"
  634. )
  635. threed = (
  636. '<?xml version="1.0"?>'
  637. '<model xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02"'
  638. ' xmlns:p="http://schemas.microsoft.com/3dmanufacturing/production/2015/06">'
  639. '<resources><object id="10" type="model"><components>'
  640. '<component p:path="/3D/Objects/missing.model" objectid="999"/>'
  641. "</components></object></resources><build/></model>"
  642. )
  643. with _make_3mf_with(
  644. {"Metadata/model_settings.config": ms, "3D/3dmodel.model": threed},
  645. ) as zf:
  646. # Top-level metadata still works; missing component model file
  647. # is silently skipped without crashing.
  648. assert extract_plate_extruder_set_from_3mf(zf, plate_id=1) == {2}
  649. class TestExtractEmbeddedPresetsFrom3mf:
  650. """Printer / process preset names read from project_settings.config so the
  651. SliceModal can default its dropdowns to the file's own config (#1325)."""
  652. def test_extracts_printer_and_process(self):
  653. config = json.dumps(
  654. {
  655. "printer_settings_id": "Bambu Lab X1 Carbon 0.4 nozzle",
  656. "print_settings_id": "0.20mm Standard @BBL X1C",
  657. "filament_settings_id": ["Bambu PLA Basic @BBL X1C"],
  658. }
  659. )
  660. with _make_3mf_with({"Metadata/project_settings.config": config}) as zf:
  661. assert extract_embedded_presets_from_3mf(zf) == {
  662. "printer": "Bambu Lab X1 Carbon 0.4 nozzle",
  663. "process": "0.20mm Standard @BBL X1C",
  664. }
  665. def test_settings_id_as_list_takes_first(self):
  666. # Some exports write *_settings_id as a per-extruder list.
  667. config = json.dumps(
  668. {
  669. "printer_settings_id": ["Bambu Lab A1 0.4 nozzle"],
  670. "print_settings_id": ["0.16mm Optimal @BBL A1", "0.20mm @BBL A1"],
  671. }
  672. )
  673. with _make_3mf_with({"Metadata/project_settings.config": config}) as zf:
  674. result = extract_embedded_presets_from_3mf(zf)
  675. assert result["printer"] == "Bambu Lab A1 0.4 nozzle"
  676. assert result["process"] == "0.16mm Optimal @BBL A1"
  677. def test_missing_config_returns_none_values(self):
  678. with _make_3mf_with({"3D/3dmodel.model": "<model/>"}) as zf:
  679. assert extract_embedded_presets_from_3mf(zf) == {
  680. "printer": None,
  681. "process": None,
  682. }
  683. def test_malformed_json_returns_none_values(self):
  684. with _make_3mf_with({"Metadata/project_settings.config": "not json"}) as zf:
  685. assert extract_embedded_presets_from_3mf(zf) == {
  686. "printer": None,
  687. "process": None,
  688. }
  689. def test_blank_and_absent_keys_yield_none(self):
  690. config = json.dumps({"printer_settings_id": " ", "other": "x"})
  691. with _make_3mf_with({"Metadata/project_settings.config": config}) as zf:
  692. assert extract_embedded_presets_from_3mf(zf) == {
  693. "printer": None,
  694. "process": None,
  695. }
  696. class TestExtractBedTypeFrom3mf:
  697. """extract_bed_type_from_3mf reads per-plate `curr_bed_type` from
  698. slice_info.config so the queue / print modal can show the right plate
  699. even on multi-plate 3MFs where different plates target different beds
  700. (#1281). archive.bed_type is one-value-per-archive (first plate's
  701. curr_bed_type — see services/archive.py:235), so for accurate
  702. per-plate surfacing we have to re-read the 3MF."""
  703. def test_single_plate_returns_bed_type(self, tmp_path):
  704. xml_content = """<?xml version="1.0" encoding="UTF-8"?>
  705. <config>
  706. <plate>
  707. <metadata key="index" value="1"/>
  708. <metadata key="curr_bed_type" value="Textured PEI Plate"/>
  709. </plate>
  710. </config>
  711. """
  712. file_path = tmp_path / "test.3mf"
  713. file_path.write_bytes(create_mock_3mf(xml_content).read())
  714. assert extract_bed_type_from_3mf(file_path) == "Textured PEI Plate"
  715. def test_multi_plate_returns_per_plate_value(self, tmp_path):
  716. # Reporter's case: a 3MF mixing PEI + Engineering across plates.
  717. # Looking up by plate_id must return THAT plate's value, not the
  718. # first plate's value the archive happens to cache.
  719. xml_content = """<?xml version="1.0" encoding="UTF-8"?>
  720. <config>
  721. <plate>
  722. <metadata key="index" value="1"/>
  723. <metadata key="curr_bed_type" value="Textured PEI Plate"/>
  724. </plate>
  725. <plate>
  726. <metadata key="index" value="2"/>
  727. <metadata key="curr_bed_type" value="Engineering Plate"/>
  728. </plate>
  729. <plate>
  730. <metadata key="index" value="3"/>
  731. <metadata key="curr_bed_type" value="Cool Plate"/>
  732. </plate>
  733. </config>
  734. """
  735. file_path = tmp_path / "test.3mf"
  736. file_path.write_bytes(create_mock_3mf(xml_content).read())
  737. assert extract_bed_type_from_3mf(file_path, plate_id=1) == "Textured PEI Plate"
  738. assert extract_bed_type_from_3mf(file_path, plate_id=2) == "Engineering Plate"
  739. assert extract_bed_type_from_3mf(file_path, plate_id=3) == "Cool Plate"
  740. def test_no_plate_id_returns_first_plate(self, tmp_path):
  741. # The plate_id=None branch must match the archive-level capture
  742. # convention (first plate wins) so callers that don't care about
  743. # plate selection see the same value the archive table holds.
  744. xml_content = """<?xml version="1.0" encoding="UTF-8"?>
  745. <config>
  746. <plate>
  747. <metadata key="index" value="1"/>
  748. <metadata key="curr_bed_type" value="Cool Plate SuperTack"/>
  749. </plate>
  750. <plate>
  751. <metadata key="index" value="2"/>
  752. <metadata key="curr_bed_type" value="Engineering Plate"/>
  753. </plate>
  754. </config>
  755. """
  756. file_path = tmp_path / "test.3mf"
  757. file_path.write_bytes(create_mock_3mf(xml_content).read())
  758. assert extract_bed_type_from_3mf(file_path) == "Cool Plate SuperTack"
  759. def test_unknown_plate_id_returns_none(self, tmp_path):
  760. xml_content = """<?xml version="1.0" encoding="UTF-8"?>
  761. <config>
  762. <plate>
  763. <metadata key="index" value="1"/>
  764. <metadata key="curr_bed_type" value="Textured PEI Plate"/>
  765. </plate>
  766. </config>
  767. """
  768. file_path = tmp_path / "test.3mf"
  769. file_path.write_bytes(create_mock_3mf(xml_content).read())
  770. assert extract_bed_type_from_3mf(file_path, plate_id=99) is None
  771. def test_plate_without_bed_type_returns_none(self, tmp_path):
  772. # Older slicers may export a plate without curr_bed_type. The
  773. # helper must return None rather than falling through to another
  774. # plate's value (which would silently lie).
  775. xml_content = """<?xml version="1.0" encoding="UTF-8"?>
  776. <config>
  777. <plate>
  778. <metadata key="index" value="1"/>
  779. </plate>
  780. <plate>
  781. <metadata key="index" value="2"/>
  782. <metadata key="curr_bed_type" value="Engineering Plate"/>
  783. </plate>
  784. </config>
  785. """
  786. file_path = tmp_path / "test.3mf"
  787. file_path.write_bytes(create_mock_3mf(xml_content).read())
  788. assert extract_bed_type_from_3mf(file_path, plate_id=1) is None
  789. assert extract_bed_type_from_3mf(file_path, plate_id=2) == "Engineering Plate"
  790. def test_missing_slice_info_returns_none(self, tmp_path):
  791. buffer = io.BytesIO()
  792. with zipfile.ZipFile(buffer, "w") as zf:
  793. zf.writestr("other_file.txt", "content")
  794. buffer.seek(0)
  795. file_path = tmp_path / "test.3mf"
  796. file_path.write_bytes(buffer.read())
  797. assert extract_bed_type_from_3mf(file_path) is None
  798. def test_invalid_file_returns_none(self, tmp_path):
  799. file_path = tmp_path / "invalid.3mf"
  800. file_path.write_text("not a zip file")
  801. assert extract_bed_type_from_3mf(file_path) is None
  802. def test_whitespace_trimmed(self, tmp_path):
  803. # 3MF values sometimes carry surrounding whitespace from manual
  804. # template tweaks; getBedTypeInfo() on the frontend is also
  805. # whitespace-tolerant, but the wire shape should be clean.
  806. xml_content = """<?xml version="1.0" encoding="UTF-8"?>
  807. <config>
  808. <plate>
  809. <metadata key="index" value="1"/>
  810. <metadata key="curr_bed_type" value=" Textured PEI Plate "/>
  811. </plate>
  812. </config>
  813. """
  814. file_path = tmp_path / "test.3mf"
  815. file_path.write_bytes(create_mock_3mf(xml_content).read())
  816. assert extract_bed_type_from_3mf(file_path) == "Textured PEI Plate"
  817. class TestExtractPrintTimeFrom3mf:
  818. """Tests for extract_print_time_from_3mf — the per-plate `prediction` reader
  819. used by the completion notification path to scope the archive-level (summed)
  820. total down to the actually-printed plate (#1785)."""
  821. def test_returns_plate_prediction_when_plate_id_matches(self, tmp_path):
  822. xml_content = """<?xml version="1.0" encoding="UTF-8"?>
  823. <config>
  824. <plate>
  825. <metadata key="index" value="1"/>
  826. <metadata key="prediction" value="3600"/>
  827. </plate>
  828. <plate>
  829. <metadata key="index" value="2"/>
  830. <metadata key="prediction" value="7200"/>
  831. </plate>
  832. <plate>
  833. <metadata key="index" value="3"/>
  834. <metadata key="prediction" value="10800"/>
  835. </plate>
  836. </config>
  837. """
  838. file_path = tmp_path / "test.3mf"
  839. file_path.write_bytes(create_mock_3mf(xml_content).read())
  840. assert extract_print_time_from_3mf(file_path, plate_id=2) == 7200
  841. def test_returns_first_plate_when_no_plate_id(self, tmp_path):
  842. xml_content = """<?xml version="1.0" encoding="UTF-8"?>
  843. <config>
  844. <plate>
  845. <metadata key="index" value="1"/>
  846. <metadata key="prediction" value="900"/>
  847. </plate>
  848. <plate>
  849. <metadata key="index" value="2"/>
  850. <metadata key="prediction" value="1800"/>
  851. </plate>
  852. </config>
  853. """
  854. file_path = tmp_path / "test.3mf"
  855. file_path.write_bytes(create_mock_3mf(xml_content).read())
  856. assert extract_print_time_from_3mf(file_path) == 900
  857. def test_returns_none_when_plate_id_missing(self, tmp_path):
  858. xml_content = """<?xml version="1.0" encoding="UTF-8"?>
  859. <config>
  860. <plate>
  861. <metadata key="index" value="1"/>
  862. <metadata key="prediction" value="3600"/>
  863. </plate>
  864. </config>
  865. """
  866. file_path = tmp_path / "test.3mf"
  867. file_path.write_bytes(create_mock_3mf(xml_content).read())
  868. assert extract_print_time_from_3mf(file_path, plate_id=5) is None
  869. def test_returns_none_when_prediction_unparseable(self, tmp_path):
  870. xml_content = """<?xml version="1.0" encoding="UTF-8"?>
  871. <config>
  872. <plate>
  873. <metadata key="index" value="1"/>
  874. <metadata key="prediction" value="not-a-number"/>
  875. </plate>
  876. </config>
  877. """
  878. file_path = tmp_path / "test.3mf"
  879. file_path.write_bytes(create_mock_3mf(xml_content).read())
  880. assert extract_print_time_from_3mf(file_path, plate_id=1) is None
  881. def test_returns_none_when_slice_info_missing(self, tmp_path):
  882. buffer = io.BytesIO()
  883. with zipfile.ZipFile(buffer, "w") as zf:
  884. zf.writestr("other_file.txt", "content")
  885. buffer.seek(0)
  886. file_path = tmp_path / "test.3mf"
  887. file_path.write_bytes(buffer.read())
  888. assert extract_print_time_from_3mf(file_path) is None
  889. assert extract_print_time_from_3mf(file_path, plate_id=1) is None
  890. def test_returns_none_when_file_invalid(self, tmp_path):
  891. file_path = tmp_path / "invalid.3mf"
  892. file_path.write_text("not a zip file")
  893. assert extract_print_time_from_3mf(file_path) is None
  894. assert extract_print_time_from_3mf(file_path, plate_id=1) is None
  895. def test_returns_none_when_file_missing(self, tmp_path):
  896. file_path = tmp_path / "nonexistent.3mf"
  897. assert extract_print_time_from_3mf(file_path) is None
  898. assert extract_print_time_from_3mf(file_path, plate_id=2) is None
  899. # ---------------------------------------------------------------------------
  900. # Tests for extract_support_filament_slots_from_3mf — #1881: a plate that uses
  901. # PVA (or any material) exclusively for supports doesn't reference the support
  902. # slot from object geometry, so without this helper substitute_unused_plate_
  903. # filaments overwrites the user's support-material profile with slot 1's.
  904. # ---------------------------------------------------------------------------
  905. class TestExtractSupportFilamentSlotsFrom3mf:
  906. def test_pla_object_plus_pva_support_returns_support_slot(self):
  907. # The reporter's exact scenario (#1881): slot 1 = PLA (model),
  908. # slot 2 = PVA (support). enable_support on. Without this the
  909. # substitute logic replaces slot 2's PVA profile with PLA and
  910. # the printed supports come out in PLA.
  911. cfg = json.dumps(
  912. {
  913. "enable_support": "1",
  914. "support_filament": "2",
  915. "support_interface_filament": "2",
  916. "filament_type": ["PLA", "PVA"],
  917. }
  918. )
  919. with _make_3mf_with({"Metadata/project_settings.config": cfg}) as zf:
  920. assert extract_support_filament_slots_from_3mf(zf) == {2}
  921. def test_distinct_support_body_and_interface_slots(self):
  922. cfg = json.dumps(
  923. {
  924. "enable_support": "1",
  925. "support_filament": "2",
  926. "support_interface_filament": "3",
  927. }
  928. )
  929. with _make_3mf_with({"Metadata/project_settings.config": cfg}) as zf:
  930. assert extract_support_filament_slots_from_3mf(zf) == {2, 3}
  931. def test_supports_disabled_returns_empty(self):
  932. # enable_support off — supports won't be printed even if a slot is
  933. # configured. Don't force it into the "used" set; substitution
  934. # should still homogenise the loaded-filament array.
  935. cfg = json.dumps(
  936. {
  937. "enable_support": "0",
  938. "support_filament": "2",
  939. "support_interface_filament": "2",
  940. }
  941. )
  942. with _make_3mf_with({"Metadata/project_settings.config": cfg}) as zf:
  943. assert extract_support_filament_slots_from_3mf(zf) == set()
  944. def test_slot_zero_treated_as_same_as_model(self):
  945. # BambuStudio's `0` for support_filament means "same as model" —
  946. # no dedicated slot to preserve.
  947. cfg = json.dumps(
  948. {
  949. "enable_support": "1",
  950. "support_filament": "0",
  951. "support_interface_filament": "0",
  952. }
  953. )
  954. with _make_3mf_with({"Metadata/project_settings.config": cfg}) as zf:
  955. assert extract_support_filament_slots_from_3mf(zf) == set()
  956. def test_boolean_enable_support_accepted(self):
  957. # Some forks / older versions write a real JSON bool instead of "1"/"0".
  958. cfg = json.dumps({"enable_support": True, "support_filament": "2"})
  959. with _make_3mf_with({"Metadata/project_settings.config": cfg}) as zf:
  960. assert extract_support_filament_slots_from_3mf(zf) == {2}
  961. def test_integer_slot_value_accepted(self):
  962. cfg = json.dumps({"enable_support": "1", "support_filament": 3})
  963. with _make_3mf_with({"Metadata/project_settings.config": cfg}) as zf:
  964. assert extract_support_filament_slots_from_3mf(zf) == {3}
  965. def test_missing_project_settings_returns_empty(self):
  966. with _make_3mf_with({"placeholder.txt": "hi"}) as zf:
  967. assert extract_support_filament_slots_from_3mf(zf) == set()
  968. def test_malformed_json_returns_empty(self):
  969. with _make_3mf_with({"Metadata/project_settings.config": b"{not json"}) as zf:
  970. assert extract_support_filament_slots_from_3mf(zf) == set()
  971. def test_root_is_list_returns_empty(self):
  972. with _make_3mf_with({"Metadata/project_settings.config": json.dumps([])}) as zf:
  973. assert extract_support_filament_slots_from_3mf(zf) == set()
  974. def test_non_numeric_slot_value_skipped(self):
  975. cfg = json.dumps({"enable_support": "1", "support_filament": "not-a-number"})
  976. with _make_3mf_with({"Metadata/project_settings.config": cfg}) as zf:
  977. assert extract_support_filament_slots_from_3mf(zf) == set()
  978. class TestExtractPlateMetadataFrom3mf:
  979. """The combined per-plate helper parses slice_info.config once and caches
  980. the result by file revision so queue polling doesn't re-open the same 3MF
  981. three times per row on every poll (#2573)."""
  982. _MULTI_PLATE = """<?xml version="1.0" encoding="UTF-8"?>
  983. <config>
  984. <plate>
  985. <metadata key="index" value="1"/>
  986. <metadata key="prediction" value="3600"/>
  987. <metadata key="curr_bed_type" value="Textured PEI Plate"/>
  988. <filament id="1" used_g="50.0" type="PLA" color="#FF0000"/>
  989. </plate>
  990. <plate>
  991. <metadata key="index" value="2"/>
  992. <metadata key="prediction" value="7200"/>
  993. <metadata key="curr_bed_type" value="Engineering Plate"/>
  994. <filament id="1" used_g="12.5" type="ABS" color="#00FF00"/>
  995. <filament id="2" used_g="7.5" type="ABS" color="#0000FF"/>
  996. </plate>
  997. </config>
  998. """
  999. def _write(self, tmp_path, xml, name="test.3mf"):
  1000. from backend.app.utils.threemf_tools import clear_plate_metadata_cache
  1001. clear_plate_metadata_cache()
  1002. file_path = tmp_path / name
  1003. file_path.write_bytes(create_mock_3mf(xml).read())
  1004. return file_path
  1005. def test_combines_all_three_fields_for_plate(self, tmp_path):
  1006. from backend.app.utils.threemf_tools import extract_plate_metadata_from_3mf
  1007. file_path = self._write(tmp_path, self._MULTI_PLATE)
  1008. meta = extract_plate_metadata_from_3mf(file_path, plate_id=2)
  1009. assert meta.print_time_seconds == 7200
  1010. assert meta.bed_type == "Engineering Plate"
  1011. assert meta.filament_used_grams == 20.0
  1012. assert {f["slot_id"] for f in meta.filament_usage} == {1, 2}
  1013. def test_plate_id_none_matches_legacy_behaviour(self, tmp_path):
  1014. # Legacy None behaviour: time+bed from the first plate, but usage
  1015. # collects EVERY filament in the file (not just plate 1).
  1016. from backend.app.utils.threemf_tools import extract_plate_metadata_from_3mf
  1017. file_path = self._write(tmp_path, self._MULTI_PLATE)
  1018. meta = extract_plate_metadata_from_3mf(file_path, plate_id=None)
  1019. assert meta.print_time_seconds == 3600
  1020. assert meta.bed_type == "Textured PEI Plate"
  1021. assert len(meta.filament_usage) == 3 # 1 from plate 1 + 2 from plate 2
  1022. def test_second_call_hits_cache_without_reparsing(self, tmp_path):
  1023. from unittest.mock import patch
  1024. import backend.app.utils.threemf_tools as tools
  1025. file_path = self._write(tmp_path, self._MULTI_PLATE)
  1026. with patch.object(tools, "_parse_plate_metadata_uncached", wraps=tools._parse_plate_metadata_uncached) as spy:
  1027. first = tools.extract_plate_metadata_from_3mf(file_path, plate_id=2)
  1028. second = tools.extract_plate_metadata_from_3mf(file_path, plate_id=2)
  1029. assert spy.call_count == 1 # parsed once, served from cache the second time
  1030. assert first is second
  1031. assert second.print_time_seconds == 7200
  1032. def test_changed_file_reparses(self, tmp_path):
  1033. from unittest.mock import patch
  1034. import backend.app.utils.threemf_tools as tools
  1035. file_path = self._write(tmp_path, self._MULTI_PLATE)
  1036. with patch.object(tools, "_parse_plate_metadata_uncached", wraps=tools._parse_plate_metadata_uncached) as spy:
  1037. tools.extract_plate_metadata_from_3mf(file_path, plate_id=1)
  1038. # Replace the file with different content (and a different size, so the
  1039. # revision key changes even if mtime resolution is coarse).
  1040. new_xml = """<?xml version="1.0" encoding="UTF-8"?>
  1041. <config>
  1042. <plate>
  1043. <metadata key="index" value="1"/>
  1044. <metadata key="prediction" value="999"/>
  1045. <metadata key="curr_bed_type" value="Cool Plate"/>
  1046. <filament id="1" used_g="1.0" type="PLA" color="#FFFFFF"/>
  1047. </plate>
  1048. </config>
  1049. """
  1050. file_path.write_bytes(create_mock_3mf(new_xml).read())
  1051. fresh = tools.extract_plate_metadata_from_3mf(file_path, plate_id=1)
  1052. assert spy.call_count == 2 # revision changed -> re-parsed
  1053. assert fresh.print_time_seconds == 999
  1054. assert fresh.bed_type == "Cool Plate"
  1055. def test_wrapper_returns_mutable_copy(self, tmp_path):
  1056. # extract_filament_usage_from_3mf callers mutate the list; that must not
  1057. # corrupt the shared cached PlateMetadata.
  1058. from backend.app.utils.threemf_tools import (
  1059. extract_filament_usage_from_3mf,
  1060. extract_plate_metadata_from_3mf,
  1061. )
  1062. file_path = self._write(tmp_path, self._MULTI_PLATE)
  1063. usage = extract_filament_usage_from_3mf(file_path, plate_id=2)
  1064. usage.append({"slot_id": 99, "used_g": 0.0, "type": "", "color": ""})
  1065. usage[0]["used_g"] = -1.0
  1066. cached = extract_plate_metadata_from_3mf(file_path, plate_id=2)
  1067. assert len(cached.filament_usage) == 2
  1068. assert all(f["used_g"] > 0 for f in cached.filament_usage)
  1069. def test_non_numeric_filament_id_is_skipped_not_raised(self, tmp_path):
  1070. # A garbage filament id (or used_g) must be silently skipped, exactly as
  1071. # the legacy helpers did — a raise here would 500 the queue listing that
  1072. # calls this per row. Guards both the plate-specific and plate_id=None paths.
  1073. from backend.app.utils.threemf_tools import (
  1074. extract_filament_usage_from_3mf,
  1075. extract_plate_metadata_from_3mf,
  1076. )
  1077. xml_content = """<?xml version="1.0" encoding="UTF-8"?>
  1078. <config>
  1079. <plate>
  1080. <metadata key="index" value="1"/>
  1081. <metadata key="prediction" value="3600"/>
  1082. <filament id="abc" used_g="5.0" type="PLA" color="#FFFFFF"/>
  1083. <filament id="1" used_g="10.0" type="PLA" color="#FF0000"/>
  1084. <filament id="2" used_g="bad" type="PLA" color="#00FF00"/>
  1085. </plate>
  1086. </config>
  1087. """
  1088. file_path = self._write(tmp_path, xml_content)
  1089. meta = extract_plate_metadata_from_3mf(file_path, plate_id=1)
  1090. assert [f["slot_id"] for f in meta.filament_usage] == [1]
  1091. assert meta.filament_used_grams == 10.0
  1092. assert meta.print_time_seconds == 3600
  1093. # plate_id=None path (collects all filaments in the file) must skip too.
  1094. none_result = extract_filament_usage_from_3mf(file_path, plate_id=None)
  1095. assert [f["slot_id"] for f in none_result] == [1]
  1096. def test_missing_file_returns_empty_and_is_not_cached(self, tmp_path):
  1097. from unittest.mock import patch
  1098. import backend.app.utils.threemf_tools as tools
  1099. tools.clear_plate_metadata_cache()
  1100. missing = tmp_path / "nope.3mf"
  1101. with patch.object(tools, "_parse_plate_metadata_uncached", wraps=tools._parse_plate_metadata_uncached) as spy:
  1102. meta = tools.extract_plate_metadata_from_3mf(missing, plate_id=1)
  1103. tools.extract_plate_metadata_from_3mf(missing, plate_id=1)
  1104. assert meta.print_time_seconds is None
  1105. assert meta.filament_usage == []
  1106. # Missing file must not create a sticky cache entry (it may appear later).
  1107. assert spy.call_count == 2
  1108. def _make_plate_3mf(tmp_path, gcode_by_name: dict[str, str], name: str = "print.3mf"):
  1109. """Write a 3MF containing the given plate G-code members."""
  1110. buffer = io.BytesIO()
  1111. with zipfile.ZipFile(buffer, "w") as zf:
  1112. for member, content in gcode_by_name.items():
  1113. zf.writestr(member, content)
  1114. buffer.seek(0)
  1115. path = tmp_path / name
  1116. path.write_bytes(buffer.read())
  1117. return path
  1118. def _header(**values: str) -> str:
  1119. lines = ["; HEADER_BLOCK_START"]
  1120. lines += [f"; {key.replace('_', ' ')}: {value}" for key, value in values.items()]
  1121. lines.append("; HEADER_BLOCK_END")
  1122. lines.append("G1 X0 Y0")
  1123. return "\n".join(lines)
  1124. class TestExtractMaxZHeightFrom3mf:
  1125. """#2547: the print's top Z, used to command the plate back into camera
  1126. framing before the finish photo.
  1127. This value becomes the target of a real Z move, so "don't know" has to be
  1128. reported as None rather than defaulted — a wrong height would drive the
  1129. nozzle into the part.
  1130. """
  1131. def test_reads_max_z_height_from_the_plate_header(self, tmp_path):
  1132. path = _make_plate_3mf(
  1133. tmp_path,
  1134. {"Metadata/plate_1.gcode": _header(max_z_height="16.00", total_layer_number="80")},
  1135. )
  1136. assert extract_max_z_height_from_3mf(path, 1) == 16.0
  1137. def test_picks_the_requested_plate(self, tmp_path):
  1138. path = _make_plate_3mf(
  1139. tmp_path,
  1140. {
  1141. "Metadata/plate_1.gcode": _header(max_z_height="16.00"),
  1142. "Metadata/plate_2.gcode": _header(max_z_height="42.50"),
  1143. },
  1144. )
  1145. assert extract_max_z_height_from_3mf(path, 2) == 42.5
  1146. def test_falls_back_to_the_only_gcode_when_the_plate_name_does_not_match(self, tmp_path):
  1147. """Files from slicers that don't use Bambu's plate naming still resolve."""
  1148. path = _make_plate_3mf(tmp_path, {"whatever.gcode": _header(max_z_height="7.25")})
  1149. assert extract_max_z_height_from_3mf(path, 3) == 7.25
  1150. def test_missing_header_key_returns_none(self, tmp_path):
  1151. path = _make_plate_3mf(tmp_path, {"Metadata/plate_1.gcode": _header(total_layer_number="80")})
  1152. assert extract_max_z_height_from_3mf(path, 1) is None
  1153. def test_non_numeric_value_returns_none(self, tmp_path):
  1154. path = _make_plate_3mf(tmp_path, {"Metadata/plate_1.gcode": _header(max_z_height="tall")})
  1155. assert extract_max_z_height_from_3mf(path, 1) is None
  1156. def test_zero_and_negative_are_treated_as_unknown(self, tmp_path):
  1157. """Passed through, either would become a Z move toward the bed."""
  1158. zero = _make_plate_3mf(tmp_path, {"Metadata/plate_1.gcode": _header(max_z_height="0")}, "z.3mf")
  1159. negative = _make_plate_3mf(tmp_path, {"Metadata/plate_1.gcode": _header(max_z_height="-3")}, "n.3mf")
  1160. assert extract_max_z_height_from_3mf(zero, 1) is None
  1161. assert extract_max_z_height_from_3mf(negative, 1) is None
  1162. def test_no_gcode_member_returns_none(self, tmp_path):
  1163. path = _make_plate_3mf(tmp_path, {"Metadata/slice_info.config": "<config/>"})
  1164. assert extract_max_z_height_from_3mf(path, 1) is None
  1165. def test_unreadable_file_returns_none(self, tmp_path):
  1166. path = tmp_path / "broken.3mf"
  1167. path.write_text("not a zip")
  1168. assert extract_max_z_height_from_3mf(path, 1) is None
  1169. def test_missing_file_returns_none(self, tmp_path):
  1170. assert extract_max_z_height_from_3mf(tmp_path / "nope.3mf", 1) is None
  1171. def test_only_the_header_is_inflated(self, tmp_path):
  1172. """A sliced plate is routinely tens of MB; reading it whole to reach ~40
  1173. header lines would stall the finish-photo path. The header is read from
  1174. a bounded prefix, so a huge body must not change the answer."""
  1175. gcode = _header(max_z_height="99.9") + "\n" + ("G1 X1 Y1 E0.1\n" * 400_000)
  1176. path = _make_plate_3mf(tmp_path, {"Metadata/plate_1.gcode": gcode})
  1177. assert extract_max_z_height_from_3mf(path, 1) == 99.9