test_archive_service.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. """Unit tests for the archive service."""
  2. from datetime import datetime
  3. class TestArchiveServiceHelpers:
  4. """Tests for archive service helper functions."""
  5. def test_parse_print_time_seconds(self):
  6. """Test parsing print time to seconds."""
  7. # Import the actual function if available, otherwise test the logic
  8. # 2h 30m 15s = 2*3600 + 30*60 + 15 = 9015 seconds
  9. _time_str = "2h 30m 15s" # Example format
  10. # Parse hours
  11. hours = 2
  12. minutes = 30
  13. seconds = 15
  14. total = hours * 3600 + minutes * 60 + seconds
  15. assert total == 9015
  16. def test_parse_filament_grams(self):
  17. """Test parsing filament usage to grams."""
  18. # Example: "150.5g" -> 150.5
  19. filament_str = "150.5g"
  20. grams = float(filament_str.replace("g", ""))
  21. assert grams == 150.5
  22. def test_format_duration(self):
  23. """Test formatting seconds to human readable duration."""
  24. # 3661 seconds = 1h 1m 1s
  25. seconds = 3661
  26. hours = seconds // 3600
  27. minutes = (seconds % 3600) // 60
  28. secs = seconds % 60
  29. assert hours == 1
  30. assert minutes == 1
  31. assert secs == 1
  32. class TestArchiveDataParsing:
  33. """Tests for parsing archive data from MQTT messages."""
  34. def test_parse_gcode_state(self):
  35. """Test parsing gcode state."""
  36. states = {
  37. "RUNNING": "printing",
  38. "FINISH": "completed",
  39. "FAILED": "failed",
  40. "IDLE": "idle",
  41. "PAUSE": "paused",
  42. }
  43. for gcode_state, expected in states.items():
  44. # Simple state mapping
  45. mapped = gcode_state.lower()
  46. if gcode_state == "RUNNING":
  47. mapped = "printing"
  48. elif gcode_state == "FINISH":
  49. mapped = "completed"
  50. elif gcode_state == "FAILED":
  51. mapped = "failed"
  52. elif gcode_state == "IDLE":
  53. mapped = "idle"
  54. elif gcode_state == "PAUSE":
  55. mapped = "paused"
  56. assert mapped == expected
  57. def test_parse_progress(self):
  58. """Test parsing print progress."""
  59. # mc_percent is the progress field in MQTT messages
  60. data = {"mc_percent": 75}
  61. progress = data.get("mc_percent", 0)
  62. assert progress == 75
  63. assert 0 <= progress <= 100
  64. def test_parse_layer_info(self):
  65. """Test parsing layer information."""
  66. data = {
  67. "layer_num": 50,
  68. "total_layers": 200,
  69. }
  70. current_layer = data.get("layer_num", 0)
  71. total_layers = data.get("total_layers", 0)
  72. assert current_layer == 50
  73. assert total_layers == 200
  74. if total_layers > 0:
  75. layer_percent = (current_layer / total_layers) * 100
  76. assert layer_percent == 25.0
  77. class TestArchiveFilePaths:
  78. """Tests for archive file path handling."""
  79. def test_generate_archive_path(self):
  80. """Test generating archive file paths."""
  81. printer_name = "X1C_01"
  82. _print_name = "benchy" # Example print name
  83. timestamp = datetime(2024, 1, 15, 14, 30, 0)
  84. # Expected pattern: archives/{printer}/{year}/{month}/{filename}
  85. year = timestamp.year
  86. month = f"{timestamp.month:02d}"
  87. expected_dir = f"archives/{printer_name}/{year}/{month}"
  88. assert "archives" in expected_dir
  89. assert printer_name in expected_dir
  90. assert str(year) in expected_dir
  91. def test_sanitize_filename(self):
  92. """Test filename sanitization."""
  93. # Characters to remove: / \ : * ? " < > |
  94. dirty_name = "test:file<name>.3mf"
  95. # Simple sanitization
  96. safe_chars = []
  97. for c in dirty_name:
  98. if c not in '\\/:*?"<>|':
  99. safe_chars.append(c)
  100. clean_name = "".join(safe_chars)
  101. assert ":" not in clean_name
  102. assert "<" not in clean_name
  103. assert ">" not in clean_name
  104. def test_thumbnail_path(self):
  105. """Test thumbnail path generation."""
  106. archive_path = "archives/X1C_01/2024/01/benchy.3mf"
  107. # Thumbnail typically has same path with _thumb.png suffix
  108. base_path = archive_path.rsplit(".", 1)[0]
  109. thumbnail_path = f"{base_path}_thumb.png"
  110. assert thumbnail_path.endswith("_thumb.png")
  111. assert "benchy" in thumbnail_path
  112. class TestArchiveStatus:
  113. """Tests for archive status handling."""
  114. def test_valid_status_values(self):
  115. """Test valid archive status values."""
  116. valid_statuses = ["completed", "failed", "cancelled", "stopped"]
  117. for status in valid_statuses:
  118. assert status in valid_statuses
  119. def test_status_from_gcode_state(self):
  120. """Test mapping gcode state to archive status."""
  121. state_mapping = {
  122. "FINISH": "completed",
  123. "FAILED": "failed",
  124. "CANCEL": "cancelled",
  125. }
  126. for gcode_state, expected_status in state_mapping.items():
  127. assert state_mapping[gcode_state] == expected_status
  128. class TestArchiveFilamentData:
  129. """Tests for filament data parsing."""
  130. def test_parse_ams_filament(self):
  131. """Test parsing AMS filament information."""
  132. ams_data = {
  133. "ams": {
  134. "ams": [
  135. {
  136. "tray": [
  137. {"tray_type": "PLA", "tray_color": "FF0000"},
  138. {"tray_type": "PETG", "tray_color": "00FF00"},
  139. ]
  140. }
  141. ]
  142. }
  143. }
  144. trays = ams_data["ams"]["ams"][0]["tray"]
  145. assert trays[0]["tray_type"] == "PLA"
  146. assert trays[1]["tray_type"] == "PETG"
  147. def test_parse_filament_color_hex(self):
  148. """Test parsing filament color from hex."""
  149. color_hex = "FF5500"
  150. # Should be valid hex
  151. assert len(color_hex) == 6
  152. r = int(color_hex[0:2], 16)
  153. g = int(color_hex[2:4], 16)
  154. b = int(color_hex[4:6], 16)
  155. assert r == 255
  156. assert g == 85
  157. assert b == 0
  158. def test_calculate_filament_cost(self):
  159. """Test calculating filament cost."""
  160. grams_used = 150.0
  161. cost_per_kg = 25.0 # $25 per kg
  162. cost = (grams_used / 1000) * cost_per_kg
  163. assert cost == 3.75
  164. class TestArchiveThumbnails:
  165. """Tests for archive thumbnail handling."""
  166. def test_thumbnail_file_types(self):
  167. """Test supported thumbnail file types."""
  168. supported_types = [".png", ".jpg", ".jpeg"]
  169. for ext in supported_types:
  170. assert ext.startswith(".")
  171. assert ext.lower() in [".png", ".jpg", ".jpeg"]
  172. def test_extract_thumbnail_from_3mf(self):
  173. """Test thumbnail extraction concept from 3MF."""
  174. # 3MF files are ZIP archives containing:
  175. # - Metadata/thumbnail.png
  176. # - 3D/3dmodel.model
  177. expected_thumbnail_paths = [
  178. "Metadata/thumbnail.png",
  179. "Metadata/plate_1.png",
  180. ]
  181. for path in expected_thumbnail_paths:
  182. assert "png" in path.lower()
  183. def test_extract_thumbnail_falls_back_to_auxiliaries(self, tmp_path):
  184. """#1493 follow-up: when BambuStudio's CLI runs with --arrange it
  185. rearranges objects but doesn't always emit a fresh
  186. ``Metadata/plate_N.png`` for the rearranged plate. The project-wide
  187. thumbnail under ``Auxiliaries/.thumbnails/`` survives though, and
  188. we use it as a cover-image fallback so re-sliced archive cards
  189. still render with a thumbnail."""
  190. import zipfile
  191. from backend.app.services.archive import ThreeMFParser
  192. threemf_path = tmp_path / "sliced.3mf"
  193. with zipfile.ZipFile(threemf_path, "w") as zf:
  194. zf.writestr("3D/3dmodel.model", "<model/>")
  195. # No Metadata/plate_1.png / thumbnail.png — only the
  196. # Auxiliaries project-wide thumbnail (what arranged slices
  197. # carry in practice).
  198. zf.writestr("Auxiliaries/.thumbnails/thumbnail_middle.png", b"PNGMIDDLE")
  199. parser = ThreeMFParser(str(threemf_path), plate_number=1)
  200. parsed = parser.parse()
  201. assert parsed.get("_thumbnail_data") == b"PNGMIDDLE"
  202. assert parsed.get("_thumbnail_ext") == ".png"
  203. def test_per_plate_png_wins_over_auxiliaries_fallback(self, tmp_path):
  204. """Order matters: when BOTH the per-plate preview and the
  205. Auxiliaries fallback are present, the per-plate one wins because
  206. it reflects the actual sliced layout."""
  207. import zipfile
  208. from backend.app.services.archive import ThreeMFParser
  209. threemf_path = tmp_path / "sliced.3mf"
  210. with zipfile.ZipFile(threemf_path, "w") as zf:
  211. zf.writestr("3D/3dmodel.model", "<model/>")
  212. zf.writestr("Metadata/plate_1.png", b"PLATE1")
  213. zf.writestr("Auxiliaries/.thumbnails/thumbnail_middle.png", b"PROJECT_WIDE")
  214. parser = ThreeMFParser(str(threemf_path), plate_number=1)
  215. parsed = parser.parse()
  216. assert parsed.get("_thumbnail_data") == b"PLATE1"
  217. class TestPrintableObjectsExtraction:
  218. """Tests for extracting printable objects count from 3MF files."""
  219. def test_extract_printable_objects_from_slice_info(self):
  220. """Test parsing printable objects from slice_info.config XML."""
  221. from defusedxml import ElementTree as ET
  222. # Example slice_info.config content with 4 objects
  223. slice_info_xml = """<?xml version="1.0" encoding="UTF-8"?>
  224. <config>
  225. <plate plate_idx="1">
  226. <metadata key="prediction" value="3600" />
  227. <metadata key="weight" value="50.5" />
  228. <object identify_id="1" name="Part_A" skipped="false" />
  229. <object identify_id="2" name="Part_B" skipped="false" />
  230. <object identify_id="3" name="Part_C" skipped="false" />
  231. <object identify_id="4" name="Part_D" skipped="true" />
  232. </plate>
  233. </config>
  234. """
  235. root = ET.fromstring(slice_info_xml)
  236. plate = root.find(".//plate")
  237. # Count non-skipped objects (should be 3, not 4)
  238. count = 0
  239. for obj in plate.findall("object"):
  240. skipped = obj.get("skipped", "false")
  241. if skipped.lower() != "true":
  242. count += 1
  243. assert count == 3 # 3 objects (Part_D is skipped)
  244. def test_extract_printable_objects_empty_plate(self):
  245. """Test handling plate with no objects."""
  246. from defusedxml import ElementTree as ET
  247. slice_info_xml = """<?xml version="1.0" encoding="UTF-8"?>
  248. <config>
  249. <plate plate_idx="1">
  250. <metadata key="prediction" value="0" />
  251. </plate>
  252. </config>
  253. """
  254. root = ET.fromstring(slice_info_xml)
  255. plate = root.find(".//plate")
  256. count = 0
  257. for obj in plate.findall("object"):
  258. skipped = obj.get("skipped", "false")
  259. if skipped.lower() != "true":
  260. count += 1
  261. assert count == 0
  262. def test_extract_printable_objects_all_skipped(self):
  263. """Test handling plate where all objects are skipped."""
  264. from defusedxml import ElementTree as ET
  265. slice_info_xml = """<?xml version="1.0" encoding="UTF-8"?>
  266. <config>
  267. <plate plate_idx="1">
  268. <object identify_id="1" name="Part_A" skipped="true" />
  269. <object identify_id="2" name="Part_B" skipped="true" />
  270. </plate>
  271. </config>
  272. """
  273. root = ET.fromstring(slice_info_xml)
  274. plate = root.find(".//plate")
  275. count = 0
  276. for obj in plate.findall("object"):
  277. skipped = obj.get("skipped", "false")
  278. if skipped.lower() != "true":
  279. count += 1
  280. assert count == 0 # All objects skipped
  281. class TestThreeMFPlateIndexExtraction:
  282. """Tests for extracting plate index from multi-plate 3MF exports (Issue #92)."""
  283. def test_extract_plate_index_from_slice_info(self):
  284. """Test parsing plate index from slice_info.config metadata."""
  285. from defusedxml import ElementTree as ET
  286. # Single-plate export from plate 5 of a multi-plate project
  287. slice_info_xml = """<?xml version="1.0" encoding="UTF-8"?>
  288. <config>
  289. <plate>
  290. <metadata key="index" value="5" />
  291. <metadata key="prediction" value="3600" />
  292. <metadata key="weight" value="50.5" />
  293. <object identify_id="1" name="Part_A" skipped="false" />
  294. </plate>
  295. </config>
  296. """
  297. root = ET.fromstring(slice_info_xml)
  298. plate = root.find(".//plate")
  299. plate_index = None
  300. for meta in plate.findall("metadata"):
  301. if meta.get("key") == "index":
  302. plate_index = int(meta.get("value"))
  303. break
  304. assert plate_index == 5
  305. def test_extract_plate_index_plate_1(self):
  306. """Test parsing plate index when it's plate 1."""
  307. from defusedxml import ElementTree as ET
  308. slice_info_xml = """<?xml version="1.0" encoding="UTF-8"?>
  309. <config>
  310. <plate>
  311. <metadata key="index" value="1" />
  312. <metadata key="prediction" value="1800" />
  313. </plate>
  314. </config>
  315. """
  316. root = ET.fromstring(slice_info_xml)
  317. plate = root.find(".//plate")
  318. plate_index = None
  319. for meta in plate.findall("metadata"):
  320. if meta.get("key") == "index":
  321. plate_index = int(meta.get("value"))
  322. break
  323. assert plate_index == 1
  324. def test_thumbnail_path_uses_plate_number(self):
  325. """Test that thumbnail path correctly uses the extracted plate number."""
  326. plate_number = 5
  327. thumbnail_paths = []
  328. if plate_number:
  329. thumbnail_paths.append(f"Metadata/plate_{plate_number}.png")
  330. thumbnail_paths.extend(
  331. [
  332. "Metadata/plate_1.png",
  333. "Metadata/thumbnail.png",
  334. ]
  335. )
  336. # First priority should be plate_5.png
  337. assert thumbnail_paths[0] == "Metadata/plate_5.png"
  338. @staticmethod
  339. def _enhance_print_name(print_name: str, plate_index: int) -> str:
  340. """Apply plate name enhancement logic from archive.py."""
  341. if plate_index and plate_index > 1:
  342. if print_name and f"Plate {plate_index}" not in print_name:
  343. print_name = f"{print_name} - Plate {plate_index}"
  344. return print_name
  345. def test_print_name_enhanced_for_plate_greater_than_1(self):
  346. """Test that print_name is enhanced with plate info for plate > 1."""
  347. assert self._enhance_print_name("Benchy", 5) == "Benchy - Plate 5"
  348. def test_print_name_not_enhanced_for_plate_1(self):
  349. """Test that print_name is NOT enhanced for plate 1."""
  350. assert self._enhance_print_name("Benchy", 1) == "Benchy"
  351. def test_print_name_not_duplicated(self):
  352. """Test that plate info is not added if already present in print_name."""
  353. assert self._enhance_print_name("Benchy - Plate 5", 5) == "Benchy - Plate 5"
  354. def test_high_plate_number_extraction(self):
  355. """Test extracting high plate numbers (e.g., plate 28)."""
  356. from defusedxml import ElementTree as ET
  357. slice_info_xml = """<?xml version="1.0" encoding="UTF-8"?>
  358. <config>
  359. <plate>
  360. <metadata key="index" value="28" />
  361. <metadata key="prediction" value="7200" />
  362. </plate>
  363. </config>
  364. """
  365. root = ET.fromstring(slice_info_xml)
  366. plate = root.find(".//plate")
  367. plate_index = None
  368. for meta in plate.findall("metadata"):
  369. if meta.get("key") == "index":
  370. plate_index = int(meta.get("value"))
  371. break
  372. assert plate_index == 28
  373. # Verify thumbnail would use correct plate
  374. thumbnail_path = f"Metadata/plate_{plate_index}.png"
  375. assert thumbnail_path == "Metadata/plate_28.png"
  376. class TestMultiPlate3MFParsing:
  377. """Tests for parsing multi-plate 3MF files (Issue #93)."""
  378. def test_parse_multiple_plates_from_slice_info(self):
  379. """Test parsing multiple plates from slice_info.config."""
  380. from defusedxml import ElementTree as ET
  381. # Multi-plate 3MF with 3 plates
  382. slice_info_xml = """<?xml version="1.0" encoding="UTF-8"?>
  383. <config>
  384. <plate>
  385. <metadata key="index" value="1" />
  386. <metadata key="prediction" value="3600" />
  387. <metadata key="weight" value="50.0" />
  388. <filament id="1" type="PLA" color="#FF0000" used_g="25.0" used_m="8.5" />
  389. <object identify_id="1" name="Part_A" skipped="false" />
  390. </plate>
  391. <plate>
  392. <metadata key="index" value="2" />
  393. <metadata key="prediction" value="7200" />
  394. <metadata key="weight" value="100.0" />
  395. <filament id="2" type="PETG" color="#00FF00" used_g="50.0" used_m="17.0" />
  396. <object identify_id="2" name="Part_B" skipped="false" />
  397. </plate>
  398. <plate>
  399. <metadata key="index" value="3" />
  400. <metadata key="prediction" value="1800" />
  401. <metadata key="weight" value="25.0" />
  402. <filament id="1" type="PLA" color="#FF0000" used_g="12.5" used_m="4.2" />
  403. <filament id="3" type="TPU" color="#0000FF" used_g="12.5" used_m="4.2" />
  404. <object identify_id="3" name="Part_C" skipped="false" />
  405. </plate>
  406. </config>
  407. """
  408. root = ET.fromstring(slice_info_xml)
  409. plates = root.findall(".//plate")
  410. assert len(plates) == 3
  411. # Parse each plate
  412. plate_data = []
  413. for plate_elem in plates:
  414. plate_info = {"index": None, "filaments": []}
  415. for meta in plate_elem.findall("metadata"):
  416. if meta.get("key") == "index":
  417. plate_info["index"] = int(meta.get("value"))
  418. for filament_elem in plate_elem.findall("filament"):
  419. used_g = float(filament_elem.get("used_g", "0"))
  420. if used_g > 0:
  421. plate_info["filaments"].append(
  422. {
  423. "slot_id": int(filament_elem.get("id")),
  424. "type": filament_elem.get("type"),
  425. "color": filament_elem.get("color"),
  426. "used_grams": used_g,
  427. }
  428. )
  429. plate_data.append(plate_info)
  430. # Verify plate 1
  431. assert plate_data[0]["index"] == 1
  432. assert len(plate_data[0]["filaments"]) == 1
  433. assert plate_data[0]["filaments"][0]["slot_id"] == 1
  434. assert plate_data[0]["filaments"][0]["type"] == "PLA"
  435. # Verify plate 2
  436. assert plate_data[1]["index"] == 2
  437. assert len(plate_data[1]["filaments"]) == 1
  438. assert plate_data[1]["filaments"][0]["slot_id"] == 2
  439. assert plate_data[1]["filaments"][0]["type"] == "PETG"
  440. # Verify plate 3 (has 2 filaments)
  441. assert plate_data[2]["index"] == 3
  442. assert len(plate_data[2]["filaments"]) == 2
  443. filament_types = {f["type"] for f in plate_data[2]["filaments"]}
  444. assert filament_types == {"PLA", "TPU"}
  445. def test_filter_filaments_by_plate_id(self):
  446. """Test filtering filaments for a specific plate."""
  447. from defusedxml import ElementTree as ET
  448. slice_info_xml = """<?xml version="1.0" encoding="UTF-8"?>
  449. <config>
  450. <plate>
  451. <metadata key="index" value="1" />
  452. <filament id="1" type="PLA" color="#FF0000" used_g="25.0" />
  453. </plate>
  454. <plate>
  455. <metadata key="index" value="2" />
  456. <filament id="2" type="PETG" color="#00FF00" used_g="50.0" />
  457. </plate>
  458. </config>
  459. """
  460. root = ET.fromstring(slice_info_xml)
  461. # Filter for plate 2 only
  462. target_plate_id = 2
  463. filaments = []
  464. for plate_elem in root.findall(".//plate"):
  465. plate_index = None
  466. for meta in plate_elem.findall("metadata"):
  467. if meta.get("key") == "index":
  468. plate_index = int(meta.get("value", "0"))
  469. break
  470. if plate_index == target_plate_id:
  471. for filament_elem in plate_elem.findall("filament"):
  472. used_g = float(filament_elem.get("used_g", "0"))
  473. if used_g > 0:
  474. filaments.append(
  475. {
  476. "slot_id": int(filament_elem.get("id")),
  477. "type": filament_elem.get("type"),
  478. }
  479. )
  480. break
  481. # Should only have plate 2's filament
  482. assert len(filaments) == 1
  483. assert filaments[0]["slot_id"] == 2
  484. assert filaments[0]["type"] == "PETG"
  485. def test_detect_multi_plate_from_gcode_files(self):
  486. """Test detecting multiple plates from gcode file presence."""
  487. # Simulate namelist from a multi-plate 3MF
  488. namelist = [
  489. "Metadata/plate_1.gcode",
  490. "Metadata/plate_2.gcode",
  491. "Metadata/plate_3.gcode",
  492. "Metadata/plate_1.png",
  493. "Metadata/plate_2.png",
  494. "Metadata/plate_3.png",
  495. "Metadata/slice_info.config",
  496. "3D/3dmodel.model",
  497. ]
  498. # Extract plate indices from gcode files
  499. gcode_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".gcode")]
  500. plate_indices = []
  501. for gf in gcode_files:
  502. plate_str = gf[15:-6] # Remove "Metadata/plate_" and ".gcode"
  503. plate_indices.append(int(plate_str))
  504. plate_indices.sort()
  505. assert len(plate_indices) == 3
  506. assert plate_indices == [1, 2, 3]
  507. # Verify it's a multi-plate file
  508. is_multi_plate = len(plate_indices) > 1
  509. assert is_multi_plate is True
  510. def test_single_plate_export_not_multi_plate(self):
  511. """Test that single-plate exports are not detected as multi-plate."""
  512. # Simulate namelist from a single-plate export (plate 5 only)
  513. namelist = [
  514. "Metadata/plate_5.gcode",
  515. "Metadata/plate_1.png",
  516. "Metadata/plate_2.png",
  517. "Metadata/plate_3.png",
  518. "Metadata/plate_4.png",
  519. "Metadata/plate_5.png", # All thumbnails present
  520. "Metadata/slice_info.config",
  521. "3D/3dmodel.model",
  522. ]
  523. # Extract plate indices from gcode files (not thumbnails!)
  524. gcode_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".gcode")]
  525. plate_indices = []
  526. for gf in gcode_files:
  527. plate_str = gf[15:-6]
  528. plate_indices.append(int(plate_str))
  529. # Only one gcode file = single plate export
  530. assert len(plate_indices) == 1
  531. assert plate_indices[0] == 5
  532. is_multi_plate = len(plate_indices) > 1
  533. assert is_multi_plate is False
  534. class TestReprintCostCalculation:
  535. """Tests for reprint cost calculation."""
  536. def test_cost_addition_logic(self):
  537. """Test that reprint costs are added correctly."""
  538. # Simulate the cost addition logic
  539. existing_cost = 5.25 # Original print cost
  540. filament_grams = 100.0
  541. cost_per_kg = 25.0 # Default cost
  542. # Calculate additional cost for reprint
  543. additional_cost = round((filament_grams / 1000) * cost_per_kg, 2)
  544. assert additional_cost == 2.50
  545. # Add to existing cost
  546. new_total = round(existing_cost + additional_cost, 2)
  547. assert new_total == 7.75
  548. def test_cost_addition_with_none_existing(self):
  549. """Test cost addition when existing cost is None."""
  550. existing_cost = None
  551. filament_grams = 200.0
  552. cost_per_kg = 15.0
  553. additional_cost = round((filament_grams / 1000) * cost_per_kg, 2)
  554. assert additional_cost == 3.0
  555. # When existing is None, just use additional
  556. new_total = additional_cost if existing_cost is None else round(existing_cost + additional_cost, 2)
  557. assert new_total == 3.0
  558. def test_cost_with_custom_filament_price(self):
  559. """Test cost calculation with custom filament price."""
  560. filament_grams = 150.0
  561. custom_cost_per_kg = 35.0 # More expensive filament
  562. cost = round((filament_grams / 1000) * custom_cost_per_kg, 2)
  563. assert cost == 5.25
  564. def test_multiple_reprints_accumulate(self):
  565. """Test that multiple reprints accumulate costs correctly."""
  566. filament_grams = 100.0
  567. cost_per_kg = 20.0
  568. single_print_cost = round((filament_grams / 1000) * cost_per_kg, 2)
  569. assert single_print_cost == 2.0
  570. # After 3 prints (1 original + 2 reprints)
  571. total_after_3_prints = round(single_print_cost * 3, 2)
  572. assert total_after_3_prints == 6.0
  573. class TestGcodeHeaderFilamentUsage:
  574. """ThreeMFParser pulls total filament usage from the produced 3MF's G-code
  575. header. Some slicer-sidecar builds leave the X-Filament-Used-* response
  576. headers unset, so the slice would otherwise report "0 g" for a real
  577. multi-hour print."""
  578. @staticmethod
  579. def _make_3mf(gcode_header: str) -> str:
  580. import tempfile
  581. import zipfile
  582. fd, path = tempfile.mkstemp(suffix=".3mf")
  583. import os
  584. os.close(fd)
  585. with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as zf:
  586. zf.writestr("3D/3dmodel.model", "<model/>")
  587. zf.writestr("Metadata/plate_1.gcode", gcode_header + "\nG1 X0 Y0\n")
  588. return path
  589. def test_extracts_filament_weight_and_length_from_header(self):
  590. from backend.app.services.archive import ThreeMFParser
  591. header = (
  592. "; HEADER_BLOCK_START\n"
  593. "; BambuStudio 02.06.00.51\n"
  594. "; total layer number: 503\n"
  595. "; total filament length [mm] : 41661.40\n"
  596. "; total filament volume [cm^3] : 100207.42\n"
  597. "; total filament weight [g] : 126.26\n"
  598. )
  599. meta = ThreeMFParser(self._make_3mf(header)).parse()
  600. assert meta.get("filament_used_grams") == 126.26
  601. assert meta.get("filament_used_mm") == 41661.40
  602. assert meta.get("total_layers") == 503
  603. def test_no_filament_keys_when_header_lacks_them(self):
  604. from backend.app.services.archive import ThreeMFParser
  605. meta = ThreeMFParser(self._make_3mf("; total layer number: 10\n")).parse()
  606. assert "filament_used_grams" not in meta
  607. assert "filament_used_mm" not in meta