test_spoolman_service.py 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309
  1. """Unit tests for Spoolman service.
  2. These tests specifically target the sync_ams_tray method's disable_weight_sync
  3. functionality that controls whether remaining_weight is updated.
  4. Also includes tests for is_bambu_lab_spool RFID detection.
  5. """
  6. import json
  7. from unittest.mock import AsyncMock, Mock, patch
  8. import pytest
  9. from backend.app.services.color_catalog_lookup import CatalogColor
  10. from backend.app.services.spoolman import AMSTray, SpoolmanClient, init_spoolman_client
  11. class _NoCatalog:
  12. """A DB session whose colour catalogue has no row for anything.
  13. ``sync_ams_tray`` resolves the roll's colour from the catalogue now (#2907),
  14. so it needs a session. These tests predate the catalogue and were written
  15. against the state where it cannot name the colour, which is this.
  16. """
  17. async def execute(self, *_args, **_kwargs):
  18. class _Result:
  19. @staticmethod
  20. def scalar_one_or_none():
  21. return None
  22. return _Result()
  23. class _BlackCatalog:
  24. """A DB session whose colour catalogue answers "Black" for anything.
  25. The fake ignores the query, so it stands for the trap rather than the lookup:
  26. a catalogue that would name a clear roll's ``000000`` if it were asked.
  27. """
  28. async def execute(self, *_args, **_kwargs):
  29. entry = type("_Entry", (), {"color_name": "Black", "extra_colors": None, "effect_type": None})()
  30. class _Result:
  31. @staticmethod
  32. def scalar_one_or_none():
  33. return entry
  34. return _Result()
  35. class TestIsBambuLabSpool:
  36. """Tests for is_bambu_lab_spool — detects BL spools via RFID hardware identifiers only."""
  37. @pytest.fixture
  38. def client(self):
  39. return SpoolmanClient("http://localhost:7912")
  40. def test_valid_tray_uuid_returns_true(self, client):
  41. """A non-zero 32-char hex tray_uuid identifies a BL spool."""
  42. assert client.is_bambu_lab_spool("A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4") is True
  43. def test_valid_tag_uid_returns_true(self, client):
  44. """A non-zero 16-char hex tag_uid identifies a BL spool (fallback)."""
  45. assert client.is_bambu_lab_spool("", tag_uid="A1B2C3D4E5F6A1B2") is True
  46. def test_zero_tray_uuid_returns_false(self, client):
  47. """All-zero tray_uuid means no RFID tag read."""
  48. assert client.is_bambu_lab_spool("00000000000000000000000000000000") is False
  49. def test_zero_tag_uid_returns_false(self, client):
  50. """All-zero tag_uid means no RFID tag read."""
  51. assert client.is_bambu_lab_spool("", tag_uid="0000000000000000") is False
  52. def test_empty_identifiers_returns_false(self, client):
  53. """No identifiers means no BL spool."""
  54. assert client.is_bambu_lab_spool("") is False
  55. assert client.is_bambu_lab_spool("", tag_uid="") is False
  56. def test_tray_info_idx_ignored(self, client):
  57. """tray_info_idx is NOT a reliable BL indicator — third-party spools
  58. using Bambu generic presets also have GF-prefixed tray_info_idx values."""
  59. # Third-party spool with Bambu preset but no RFID identifiers
  60. assert client.is_bambu_lab_spool("", tray_info_idx="GFA00") is False
  61. assert client.is_bambu_lab_spool("", tray_info_idx="GFB00") is False
  62. assert client.is_bambu_lab_spool("", tray_info_idx="GFSA02_04") is False
  63. def test_tray_info_idx_with_valid_uuid_returns_true(self, client):
  64. """BL spool with both RFID UUID and preset ID — detected by UUID."""
  65. assert (
  66. client.is_bambu_lab_spool(
  67. "A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4",
  68. tray_info_idx="GFA00",
  69. )
  70. is True
  71. )
  72. def test_tray_uuid_preferred_over_tag_uid(self, client):
  73. """tray_uuid is checked before tag_uid (both valid)."""
  74. assert (
  75. client.is_bambu_lab_spool(
  76. "A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4",
  77. tag_uid="A1B2C3D4E5F6A1B2",
  78. )
  79. is True
  80. )
  81. def test_short_tray_uuid_returns_false(self, client):
  82. """UUID must be exactly 32 hex chars."""
  83. assert client.is_bambu_lab_spool("A1B2C3D4") is False
  84. def test_non_hex_tray_uuid_returns_false(self, client):
  85. """UUID must be valid hex."""
  86. assert client.is_bambu_lab_spool("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ") is False
  87. class TestSpoolmanClient:
  88. """Tests for SpoolmanClient class."""
  89. @pytest.fixture
  90. def client(self):
  91. """Create a SpoolmanClient instance."""
  92. return SpoolmanClient("http://localhost:7912")
  93. @pytest.fixture
  94. def sample_tray(self):
  95. """Create a sample AMSTray for testing."""
  96. return AMSTray(
  97. ams_id=0,
  98. tray_id=0,
  99. tray_type="PLA",
  100. tray_sub_brands="PLA Basic",
  101. tray_color="FF0000FF",
  102. remain=50,
  103. tag_uid="",
  104. tray_uuid="A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4",
  105. tray_info_idx="GFA00",
  106. tray_weight=1000,
  107. )
  108. @pytest.fixture
  109. def existing_spool(self):
  110. """Create a mock existing spool response."""
  111. return {
  112. "id": 42,
  113. "remaining_weight": 800,
  114. "extra": {"tag": '"A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4"'},
  115. "filament": {"id": 1, "name": "PLA Red", "material": "PLA"},
  116. }
  117. @pytest.fixture
  118. def mock_filament(self):
  119. """Create a mock filament response."""
  120. return {"id": 1, "name": "PLA Basic", "material": "PLA"}
  121. # ========================================================================
  122. # Tests for sync_ams_tray with disable_weight_sync
  123. # ========================================================================
  124. @pytest.mark.asyncio
  125. async def test_sync_ams_tray_updates_weight_by_default(self, client, sample_tray, existing_spool):
  126. """Verify sync_ams_tray updates remaining_weight by default."""
  127. with (
  128. patch.object(client, "find_spool_by_tag", AsyncMock(return_value=existing_spool)),
  129. patch.object(client, "update_spool", AsyncMock(return_value={"id": 42})) as mock_update,
  130. ):
  131. await client.sync_ams_tray(sample_tray, "TestPrinter", _NoCatalog())
  132. mock_update.assert_called_once()
  133. call_kwargs = mock_update.call_args.kwargs
  134. assert "remaining_weight" in call_kwargs
  135. assert call_kwargs["remaining_weight"] == 500.0 # 50% of 1000g
  136. assert "location" not in call_kwargs
  137. @pytest.mark.asyncio
  138. async def test_sync_ams_tray_skips_weight_when_disabled(self, client, sample_tray, existing_spool):
  139. """Verify sync_ams_tray skips remaining_weight when disable_weight_sync=True."""
  140. with (
  141. patch.object(client, "find_spool_by_tag", AsyncMock(return_value=existing_spool)),
  142. patch.object(client, "update_spool", AsyncMock(return_value={"id": 42})) as mock_update,
  143. ):
  144. await client.sync_ams_tray(sample_tray, "TestPrinter", _NoCatalog(), disable_weight_sync=True)
  145. mock_update.assert_called_once()
  146. call_kwargs = mock_update.call_args.kwargs
  147. # remaining_weight should be None (not updated)
  148. assert call_kwargs.get("remaining_weight") is None
  149. # location must never be written by Bambuddy — user-managed in Spoolman
  150. assert "location" not in call_kwargs
  151. @pytest.mark.asyncio
  152. async def test_sync_ams_tray_new_spool_always_includes_weight(self, client, sample_tray, mock_filament):
  153. """Verify new spool creation always includes remaining_weight even when disabled."""
  154. with (
  155. patch.object(client, "find_spool_by_tag", AsyncMock(return_value=None)),
  156. patch.object(client, "_find_or_create_filament", AsyncMock(return_value=mock_filament)),
  157. patch.object(client, "create_spool", AsyncMock(return_value={"id": 99})) as mock_create,
  158. ):
  159. await client.sync_ams_tray(sample_tray, "TestPrinter", _NoCatalog(), disable_weight_sync=True)
  160. mock_create.assert_called_once()
  161. call_kwargs = mock_create.call_args.kwargs
  162. # New spools should ALWAYS include remaining_weight
  163. assert "remaining_weight" in call_kwargs
  164. assert call_kwargs["remaining_weight"] == 500.0 # 50% of 1000g
  165. @pytest.mark.asyncio
  166. async def test_a_new_spool_carries_the_catalogue_colour_name(self, client, sample_tray, mock_filament):
  167. """Where #1357 put the colour name on this side: Spoolman has no color_name
  168. on Filament, so it lives in spool.extra.bambu_color_name and
  169. _map_spoolman_spool reads that first. The AMS path never wrote it, which
  170. is why the colour ended up in the filament name and the product line fell
  171. out of the subtype (#2907, round three)."""
  172. with (
  173. patch.object(client, "find_spool_by_tag", AsyncMock(return_value=None)),
  174. patch.object(client, "_find_or_create_filament", AsyncMock(return_value=mock_filament)) as mock_find,
  175. patch.object(client, "create_spool", AsyncMock(return_value={"id": 99})) as mock_create,
  176. ):
  177. await client.sync_ams_tray(sample_tray, "TestPrinter", _BlackCatalog())
  178. # The same answer goes to the filament lookup and onto the spool.
  179. assert mock_find.call_args.args[1] == CatalogColor("Black")
  180. extra = mock_create.call_args.kwargs["extra"]
  181. assert extra["bambu_color_name"] == json.dumps("Black")
  182. assert "tag" in extra
  183. @pytest.mark.asyncio
  184. async def test_no_catalogue_row_means_no_colour_name_rather_than_an_empty_one(
  185. self, client, sample_tray, mock_filament
  186. ):
  187. """An empty string would read back as a name. Leaving the key out lets
  188. _map_spoolman_spool fall through to the subtype, as it did before."""
  189. with (
  190. patch.object(client, "find_spool_by_tag", AsyncMock(return_value=None)),
  191. patch.object(client, "_find_or_create_filament", AsyncMock(return_value=mock_filament)),
  192. patch.object(client, "create_spool", AsyncMock(return_value={"id": 99})) as mock_create,
  193. ):
  194. await client.sync_ams_tray(sample_tray, "TestPrinter", _NoCatalog())
  195. assert "bambu_color_name" not in mock_create.call_args.kwargs["extra"]
  196. @pytest.mark.asyncio
  197. async def test_sync_ams_tray_does_not_write_location(self, client, sample_tray, existing_spool):
  198. """Verify sync_ams_tray never writes location= to Spoolman (user-managed field)."""
  199. with (
  200. patch.object(client, "find_spool_by_tag", AsyncMock(return_value=existing_spool)),
  201. patch.object(client, "update_spool", AsyncMock(return_value={"id": 42})) as mock_update,
  202. ):
  203. await client.sync_ams_tray(sample_tray, "My Printer", _NoCatalog(), disable_weight_sync=True)
  204. call_kwargs = mock_update.call_args.kwargs
  205. # Bambuddy must never auto-set spool.location — it is user-managed in Spoolman
  206. assert "location" not in call_kwargs
  207. # ========================================================================
  208. # T6: non-BL spool with custom RFID (H5 guard)
  209. # ========================================================================
  210. @pytest.mark.asyncio
  211. async def test_sync_ams_tray_non_bl_rfid_find_or_create_error_returns_none(self, client):
  212. """Non-BL spool with custom RFID: find_or_create_filament failure returns None, not raises.
  213. A third-party spool whose tag_uid is not exactly 16 hex chars is not
  214. identified as BL. sync_ams_tray must catch find_or_create_filament
  215. errors and return None instead of propagating the exception.
  216. """
  217. from backend.app.services.spoolman import SpoolmanUnavailableError
  218. # 8-char tag → spool_tag is set, but is_bambu_lab_spool returns False
  219. tray = AMSTray(
  220. ams_id=0,
  221. tray_id=2,
  222. tray_type="PLA",
  223. tray_sub_brands="eSun PLA+",
  224. tray_color="00FF00FF",
  225. remain=50,
  226. tag_uid="AABB1234",
  227. tray_uuid="",
  228. tray_info_idx="",
  229. tray_weight=1000,
  230. )
  231. with (
  232. patch.object(client, "find_spool_by_tag", AsyncMock(return_value=None)),
  233. patch.object(
  234. client,
  235. "find_or_create_filament",
  236. AsyncMock(side_effect=SpoolmanUnavailableError("timeout")),
  237. ),
  238. ):
  239. result = await client.sync_ams_tray(tray, "TestPrinter", _NoCatalog())
  240. assert result is None
  241. # ========================================================================
  242. # T7: hint path uncached — get_spool(hint) called when not in cached_spools
  243. # ========================================================================
  244. @pytest.mark.asyncio
  245. async def test_sync_ams_tray_hint_uncached_calls_get_spool(self, client):
  246. """No-RFID path: when hint spool is absent from cached_spools, get_spool is called."""
  247. tray = AMSTray(
  248. ams_id=0,
  249. tray_id=3,
  250. tray_type="PETG",
  251. tray_sub_brands="Generic PETG",
  252. tray_color="0000FFFF",
  253. remain=75,
  254. tag_uid="",
  255. tray_uuid="",
  256. tray_info_idx="",
  257. tray_weight=1000,
  258. )
  259. # cached_spools exists but does NOT contain spool 99
  260. cached_spools = [{"id": 1, "extra": {}}]
  261. fetched_spool = {"id": 99, "extra": {}}
  262. with (
  263. patch.object(client, "get_spool", AsyncMock(return_value=fetched_spool)) as mock_get,
  264. patch.object(client, "update_spool", AsyncMock(return_value=fetched_spool)),
  265. ):
  266. result = await client.sync_ams_tray(
  267. tray,
  268. "TestPrinter",
  269. _NoCatalog(),
  270. cached_spools=cached_spools,
  271. spoolman_spool_id_hint=99,
  272. )
  273. assert result is not None
  274. mock_get.assert_awaited_once_with(99)
  275. # ========================================================================
  276. # T8: hint ignored when RFID tag is present
  277. # ========================================================================
  278. @pytest.mark.asyncio
  279. async def test_sync_ams_tray_rfid_takes_precedence_over_hint(self, client, existing_spool):
  280. """When tray_uuid is set, the RFID path is used and the hint is never consulted."""
  281. tray = AMSTray(
  282. ams_id=0,
  283. tray_id=4,
  284. tray_type="PLA",
  285. tray_sub_brands="PLA Basic",
  286. tray_color="FF0000FF",
  287. remain=50,
  288. tag_uid="",
  289. tray_uuid="A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4",
  290. tray_info_idx="GFA00",
  291. tray_weight=1000,
  292. )
  293. with (
  294. patch.object(client, "find_spool_by_tag", AsyncMock(return_value=existing_spool)),
  295. patch.object(client, "update_spool", AsyncMock(return_value={"id": 42})),
  296. patch.object(client, "get_spool", AsyncMock()) as mock_get_spool,
  297. ):
  298. result = await client.sync_ams_tray(
  299. tray,
  300. "TestPrinter",
  301. _NoCatalog(),
  302. spoolman_spool_id_hint=99,
  303. )
  304. assert result is not None
  305. # hint path (get_spool) must NOT be called when RFID is present
  306. mock_get_spool.assert_not_called()
  307. @pytest.mark.asyncio
  308. async def test_sync_ams_tray_non_bambu_no_rfid_returns_none(self, client):
  309. """Third-party spool without any RFID and no hint returns None."""
  310. # Non-BL spool: no tray_uuid, no tag_uid, no spoolman_spool_id_hint → nothing to match
  311. tray = AMSTray(
  312. ams_id=0,
  313. tray_id=0,
  314. tray_type="PLA",
  315. tray_sub_brands="Third Party PLA",
  316. tray_color="FF0000FF",
  317. remain=50,
  318. tag_uid="",
  319. tray_uuid="",
  320. tray_info_idx="",
  321. tray_weight=1000,
  322. )
  323. result = await client.sync_ams_tray(tray, "TestPrinter", _NoCatalog())
  324. assert result is None
  325. @pytest.mark.asyncio
  326. async def test_sync_ams_tray_hint_updates_spool_without_rfid(self, client):
  327. """No-RFID fallback: spool_id_hint from local slot-assignment table updates the spool."""
  328. tray = AMSTray(
  329. ams_id=0,
  330. tray_id=0,
  331. tray_type="PLA",
  332. tray_sub_brands="Generic PLA",
  333. tray_color="00FF00FF",
  334. remain=80,
  335. tag_uid="",
  336. tray_uuid="",
  337. tray_info_idx="",
  338. tray_weight=1000,
  339. )
  340. cached_spools = [{"id": 99, "extra": {}}]
  341. with patch.object(client, "update_spool", new_callable=AsyncMock) as mock_update:
  342. mock_update.return_value = {"id": 99}
  343. result = await client.sync_ams_tray(
  344. tray, "TestPrinter", _NoCatalog(), cached_spools=cached_spools, spoolman_spool_id_hint=99
  345. )
  346. assert result is not None
  347. assert result["id"] == 99
  348. mock_update.assert_called_once()
  349. call_kwargs = mock_update.call_args.kwargs
  350. assert "location" not in call_kwargs
  351. @pytest.mark.asyncio
  352. async def test_sync_ams_tray_weight_calculation(self, client, existing_spool):
  353. """Verify remaining weight is calculated correctly for various percentages."""
  354. test_cases = [
  355. (100, 1000, 1000.0), # Full spool
  356. (50, 1000, 500.0), # Half spool
  357. (25, 1000, 250.0), # Quarter spool
  358. (0, 1000, 0.0), # Empty spool
  359. (75, 500, 375.0), # Different spool weight
  360. ]
  361. for remain, weight, expected in test_cases:
  362. tray = AMSTray(
  363. ams_id=0,
  364. tray_id=0,
  365. tray_type="PLA",
  366. tray_sub_brands="PLA Basic",
  367. tray_color="FF0000FF",
  368. remain=remain,
  369. tag_uid="",
  370. tray_uuid="A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4",
  371. tray_info_idx="GFA00",
  372. tray_weight=weight,
  373. )
  374. with (
  375. patch.object(client, "find_spool_by_tag", AsyncMock(return_value=existing_spool)),
  376. patch.object(client, "update_spool", AsyncMock(return_value={"id": 42})) as mock_update,
  377. ):
  378. await client.sync_ams_tray(tray, "TestPrinter", _NoCatalog(), disable_weight_sync=False)
  379. call_kwargs = mock_update.call_args.kwargs
  380. assert call_kwargs["remaining_weight"] == expected, (
  381. f"Expected {expected}g for {remain}% of {weight}g, got {call_kwargs['remaining_weight']}"
  382. )
  383. # ========================================================================
  384. # Tests for caching functionality
  385. # ========================================================================
  386. @pytest.mark.asyncio
  387. async def test_find_spool_by_tag_with_cached_spools(self, client):
  388. """Verify find_spool_by_tag uses cached spools when provided (no API call)."""
  389. cached = [
  390. {"id": 1, "extra": {"tag": '"ABC123"'}},
  391. {"id": 2, "extra": {"tag": '"XYZ789"'}},
  392. ]
  393. with patch.object(client, "get_spools", AsyncMock()) as mock_get:
  394. result = await client.find_spool_by_tag("ABC123", cached_spools=cached)
  395. assert result["id"] == 1
  396. mock_get.assert_not_called() # Should NOT call get_spools
  397. @pytest.mark.asyncio
  398. async def test_find_spool_by_tag_without_cached_spools(self, client):
  399. """Verify find_spool_by_tag fetches spools when cache not provided."""
  400. mock_spools = [{"id": 1, "extra": {"tag": '"ABC123"'}}]
  401. with patch.object(client, "get_spools", AsyncMock(return_value=mock_spools)) as mock_get:
  402. result = await client.find_spool_by_tag("ABC123")
  403. assert result["id"] == 1
  404. mock_get.assert_called_once() # Should call get_spools
  405. @pytest.mark.asyncio
  406. async def test_sync_ams_tray_with_cached_spools(self, client, sample_tray, existing_spool):
  407. """Verify sync_ams_tray passes cached_spools to find_spool_by_tag."""
  408. cached = [existing_spool]
  409. with (
  410. patch.object(client, "get_spools", AsyncMock()) as mock_get,
  411. patch.object(client, "update_spool", AsyncMock(return_value={"id": 42})),
  412. ):
  413. await client.sync_ams_tray(sample_tray, "TestPrinter", _NoCatalog(), cached_spools=cached)
  414. mock_get.assert_not_called() # Should NOT call get_spools
  415. @pytest.mark.asyncio
  416. async def test_get_spools_succeeds_on_first_attempt(self, client):
  417. """Verify get_spools succeeds immediately when no errors occur."""
  418. mock_spools = [{"id": 1}, {"id": 2}]
  419. with patch.object(client, "_get_client") as mock_get_client:
  420. mock_http_client = AsyncMock()
  421. mock_response = Mock()
  422. mock_response.raise_for_status = Mock()
  423. mock_response.json = Mock(return_value=mock_spools)
  424. mock_http_client.get = AsyncMock(return_value=mock_response)
  425. mock_get_client.return_value = mock_http_client
  426. result = await client.get_spools()
  427. assert result == mock_spools
  428. mock_get_client.assert_called_once()
  429. mock_http_client.get.assert_called_once()
  430. @pytest.mark.asyncio
  431. async def test_get_spools_retries_on_connection_error(self, client):
  432. """Verify get_spools retries up to 3 times on connection errors."""
  433. import httpx
  434. mock_spools = [{"id": 1}]
  435. with (
  436. patch.object(client, "_get_client") as mock_get_client,
  437. patch.object(client, "close", AsyncMock()) as mock_close,
  438. patch("asyncio.sleep", AsyncMock()) as mock_sleep,
  439. ):
  440. mock_http_client = AsyncMock()
  441. mock_get_client.return_value = mock_http_client
  442. # First 2 attempts fail with ReadError, 3rd succeeds
  443. mock_response = Mock()
  444. mock_response.raise_for_status = Mock()
  445. mock_response.json = Mock(return_value=mock_spools)
  446. mock_http_client.get = AsyncMock(
  447. side_effect=[
  448. httpx.ReadError("Connection closed"),
  449. httpx.ReadError("Connection closed"),
  450. mock_response,
  451. ]
  452. )
  453. result = await client.get_spools()
  454. assert result == mock_spools
  455. assert mock_get_client.call_count == 3
  456. assert mock_http_client.get.call_count == 3
  457. # Should close client twice (after each failed attempt)
  458. assert mock_close.call_count == 2
  459. # Should sleep twice (after first 2 attempts)
  460. assert mock_sleep.call_count == 2
  461. mock_sleep.assert_called_with(0.5)
  462. @pytest.mark.asyncio
  463. async def test_get_spools_raises_after_3_failed_attempts(self, client):
  464. """Verify get_spools raises SpoolmanUnavailableError after 3 failed connection attempts."""
  465. import httpx
  466. from backend.app.services.spoolman import SpoolmanUnavailableError
  467. with (
  468. patch.object(client, "_get_client", AsyncMock()) as mock_get_client,
  469. patch.object(client, "close", AsyncMock()) as mock_close,
  470. patch("asyncio.sleep", AsyncMock()) as mock_sleep,
  471. ):
  472. mock_http_client = AsyncMock()
  473. mock_get_client.return_value = mock_http_client
  474. # All 3 attempts fail
  475. mock_http_client.get.side_effect = httpx.ReadError("Connection closed")
  476. with pytest.raises(SpoolmanUnavailableError):
  477. await client.get_spools()
  478. assert mock_get_client.call_count == 3
  479. assert mock_http_client.get.call_count == 3
  480. # Should close client twice (after first 2 failed attempts, not after 3rd)
  481. assert mock_close.call_count == 2
  482. # Should sleep twice (after first 2 attempts, not after 3rd)
  483. assert mock_sleep.call_count == 2
  484. @pytest.mark.asyncio
  485. async def test_get_spools_handles_non_connection_errors(self, client):
  486. """Verify get_spools retries on non-connection errors without recreating client."""
  487. import httpx
  488. mock_spools = [{"id": 1}]
  489. with (
  490. patch.object(client, "_get_client") as mock_get_client,
  491. patch.object(client, "close", AsyncMock()) as mock_close,
  492. patch("asyncio.sleep", AsyncMock()) as mock_sleep,
  493. ):
  494. mock_http_client = AsyncMock()
  495. mock_get_client.return_value = mock_http_client
  496. # First attempt fails with HTTP error, 2nd succeeds
  497. mock_response_error = Mock()
  498. mock_response_error.raise_for_status = Mock(
  499. side_effect=httpx.HTTPStatusError("500 Server Error", request=Mock(), response=Mock())
  500. )
  501. mock_response_success = Mock()
  502. mock_response_success.raise_for_status = Mock()
  503. mock_response_success.json = Mock(return_value=mock_spools)
  504. mock_http_client.get = AsyncMock(side_effect=[mock_response_error, mock_response_success])
  505. result = await client.get_spools()
  506. assert result == mock_spools
  507. assert mock_get_client.call_count == 2
  508. # Should NOT close client for HTTP errors (only connection errors)
  509. mock_close.assert_not_called()
  510. # Should sleep once (after first failed attempt)
  511. assert mock_sleep.call_count == 1
  512. # ---------------------------------------------------------------------------
  513. # init_spoolman_client — SSRF guard (B4 / T3)
  514. # ---------------------------------------------------------------------------
  515. class TestInitSpoolmanClientSSRFGuard:
  516. """init_spoolman_client must reject genuinely unsafe URLs before creating a client.
  517. Scope: cloud metadata endpoints, multicast, unspecified, non-http(s) schemes,
  518. and numeric-encoded IP bypasses. Loopback and RFC-1918 private ranges are
  519. explicitly allowed — Bambuddy's primary deployment is LAN-local Spoolman.
  520. """
  521. @pytest.mark.asyncio
  522. async def test_cloud_metadata_raises_value_error(self):
  523. with pytest.raises(ValueError, match="cloud metadata"):
  524. await init_spoolman_client("http://169.254.169.254/latest/meta-data/")
  525. @pytest.mark.asyncio
  526. async def test_multicast_raises_value_error(self):
  527. with pytest.raises(ValueError, match="multicast|unspecified"):
  528. await init_spoolman_client("http://224.0.0.1/")
  529. @pytest.mark.asyncio
  530. async def test_unspecified_raises_value_error(self):
  531. with pytest.raises(ValueError, match="multicast|unspecified"):
  532. await init_spoolman_client("http://0.0.0.0/")
  533. @pytest.mark.asyncio
  534. async def test_numeric_encoded_ip_raises_value_error(self):
  535. # decimal-encoded 127.0.0.1 — libc resolves these but ipaddress doesn't
  536. with pytest.raises(ValueError, match="numeric-encoded"):
  537. await init_spoolman_client("http://2130706433/")
  538. @pytest.mark.asyncio
  539. async def test_non_http_scheme_raises_value_error(self):
  540. with pytest.raises(ValueError, match="http or https"):
  541. await init_spoolman_client("file:///etc/passwd")
  542. @pytest.mark.asyncio
  543. async def test_private_ip_is_allowed(self):
  544. """Regression: RFC-1918 private addresses are the normal LAN topology."""
  545. mock_instance = AsyncMock()
  546. with (
  547. patch("backend.app.services.spoolman._spoolman_client", None),
  548. patch("backend.app.services.spoolman.SpoolmanClient", return_value=mock_instance) as mock_cls,
  549. ):
  550. client = await init_spoolman_client("http://192.168.1.50:7912/")
  551. mock_cls.assert_called_once_with("http://192.168.1.50:7912/")
  552. assert client is mock_instance
  553. @pytest.mark.asyncio
  554. async def test_loopback_ip_is_allowed(self):
  555. """Regression: same-host Spoolman via loopback is a supported topology."""
  556. mock_instance = AsyncMock()
  557. with (
  558. patch("backend.app.services.spoolman._spoolman_client", None),
  559. patch("backend.app.services.spoolman.SpoolmanClient", return_value=mock_instance) as mock_cls,
  560. ):
  561. client = await init_spoolman_client("http://127.0.0.1:7912/")
  562. mock_cls.assert_called_once_with("http://127.0.0.1:7912/")
  563. assert client is mock_instance
  564. @pytest.mark.asyncio
  565. async def test_localhost_hostname_is_allowed(self):
  566. # localhost (hostname, not bare IP) is a supported topology for same-host Spoolman
  567. mock_instance = AsyncMock()
  568. with (
  569. patch("backend.app.services.spoolman._spoolman_client", None),
  570. patch("backend.app.services.spoolman.SpoolmanClient", return_value=mock_instance) as mock_cls,
  571. ):
  572. client = await init_spoolman_client("http://localhost:7912/")
  573. mock_cls.assert_called_once_with("http://localhost:7912/")
  574. assert client is mock_instance
  575. @pytest.mark.asyncio
  576. async def test_public_url_is_allowed(self):
  577. mock_instance = AsyncMock()
  578. with (
  579. patch("backend.app.services.spoolman._spoolman_client", None),
  580. patch("backend.app.services.spoolman.SpoolmanClient", return_value=mock_instance) as mock_cls,
  581. ):
  582. client = await init_spoolman_client("http://spoolman.example.com:7912/")
  583. mock_cls.assert_called_once_with("http://spoolman.example.com:7912/")
  584. assert client is mock_instance
  585. class TestFindOrCreateFilament:
  586. """Tests for SpoolmanClient._find_or_create_filament — the auto-create path
  587. that runs when AMS sync sees an RFID spool that isn't already in Spoolman.
  588. Regression tests for #1309 (Bambu Lab RFID spools getting competitor names
  589. like "3DXTECH™ Black" from the unfiltered SpoolmanDB lookup).
  590. """
  591. @pytest.fixture
  592. def client(self):
  593. return SpoolmanClient("http://localhost:7912")
  594. @pytest.fixture
  595. def tray_pla_black(self):
  596. """A typical Bambu PLA Basic Black RFID read."""
  597. return AMSTray(
  598. ams_id=0,
  599. tray_id=0,
  600. tray_type="PLA",
  601. tray_sub_brands="PLA Basic",
  602. tray_color="000000FF",
  603. remain=100,
  604. tag_uid="",
  605. tray_uuid="A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4",
  606. tray_info_idx="GFA00",
  607. tray_weight=1000,
  608. )
  609. @pytest.fixture
  610. def tray_matte(self):
  611. """The reported roll: PLA Matte Charcoal, same material and hex as PLA Basic Black."""
  612. return AMSTray(
  613. ams_id=0,
  614. tray_id=0,
  615. tray_type="PLA",
  616. tray_sub_brands="PLA Matte",
  617. tray_color="000000FF",
  618. remain=100,
  619. tag_uid="",
  620. tray_uuid="A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4",
  621. tray_info_idx="GFA01",
  622. tray_weight=1000,
  623. )
  624. async def _run(self, client, tray, catalog_color, *, filaments=None, external=None):
  625. with (
  626. patch.object(client, "ensure_bambu_vendor", AsyncMock(return_value=2)),
  627. patch.object(client, "get_filaments", AsyncMock(return_value=filaments or [])),
  628. patch.object(client, "get_external_filaments", AsyncMock(return_value=external or [])) as mock_external,
  629. patch.object(client, "create_filament", AsyncMock(return_value={"id": 99})) as mock_create,
  630. ):
  631. result = await client._find_or_create_filament(tray, catalog_color)
  632. return result, mock_external, mock_create
  633. @pytest.mark.asyncio
  634. async def test_reuses_an_existing_filament_of_the_same_product_line(self, client, tray_pla_black):
  635. """The short-circuit still short-circuits — for a filament that is actually
  636. this roll's.
  637. This test used to pin the version that matched on material and colour alone,
  638. with a filament named "Black" standing in for a PLA Basic roll. That is the
  639. defect in #2907: PLA Basic Black and PLA Matte Charcoal are both PLA at
  640. #000000, so a Matte roll was linked to the Basic filament. The name is the
  641. only field on a Spoolman filament that carries the product line, so it is
  642. now part of the match.
  643. Named for the sub-brand here because that is what Bambuddy has been calling
  644. its own creations (``name=tray.tray_sub_brands``) — which is what stops this
  645. change minting a duplicate filament for every spool on an existing instance.
  646. """
  647. existing = {
  648. "id": 6,
  649. "name": "PLA Basic",
  650. "material": "PLA",
  651. "color_hex": "000000", # alpha stripped by create_filament at insert time
  652. "vendor_id": 2,
  653. }
  654. result, mock_external, mock_create = await self._run(client, tray_pla_black, None, filaments=[existing])
  655. assert result is existing
  656. mock_external.assert_not_called()
  657. mock_create.assert_not_called()
  658. @pytest.mark.asyncio
  659. async def test_reuses_a_filament_named_for_the_catalogue_colour(self, client, tray_pla_black):
  660. """The bare-colour spelling: what an entry taken from the external library
  661. used to be called, and what PLA Basic is called there. An existing instance
  662. is full of these, so refusing it would duplicate every one."""
  663. existing = {"id": 6, "name": "Black", "material": "PLA", "color_hex": "000000", "vendor_id": 2}
  664. result, _, mock_create = await self._run(client, tray_pla_black, CatalogColor("Black"), filaments=[existing])
  665. assert result is existing
  666. mock_create.assert_not_called()
  667. @pytest.mark.asyncio
  668. async def test_does_not_reuse_a_filament_from_a_different_product_line(self, client, tray_matte):
  669. """The reported case. A PLA Matte Charcoal roll must not attach to the
  670. PLA Basic Black filament that happens to share its material and hex."""
  671. pla_basic_black = {"id": 6, "name": "Black", "material": "PLA", "color_hex": "000000", "vendor_id": 2}
  672. _, _, mock_create = await self._run(client, tray_matte, CatalogColor("Charcoal"), filaments=[pla_basic_black])
  673. mock_create.assert_called_once()
  674. assert mock_create.call_args.kwargs["name"] == "PLA Matte"
  675. @pytest.mark.asyncio
  676. async def test_skips_non_bambu_lab_external_entries(self, client, tray_pla_black):
  677. """Regression for #1309: the external-library loop must filter out non-Bambu-Lab
  678. manufacturers. PLA black 000000 is offered by 3DJAKE, 3DXTECH (and 60+ others)
  679. in SpoolmanDB before Bambu Lab's entry; without the filter the first hit wins
  680. and Bambu Lab spools get labeled with competitor names.
  681. """
  682. external = [
  683. {
  684. "id": "3djake_pla_black_1000_175_n",
  685. "manufacturer": "3DJAKE",
  686. "name": "Black",
  687. "material": "PLA",
  688. "color_hex": "000000",
  689. "density": 1.24,
  690. },
  691. {
  692. "id": "3dxtech_pla_carbonxcarbonfiberblack_500_175_p",
  693. "manufacturer": "3DXTECH",
  694. "name": "CarbonX™ Carbon Fiber Black",
  695. "material": "PLA",
  696. "color_hex": "000000",
  697. "density": 1.29,
  698. },
  699. {
  700. "id": "bambulab_pla_black_1000_175_n",
  701. "manufacturer": "Bambu Lab",
  702. "name": "Black",
  703. "material": "PLA",
  704. "color_hex": "000000",
  705. "density": 1.26,
  706. },
  707. ]
  708. with (
  709. patch.object(client, "ensure_bambu_vendor", AsyncMock(return_value=2)),
  710. patch.object(client, "get_filaments", AsyncMock(return_value=[])),
  711. patch.object(client, "get_external_filaments", AsyncMock(return_value=external)),
  712. patch.object(client, "create_filament", AsyncMock(return_value={"id": 99})) as mock_create,
  713. ):
  714. await client._find_or_create_filament(tray_pla_black, CatalogColor("Black"))
  715. mock_create.assert_called_once()
  716. kwargs = mock_create.call_args.kwargs
  717. # The Bambu Lab entry must win — not 3DJAKE / 3DXTECH which sort earlier.
  718. # The name is the tray's either way, so the density says which entry it was.
  719. assert kwargs["name"] == "PLA Basic"
  720. assert kwargs["density"] == 1.26
  721. @pytest.mark.asyncio
  722. async def test_prefers_the_external_entry_that_carries_the_line(self, client, tray_matte):
  723. """The tie-break selects on the line and the catalogue's colour together.
  724. The fixture is the real pair. A current SpoolmanDB carries, for Bambu Lab
  725. PLA at #000000, ``bambulab_pla_black_1000_175_n`` named "Black" and
  726. ``bambulab_pla_mattecharcoal_1000_175_n`` named "Matte Charcoal" -- both
  727. material "PLA", because the line lives in the id and the name, never in
  728. the material column. The previous version of this test staged an entry
  729. named "PLA Basic" instead, which is a row SpoolmanDB does not contain:
  730. none of its 269 Bambu Lab entries is named for a sub-brand.
  731. That matters for what the old code did. Against this fixture the old
  732. equality (``name == tray_sub_brands``, i.e. "pla matte") matches nothing,
  733. so it falls through to candidates[0] -- "Black" -- and a Matte roll is
  734. created as PLA Basic Black. That is #2907. Against the invented fixture
  735. it matched, which is why the old test passed.
  736. The catalogue value is the real one too. ``catalog_defaults.py`` seeds
  737. #000000 under PLA Matte as "Charcoal", with the line in its material
  738. column; the round-two version of this test staged "Matte Charcoal", which
  739. is the library's spelling, and so exercised a branch the seed never
  740. reaches. Neither side's name equals the other's here, which is why the
  741. selector rebuilds the library's spelling from the line and the colour.
  742. """
  743. external = [
  744. {
  745. "id": "bambulab_pla_black_1000_175_n",
  746. "manufacturer": "Bambu Lab",
  747. "name": "Black",
  748. "material": "PLA",
  749. "color_hex": "000000",
  750. "density": 1.24,
  751. },
  752. {
  753. "id": "bambulab_pla_mattecharcoal_1000_175_n",
  754. "manufacturer": "Bambu Lab",
  755. "name": "Matte Charcoal",
  756. "material": "PLA",
  757. "color_hex": "000000",
  758. "density": 1.26,
  759. },
  760. ]
  761. with (
  762. patch.object(client, "ensure_bambu_vendor", AsyncMock(return_value=2)),
  763. patch.object(client, "get_filaments", AsyncMock(return_value=[])),
  764. patch.object(client, "get_external_filaments", AsyncMock(return_value=external)),
  765. patch.object(client, "create_filament", AsyncMock(return_value={"id": 99})) as mock_create,
  766. ):
  767. await client._find_or_create_filament(tray_matte, CatalogColor("Charcoal"))
  768. mock_create.assert_called_once()
  769. kwargs = mock_create.call_args.kwargs
  770. # "Matte Charcoal" is the entry, and the density that comes with it says
  771. # so. candidates[0] is "Black", which the old tie-break would have taken.
  772. # The filament is named for the line either way, as internal mode's
  773. # subtype is.
  774. assert kwargs["density"] == 1.26
  775. assert kwargs["name"] == "PLA Matte"
  776. @pytest.mark.asyncio
  777. async def test_falls_back_to_create_when_no_bambu_match_anywhere(self, client, tray_pla_black):
  778. """If no internal Bambu Lab filament exists AND SpoolmanDB has no Bambu Lab
  779. entry for this material+color (e.g. the catalog hasn't been updated yet for a
  780. brand-new BL product), fall back to creating a fresh filament from the tray's
  781. own RFID data — without leaking a competitor's name in.
  782. """
  783. external = [
  784. {
  785. "id": "3djake_pla_black_1000_175_n",
  786. "manufacturer": "3DJAKE",
  787. "name": "Black",
  788. "material": "PLA",
  789. "color_hex": "000000",
  790. },
  791. ]
  792. with (
  793. patch.object(client, "ensure_bambu_vendor", AsyncMock(return_value=2)),
  794. patch.object(client, "get_filaments", AsyncMock(return_value=[])),
  795. patch.object(client, "get_external_filaments", AsyncMock(return_value=external)),
  796. patch.object(client, "create_filament", AsyncMock(return_value={"id": 99})) as mock_create,
  797. ):
  798. await client._find_or_create_filament(tray_pla_black, None)
  799. mock_create.assert_called_once()
  800. kwargs = mock_create.call_args.kwargs
  801. # The 3DJAKE entry was rejected by the manufacturer filter; tray_sub_brands wins.
  802. assert kwargs["name"] == "PLA Basic"
  803. assert kwargs["material"] == "PLA"
  804. assert kwargs["color_hex"] == "000000" # alpha channel stripped from tray_color
  805. assert kwargs["vendor_id"] == 2
  806. @pytest.mark.asyncio
  807. async def test_a_colour_the_catalogue_lags_is_built_from_the_tray_not_a_bambu_entry(self, client, tray_pla_black):
  808. """A real Bambu candidate is present and deliberately not used.
  809. This is the first half of the decision the fall-through makes, and the
  810. half ``test_falls_back_to_create_when_no_bambu_match_anywhere`` does not
  811. reach: its only external entry is 3DJAKE, which the manufacturer filter
  812. drops before ``bambu_candidates`` is built, so that test arrives at this
  813. branch with an empty candidate list. An empty list exercises nothing
  814. about the choice.
  815. Here the library does carry this roll's material and colour under Bambu
  816. Lab, and the catalogue -- seeded from Bambu's published list, so it lags
  817. new releases -- has no row to name it. Without a name there is nothing to
  818. select on, and attaching to whichever candidate came first is the
  819. misattribution #2907 is about, so the roll is built from what the printer
  820. reported instead.
  821. """
  822. external = [
  823. {
  824. "id": "bambulab_pla_black_1000_175_n",
  825. "manufacturer": "Bambu Lab",
  826. "name": "Black",
  827. "material": "PLA",
  828. "color_hex": "000000",
  829. "density": 1.31,
  830. },
  831. ]
  832. _, _, mock_create = await self._run(client, tray_pla_black, None, external=external)
  833. mock_create.assert_called_once()
  834. kwargs = mock_create.call_args.kwargs
  835. # The tray's own sub-brand, not the candidate's colour name.
  836. assert kwargs["name"] == "PLA Basic"
  837. assert kwargs["material"] == "PLA"
  838. assert kwargs["color_hex"] == "000000"
  839. assert kwargs["weight"] == 1000
  840. # `density` reaches create_filament only via _create_filament_from_external,
  841. # so its absence is what separates the two paths -- the name alone would
  842. # not, since the candidate here is called "Black" for other reasons too.
  843. assert "density" not in kwargs
  844. @pytest.mark.asyncio
  845. async def test_a_name_the_library_does_not_carry_is_built_from_the_tray_too(self, client, tray_matte):
  846. """The other half: the catalogue answers and no candidate carries that name.
  847. The catalogue names this roll "Charcoal" under PLA Matte; the library
  848. offers only "Black" for Bambu Lab PLA at #000000. That is the state an instance sits
  849. in between a colour shipping and SpoolmanDB catching up. The name is the
  850. only field separating the two product lines at this hex, so a candidate
  851. that does not carry it is not this roll -- and "Black" is exactly the
  852. entry the old tie-break took.
  853. """
  854. external = [
  855. {
  856. "id": "bambulab_pla_black_1000_175_n",
  857. "manufacturer": "Bambu Lab",
  858. "name": "Black",
  859. "material": "PLA",
  860. "color_hex": "000000",
  861. "density": 1.24,
  862. },
  863. ]
  864. _, _, mock_create = await self._run(client, tray_matte, CatalogColor("Charcoal"), external=external)
  865. mock_create.assert_called_once()
  866. kwargs = mock_create.call_args.kwargs
  867. # Named for the line, as every filament this path creates is; what it
  868. # must not take is the "Black" entry's identity or the density with it.
  869. assert kwargs["name"] == "PLA Matte"
  870. assert kwargs["material"] == "PLA"
  871. assert kwargs["color_hex"] == "000000"
  872. assert "density" not in kwargs
  873. @pytest.mark.asyncio
  874. async def test_accepts_external_entry_via_id_prefix_when_manufacturer_missing(self, client, tray_pla_black):
  875. """Defensive fallback: if `manufacturer` is absent or empty but the entry's `id`
  876. starts with `bambulab_`, treat it as a Bambu Lab entry. Keeps the filter robust
  877. against SpoolmanDB schema drift or stale catalog snapshots that omit the field.
  878. """
  879. external = [
  880. {
  881. "id": "bambulab_pla_black_1000_175_n",
  882. "name": "Black",
  883. "material": "PLA",
  884. "color_hex": "000000",
  885. "density": 1.24,
  886. }, # no `manufacturer` key at all
  887. ]
  888. with (
  889. patch.object(client, "ensure_bambu_vendor", AsyncMock(return_value=2)),
  890. patch.object(client, "get_filaments", AsyncMock(return_value=[])),
  891. patch.object(client, "get_external_filaments", AsyncMock(return_value=external)),
  892. patch.object(client, "create_filament", AsyncMock(return_value={"id": 99})) as mock_create,
  893. ):
  894. await client._find_or_create_filament(tray_pla_black, CatalogColor("Black"))
  895. mock_create.assert_called_once()
  896. # Only the external path forwards a density, so this is what shows the
  897. # entry was accepted rather than the roll being built from scratch.
  898. assert mock_create.call_args.kwargs["density"] == 1.24
  899. @pytest.mark.asyncio
  900. async def test_external_density_propagates_to_create_filament(self, client, tray_pla_black):
  901. """The chosen external entry's `density` must be forwarded to `create_filament`
  902. instead of being silently replaced by the PLA-default 1.24 fallback inside
  903. `create_filament` itself. Verified end-to-end via the public
  904. `_find_or_create_filament` entry point.
  905. """
  906. external = [
  907. {
  908. "id": "bambulab_pla_black_1000_175_n",
  909. "manufacturer": "Bambu Lab",
  910. "name": "Black",
  911. "material": "PLA",
  912. "color_hex": "000000",
  913. "density": 1.31,
  914. },
  915. ]
  916. with (
  917. patch.object(client, "ensure_bambu_vendor", AsyncMock(return_value=2)),
  918. patch.object(client, "get_filaments", AsyncMock(return_value=[])),
  919. patch.object(client, "get_external_filaments", AsyncMock(return_value=external)),
  920. patch.object(client, "create_filament", AsyncMock(return_value={"id": 99})) as mock_create,
  921. ):
  922. await client._find_or_create_filament(tray_pla_black, CatalogColor("Black"))
  923. mock_create.assert_called_once()
  924. assert mock_create.call_args.kwargs["density"] == 1.31
  925. class TestColorHexAlphaHandling:
  926. """#2912 — a clear spool must not be stored as opaque black, and widening the
  927. stored value must not mint duplicates against inventories that hold six
  928. characters everywhere.
  929. """
  930. @pytest.fixture
  931. def client(self):
  932. return SpoolmanClient("http://localhost:7912")
  933. def _tray(self, tray_color: str) -> AMSTray:
  934. return AMSTray(
  935. ams_id=0,
  936. tray_id=0,
  937. tray_type="PLA",
  938. tray_sub_brands="PLA Basic",
  939. tray_color=tray_color,
  940. remain=100,
  941. tag_uid="",
  942. tray_uuid="A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4",
  943. tray_info_idx="GFA00",
  944. tray_weight=1000,
  945. )
  946. async def _posted_payload(self, client, color_hex: str) -> dict:
  947. """Run create_filament and return the JSON body it actually sent."""
  948. with patch.object(client, "_get_client") as mock_get_client:
  949. mock_http_client = AsyncMock()
  950. mock_response = Mock()
  951. mock_response.status_code = 200
  952. mock_response.raise_for_status = Mock()
  953. mock_response.json = Mock(return_value={"id": 99})
  954. mock_http_client.post = AsyncMock(return_value=mock_response)
  955. mock_get_client.return_value = mock_http_client
  956. await client.create_filament(name="PLA Basic", material="PLA", color_hex=color_hex)
  957. return mock_http_client.post.call_args.kwargs["json"]
  958. @pytest.mark.asyncio
  959. async def test_create_filament_stores_alpha_for_a_translucent_spool(self, client):
  960. """create_filament is the chokepoint every create funnels through — it
  961. truncated to six characters unconditionally, which is what turned a clear
  962. spool into opaque black."""
  963. payload = await self._posted_payload(client, "00000000")
  964. assert payload["color_hex"] == "00000000"
  965. @pytest.mark.asyncio
  966. async def test_create_filament_keeps_an_opaque_spool_at_six(self, client):
  967. """Passing everything through would rewrite the color_hex of every opaque
  968. spool on its next touch. Existing data has to stay byte-identical."""
  969. payload = await self._posted_payload(client, "FF0000FF")
  970. assert payload["color_hex"] == "FF0000"
  971. @pytest.mark.asyncio
  972. async def test_clear_tray_creates_a_translucent_filament(self, client):
  973. """End-to-end through the AMS auto-create path with nothing to match."""
  974. with (
  975. patch.object(client, "ensure_bambu_vendor", AsyncMock(return_value=2)),
  976. patch.object(client, "get_filaments", AsyncMock(return_value=[])),
  977. patch.object(client, "get_external_filaments", AsyncMock(return_value=[])),
  978. patch.object(client, "create_filament", AsyncMock(return_value={"id": 99})) as mock_create,
  979. ):
  980. await client._find_or_create_filament(self._tray("00000000"), None)
  981. assert mock_create.call_args.kwargs["color_hex"] == "00000000"
  982. @pytest.mark.asyncio
  983. async def test_a_clear_tray_is_not_named_from_the_catalogue_even_when_it_can_answer(self, client):
  984. """#1545 at this level: the catalogue must not get to name a clear roll.
  985. The catalogue here does have a row -- the trap is that a clear roll
  986. reports ``00000000`` and the catalogue stores RGB, so the lookup would hit
  987. #000000 and come back "Black". Without the guard the spool is stored as
  988. "Black" for a clear roll, while the built-in path calls the same roll
  989. "Clear" on the same printer. The colour is resolved in ``sync_ams_tray``
  990. and handed down, so that is where this has to be driven from.
  991. """
  992. with (
  993. patch.object(client, "find_spool_by_tag", AsyncMock(return_value=None)),
  994. patch.object(client, "_find_or_create_filament", AsyncMock(return_value={"id": 7})) as mock_find,
  995. patch.object(client, "create_spool", AsyncMock(return_value={"id": 99})) as mock_create,
  996. ):
  997. await client.sync_ams_tray(self._tray("00000000"), "TestPrinter", _BlackCatalog())
  998. assert mock_find.call_args.args[1] == CatalogColor("Clear")
  999. assert mock_create.call_args.kwargs["extra"]["bambu_color_name"] == json.dumps("Clear")
  1000. @pytest.mark.asyncio
  1001. async def test_opaque_tray_still_matches_an_existing_six_char_filament(self, client):
  1002. """The upgrade hazard neither the report nor the original patch mentioned.
  1003. Every filament already in a user's Spoolman is stored six characters. If
  1004. the match compared full strings, an 8-char tray colour would stop matching
  1005. them and the next AMS sync would mint a duplicate filament for every spool
  1006. on the instance. An opaque tray keys to six characters and still matches.
  1007. """
  1008. existing = {"id": 6, "name": "Black", "material": "PLA", "color_hex": "000000", "vendor_id": 2}
  1009. with (
  1010. patch.object(client, "ensure_bambu_vendor", AsyncMock(return_value=2)),
  1011. patch.object(client, "get_filaments", AsyncMock(return_value=[existing])),
  1012. patch.object(client, "get_external_filaments", AsyncMock()) as mock_external,
  1013. patch.object(client, "create_filament", AsyncMock()) as mock_create,
  1014. ):
  1015. # Named after the catalogue's colour name, so the product-line
  1016. # criterion (#2907) is satisfied and the six/eight-character key is
  1017. # the only thing this test can fail on.
  1018. result = await client._find_or_create_filament(self._tray("000000FF"), CatalogColor("Black"))
  1019. assert result is existing
  1020. mock_external.assert_not_called()
  1021. mock_create.assert_not_called()
  1022. @pytest.mark.asyncio
  1023. async def test_clear_tray_does_not_attach_to_the_black_filament(self, client):
  1024. """A translucent tray keys to eight characters, so it does not match the
  1025. opaque filament of the same RGB and gets its own record instead."""
  1026. black = {"id": 6, "name": "Black", "material": "PLA", "color_hex": "000000", "vendor_id": 2}
  1027. with (
  1028. patch.object(client, "ensure_bambu_vendor", AsyncMock(return_value=2)),
  1029. patch.object(client, "get_filaments", AsyncMock(return_value=[black])),
  1030. patch.object(client, "get_external_filaments", AsyncMock(return_value=[])),
  1031. patch.object(client, "create_filament", AsyncMock(return_value={"id": 99})) as mock_create,
  1032. ):
  1033. await client._find_or_create_filament(self._tray("00000000"), CatalogColor("Black"))
  1034. assert mock_create.call_args.kwargs["color_hex"] == "00000000"
  1035. @pytest.mark.asyncio
  1036. async def test_black_tray_does_not_attach_to_a_clear_filament(self, client):
  1037. """The inverse direction, which only became possible once 8-char values
  1038. were storable at all: without the alpha in the key, an opaque black roll
  1039. would match the clear filament, then render as the transparency
  1040. checkerboard and be named Clear. Whichever roll synced first would decide
  1041. and the other would be mislabelled.
  1042. """
  1043. clear = {"id": 6, "name": "Clear", "material": "PLA", "color_hex": "00000000", "vendor_id": 2}
  1044. with (
  1045. patch.object(client, "ensure_bambu_vendor", AsyncMock(return_value=2)),
  1046. patch.object(client, "get_filaments", AsyncMock(return_value=[clear])),
  1047. patch.object(client, "get_external_filaments", AsyncMock(return_value=[])),
  1048. patch.object(client, "create_filament", AsyncMock(return_value={"id": 99})) as mock_create,
  1049. ):
  1050. await client._find_or_create_filament(self._tray("000000FF"), CatalogColor("Clear"))
  1051. assert mock_create.call_args.kwargs["color_hex"] == "000000"
  1052. @pytest.mark.asyncio
  1053. async def test_clear_tray_does_not_take_a_same_rgb_external_entry(self, client):
  1054. """The reported path on a fresh Spoolman with the external library
  1055. reachable. Candidates are built with the same key, so SpoolmanDB's opaque
  1056. "PLA Basic Black" is no longer a candidate for a clear tray and the
  1057. filament is created from the tray data with its alpha intact.
  1058. """
  1059. external = [
  1060. {
  1061. "id": "bambulab_pla_black_1000_175_n",
  1062. "manufacturer": "Bambu Lab",
  1063. "name": "PLA Basic Black",
  1064. "material": "PLA",
  1065. "color_hex": "000000",
  1066. },
  1067. ]
  1068. with (
  1069. patch.object(client, "ensure_bambu_vendor", AsyncMock(return_value=2)),
  1070. patch.object(client, "get_filaments", AsyncMock(return_value=[])),
  1071. patch.object(client, "get_external_filaments", AsyncMock(return_value=external)),
  1072. patch.object(client, "create_filament", AsyncMock(return_value={"id": 99})) as mock_create,
  1073. ):
  1074. # The catalogue is made to name this colour exactly what the external
  1075. # entry is called, so the selector (#2907) would take it. Only the
  1076. # colour key keeps it out of the candidate list at all.
  1077. await client._find_or_create_filament(self._tray("00000000"), CatalogColor("PLA Basic Black"))
  1078. assert mock_create.call_args.kwargs["color_hex"] == "00000000"
  1079. @pytest.mark.asyncio
  1080. async def test_find_or_create_filament_creates_a_clear_filament_with_its_alpha(self, client):
  1081. """The user-driven path, with nothing to match. There is no split to pin
  1082. here: the key and the created value are the same string, and for a clear
  1083. spool that string is eight characters."""
  1084. with (
  1085. patch.object(client, "find_or_create_vendor", AsyncMock(return_value=3)),
  1086. patch.object(client, "get_filaments", AsyncMock(return_value=[])),
  1087. patch.object(client, "create_filament", AsyncMock(return_value={"id": 99})) as mock_create,
  1088. ):
  1089. await client.find_or_create_filament(
  1090. material="PLA",
  1091. subtype="Basic",
  1092. brand="Bambu Lab",
  1093. color_hex="00000000",
  1094. label_weight=1000,
  1095. )
  1096. assert mock_create.call_args.kwargs["color_hex"] == "00000000"
  1097. @pytest.mark.asyncio
  1098. async def test_find_or_create_filament_matches_an_existing_six_char_filament(self, client):
  1099. """The upgrade guard on the *other* match loop.
  1100. `test_opaque_tray_still_matches_an_existing_six_char_filament` pins it for
  1101. the AMS path. The public `find_or_create_filament` has its own loop, and
  1102. the non-BL RFID auto-create (spoolman.py, `_sync_tray_to_spoolman`) now
  1103. hands it `tray.tray_color` whole where it used to hand over
  1104. `tray.tray_color[:6]`. If the opaque fold ever came off this key, every
  1105. non-Bambu RFID spool on an instance would mint a duplicate filament on the
  1106. next sync and nothing would go red.
  1107. """
  1108. existing = {
  1109. "id": 7,
  1110. "name": "PLA Basic",
  1111. "material": "PLA",
  1112. "color_hex": "FF0000",
  1113. "vendor": {"id": 3, "name": "Bambu Lab"},
  1114. }
  1115. with (
  1116. patch.object(client, "find_or_create_vendor", AsyncMock(return_value=3)),
  1117. patch.object(client, "get_filaments", AsyncMock(return_value=[existing])),
  1118. patch.object(client, "create_filament", AsyncMock()) as mock_create,
  1119. ):
  1120. result = await client.find_or_create_filament(
  1121. material="PLA",
  1122. subtype="Basic",
  1123. brand="Bambu Lab",
  1124. color_hex="FF0000FF",
  1125. label_weight=1000,
  1126. )
  1127. assert result == 7
  1128. mock_create.assert_not_called()