test_threemf_tools.py 60 KB

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