test_spoolman_tracking.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. """Unit tests for Spoolman tracking service helpers."""
  2. import json
  3. from types import SimpleNamespace
  4. from unittest.mock import AsyncMock, MagicMock, patch
  5. import pytest
  6. from backend.app.services.spoolman_tracking import (
  7. _apply_spool_types_to_archive,
  8. _get_fallback_spool_tag,
  9. _global_tray_id_to_ams_slot,
  10. _hash_serial_to_hex32,
  11. _resolve_global_tray_id,
  12. _resolve_spool_tag,
  13. build_ams_tray_lookup,
  14. store_print_data,
  15. )
  16. class TestResolveSpoolTag:
  17. """Tests for _resolve_spool_tag()."""
  18. def test_prefers_tray_uuid_over_tag_uid(self):
  19. tray = {"tray_uuid": "A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4", "tag_uid": "DEADBEEF"}
  20. assert _resolve_spool_tag(tray) == "A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4"
  21. def test_falls_back_to_tag_uid_when_no_uuid(self):
  22. tray = {"tray_uuid": "", "tag_uid": "DEADBEEF"}
  23. assert _resolve_spool_tag(tray) == "DEADBEEF"
  24. def test_falls_back_to_tag_uid_when_uuid_zero(self):
  25. tray = {"tray_uuid": "00000000000000000000000000000000", "tag_uid": "DEADBEEF"}
  26. assert _resolve_spool_tag(tray) == "DEADBEEF"
  27. def test_rejects_zero_tag_uid(self):
  28. tray = {"tray_uuid": "", "tag_uid": "0000000000000000"}
  29. assert _resolve_spool_tag(tray) == ""
  30. def test_uses_fallback_tag_when_ids_missing(self):
  31. tray = {"tray_uuid": "", "tag_uid": ""}
  32. # global_tray_id 0 -> ams_id 0, tray_id 0
  33. assert _resolve_spool_tag(tray, "01P00A000000000", 0) == "ABA7845700000000"
  34. def test_uses_fallback_tag_when_ids_zero(self):
  35. tray = {"tray_uuid": "00000000000000000000000000000000", "tag_uid": "0000000000000000"}
  36. # global_tray_id 5 -> ams_id 1, tray_id 1
  37. assert _resolve_spool_tag(tray, "01P00A000000000", 5) == "ABA7845700010001"
  38. def test_prefers_tray_uuid_over_fallback_when_non_zero(self):
  39. tray = {"tray_uuid": "A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4", "tag_uid": ""}
  40. assert _resolve_spool_tag(tray, "01P00A000000000", 0) == "A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4"
  41. def test_empty_both(self):
  42. tray = {"tray_uuid": "", "tag_uid": ""}
  43. assert _resolve_spool_tag(tray) == ""
  44. def test_missing_keys(self):
  45. assert _resolve_spool_tag({}) == ""
  46. def test_zero_uuid_no_tag(self):
  47. tray = {"tray_uuid": "00000000000000000000000000000000", "tag_uid": ""}
  48. assert _resolve_spool_tag(tray) == ""
  49. class TestResolveGlobalTrayId:
  50. """Tests for _resolve_global_tray_id()."""
  51. def test_default_mapping(self):
  52. """slot 1 -> tray 0, slot 2 -> tray 1, etc."""
  53. assert _resolve_global_tray_id(1, None) == 0
  54. assert _resolve_global_tray_id(2, None) == 1
  55. assert _resolve_global_tray_id(4, None) == 3
  56. def test_custom_mapping(self):
  57. """Custom slot_to_tray overrides default."""
  58. mapping = [5, 2, -1, 0]
  59. assert _resolve_global_tray_id(1, mapping) == 5
  60. assert _resolve_global_tray_id(2, mapping) == 2
  61. assert _resolve_global_tray_id(4, mapping) == 0
  62. def test_unmapped_slot(self):
  63. """Slot with -1 in mapping uses default."""
  64. mapping = [5, -1, 2, 0]
  65. assert _resolve_global_tray_id(2, mapping) == 1 # default: slot 2 -> tray 1
  66. def test_slot_beyond_mapping(self):
  67. """Slot beyond mapping length uses default."""
  68. mapping = [5, 2]
  69. assert _resolve_global_tray_id(3, mapping) == 2 # default: slot 3 -> tray 2
  70. def test_empty_mapping(self):
  71. mapping = []
  72. assert _resolve_global_tray_id(1, mapping) == 0
  73. class TestFallbackTagHelpers:
  74. """Tests for frontend-mirrored fallback tag helpers."""
  75. def test_hash_serial_matches_frontend_algorithm(self):
  76. assert _hash_serial_to_hex32("01P00A000000000") == "ABA78457"
  77. # Frontend trims and uppercases before hashing
  78. assert _hash_serial_to_hex32(" 01p00a000000000 ") == "ABA78457"
  79. def test_global_tray_to_ams_slot_standard_ams(self):
  80. assert _global_tray_id_to_ams_slot(0) == (0, 0)
  81. assert _global_tray_id_to_ams_slot(7) == (1, 3)
  82. def test_global_tray_to_ams_slot_ams_ht(self):
  83. assert _global_tray_id_to_ams_slot(128) == (128, 0)
  84. assert _global_tray_id_to_ams_slot(135) == (135, 0)
  85. def test_global_tray_to_ams_slot_external(self):
  86. assert _global_tray_id_to_ams_slot(254) == (255, 0)
  87. assert _global_tray_id_to_ams_slot(255) == (255, 1)
  88. def test_get_fallback_spool_tag_standard(self):
  89. assert _get_fallback_spool_tag("01P00A000000000", 5) == "ABA7845700010001"
  90. def test_get_fallback_spool_tag_ams_ht(self):
  91. assert _get_fallback_spool_tag("01P00A000000000", 128) == "ABA7845700800000"
  92. def test_get_fallback_spool_tag_external(self):
  93. assert _get_fallback_spool_tag("01P00A000000000", 255) == "ABA7845700FF0001"
  94. class TestBuildAmsTrayLookup:
  95. """Tests for build_ams_tray_lookup()."""
  96. def test_single_ams_unit(self):
  97. raw = {
  98. "ams": [
  99. {
  100. "id": 0,
  101. "tray": [
  102. {"id": 0, "tray_uuid": "AAA", "tag_uid": "111", "tray_type": "PLA"},
  103. {"id": 1, "tray_uuid": "BBB", "tag_uid": "222", "tray_type": "ABS"},
  104. ],
  105. }
  106. ]
  107. }
  108. lookup = build_ams_tray_lookup(raw)
  109. assert lookup[0] == {"tray_uuid": "AAA", "tag_uid": "111", "tray_type": "PLA"}
  110. assert lookup[1] == {"tray_uuid": "BBB", "tag_uid": "222", "tray_type": "ABS"}
  111. def test_multiple_ams_units(self):
  112. raw = {
  113. "ams": [
  114. {"id": 0, "tray": [{"id": 0, "tray_uuid": "A", "tag_uid": "", "tray_type": "PLA"}]},
  115. {"id": 1, "tray": [{"id": 0, "tray_uuid": "B", "tag_uid": "", "tray_type": "PETG"}]},
  116. ]
  117. }
  118. lookup = build_ams_tray_lookup(raw)
  119. assert 0 in lookup # AMS 0, tray 0
  120. assert 4 in lookup # AMS 1, tray 0 (1*4+0)
  121. assert lookup[4]["tray_uuid"] == "B"
  122. def test_external_spool(self):
  123. raw = {
  124. "ams": [],
  125. "vt_tray": [{"tray_uuid": "EXT", "tag_uid": "X", "tray_type": "TPU"}],
  126. }
  127. lookup = build_ams_tray_lookup(raw)
  128. assert 254 in lookup
  129. assert lookup[254]["tray_type"] == "TPU"
  130. def test_empty_external_spool_skipped(self):
  131. raw = {"ams": [], "vt_tray": [{"tray_type": ""}]}
  132. lookup = build_ams_tray_lookup(raw)
  133. assert 254 not in lookup
  134. def test_no_ams_data(self):
  135. assert build_ams_tray_lookup({}) == {}
  136. assert build_ams_tray_lookup({"ams": []}) == {}
  137. def test_missing_fields_default(self):
  138. raw = {"ams": [{"id": 0, "tray": [{"id": 0}]}]}
  139. lookup = build_ams_tray_lookup(raw)
  140. assert lookup[0] == {"tray_uuid": "", "tag_uid": "", "tray_type": ""}
  141. class TestStorePrintData:
  142. """Tests for store_print_data()."""
  143. @pytest.mark.asyncio
  144. async def test_prefers_explicit_ams_mapping_over_queue_mapping(self):
  145. db = AsyncMock()
  146. # store_print_data now queries the queue item unconditionally (to pick up
  147. # plate_id for multi-plate 3MFs, #1697), then deletes any stale spoolman
  148. # row before inserting the new one. Two execute calls in that order.
  149. queue_item = SimpleNamespace(ams_mapping=json.dumps([2, -1, -1, -1]), plate_id=None)
  150. queue_result = MagicMock()
  151. queue_result.scalar_one_or_none.return_value = queue_item
  152. delete_result = MagicMock()
  153. db.execute = AsyncMock(side_effect=[queue_result, delete_result])
  154. db.add = MagicMock()
  155. db.commit = AsyncMock()
  156. printer_manager = MagicMock()
  157. printer_manager.get_status.return_value = SimpleNamespace(
  158. raw_data={"ams": [{"id": 0, "tray": [{"id": 0, "tray_type": "PLA"}, {"id": 1, "tray_type": "PLA"}]}]}
  159. )
  160. mock_settings = MagicMock()
  161. mock_path = MagicMock()
  162. mock_path.exists.return_value = True
  163. mock_settings.base_dir.__truediv__.return_value = mock_path
  164. with (
  165. patch("backend.app.services.spoolman_tracking.app_settings", mock_settings),
  166. patch("backend.app.api.routes.settings.get_setting", AsyncMock(side_effect=["true", "true"])),
  167. patch(
  168. "backend.app.utils.threemf_tools.extract_filament_usage_from_3mf",
  169. return_value=[{"slot_id": 1, "used_g": 3.83, "type": "PLA", "color": "#FF0000"}],
  170. ),
  171. patch("backend.app.utils.threemf_tools.extract_layer_filament_usage_from_3mf", return_value=None),
  172. patch("backend.app.utils.threemf_tools.extract_filament_properties_from_3mf", return_value={}),
  173. ):
  174. await store_print_data(
  175. printer_id=1,
  176. archive_id=15,
  177. file_path="archives/test.3mf",
  178. db=db,
  179. printer_manager=printer_manager,
  180. ams_mapping=[1, -1, -1, -1],
  181. )
  182. db.add.assert_called_once()
  183. tracking = db.add.call_args.args[0]
  184. assert tracking.slot_to_tray == [1, -1, -1, -1]
  185. assert db.execute.await_count == 2
  186. @pytest.mark.asyncio
  187. async def test_passes_queue_plate_id_to_3mf_extract(self):
  188. """Multi-plate 3MFs queued for one plate must only count that plate's filament (#1697)."""
  189. db = AsyncMock()
  190. queue_item = SimpleNamespace(ams_mapping=None, plate_id=2)
  191. queue_result = MagicMock()
  192. queue_result.scalar_one_or_none.return_value = queue_item
  193. delete_result = MagicMock()
  194. db.execute = AsyncMock(side_effect=[queue_result, delete_result])
  195. db.add = MagicMock()
  196. db.commit = AsyncMock()
  197. printer_manager = MagicMock()
  198. printer_manager.get_status.return_value = SimpleNamespace(
  199. raw_data={"ams": [{"id": 0, "tray": [{"id": 0, "tray_type": "PLA"}]}]}
  200. )
  201. mock_settings = MagicMock()
  202. mock_path = MagicMock()
  203. mock_path.exists.return_value = True
  204. mock_settings.base_dir.__truediv__.return_value = mock_path
  205. extract_mock = MagicMock(return_value=[{"slot_id": 1, "used_g": 190.0, "type": "PETG", "color": "#888888"}])
  206. with (
  207. patch("backend.app.services.spoolman_tracking.app_settings", mock_settings),
  208. patch("backend.app.api.routes.settings.get_setting", AsyncMock(side_effect=["true", "true"])),
  209. patch("backend.app.utils.threemf_tools.extract_filament_usage_from_3mf", extract_mock),
  210. patch("backend.app.utils.threemf_tools.extract_layer_filament_usage_from_3mf", return_value=None),
  211. patch("backend.app.utils.threemf_tools.extract_filament_properties_from_3mf", return_value={}),
  212. ):
  213. await store_print_data(
  214. printer_id=1,
  215. archive_id=15,
  216. file_path="archives/test.3mf",
  217. db=db,
  218. printer_manager=printer_manager,
  219. ams_mapping=[1, -1, -1, -1],
  220. )
  221. # plate_id=2 must be passed as the second positional arg
  222. assert extract_mock.call_count == 1
  223. assert extract_mock.call_args.args[1] == 2
  224. class TestApplySpoolTypesToArchive:
  225. """_apply_spool_types_to_archive() rewrites the archive's filament_type
  226. from the resolved Spoolman spools' materials (#2563)."""
  227. @staticmethod
  228. async def _make_archive(db, filament_type):
  229. from backend.app.models.archive import PrintArchive
  230. archive = PrintArchive(
  231. filename="job.gcode.3mf",
  232. file_path="archive/job.3mf",
  233. file_size=1,
  234. filament_type=filament_type,
  235. )
  236. db.add(archive)
  237. await db.commit()
  238. await db.refresh(archive)
  239. return archive
  240. @pytest.mark.asyncio
  241. async def test_overwrites_sliced_type_with_spool_material(self, db_session):
  242. """PLA-sliced job mapped to a PETG Spoolman spool → recorded as PETG."""
  243. archive = await self._make_archive(db_session, "PLA")
  244. usage = [{"slot_id": 1, "used_g": 2.9}]
  245. await _apply_spool_types_to_archive(db_session, archive.id, usage, {1: "PETG"})
  246. await db_session.refresh(archive)
  247. assert archive.filament_type == "PETG"
  248. @pytest.mark.asyncio
  249. async def test_partial_match_leaves_type_untouched(self, db_session):
  250. """All-or-nothing: an unmatched used slot means no rewrite."""
  251. archive = await self._make_archive(db_session, "PLA,PLA")
  252. usage = [{"slot_id": 1, "used_g": 5.0}, {"slot_id": 2, "used_g": 3.0}]
  253. await _apply_spool_types_to_archive(db_session, archive.id, usage, {1: "PETG"})
  254. await db_session.refresh(archive)
  255. assert archive.filament_type == "PLA,PLA"
  256. @pytest.mark.asyncio
  257. async def test_empty_materials_is_noop(self, db_session):
  258. archive = await self._make_archive(db_session, "PLA")
  259. await _apply_spool_types_to_archive(db_session, archive.id, [{"slot_id": 1, "used_g": 2.9}], {})
  260. await db_session.refresh(archive)
  261. assert archive.filament_type == "PLA"