test_spoolman_inventory_api.py 111 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815
  1. """Integration tests for the Spoolman inventory proxy endpoints.
  2. These tests verify that /api/v1/spoolman/inventory/spools/* correctly
  3. translates between Spoolman's data model and Bambuddy's InventorySpool format.
  4. """
  5. from unittest.mock import AsyncMock, MagicMock, patch
  6. import pytest
  7. from fastapi import HTTPException
  8. from httpx import AsyncClient
  9. # ---------------------------------------------------------------------------
  10. # Shared fixtures
  11. # ---------------------------------------------------------------------------
  12. SAMPLE_SPOOLMAN_SPOOL = {
  13. "id": 42,
  14. "filament": {
  15. "id": 7,
  16. "name": "PLA Basic",
  17. "material": "PLA",
  18. "color_hex": "FF0000",
  19. "weight": 1000,
  20. "vendor": {"id": 3, "name": "Bambu Lab"},
  21. },
  22. "remaining_weight": 750.0,
  23. "used_weight": 250.0,
  24. "location": "Printer1 - AMS A1",
  25. "comment": "test note",
  26. "first_used": "2024-01-01T00:00:00+00:00",
  27. "last_used": "2024-02-01T00:00:00+00:00",
  28. "registered": "2024-01-01T00:00:00+00:00",
  29. "archived": False,
  30. "price": None,
  31. "extra": {"tag": '"AABBCCDDEEFF0011AABBCCDDEEFF0011"'},
  32. }
  33. @pytest.fixture
  34. async def spoolman_settings(db_session):
  35. """Create Spoolman settings in the database (enabled with URL)."""
  36. from backend.app.models.settings import Settings
  37. enabled_setting = Settings(key="spoolman_enabled", value="true")
  38. url_setting = Settings(key="spoolman_url", value="http://localhost:7912")
  39. db_session.add(enabled_setting)
  40. db_session.add(url_setting)
  41. await db_session.commit()
  42. return {"enabled": enabled_setting, "url": url_setting}
  43. @pytest.fixture
  44. def mock_spoolman_client():
  45. """Mock the Spoolman client with a sample spool."""
  46. mock_client = MagicMock()
  47. mock_client.base_url = "http://localhost:7912"
  48. mock_client.health_check = AsyncMock(return_value=True)
  49. mock_client.get_all_spools = AsyncMock(return_value=[SAMPLE_SPOOLMAN_SPOOL])
  50. mock_client.get_spool = AsyncMock(return_value=SAMPLE_SPOOLMAN_SPOOL)
  51. mock_client.create_spool = AsyncMock(return_value=SAMPLE_SPOOLMAN_SPOOL)
  52. mock_client.delete_spool = AsyncMock(return_value=True)
  53. mock_client.set_spool_archived = AsyncMock(
  54. side_effect=lambda spool_id, archived: {**SAMPLE_SPOOLMAN_SPOOL, "archived": archived}
  55. )
  56. mock_client.reset_spool_usage = AsyncMock(return_value={**SAMPLE_SPOOLMAN_SPOOL, "used_weight": 0})
  57. mock_client.update_spool_full = AsyncMock(return_value=SAMPLE_SPOOLMAN_SPOOL)
  58. mock_client.merge_spool_extra = AsyncMock(return_value=SAMPLE_SPOOLMAN_SPOOL)
  59. mock_client.find_or_create_filament = AsyncMock(return_value=7)
  60. mock_client.find_or_create_vendor = AsyncMock(return_value=3)
  61. mock_client.patch_filament = AsyncMock(return_value={"id": 7})
  62. # Default to singleton (only this spool uses the filament) so edits
  63. # exercise the new in-place-PATCH path; tests that need the shared
  64. # branch override this on the fly.
  65. mock_client.is_filament_shared = AsyncMock(return_value=False)
  66. mock_client.ensure_extra_field = AsyncMock(return_value=True)
  67. # list_spools calls maybe_sync_spoolman_locations which invokes
  68. # get_distinct_locations on the route-resolved client. Empty list keeps the
  69. # mock honest without staging phantom catalog rows.
  70. mock_client.get_distinct_locations = AsyncMock(return_value=[])
  71. with (
  72. patch(
  73. "backend.app.api.routes.spoolman_inventory.get_spoolman_client",
  74. AsyncMock(return_value=mock_client),
  75. ),
  76. patch(
  77. "backend.app.api.routes.spoolman_inventory.init_spoolman_client",
  78. AsyncMock(return_value=mock_client),
  79. ),
  80. ):
  81. yield mock_client
  82. class TestSpoolmanInventoryMapping:
  83. """Tests for the Spoolman → InventorySpool data mapping."""
  84. @pytest.mark.asyncio
  85. @pytest.mark.integration
  86. async def test_list_spools_returns_inventory_format(
  87. self,
  88. async_client: AsyncClient,
  89. spoolman_settings,
  90. mock_spoolman_client,
  91. ):
  92. """GET /spoolman/inventory/spools returns spools in InventorySpool format."""
  93. response = await async_client.get("/api/v1/spoolman/inventory/spools")
  94. assert response.status_code == 200
  95. spools = response.json()
  96. assert isinstance(spools, list)
  97. assert len(spools) == 1
  98. spool = spools[0]
  99. assert spool["id"] == 42
  100. assert spool["material"] == "PLA"
  101. assert spool["subtype"] == "Basic"
  102. assert spool["brand"] == "Bambu Lab"
  103. assert spool["label_weight"] == 1000
  104. assert spool["weight_used"] == 250.0
  105. assert spool["note"] == "test note"
  106. assert spool["data_origin"] == "spoolman"
  107. assert spool["tag_type"] == "spoolman"
  108. # RRGGBB + FF alpha
  109. assert spool["rgba"] == "FF0000FF"
  110. # Spoolman location mapped to storage_location
  111. assert spool["storage_location"] == "Printer1 - AMS A1"
  112. # RFID tag: 32-char → tray_uuid
  113. assert spool["tray_uuid"] == "AABBCCDDEEFF0011AABBCCDDEEFF0011"
  114. assert spool["tag_uid"] is None
  115. @pytest.mark.asyncio
  116. @pytest.mark.integration
  117. async def test_get_single_spool(
  118. self,
  119. async_client: AsyncClient,
  120. spoolman_settings,
  121. mock_spoolman_client,
  122. ):
  123. """GET /spoolman/inventory/spools/{id} returns a single spool."""
  124. response = await async_client.get("/api/v1/spoolman/inventory/spools/42")
  125. assert response.status_code == 200
  126. spool = response.json()
  127. assert spool["id"] == 42
  128. assert spool["material"] == "PLA"
  129. @pytest.mark.asyncio
  130. @pytest.mark.integration
  131. async def test_list_includes_archived_when_requested(
  132. self,
  133. async_client: AsyncClient,
  134. spoolman_settings,
  135. mock_spoolman_client,
  136. ):
  137. """GET /spoolman/inventory/spools?include_archived=true calls Spoolman with allow_archived."""
  138. await async_client.get("/api/v1/spoolman/inventory/spools?include_archived=true")
  139. mock_spoolman_client.get_all_spools.assert_called_once_with(allow_archived=True)
  140. @pytest.mark.asyncio
  141. @pytest.mark.integration
  142. async def test_archived_spool_has_archived_at(
  143. self,
  144. async_client: AsyncClient,
  145. spoolman_settings,
  146. mock_spoolman_client,
  147. ):
  148. """An archived Spoolman spool maps to archived_at != None."""
  149. archived_spool = {
  150. **SAMPLE_SPOOLMAN_SPOOL,
  151. "archived": True,
  152. }
  153. mock_spoolman_client.get_all_spools.return_value = [archived_spool]
  154. response = await async_client.get("/api/v1/spoolman/inventory/spools?include_archived=true")
  155. spool = response.json()[0]
  156. assert spool["archived_at"] is not None
  157. @pytest.mark.asyncio
  158. @pytest.mark.integration
  159. async def test_malformed_spool_skipped_in_list(
  160. self,
  161. async_client: AsyncClient,
  162. spoolman_settings,
  163. mock_spoolman_client,
  164. ):
  165. """A spool with an invalid id (e.g. 0) is silently skipped; others still appear."""
  166. bad_spool = {**SAMPLE_SPOOLMAN_SPOOL, "id": 0}
  167. mock_spoolman_client.get_all_spools.return_value = [bad_spool, SAMPLE_SPOOLMAN_SPOOL]
  168. response = await async_client.get("/api/v1/spoolman/inventory/spools")
  169. assert response.status_code == 200
  170. spools = response.json()
  171. # bad_spool is dropped; the valid one survives
  172. assert len(spools) == 1
  173. assert spools[0]["id"] == 42
  174. @pytest.mark.asyncio
  175. @pytest.mark.integration
  176. async def test_list_spools_returns_503_when_spoolman_unavailable(
  177. self,
  178. async_client: AsyncClient,
  179. spoolman_settings,
  180. mock_spoolman_client,
  181. ):
  182. """GET /spoolman/inventory/spools returns 503 when Spoolman is unreachable (H10)."""
  183. from backend.app.services.spoolman import SpoolmanUnavailableError
  184. mock_spoolman_client.get_all_spools.side_effect = SpoolmanUnavailableError("down")
  185. response = await async_client.get("/api/v1/spoolman/inventory/spools")
  186. assert response.status_code == 503
  187. @pytest.mark.asyncio
  188. @pytest.mark.integration
  189. async def test_tag_uid_16char_maps_correctly(
  190. self,
  191. async_client: AsyncClient,
  192. spoolman_settings,
  193. mock_spoolman_client,
  194. ):
  195. """A 16-char tag maps to tag_uid, not tray_uuid."""
  196. spool_with_short_tag = {
  197. **SAMPLE_SPOOLMAN_SPOOL,
  198. "extra": {"tag": '"AABBCCDDEEFF0011"'},
  199. }
  200. mock_spoolman_client.get_all_spools.return_value = [spool_with_short_tag]
  201. response = await async_client.get("/api/v1/spoolman/inventory/spools")
  202. spool = response.json()[0]
  203. assert spool["tag_uid"] == "AABBCCDDEEFF0011"
  204. assert spool["tray_uuid"] is None
  205. class TestSpoolmanInventoryCRUD:
  206. """Tests for create, update, delete, archive, restore operations."""
  207. @pytest.mark.asyncio
  208. @pytest.mark.integration
  209. async def test_not_enabled_returns_400(self, async_client: AsyncClient):
  210. """All endpoints return 400 when Spoolman is not enabled."""
  211. response = await async_client.get("/api/v1/spoolman/inventory/spools")
  212. assert response.status_code == 400
  213. assert "not enabled" in response.json()["detail"].lower()
  214. @pytest.mark.asyncio
  215. @pytest.mark.integration
  216. async def test_create_spool(
  217. self,
  218. async_client: AsyncClient,
  219. spoolman_settings,
  220. mock_spoolman_client,
  221. ):
  222. """POST /spoolman/inventory/spools creates a spool via Spoolman."""
  223. payload = {
  224. "material": "PLA",
  225. "subtype": "Basic",
  226. "brand": "Bambu Lab",
  227. "rgba": "FF0000FF",
  228. "label_weight": 1000,
  229. "weight_used": 0,
  230. }
  231. response = await async_client.post("/api/v1/spoolman/inventory/spools", json=payload)
  232. assert response.status_code == 200
  233. mock_spoolman_client.find_or_create_filament.assert_called_once()
  234. mock_spoolman_client.create_spool.assert_called_once()
  235. data = response.json()
  236. assert data["material"] == "PLA"
  237. @pytest.mark.asyncio
  238. @pytest.mark.integration
  239. async def test_bulk_create_spools(
  240. self,
  241. async_client: AsyncClient,
  242. spoolman_settings,
  243. mock_spoolman_client,
  244. ):
  245. """POST /spoolman/inventory/spools/bulk creates multiple spools."""
  246. payload = {
  247. "spool": {"material": "PETG", "label_weight": 1000, "weight_used": 0},
  248. "quantity": 3,
  249. }
  250. response = await async_client.post("/api/v1/spoolman/inventory/spools/bulk", json=payload)
  251. assert response.status_code == 200
  252. assert mock_spoolman_client.create_spool.call_count == 3
  253. @pytest.mark.asyncio
  254. @pytest.mark.integration
  255. async def test_bulk_create_quantity_out_of_range_returns_422(
  256. self,
  257. async_client: AsyncClient,
  258. spoolman_settings,
  259. mock_spoolman_client,
  260. ):
  261. """Bulk create quantity outside 1-50 is rejected with 422 (not silently clamped)."""
  262. payload = {
  263. "spool": {"material": "ABS", "label_weight": 1000, "weight_used": 0},
  264. "quantity": 999,
  265. }
  266. response = await async_client.post("/api/v1/spoolman/inventory/spools/bulk", json=payload)
  267. assert response.status_code == 422
  268. @pytest.mark.asyncio
  269. @pytest.mark.integration
  270. async def test_bulk_create_quantity_zero_returns_422(
  271. self,
  272. async_client: AsyncClient,
  273. spoolman_settings,
  274. mock_spoolman_client,
  275. ):
  276. """Bulk create quantity of 0 is rejected with 422."""
  277. payload = {
  278. "spool": {"material": "ABS", "label_weight": 1000, "weight_used": 0},
  279. "quantity": 0,
  280. }
  281. response = await async_client.post("/api/v1/spoolman/inventory/spools/bulk", json=payload)
  282. assert response.status_code == 422
  283. @pytest.mark.asyncio
  284. @pytest.mark.integration
  285. async def test_update_spool(
  286. self,
  287. async_client: AsyncClient,
  288. spoolman_settings,
  289. mock_spoolman_client,
  290. ):
  291. """PATCH /spoolman/inventory/spools/{id} updates a spool."""
  292. payload = {"note": "updated note", "weight_used": 100.0}
  293. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  294. assert response.status_code == 200
  295. mock_spoolman_client.update_spool_full.assert_called_once()
  296. @pytest.mark.asyncio
  297. @pytest.mark.integration
  298. async def test_update_noop_metadata_reuses_filament(
  299. self,
  300. async_client: AsyncClient,
  301. spoolman_settings,
  302. mock_spoolman_client,
  303. ):
  304. """#1357 follow-up: an edit that doesn't touch any filament-shaping
  305. field (only weight_used / note / color_name) must NOT hit
  306. find_or_create_filament OR patch_filament — the link stays put and
  307. the filament catalogue is left alone."""
  308. payload = {"note": "just a note change", "weight_used": 50.0}
  309. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  310. assert response.status_code == 200
  311. mock_spoolman_client.find_or_create_filament.assert_not_called()
  312. mock_spoolman_client.patch_filament.assert_not_called()
  313. @pytest.mark.asyncio
  314. @pytest.mark.integration
  315. async def test_update_singleton_filament_patches_in_place(
  316. self,
  317. async_client: AsyncClient,
  318. spoolman_settings,
  319. mock_spoolman_client,
  320. ):
  321. """#1357 follow-up: when the linked filament is only used by the
  322. spool being edited (singleton), changing the subtype must PATCH that
  323. filament in place — NOT create a new filament and orphan the old
  324. one. This is the exact failure the reporter showed: editing Subtype
  325. "Red" → "Basic" minted a new "PETG Basic" filament every time.
  326. """
  327. # Sample filament is "PLA Basic"; flip to "Matte" so the metadata
  328. # actually changes and the singleton path engages.
  329. payload = {"subtype": "Matte"}
  330. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  331. assert response.status_code == 200
  332. # Singleton path: PATCH the existing filament, do NOT find_or_create.
  333. mock_spoolman_client.patch_filament.assert_called_once()
  334. mock_spoolman_client.find_or_create_filament.assert_not_called()
  335. # PATCH targets the spool's current filament (id=7) with the new name.
  336. call_args = mock_spoolman_client.patch_filament.call_args
  337. assert call_args.args[0] == 7
  338. assert call_args.args[1]["name"] == "PLA Matte"
  339. @pytest.mark.asyncio
  340. @pytest.mark.integration
  341. async def test_create_spool_keeps_a_clear_colour_translucent(
  342. self,
  343. async_client: AsyncClient,
  344. spoolman_settings,
  345. mock_spoolman_client,
  346. ):
  347. """#2912: the create route truncated rgba to six characters, so entering
  348. "fully transparent" by hand landed on the same opaque black as the AMS
  349. case in the report."""
  350. payload = {
  351. "material": "PLA",
  352. "rgba": "00000000",
  353. "label_weight": 1000,
  354. "weight_used": 0,
  355. }
  356. response = await async_client.post("/api/v1/spoolman/inventory/spools", json=payload)
  357. assert response.status_code == 200
  358. assert mock_spoolman_client.find_or_create_filament.call_args.kwargs["color_hex"] == "00000000"
  359. @pytest.mark.asyncio
  360. @pytest.mark.integration
  361. async def test_create_spool_keeps_an_opaque_colour_at_six(
  362. self,
  363. async_client: AsyncClient,
  364. spoolman_settings,
  365. mock_spoolman_client,
  366. ):
  367. """The opaque case has to stay six characters or every create starts
  368. writing a shape the rest of the instance does not hold."""
  369. payload = {
  370. "material": "PLA",
  371. "rgba": "FF0000FF",
  372. "label_weight": 1000,
  373. "weight_used": 0,
  374. }
  375. response = await async_client.post("/api/v1/spoolman/inventory/spools", json=payload)
  376. assert response.status_code == 200
  377. assert mock_spoolman_client.find_or_create_filament.call_args.kwargs["color_hex"] == "FF0000"
  378. @pytest.mark.asyncio
  379. @pytest.mark.integration
  380. async def test_update_alpha_only_edit_reaches_the_filament(
  381. self,
  382. async_client: AsyncClient,
  383. spoolman_settings,
  384. mock_spoolman_client,
  385. ):
  386. """#2912: making a spool translucent is a real change to the filament's
  387. colour. Comparing bare RGB prefixes would call it a no-op and the edit
  388. would never land."""
  389. # Sample filament is FF0000; make it half-transparent.
  390. payload = {"rgba": "FF000080"}
  391. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  392. assert response.status_code == 200
  393. mock_spoolman_client.patch_filament.assert_called_once()
  394. assert mock_spoolman_client.patch_filament.call_args.args[1]["color_hex"] == "FF000080"
  395. @pytest.mark.asyncio
  396. @pytest.mark.integration
  397. async def test_update_with_the_round_tripped_opaque_rgba_is_a_no_op(
  398. self,
  399. async_client: AsyncClient,
  400. spoolman_settings,
  401. mock_spoolman_client,
  402. ):
  403. """#2912: the read side hands the frontend FF0000FF for a filament stored
  404. as FF0000, and the edit form sends it straight back. Comparing raw strings
  405. would make metadata_unchanged permanently False and PATCH the filament on
  406. every no-op edit.
  407. """
  408. payload = {"rgba": "FF0000FF", "note": "unrelated change"}
  409. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  410. assert response.status_code == 200
  411. mock_spoolman_client.patch_filament.assert_not_called()
  412. mock_spoolman_client.find_or_create_filament.assert_not_called()
  413. @pytest.mark.asyncio
  414. @pytest.mark.integration
  415. async def test_update_shared_filament_falls_back_to_find_or_create(
  416. self,
  417. async_client: AsyncClient,
  418. spoolman_settings,
  419. mock_spoolman_client,
  420. ):
  421. """#1357 follow-up: when the linked filament is shared with another
  422. spool, PATCHing in place would silently rewrite the sibling's
  423. metadata too. Fall back to find_or_create — only this spool's
  424. filament_id moves."""
  425. mock_spoolman_client.is_filament_shared.return_value = True
  426. payload = {"subtype": "Matte"}
  427. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  428. assert response.status_code == 200
  429. mock_spoolman_client.find_or_create_filament.assert_called_once()
  430. mock_spoolman_client.patch_filament.assert_not_called()
  431. @pytest.mark.asyncio
  432. @pytest.mark.integration
  433. async def test_update_with_explicit_null_color_name_clears_extra(
  434. self,
  435. async_client: AsyncClient,
  436. spoolman_settings,
  437. mock_spoolman_client,
  438. ):
  439. """#1357: explicit color_name=null means "clear". The route writes a
  440. JSON-encoded empty string to spool.extra.bambu_color_name so the read
  441. path falls back to the synth value next time."""
  442. payload = {"color_name": None}
  443. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  444. assert response.status_code == 200
  445. mock_spoolman_client.ensure_extra_field.assert_any_call("bambu_color_name")
  446. mock_spoolman_client.merge_spool_extra.assert_called_once()
  447. _, kwargs = mock_spoolman_client.merge_spool_extra.call_args
  448. # First positional arg is spool_id; second is the extra-dict patch.
  449. args = mock_spoolman_client.merge_spool_extra.call_args.args
  450. extra_patch = args[1] if len(args) > 1 else kwargs.get("new_fields", {})
  451. import json as _json
  452. assert _json.loads(extra_patch["bambu_color_name"]) == ""
  453. @pytest.mark.asyncio
  454. @pytest.mark.integration
  455. async def test_update_without_color_name_skips_extra_write(
  456. self,
  457. async_client: AsyncClient,
  458. spoolman_settings,
  459. mock_spoolman_client,
  460. ):
  461. """#1357: when color_name is omitted from the PATCH body the extra
  462. write is skipped entirely — no merge_spool_extra call, no ensure_extra
  463. call for bambu_color_name. Only fields the request explicitly set go
  464. through the extra round-trip."""
  465. payload = {"note": "only updating note"}
  466. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  467. assert response.status_code == 200
  468. # No call should target bambu_color_name when color_name wasn't in the body.
  469. color_name_calls = [
  470. c
  471. for c in mock_spoolman_client.ensure_extra_field.call_args_list
  472. if c.args and c.args[0] == "bambu_color_name"
  473. ]
  474. assert color_name_calls == []
  475. @pytest.mark.asyncio
  476. @pytest.mark.integration
  477. async def test_update_spool_not_found(
  478. self,
  479. async_client: AsyncClient,
  480. spoolman_settings,
  481. mock_spoolman_client,
  482. ):
  483. """PATCH returns 404 when Spoolman spool does not exist."""
  484. from backend.app.services.spoolman import SpoolmanNotFoundError
  485. mock_spoolman_client.get_spool.side_effect = SpoolmanNotFoundError("spool not found")
  486. response = await async_client.patch("/api/v1/spoolman/inventory/spools/999", json={"note": "x"})
  487. assert response.status_code == 404
  488. @pytest.mark.asyncio
  489. @pytest.mark.integration
  490. async def test_delete_spool(
  491. self,
  492. async_client: AsyncClient,
  493. spoolman_settings,
  494. mock_spoolman_client,
  495. ):
  496. """DELETE /spoolman/inventory/spools/{id} deletes a spool."""
  497. response = await async_client.delete("/api/v1/spoolman/inventory/spools/42")
  498. assert response.status_code == 200
  499. assert response.json()["status"] == "deleted"
  500. mock_spoolman_client.delete_spool.assert_called_once_with(42)
  501. @pytest.mark.asyncio
  502. @pytest.mark.integration
  503. async def test_delete_spool_failure(
  504. self,
  505. async_client: AsyncClient,
  506. spoolman_settings,
  507. mock_spoolman_client,
  508. ):
  509. """DELETE returns 503 when Spoolman is unreachable."""
  510. from backend.app.services.spoolman import SpoolmanUnavailableError
  511. mock_spoolman_client.delete_spool.side_effect = SpoolmanUnavailableError("unreachable")
  512. response = await async_client.delete("/api/v1/spoolman/inventory/spools/42")
  513. assert response.status_code == 503
  514. @pytest.mark.asyncio
  515. @pytest.mark.integration
  516. async def test_delete_spool_not_found(
  517. self,
  518. async_client: AsyncClient,
  519. spoolman_settings,
  520. mock_spoolman_client,
  521. ):
  522. """DELETE returns 404 when Spoolman reports the spool does not exist."""
  523. from backend.app.services.spoolman import SpoolmanNotFoundError
  524. mock_spoolman_client.delete_spool.side_effect = SpoolmanNotFoundError("gone")
  525. response = await async_client.delete("/api/v1/spoolman/inventory/spools/42")
  526. assert response.status_code == 404
  527. @pytest.mark.asyncio
  528. @pytest.mark.integration
  529. async def test_archive_spool_not_found(
  530. self,
  531. async_client: AsyncClient,
  532. spoolman_settings,
  533. mock_spoolman_client,
  534. ):
  535. """POST /archive returns 404 when Spoolman reports the spool does not exist."""
  536. from backend.app.services.spoolman import SpoolmanNotFoundError
  537. mock_spoolman_client.set_spool_archived.side_effect = SpoolmanNotFoundError("gone")
  538. response = await async_client.post("/api/v1/spoolman/inventory/spools/42/archive")
  539. assert response.status_code == 404
  540. @pytest.mark.asyncio
  541. @pytest.mark.integration
  542. async def test_restore_spool_not_found(
  543. self,
  544. async_client: AsyncClient,
  545. spoolman_settings,
  546. mock_spoolman_client,
  547. ):
  548. """POST /restore returns 404 when Spoolman reports the spool does not exist."""
  549. from backend.app.services.spoolman import SpoolmanNotFoundError
  550. mock_spoolman_client.set_spool_archived.side_effect = SpoolmanNotFoundError("gone")
  551. response = await async_client.post("/api/v1/spoolman/inventory/spools/42/restore")
  552. assert response.status_code == 404
  553. @pytest.mark.asyncio
  554. @pytest.mark.integration
  555. async def test_archive_spool(
  556. self,
  557. async_client: AsyncClient,
  558. spoolman_settings,
  559. mock_spoolman_client,
  560. ):
  561. """POST /spoolman/inventory/spools/{id}/archive archives a spool."""
  562. response = await async_client.post("/api/v1/spoolman/inventory/spools/42/archive")
  563. assert response.status_code == 200
  564. mock_spoolman_client.set_spool_archived.assert_called_once_with(42, archived=True)
  565. @pytest.mark.asyncio
  566. @pytest.mark.integration
  567. async def test_restore_spool(
  568. self,
  569. async_client: AsyncClient,
  570. spoolman_settings,
  571. mock_spoolman_client,
  572. ):
  573. """POST /spoolman/inventory/spools/{id}/restore restores an archived spool."""
  574. response = await async_client.post("/api/v1/spoolman/inventory/spools/42/restore")
  575. assert response.status_code == 200
  576. mock_spoolman_client.set_spool_archived.assert_called_once_with(42, archived=False)
  577. @pytest.mark.asyncio
  578. @pytest.mark.integration
  579. async def test_reset_spool_consumed_counter(
  580. self,
  581. async_client: AsyncClient,
  582. spoolman_settings,
  583. mock_spoolman_client,
  584. ):
  585. """POST /spoolman/inventory/spools/{id}/reset-consumed-counter zeroes the displayed counter.
  586. Parity with internal mode (#1390): the InventorySpool response
  587. carries `weight_used = label - remaining` and
  588. `weight_used_baseline = weight_used - real_used_weight`, so the
  589. displayed consumed counter (weight_used - baseline) reads 0
  590. while remaining (= label - weight_used) preserves Spoolman's
  591. independent remaining_weight field.
  592. """
  593. response = await async_client.post("/api/v1/spoolman/inventory/spools/42/reset-consumed-counter")
  594. assert response.status_code == 200
  595. body = response.json()
  596. # Sample spool: label=1000, remaining=750, used_weight=0 after Spoolman reset.
  597. assert body["weight_used"] == 250.0, "synthetic weight_used = label - remaining"
  598. assert body["weight_used_baseline"] == 250.0, "baseline absorbs the reset"
  599. assert body["weight_used"] - body["weight_used_baseline"] == 0, "displayed consumed = 0"
  600. assert body["label_weight"] - body["weight_used"] == 750, "remaining unchanged"
  601. mock_spoolman_client.reset_spool_usage.assert_called_once_with(42)
  602. @pytest.mark.asyncio
  603. @pytest.mark.integration
  604. async def test_bulk_reset_spool_consumed_counter(
  605. self,
  606. async_client: AsyncClient,
  607. spoolman_settings,
  608. mock_spoolman_client,
  609. ):
  610. """Bulk endpoint resets each listed spool's counter and returns the count."""
  611. response = await async_client.post(
  612. "/api/v1/spoolman/inventory/spools/reset-consumed-counter-bulk",
  613. json={"spool_ids": [1, 2, 3]},
  614. )
  615. assert response.status_code == 200
  616. assert response.json() == {"reset": 3}
  617. assert mock_spoolman_client.reset_spool_usage.call_count == 3
  618. @pytest.mark.asyncio
  619. @pytest.mark.integration
  620. async def test_bulk_reset_rejects_empty_list(
  621. self,
  622. async_client: AsyncClient,
  623. spoolman_settings,
  624. mock_spoolman_client,
  625. ):
  626. """Empty list must be rejected — guards against accidental wildcard wipes."""
  627. response = await async_client.post(
  628. "/api/v1/spoolman/inventory/spools/reset-consumed-counter-bulk",
  629. json={"spool_ids": []},
  630. )
  631. assert response.status_code == 400
  632. mock_spoolman_client.reset_spool_usage.assert_not_called()
  633. @pytest.mark.asyncio
  634. @pytest.mark.integration
  635. async def test_sync_weight(
  636. self,
  637. async_client: AsyncClient,
  638. spoolman_settings,
  639. mock_spoolman_client,
  640. ):
  641. """PATCH /spoolman/inventory/spools/{id}/weight updates remaining weight."""
  642. payload = {"weight_grams": 850.0}
  643. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42/weight", json=payload)
  644. assert response.status_code == 200
  645. result = response.json()
  646. assert result["status"] == "ok"
  647. # remaining = 850 - 250 core = 600; weight_used = 1000 - 600 = 400
  648. assert result["weight_used"] == 400.0
  649. mock_spoolman_client.update_spool_full.assert_called_once_with(spool_id=42, remaining_weight=600.0)
  650. @pytest.mark.asyncio
  651. @pytest.mark.integration
  652. async def test_update_spool_returns_404_on_not_found(
  653. self,
  654. async_client: AsyncClient,
  655. spoolman_settings,
  656. mock_spoolman_client,
  657. ):
  658. """PATCH returns 404 when update_spool_full raises SpoolmanNotFoundError (I2)."""
  659. from backend.app.services.spoolman import SpoolmanNotFoundError
  660. mock_spoolman_client.update_spool_full.side_effect = SpoolmanNotFoundError("gone")
  661. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json={"note": "x"})
  662. assert response.status_code == 404
  663. @pytest.mark.asyncio
  664. @pytest.mark.integration
  665. async def test_update_spool_returns_503_on_unavailable(
  666. self,
  667. async_client: AsyncClient,
  668. spoolman_settings,
  669. mock_spoolman_client,
  670. ):
  671. """PATCH returns 503 when update_spool_full raises SpoolmanUnavailableError (I2)."""
  672. from backend.app.services.spoolman import SpoolmanUnavailableError
  673. mock_spoolman_client.update_spool_full.side_effect = SpoolmanUnavailableError("down")
  674. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json={"note": "x"})
  675. assert response.status_code == 503
  676. @pytest.mark.asyncio
  677. @pytest.mark.integration
  678. async def test_sync_weight_returns_404_on_not_found(
  679. self,
  680. async_client: AsyncClient,
  681. spoolman_settings,
  682. mock_spoolman_client,
  683. ):
  684. """PATCH /weight returns 404 when update_spool_full raises SpoolmanNotFoundError (I2)."""
  685. from backend.app.services.spoolman import SpoolmanNotFoundError
  686. mock_spoolman_client.update_spool_full.side_effect = SpoolmanNotFoundError("gone")
  687. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42/weight", json={"weight_grams": 500.0})
  688. assert response.status_code == 404
  689. @pytest.mark.asyncio
  690. @pytest.mark.integration
  691. async def test_sync_weight_returns_503_on_unavailable(
  692. self,
  693. async_client: AsyncClient,
  694. spoolman_settings,
  695. mock_spoolman_client,
  696. ):
  697. """PATCH /weight returns 503 when update_spool_full raises SpoolmanUnavailableError (I2)."""
  698. from backend.app.services.spoolman import SpoolmanUnavailableError
  699. mock_spoolman_client.update_spool_full.side_effect = SpoolmanUnavailableError("down")
  700. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42/weight", json={"weight_grams": 500.0})
  701. assert response.status_code == 503
  702. class TestSpoolmanInventorySlicerFilament:
  703. """slicer_filament persistence via Spoolman extra dict.
  704. Spoolman has no native slicer_filament field — Bambuddy persists the
  705. BambuStudio preset under bambu_slicer_filament[_name] keys in the
  706. spool's extra dict and unwraps them in _map_spoolman_spool. Without
  707. this round-trip the user's slicer-preset selection on the spool form
  708. is silently dropped (#1114).
  709. """
  710. @pytest.mark.asyncio
  711. @pytest.mark.integration
  712. async def test_update_persists_slicer_filament_to_extra(
  713. self,
  714. async_client: AsyncClient,
  715. spoolman_settings,
  716. mock_spoolman_client,
  717. ):
  718. """PATCH with slicer_filament writes bambu_slicer_filament to extra.
  719. Spoolman's PATCH MERGES extra keys, so we send via merge_spool_extra
  720. not update_spool_full. Values are JSON-encoded strings.
  721. """
  722. import json as _json
  723. mock_spoolman_client.ensure_extra_field = AsyncMock(return_value=True)
  724. response = await async_client.patch(
  725. "/api/v1/spoolman/inventory/spools/42",
  726. json={
  727. "slicer_filament": "PFUSf543b298f8ea66",
  728. "slicer_filament_name": "Devil Design PLA Basic @Bambu Lab H2D 0.4 nozzle (Custom)",
  729. },
  730. )
  731. assert response.status_code == 200
  732. # Field registration is idempotent — must be called for each key
  733. ensure_calls = [c.args[0] for c in mock_spoolman_client.ensure_extra_field.call_args_list]
  734. assert "bambu_slicer_filament" in ensure_calls
  735. assert "bambu_slicer_filament_name" in ensure_calls
  736. # Values must be JSON-encoded so read-side can json.loads + .strip('"')
  737. mock_spoolman_client.merge_spool_extra.assert_called_once_with(
  738. 42,
  739. {
  740. "bambu_slicer_filament": _json.dumps("PFUSf543b298f8ea66"),
  741. "bambu_slicer_filament_name": _json.dumps("Devil Design PLA Basic @Bambu Lab H2D 0.4 nozzle (Custom)"),
  742. },
  743. )
  744. @pytest.mark.asyncio
  745. @pytest.mark.integration
  746. async def test_update_without_slicer_filament_skips_merge(
  747. self,
  748. async_client: AsyncClient,
  749. spoolman_settings,
  750. mock_spoolman_client,
  751. ):
  752. """PATCH without slicer_filament fields must not call merge_spool_extra.
  753. Avoids overwriting an existing preset with empty/null when the user
  754. just changed an unrelated field (e.g. note, weight).
  755. """
  756. response = await async_client.patch(
  757. "/api/v1/spoolman/inventory/spools/42",
  758. json={"note": "just changing the note"},
  759. )
  760. assert response.status_code == 200
  761. mock_spoolman_client.merge_spool_extra.assert_not_called()
  762. @pytest.mark.asyncio
  763. @pytest.mark.integration
  764. async def test_update_clears_slicer_filament_with_empty_string(
  765. self,
  766. async_client: AsyncClient,
  767. spoolman_settings,
  768. mock_spoolman_client,
  769. ):
  770. """Empty-string slicer_filament writes the JSON-encoded "" sentinel.
  771. The read-side strip('"') resolves it to an empty string and falls
  772. back to filament.name — matches the user-facing "clear preset" flow.
  773. """
  774. import json as _json
  775. mock_spoolman_client.ensure_extra_field = AsyncMock(return_value=True)
  776. response = await async_client.patch(
  777. "/api/v1/spoolman/inventory/spools/42",
  778. json={"slicer_filament": "", "slicer_filament_name": ""},
  779. )
  780. assert response.status_code == 200
  781. mock_spoolman_client.merge_spool_extra.assert_called_once_with(
  782. 42,
  783. {
  784. "bambu_slicer_filament": _json.dumps(""),
  785. "bambu_slicer_filament_name": _json.dumps(""),
  786. },
  787. )
  788. class TestSpoolmanInventoryCostPerKg:
  789. """Tests for the two-step cost_per_kg create path (PT-C2)."""
  790. @pytest.mark.asyncio
  791. @pytest.mark.integration
  792. async def test_create_spool_with_cost_per_kg_calls_price_update(
  793. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  794. ):
  795. """POST with cost_per_kg calls update_spool_full with price= after creation."""
  796. from unittest.mock import AsyncMock
  797. mock_spoolman_client.update_spool_full = AsyncMock(return_value=SAMPLE_SPOOLMAN_SPOOL)
  798. payload = {
  799. "material": "PLA",
  800. "brand": "Bambu Lab",
  801. "label_weight": 1000,
  802. "cost_per_kg": 24.99,
  803. }
  804. resp = await async_client.post("/api/v1/spoolman/inventory/spools", json=payload)
  805. assert resp.status_code == 200
  806. # update_spool_full must have been called with price=24.99
  807. calls = [
  808. c
  809. for c in mock_spoolman_client.update_spool_full.call_args_list
  810. if c.kwargs.get("price") == 24.99 or (c.args and 24.99 in c.args)
  811. ]
  812. assert len(calls) >= 1
  813. @pytest.mark.asyncio
  814. @pytest.mark.integration
  815. async def test_create_spool_without_cost_per_kg_skips_price_update(
  816. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  817. ):
  818. """POST without cost_per_kg does not call update_spool_full."""
  819. from unittest.mock import AsyncMock
  820. mock_spoolman_client.update_spool_full = AsyncMock(return_value=SAMPLE_SPOOLMAN_SPOOL)
  821. payload = {"material": "PLA", "brand": "Bambu Lab", "label_weight": 1000}
  822. resp = await async_client.post("/api/v1/spoolman/inventory/spools", json=payload)
  823. assert resp.status_code == 200
  824. mock_spoolman_client.update_spool_full.assert_not_called()
  825. class TestSpoolmanInventoryInputValidation:
  826. """Tests for input validation added as security hardening."""
  827. @pytest.mark.asyncio
  828. @pytest.mark.integration
  829. async def test_create_rejects_material_too_long(
  830. self,
  831. async_client: AsyncClient,
  832. spoolman_settings,
  833. mock_spoolman_client,
  834. ):
  835. """material longer than 64 chars is rejected with 422."""
  836. payload = {"material": "A" * 65, "label_weight": 1000, "weight_used": 0}
  837. response = await async_client.post("/api/v1/spoolman/inventory/spools", json=payload)
  838. assert response.status_code == 422
  839. @pytest.mark.asyncio
  840. @pytest.mark.integration
  841. async def test_create_rejects_note_too_long(
  842. self,
  843. async_client: AsyncClient,
  844. spoolman_settings,
  845. mock_spoolman_client,
  846. ):
  847. """note longer than 1000 chars is rejected with 422."""
  848. payload = {
  849. "material": "PLA",
  850. "label_weight": 1000,
  851. "weight_used": 0,
  852. "note": "x" * 1001,
  853. }
  854. response = await async_client.post("/api/v1/spoolman/inventory/spools", json=payload)
  855. assert response.status_code == 422
  856. @pytest.mark.asyncio
  857. @pytest.mark.integration
  858. async def test_create_rejects_negative_weight_used(
  859. self,
  860. async_client: AsyncClient,
  861. spoolman_settings,
  862. mock_spoolman_client,
  863. ):
  864. """Negative weight_used is rejected with 422."""
  865. payload = {"material": "PLA", "label_weight": 1000, "weight_used": -1.0}
  866. response = await async_client.post("/api/v1/spoolman/inventory/spools", json=payload)
  867. assert response.status_code == 422
  868. @pytest.mark.asyncio
  869. @pytest.mark.integration
  870. async def test_create_rejects_zero_label_weight(
  871. self,
  872. async_client: AsyncClient,
  873. spoolman_settings,
  874. mock_spoolman_client,
  875. ):
  876. """label_weight of 0 is rejected (minimum is 1)."""
  877. payload = {"material": "PLA", "label_weight": 0, "weight_used": 0}
  878. response = await async_client.post("/api/v1/spoolman/inventory/spools", json=payload)
  879. assert response.status_code == 422
  880. @pytest.mark.asyncio
  881. @pytest.mark.integration
  882. async def test_create_rejects_invalid_rgba(
  883. self,
  884. async_client: AsyncClient,
  885. spoolman_settings,
  886. mock_spoolman_client,
  887. ):
  888. """Non-hex rgba string is rejected with 422."""
  889. payload = {"material": "PLA", "label_weight": 1000, "weight_used": 0, "rgba": "GGGGGGFF"}
  890. response = await async_client.post("/api/v1/spoolman/inventory/spools", json=payload)
  891. assert response.status_code == 422
  892. @pytest.mark.asyncio
  893. @pytest.mark.integration
  894. async def test_create_accepts_valid_6char_rgba(
  895. self,
  896. async_client: AsyncClient,
  897. spoolman_settings,
  898. mock_spoolman_client,
  899. ):
  900. """A valid 6-char hex rgba is accepted."""
  901. payload = {"material": "PLA", "label_weight": 1000, "weight_used": 0, "rgba": "FF0000"}
  902. response = await async_client.post("/api/v1/spoolman/inventory/spools", json=payload)
  903. assert response.status_code == 200
  904. @pytest.mark.asyncio
  905. @pytest.mark.integration
  906. async def test_weight_update_rejects_negative_grams(
  907. self,
  908. async_client: AsyncClient,
  909. spoolman_settings,
  910. mock_spoolman_client,
  911. ):
  912. """Negative weight_grams on weight sync endpoint is rejected with 422."""
  913. response = await async_client.patch(
  914. "/api/v1/spoolman/inventory/spools/42/weight",
  915. json={"weight_grams": -50.0},
  916. )
  917. assert response.status_code == 422
  918. @pytest.mark.asyncio
  919. @pytest.mark.integration
  920. async def test_update_rejects_tag_uid_too_long(
  921. self,
  922. async_client: AsyncClient,
  923. spoolman_settings,
  924. mock_spoolman_client,
  925. ):
  926. """tag_uid longer than 30 chars is rejected with 422 (NFC UID max 10 bytes = 20 hex chars, capped at 30)."""
  927. payload = {"tag_uid": "A" * 65}
  928. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  929. assert response.status_code == 422
  930. @pytest.mark.asyncio
  931. @pytest.mark.integration
  932. async def test_update_rejects_tray_uuid_too_long(
  933. self,
  934. async_client: AsyncClient,
  935. spoolman_settings,
  936. mock_spoolman_client,
  937. ):
  938. """tray_uuid longer than 32 chars is rejected with 422."""
  939. payload = {"tray_uuid": "B" * 65}
  940. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  941. assert response.status_code == 422
  942. @pytest.mark.asyncio
  943. @pytest.mark.integration
  944. @pytest.mark.parametrize("uuid_len", [16, 31])
  945. async def test_update_rejects_tray_uuid_too_short(
  946. self,
  947. async_client: AsyncClient,
  948. spoolman_settings,
  949. mock_spoolman_client,
  950. uuid_len: int,
  951. ):
  952. """tray_uuid shorter than 32 chars is rejected (min_length=max_length=32)."""
  953. payload = {"tray_uuid": "A" * uuid_len}
  954. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  955. assert response.status_code == 422
  956. @pytest.mark.asyncio
  957. @pytest.mark.integration
  958. async def test_update_rejects_rgba_nine_chars(
  959. self,
  960. async_client: AsyncClient,
  961. spoolman_settings,
  962. mock_spoolman_client,
  963. ):
  964. """rgba must be max 8 hex chars; 9-char value is rejected with 422."""
  965. payload = {"rgba": "FF0000FFA"} # 9 chars
  966. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  967. assert response.status_code == 422
  968. @pytest.mark.asyncio
  969. @pytest.mark.integration
  970. async def test_tag_uid_below_min_length_rejected(
  971. self,
  972. async_client: AsyncClient,
  973. spoolman_settings,
  974. mock_spoolman_client,
  975. ):
  976. """tag_uid shorter than 8 hex chars is rejected with 422 (PT-I5)."""
  977. payload = {"tag_uid": "AABBCC"} # 6 chars, below min_length=8
  978. resp = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  979. assert resp.status_code == 422
  980. @pytest.mark.asyncio
  981. @pytest.mark.integration
  982. async def test_invalid_spoolman_url_scheme_returns_400(
  983. self,
  984. async_client: AsyncClient,
  985. db_session,
  986. mock_spoolman_client,
  987. ):
  988. """A spoolman_url with a non-http(s) scheme is rejected."""
  989. from backend.app.models.settings import Settings
  990. db_session.add(Settings(key="spoolman_enabled", value="true"))
  991. db_session.add(Settings(key="spoolman_url", value="ftp://evil.internal/"))
  992. await db_session.commit()
  993. response = await async_client.get("/api/v1/spoolman/inventory/spools")
  994. assert response.status_code == 400
  995. assert "http" in response.json()["detail"].lower()
  996. @pytest.mark.asyncio
  997. @pytest.mark.integration
  998. @pytest.mark.parametrize(
  999. "evil_url",
  1000. [
  1001. "file:///etc/passwd",
  1002. "gopher://127.0.0.1:70/",
  1003. "dict://internal.corp/",
  1004. "javascript:alert(1)",
  1005. "http://169.254.169.254/latest/meta-data/", # AWS IMDS
  1006. "http://100.100.100.200/", # Alibaba Cloud metadata
  1007. "http://[fd00:ec2::254]/", # AWS IMDS IPv6
  1008. "http://0.0.0.0/", # unspecified
  1009. "http://224.0.0.1/", # IPv4 multicast
  1010. "http://[ff02::1]/", # IPv6 multicast
  1011. "http://[::ffff:169.254.169.254]/", # IPv4-mapped IPv6 IMDS bypass
  1012. "http://2130706433/", # decimal-encoded 127.0.0.1
  1013. "http://0x7f000001/", # hex-encoded 127.0.0.1
  1014. ],
  1015. )
  1016. async def test_ssrf_blocked_schemes_and_addresses(
  1017. self,
  1018. async_client: AsyncClient,
  1019. db_session,
  1020. mock_spoolman_client,
  1021. evil_url: str,
  1022. ):
  1023. """SSRF: dangerous schemes, cloud metadata IPs, multicast, unspecified,
  1024. and numeric-encoded IPs must be rejected with 400. Loopback and
  1025. RFC-1918 private ranges are allowed — they are legitimate Spoolman
  1026. topologies for self-hosted Bambuddy deployments."""
  1027. from backend.app.models.settings import Settings
  1028. db_session.add(Settings(key="spoolman_enabled", value="true"))
  1029. db_session.add(Settings(key="spoolman_url", value=evil_url))
  1030. await db_session.commit()
  1031. response = await async_client.get("/api/v1/spoolman/inventory/spools")
  1032. assert response.status_code == 400, (
  1033. f"Expected 400 for SSRF URL {evil_url!r} but got {response.status_code}: {response.json()}"
  1034. )
  1035. @pytest.mark.asyncio
  1036. @pytest.mark.integration
  1037. @pytest.mark.parametrize(
  1038. "lan_url",
  1039. [
  1040. "http://127.0.0.1:7912/", # loopback
  1041. "http://[::1]:7912/", # IPv6 loopback
  1042. "http://192.168.1.50:7912/", # RFC-1918 /16
  1043. "http://10.0.0.5:7912/", # RFC-1918 /8
  1044. "http://172.20.0.3:7912/", # RFC-1918 /12
  1045. ],
  1046. )
  1047. async def test_ssrf_allows_lan_spoolman_topologies(
  1048. self,
  1049. async_client: AsyncClient,
  1050. db_session,
  1051. mock_spoolman_client,
  1052. lan_url: str,
  1053. ):
  1054. """Regression: Bambuddy's normal deployment is LAN-local Spoolman.
  1055. Loopback and RFC-1918 private addresses must NOT be rejected as SSRF."""
  1056. from backend.app.models.settings import Settings
  1057. db_session.add(Settings(key="spoolman_enabled", value="true"))
  1058. db_session.add(Settings(key="spoolman_url", value=lan_url))
  1059. await db_session.commit()
  1060. response = await async_client.get("/api/v1/spoolman/inventory/spools")
  1061. assert response.status_code != 400, f"LAN URL {lan_url!r} was incorrectly blocked as SSRF: {response.json()}"
  1062. @pytest.mark.asyncio
  1063. @pytest.mark.integration
  1064. async def test_create_rejects_storage_location_too_long(
  1065. self,
  1066. async_client: AsyncClient,
  1067. spoolman_settings,
  1068. mock_spoolman_client,
  1069. ):
  1070. """storage_location longer than 255 chars is rejected with 422."""
  1071. payload = {
  1072. "material": "PLA",
  1073. "label_weight": 1000,
  1074. "weight_used": 0,
  1075. "storage_location": "x" * 256,
  1076. }
  1077. response = await async_client.post("/api/v1/spoolman/inventory/spools", json=payload)
  1078. assert response.status_code == 422
  1079. @pytest.mark.asyncio
  1080. @pytest.mark.integration
  1081. async def test_update_rejects_storage_location_too_long(
  1082. self,
  1083. async_client: AsyncClient,
  1084. spoolman_settings,
  1085. mock_spoolman_client,
  1086. ):
  1087. """storage_location longer than 255 chars on PATCH is rejected with 422."""
  1088. payload = {"storage_location": "y" * 256}
  1089. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  1090. assert response.status_code == 422
  1091. class TestStorageLocationPassthrough:
  1092. """Tests that storage_location is correctly passed to and from Spoolman."""
  1093. @pytest.mark.asyncio
  1094. @pytest.mark.integration
  1095. async def test_list_spools_maps_spoolman_location_to_storage_location(
  1096. self,
  1097. async_client: AsyncClient,
  1098. spoolman_settings,
  1099. mock_spoolman_client,
  1100. ):
  1101. """Spoolman's location field is exposed as storage_location in the response."""
  1102. response = await async_client.get("/api/v1/spoolman/inventory/spools")
  1103. spool = response.json()[0]
  1104. assert spool["storage_location"] == "Printer1 - AMS A1"
  1105. @pytest.mark.asyncio
  1106. @pytest.mark.integration
  1107. async def test_list_spools_null_location_gives_null_storage_location(
  1108. self,
  1109. async_client: AsyncClient,
  1110. spoolman_settings,
  1111. mock_spoolman_client,
  1112. ):
  1113. """A Spoolman spool with no location gives null storage_location."""
  1114. spool_no_loc = {**SAMPLE_SPOOLMAN_SPOOL, "location": None}
  1115. mock_spoolman_client.get_all_spools.return_value = [spool_no_loc]
  1116. response = await async_client.get("/api/v1/spoolman/inventory/spools")
  1117. spool = response.json()[0]
  1118. assert spool["storage_location"] is None
  1119. @pytest.mark.asyncio
  1120. @pytest.mark.integration
  1121. async def test_create_passes_storage_location_to_spoolman(
  1122. self,
  1123. async_client: AsyncClient,
  1124. spoolman_settings,
  1125. mock_spoolman_client,
  1126. ):
  1127. """storage_location is forwarded as location when creating a Spoolman spool."""
  1128. payload = {
  1129. "material": "PLA",
  1130. "label_weight": 1000,
  1131. "weight_used": 0,
  1132. "storage_location": "Shelf B",
  1133. }
  1134. response = await async_client.post("/api/v1/spoolman/inventory/spools", json=payload)
  1135. assert response.status_code == 200
  1136. mock_spoolman_client.create_spool.assert_called_once()
  1137. _, kwargs = mock_spoolman_client.create_spool.call_args
  1138. assert kwargs.get("location") == "Shelf B"
  1139. @pytest.mark.asyncio
  1140. @pytest.mark.integration
  1141. async def test_update_passes_storage_location_to_spoolman(
  1142. self,
  1143. async_client: AsyncClient,
  1144. spoolman_settings,
  1145. mock_spoolman_client,
  1146. ):
  1147. """storage_location is forwarded as location when updating a Spoolman spool."""
  1148. payload = {"storage_location": "Drawer 3"}
  1149. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  1150. assert response.status_code == 200
  1151. mock_spoolman_client.update_spool_full.assert_called_once()
  1152. _, kwargs = mock_spoolman_client.update_spool_full.call_args
  1153. assert kwargs.get("location") == "Drawer 3"
  1154. assert kwargs.get("clear_location") is False
  1155. @pytest.mark.asyncio
  1156. @pytest.mark.integration
  1157. async def test_update_clears_storage_location_when_null_sent(
  1158. self,
  1159. async_client: AsyncClient,
  1160. spoolman_settings,
  1161. mock_spoolman_client,
  1162. ):
  1163. """Explicitly sending null storage_location clears the Spoolman location."""
  1164. payload = {"storage_location": None}
  1165. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  1166. assert response.status_code == 200
  1167. _, kwargs = mock_spoolman_client.update_spool_full.call_args
  1168. assert kwargs.get("clear_location") is True
  1169. @pytest.mark.asyncio
  1170. @pytest.mark.integration
  1171. async def test_update_clears_storage_location_when_empty_string_sent(
  1172. self,
  1173. async_client: AsyncClient,
  1174. spoolman_settings,
  1175. mock_spoolman_client,
  1176. ):
  1177. """Sending an empty string for storage_location also clears the Spoolman location."""
  1178. payload = {"storage_location": ""}
  1179. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  1180. assert response.status_code == 200
  1181. _, kwargs = mock_spoolman_client.update_spool_full.call_args
  1182. assert kwargs.get("clear_location") is True
  1183. @pytest.mark.asyncio
  1184. @pytest.mark.integration
  1185. async def test_update_omitting_storage_location_does_not_write_location_to_spoolman(
  1186. self,
  1187. async_client: AsyncClient,
  1188. spoolman_settings,
  1189. mock_spoolman_client,
  1190. ):
  1191. """PATCH without storage_location in the payload must not touch Spoolman's location field.
  1192. Regression test for the round-trip bug: opening the edit modal and saving without
  1193. changing the location would previously echo the current Spoolman value back
  1194. (storage_location_changed=False branch used current.get("location") instead of None).
  1195. """
  1196. # Payload deliberately omits storage_location — simulates saving the modal
  1197. # without touching that field.
  1198. payload = {"note": "just updating the note"}
  1199. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  1200. assert response.status_code == 200
  1201. mock_spoolman_client.update_spool_full.assert_called_once()
  1202. _, kwargs = mock_spoolman_client.update_spool_full.call_args
  1203. # location must be None so update_spool_full skips writing the field entirely
  1204. assert kwargs.get("location") is None
  1205. # clear_location must also be False — we are not explicitly clearing it either
  1206. assert kwargs.get("clear_location") is False
  1207. class TestColorNamePassthrough:
  1208. """color_name persistence via spool.extra.bambu_color_name (#1357).
  1209. Spoolman 0.23.1 has no `color_name` field on Filament, so Bambuddy owns
  1210. the round-trip via the spool's extra dict — same shape as the existing
  1211. bambu_slicer_filament storage. These tests pin that the create/update
  1212. routes register the extra field and write to merge_spool_extra, NOT to
  1213. find_or_create_filament's color_name parameter.
  1214. """
  1215. @pytest.mark.asyncio
  1216. @pytest.mark.integration
  1217. async def test_create_writes_color_name_to_spool_extra(
  1218. self,
  1219. async_client: AsyncClient,
  1220. spoolman_settings,
  1221. mock_spoolman_client,
  1222. ):
  1223. """color_name from create payload lands in spool.extra.bambu_color_name."""
  1224. import json as _json
  1225. payload = {
  1226. "material": "PLA",
  1227. "label_weight": 1000,
  1228. "weight_used": 0,
  1229. "color_name": "Bambu Green",
  1230. }
  1231. response = await async_client.post("/api/v1/spoolman/inventory/spools", json=payload)
  1232. assert response.status_code == 200
  1233. mock_spoolman_client.ensure_extra_field.assert_any_call("bambu_color_name")
  1234. mock_spoolman_client.merge_spool_extra.assert_called_once()
  1235. args = mock_spoolman_client.merge_spool_extra.call_args.args
  1236. extra_patch = args[1]
  1237. assert _json.loads(extra_patch["bambu_color_name"]) == "Bambu Green"
  1238. @pytest.mark.asyncio
  1239. @pytest.mark.integration
  1240. async def test_update_writes_color_name_to_spool_extra(
  1241. self,
  1242. async_client: AsyncClient,
  1243. spoolman_settings,
  1244. mock_spoolman_client,
  1245. ):
  1246. """color_name from update payload lands in spool.extra.bambu_color_name —
  1247. this is the #1357 reproduction: previously the value went to
  1248. filament.color_name which Spoolman silently dropped."""
  1249. import json as _json
  1250. payload = {"color_name": "Jade White"}
  1251. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  1252. assert response.status_code == 200
  1253. mock_spoolman_client.ensure_extra_field.assert_any_call("bambu_color_name")
  1254. mock_spoolman_client.merge_spool_extra.assert_called_once()
  1255. args = mock_spoolman_client.merge_spool_extra.call_args.args
  1256. extra_patch = args[1]
  1257. assert _json.loads(extra_patch["bambu_color_name"]) == "Jade White"
  1258. @pytest.mark.asyncio
  1259. @pytest.mark.integration
  1260. async def test_update_omits_color_name_skips_extra_write(
  1261. self,
  1262. async_client: AsyncClient,
  1263. spoolman_settings,
  1264. mock_spoolman_client,
  1265. ):
  1266. """When color_name is absent from the PATCH body, the route must not
  1267. write to spool.extra at all (preserves any existing value)."""
  1268. payload = {"note": "no color_name here"}
  1269. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  1270. assert response.status_code == 200
  1271. color_name_calls = [
  1272. c
  1273. for c in mock_spoolman_client.ensure_extra_field.call_args_list
  1274. if c.args and c.args[0] == "bambu_color_name"
  1275. ]
  1276. assert color_name_calls == []
  1277. class TestSpoolmanInventoryAuth:
  1278. """Write/delete endpoints require INVENTORY_UPDATE when auth is enabled."""
  1279. @pytest.fixture
  1280. async def auth_and_spoolman_settings(self, db_session):
  1281. """Enable both Spoolman and auth."""
  1282. from backend.app.models.settings import Settings
  1283. db_session.add(Settings(key="spoolman_enabled", value="true"))
  1284. db_session.add(Settings(key="spoolman_url", value="http://localhost:7912"))
  1285. db_session.add(Settings(key="auth_enabled", value="true"))
  1286. await db_session.commit()
  1287. @pytest.mark.asyncio
  1288. @pytest.mark.integration
  1289. @pytest.mark.parametrize(
  1290. "method,path,payload",
  1291. [
  1292. ("POST", "/api/v1/spoolman/inventory/spools", {"material": "PLA", "label_weight": 1000, "weight_used": 0}),
  1293. (
  1294. "POST",
  1295. "/api/v1/spoolman/inventory/spools/bulk",
  1296. {"spool": {"material": "PLA", "label_weight": 1000, "weight_used": 0}, "quantity": 1},
  1297. ),
  1298. ("PATCH", "/api/v1/spoolman/inventory/spools/42", {"note": "x"}),
  1299. ("DELETE", "/api/v1/spoolman/inventory/spools/42", None),
  1300. ("POST", "/api/v1/spoolman/inventory/spools/42/archive", None),
  1301. ("POST", "/api/v1/spoolman/inventory/spools/42/restore", None),
  1302. ("PATCH", "/api/v1/spoolman/inventory/spools/42/weight", {"weight_grams": 100.0}),
  1303. ],
  1304. )
  1305. async def test_write_endpoints_require_auth(
  1306. self,
  1307. async_client: AsyncClient,
  1308. auth_and_spoolman_settings,
  1309. method: str,
  1310. path: str,
  1311. payload: dict | None,
  1312. ):
  1313. """All write/delete endpoints return 401 when auth is enabled and no token is provided."""
  1314. response = await async_client.request(method, path, json=payload)
  1315. assert response.status_code == 401, (
  1316. f"{method} {path} should require auth but got {response.status_code}: {response.json()}"
  1317. )
  1318. @pytest.mark.asyncio
  1319. @pytest.mark.integration
  1320. @pytest.mark.parametrize(
  1321. "method,path",
  1322. [
  1323. ("GET", "/api/v1/spoolman/inventory/spools"),
  1324. ("GET", "/api/v1/spoolman/inventory/spools/42"),
  1325. ],
  1326. )
  1327. async def test_read_endpoints_require_auth(
  1328. self,
  1329. async_client: AsyncClient,
  1330. auth_and_spoolman_settings,
  1331. method: str,
  1332. path: str,
  1333. ):
  1334. """Read endpoints also require auth when auth is enabled."""
  1335. response = await async_client.request(method, path)
  1336. assert response.status_code == 401, (
  1337. f"{method} {path} should require auth but got {response.status_code}: {response.json()}"
  1338. )
  1339. @pytest.fixture
  1340. async def viewer_token(self, db_session):
  1341. """Create a Viewer-group user (INVENTORY_READ only, no INVENTORY_UPDATE)."""
  1342. from sqlalchemy import select
  1343. from backend.app.core.auth import create_access_token, get_password_hash
  1344. from backend.app.models.group import Group
  1345. from backend.app.models.settings import Settings
  1346. from backend.app.models.user import User
  1347. db_session.add(Settings(key="spoolman_enabled", value="true"))
  1348. db_session.add(Settings(key="spoolman_url", value="http://localhost:7912"))
  1349. db_session.add(Settings(key="auth_enabled", value="true"))
  1350. await db_session.commit()
  1351. viewer_group = (await db_session.execute(select(Group).where(Group.name == "Viewers"))).scalar_one()
  1352. viewer = User(
  1353. username="sm_inv_viewer",
  1354. password_hash=get_password_hash("pw"),
  1355. is_active=True,
  1356. )
  1357. viewer.groups.append(viewer_group)
  1358. db_session.add(viewer)
  1359. await db_session.commit()
  1360. return create_access_token(data={"sub": viewer.username})
  1361. @pytest.mark.asyncio
  1362. @pytest.mark.integration
  1363. @pytest.mark.parametrize(
  1364. "method,path,payload",
  1365. [
  1366. ("POST", "/api/v1/spoolman/inventory/spools", {"material": "PLA", "label_weight": 1000, "weight_used": 0}),
  1367. (
  1368. "POST",
  1369. "/api/v1/spoolman/inventory/spools/bulk",
  1370. {"spool": {"material": "PLA", "label_weight": 1000, "weight_used": 0}, "quantity": 1},
  1371. ),
  1372. ("PATCH", "/api/v1/spoolman/inventory/spools/42", {"note": "x"}),
  1373. ("DELETE", "/api/v1/spoolman/inventory/spools/42", None),
  1374. ("POST", "/api/v1/spoolman/inventory/spools/42/archive", None),
  1375. ("POST", "/api/v1/spoolman/inventory/spools/42/restore", None),
  1376. ("PATCH", "/api/v1/spoolman/inventory/spools/42/weight", {"weight_grams": 100.0}),
  1377. ],
  1378. )
  1379. async def test_write_endpoints_return_403_for_viewer(
  1380. self,
  1381. async_client: AsyncClient,
  1382. viewer_token,
  1383. method: str,
  1384. path: str,
  1385. payload: dict | None,
  1386. ):
  1387. """Viewer-group users (INVENTORY_READ, no INVENTORY_UPDATE) get 403 on write endpoints."""
  1388. response = await async_client.request(
  1389. method,
  1390. path,
  1391. json=payload,
  1392. headers={"Authorization": f"Bearer {viewer_token}"},
  1393. )
  1394. assert response.status_code == 403, (
  1395. f"{method} {path} should return 403 for read-only user but got {response.status_code}: {response.json()}"
  1396. )
  1397. # Error body must mention the permission string so a "banned-user middleware"
  1398. # regression (generic 403 with no permission context) doesn't pass silently.
  1399. detail = response.json().get("detail", "")
  1400. assert "inventory:update" in detail, f"Expected 'inventory:update' in 403 detail but got: {detail!r}"
  1401. # ---------------------------------------------------------------------------
  1402. # Additional regression tests for second-round review items
  1403. # ---------------------------------------------------------------------------
  1404. class TestSpoolmanInventorySecurityExtras:
  1405. """Additional security/validation tests added in second review round."""
  1406. @pytest.mark.asyncio
  1407. @pytest.mark.integration
  1408. async def test_create_rejects_double_hash_rgba(
  1409. self,
  1410. async_client: AsyncClient,
  1411. spoolman_settings,
  1412. mock_spoolman_client,
  1413. ):
  1414. """SEC-3: rgba like '##FF0000' (double hash) must be rejected with 422."""
  1415. payload = {"material": "PLA", "label_weight": 1000, "weight_used": 0, "rgba": "##FF0000"}
  1416. response = await async_client.post("/api/v1/spoolman/inventory/spools", json=payload)
  1417. assert response.status_code == 422
  1418. @pytest.mark.asyncio
  1419. @pytest.mark.integration
  1420. @pytest.mark.parametrize("spool_id", [0, -1])
  1421. async def test_path_param_non_positive_spool_id_returns_422(
  1422. self,
  1423. async_client: AsyncClient,
  1424. spoolman_settings,
  1425. mock_spoolman_client,
  1426. spool_id: int,
  1427. ):
  1428. """SEC-5: /spools/0 and /spools/-1 must be rejected with 422 (Path gt=0)."""
  1429. response = await async_client.get(f"/api/v1/spoolman/inventory/spools/{spool_id}")
  1430. assert response.status_code == 422, f"Expected 422 for spool_id={spool_id} but got {response.status_code}"
  1431. @pytest.mark.asyncio
  1432. @pytest.mark.integration
  1433. @pytest.mark.parametrize(
  1434. "tag_uid,expected_status",
  1435. [
  1436. # After B1 fix: non-null tag_uid on PATCH /spools/{id} is rejected (use /tag endpoint)
  1437. ("A" * 30, 422), # non-null → 422 (use /tag endpoint instead)
  1438. ("DEADBEEF12345678", 422), # non-null → 422 regardless of length
  1439. ("A" * 31, 422), # exceeds max_length — also 422
  1440. ("A" * 32, 422), # tray_uuid-length value — also 422
  1441. ],
  1442. )
  1443. async def test_tag_uid_length_boundary(
  1444. self,
  1445. async_client: AsyncClient,
  1446. spoolman_settings,
  1447. mock_spoolman_client,
  1448. tag_uid: str,
  1449. expected_status: int,
  1450. ):
  1451. """tag_uid on PATCH /spools/{id} — all non-null values are rejected (B1 fix; use /tag endpoint)."""
  1452. payload = {"tag_uid": tag_uid}
  1453. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  1454. assert response.status_code == expected_status, (
  1455. f"tag_uid len={len(tag_uid)}: expected {expected_status} but got {response.status_code}"
  1456. )
  1457. @pytest.mark.asyncio
  1458. @pytest.mark.integration
  1459. async def test_bulk_create_partial_failure_returns_207(
  1460. self,
  1461. async_client: AsyncClient,
  1462. spoolman_settings,
  1463. mock_spoolman_client,
  1464. ):
  1465. """I9: bulk create with quantity=3 where middle call fails → 207 Multi-Status."""
  1466. from backend.app.services.spoolman import SpoolmanUnavailableError
  1467. results = [SAMPLE_SPOOLMAN_SPOOL, SpoolmanUnavailableError("Spoolman down"), SAMPLE_SPOOLMAN_SPOOL]
  1468. mock_spoolman_client.create_spool.side_effect = results
  1469. payload = {
  1470. "spool": {"material": "PLA", "label_weight": 1000, "weight_used": 0},
  1471. "quantity": 3,
  1472. }
  1473. response = await async_client.post("/api/v1/spoolman/inventory/spools/bulk", json=payload)
  1474. assert response.status_code == 207, (
  1475. f"Expected 207 Multi-Status for partial failure but got {response.status_code}"
  1476. )
  1477. body = response.json()
  1478. assert isinstance(body, dict)
  1479. assert body["requested_count"] == 3
  1480. assert body["failed_count"] == 1
  1481. assert len(body["created"]) == 2
  1482. class TestTagClearPreservesExtraKeys:
  1483. """Regression test: clearing tag_uid must not wipe unrelated Spoolman extra fields."""
  1484. @pytest.mark.asyncio
  1485. @pytest.mark.integration
  1486. async def test_tag_clear_preserves_custom_extra_key(
  1487. self,
  1488. async_client: AsyncClient,
  1489. spoolman_settings,
  1490. mock_spoolman_client,
  1491. ):
  1492. """PATCH tag_uid=None clears tag without dropping unrelated extra keys.
  1493. Spoolman PATCHes the extra dict by MERGING — popping a key from the
  1494. dict and sending the rest doesn't actually clear it. The endpoint
  1495. sets tag = json.dumps("") explicitly; read-side filters strip the
  1496. wrapping quotes and treat the empty string as "no tag" (#1114).
  1497. """
  1498. import json as _json
  1499. spool_with_extra = {
  1500. **SAMPLE_SPOOLMAN_SPOOL,
  1501. "extra": {"tag": '"AABBCCDDEEFF0011AABBCCDDEEFF0011"', "custom_key": "keep_me"},
  1502. }
  1503. mock_spoolman_client.get_spool = AsyncMock(return_value=spool_with_extra)
  1504. mock_spoolman_client.update_spool_full = AsyncMock(return_value=spool_with_extra)
  1505. response = await async_client.patch(
  1506. "/api/v1/spoolman/inventory/spools/42",
  1507. json={"tag_uid": None},
  1508. )
  1509. assert response.status_code == 200
  1510. mock_spoolman_client.update_spool_full.assert_called_once()
  1511. _, kwargs = mock_spoolman_client.update_spool_full.call_args
  1512. sent_extra = kwargs.get("extra")
  1513. assert sent_extra is not None, "extra must be sent when tag is cleared"
  1514. assert sent_extra.get("tag") == _json.dumps(""), (
  1515. "tag must be set to JSON empty-string sentinel (Spoolman PATCH merges; "
  1516. "popping the key would leave the previous value in place)"
  1517. )
  1518. assert sent_extra.get("custom_key") == "keep_me", "unrelated extra keys must survive"
  1519. @pytest.mark.asyncio
  1520. @pytest.mark.integration
  1521. async def test_tag_clear_refetches_spool_inside_lock(
  1522. self,
  1523. async_client: AsyncClient,
  1524. spoolman_settings,
  1525. mock_spoolman_client,
  1526. ):
  1527. """B7: tag-clear does a fresh get_spool() re-fetch inside the lock, not the stale one.
  1528. Simulates a write that changes extra between the initial get_spool (used for
  1529. other field resolution) and the lock acquisition. The extra sent to
  1530. update_spool_full must come from the second (in-lock) fetch, not the first.
  1531. """
  1532. stale_extra = {"tag": '"AABBCCDD"', "custom_key": "stale_value"}
  1533. fresh_extra = {"tag": '"AABBCCDD"', "custom_key": "fresh_value"}
  1534. stale_spool = {**SAMPLE_SPOOLMAN_SPOOL, "extra": stale_extra}
  1535. fresh_spool = {**SAMPLE_SPOOLMAN_SPOOL, "extra": fresh_extra}
  1536. # First call returns stale; second call (inside lock) returns fresh
  1537. mock_spoolman_client.get_spool = AsyncMock(side_effect=[stale_spool, fresh_spool])
  1538. mock_spoolman_client.update_spool_full = AsyncMock(return_value=fresh_spool)
  1539. response = await async_client.patch(
  1540. "/api/v1/spoolman/inventory/spools/42",
  1541. json={"tag_uid": None, "tray_uuid": None},
  1542. )
  1543. assert response.status_code == 200
  1544. # get_spool called twice: once for field resolution, once for fresh extra fetch
  1545. assert mock_spoolman_client.get_spool.call_count == 2
  1546. import json as _json
  1547. _, kwargs = mock_spoolman_client.update_spool_full.call_args
  1548. sent_extra = kwargs.get("extra")
  1549. assert sent_extra is not None
  1550. # Tag is set to the JSON empty-string sentinel (not popped) — Spoolman
  1551. # PATCH merges, so popping the key would leave the previous value.
  1552. assert sent_extra.get("tag") == _json.dumps("")
  1553. # custom_key must come from the fresh re-fetch, not the stale first fetch
  1554. assert sent_extra.get("custom_key") == "fresh_value"
  1555. class TestSpoolmanInventorySSRFSpoolBuddyPath:
  1556. """SSRF tests for _get_spoolman_client_or_none (nfc/* and scale/ endpoints)."""
  1557. @pytest.mark.asyncio
  1558. @pytest.mark.integration
  1559. @pytest.mark.parametrize(
  1560. "evil_url",
  1561. [
  1562. "file:///etc/passwd",
  1563. "http://169.254.169.254/latest/meta-data/", # AWS IMDS
  1564. "http://0.0.0.0/", # unspecified
  1565. "http://[::ffff:169.254.169.254]/", # IPv4-mapped IMDS bypass
  1566. ],
  1567. )
  1568. async def test_nfc_tag_scanned_with_ssrf_url_ignores_spoolman(
  1569. self,
  1570. async_client: AsyncClient,
  1571. db_session,
  1572. evil_url: str,
  1573. ):
  1574. """SSRF: _get_spoolman_client_or_none silently disables Spoolman for unsafe URLs
  1575. on the SpoolBuddy NFC path (tag-scanned broadcasts unknown_tag, not 400)."""
  1576. from backend.app.models.settings import Settings
  1577. db_session.add(Settings(key="spoolman_enabled", value="true"))
  1578. db_session.add(Settings(key="spoolman_url", value=evil_url))
  1579. await db_session.commit()
  1580. from unittest.mock import AsyncMock, patch
  1581. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  1582. mock_ws.broadcast = AsyncMock()
  1583. resp = await async_client.post(
  1584. "/api/v1/spoolbuddy/nfc/tag-scanned",
  1585. json={"device_id": "sb-ssrf", "tag_uid": "AABBCCDD"},
  1586. )
  1587. # Must not crash or proxy the SSRF URL — unknown_tag is the safe degraded response
  1588. assert resp.status_code == 200
  1589. if mock_ws.broadcast.called:
  1590. msg = mock_ws.broadcast.call_args[0][0]
  1591. assert msg["type"] == "spoolbuddy_unknown_tag"
  1592. @pytest.mark.asyncio
  1593. @pytest.mark.integration
  1594. @pytest.mark.parametrize(
  1595. "evil_url",
  1596. [
  1597. "http://169.254.169.254/latest/meta-data/", # AWS IMDS
  1598. "http://[::ffff:169.254.169.254]/", # IPv4-mapped IMDS bypass
  1599. ],
  1600. )
  1601. async def test_nfc_write_result_with_ssrf_url_degrades_gracefully(
  1602. self,
  1603. async_client: AsyncClient,
  1604. db_session,
  1605. evil_url: str,
  1606. ):
  1607. """SSRF: write-result with unsafe Spoolman URL must not proxy to the evil host.
  1608. write-result calls Spoolman to write-back the tag UID when data_origin='spoolman'.
  1609. With an SSRF URL, _get_spoolman_client_or_none returns None so the call is skipped
  1610. and the route returns 502 (tag written but link not persisted — not a server crash).
  1611. """
  1612. import json as _json
  1613. from backend.app.models.settings import Settings
  1614. from backend.app.models.spoolbuddy_device import SpoolBuddyDevice
  1615. db_session.add(Settings(key="spoolman_enabled", value="true"))
  1616. db_session.add(Settings(key="spoolman_url", value=evil_url))
  1617. # Register the device so the route doesn't 404 before reaching the SSRF guard.
  1618. db_session.add(
  1619. SpoolBuddyDevice(
  1620. device_id="sb-ssrf-wr",
  1621. hostname="sb-ssrf-wr.local",
  1622. ip_address="127.0.0.1",
  1623. pending_command="write_tag",
  1624. pending_write_payload=_json.dumps({"spool_id": 99, "ndef_data_hex": "DEAD", "data_origin": "spoolman"}),
  1625. )
  1626. )
  1627. await db_session.commit()
  1628. from unittest.mock import AsyncMock, patch
  1629. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  1630. mock_ws.broadcast = AsyncMock()
  1631. resp = await async_client.post(
  1632. "/api/v1/spoolbuddy/nfc/write-result",
  1633. json={
  1634. "device_id": "sb-ssrf-wr",
  1635. "spool_id": 99,
  1636. "tag_uid": "AABBCCDD",
  1637. "success": True,
  1638. },
  1639. )
  1640. # 502 = tag written to NFC but Spoolman link not persisted (SSRF guard blocked it).
  1641. # Must not be 500 (crash) and must not have proxied to the evil host.
  1642. assert resp.status_code == 502
  1643. @pytest.mark.asyncio
  1644. @pytest.mark.integration
  1645. @pytest.mark.parametrize(
  1646. "evil_url",
  1647. [
  1648. "http://169.254.169.254/latest/meta-data/", # AWS IMDS
  1649. ],
  1650. )
  1651. async def test_scale_update_weight_with_ssrf_url_degrades_gracefully(
  1652. self,
  1653. async_client: AsyncClient,
  1654. db_session,
  1655. evil_url: str,
  1656. ):
  1657. """SSRF: scale weight update with unsafe Spoolman URL must not proxy to the evil host."""
  1658. from backend.app.models.settings import Settings
  1659. db_session.add(Settings(key="spoolman_enabled", value="true"))
  1660. db_session.add(Settings(key="spoolman_url", value=evil_url))
  1661. await db_session.commit()
  1662. from unittest.mock import AsyncMock, patch
  1663. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  1664. mock_ws.broadcast = AsyncMock()
  1665. resp = await async_client.post(
  1666. "/api/v1/spoolbuddy/scale/update-spool-weight",
  1667. json={"device_id": "sb-ssrf-scale", "spool_id": 1, "weight_grams": 500.0},
  1668. )
  1669. # Must not crash or proxy to an SSRF host
  1670. assert resp.status_code in (200, 404, 422)
  1671. class TestMergeSpoolExtraPreservesKeys:
  1672. """Unit-level test for merge_spool_extra key preservation (via mocked Spoolman)."""
  1673. @pytest.mark.asyncio
  1674. @pytest.mark.integration
  1675. async def test_merge_preserves_unrelated_extra_keys(
  1676. self,
  1677. async_client: AsyncClient,
  1678. spoolman_settings,
  1679. mock_spoolman_client,
  1680. ):
  1681. """merge_spool_extra must deep-merge rather than overwrite the extra dict.
  1682. Seed extra={"custom_key": "keep_me", "tag": "old"}.
  1683. After merging {"tag": "new"}, the PATCH payload must still contain custom_key.
  1684. """
  1685. from unittest.mock import AsyncMock, patch
  1686. existing_spool = {
  1687. **SAMPLE_SPOOLMAN_SPOOL,
  1688. "extra": {"custom_key": "keep_me", "tag": '"old"'},
  1689. }
  1690. updated_spool = {**existing_spool, "extra": {"custom_key": "keep_me", "tag": '"new"'}}
  1691. mock_client = mock_spoolman_client
  1692. mock_client.get_spool = AsyncMock(return_value=existing_spool)
  1693. mock_client.update_spool_full = AsyncMock(return_value=updated_spool)
  1694. # Call merge_spool_extra directly through the service
  1695. from backend.app.services.spoolman import SpoolmanClient
  1696. client = SpoolmanClient.__new__(SpoolmanClient)
  1697. client.base_url = "http://localhost:7912"
  1698. client.api_url = "http://localhost:7912/api/v1"
  1699. client._extra_locks = {}
  1700. async def _mock_get(spool_id):
  1701. return existing_spool
  1702. async def _mock_update(spool_id, **kwargs):
  1703. # Capture what was actually sent
  1704. _mock_update.captured_extra = kwargs.get("extra")
  1705. return updated_spool
  1706. _mock_update.captured_extra = None
  1707. client.get_spool = _mock_get
  1708. client.update_spool_full = _mock_update
  1709. result = await client.merge_spool_extra(42, {"tag": '"new"'})
  1710. # The merged extra must include the unrelated key
  1711. assert _mock_update.captured_extra is not None
  1712. assert _mock_update.captured_extra.get("custom_key") == "keep_me"
  1713. assert _mock_update.captured_extra.get("tag") == '"new"'
  1714. assert result is not None
  1715. class TestGetClientValueError:
  1716. """Test the ValueError branch in _get_client when init_spoolman_client fails (Gap 5)."""
  1717. @pytest.mark.asyncio
  1718. @pytest.mark.integration
  1719. async def test_returns_400_when_init_spoolman_client_raises_value_error(
  1720. self, async_client: AsyncClient, spoolman_settings
  1721. ):
  1722. """If init_spoolman_client raises ValueError after SSRF check passes, return HTTP 400."""
  1723. with (
  1724. patch(
  1725. "backend.app.api.routes.spoolman_inventory.get_spoolman_client",
  1726. AsyncMock(return_value=None),
  1727. ),
  1728. patch(
  1729. "backend.app.api.routes.spoolman_inventory.init_spoolman_client",
  1730. AsyncMock(side_effect=ValueError("unsupported scheme")),
  1731. ),
  1732. ):
  1733. resp = await async_client.get("/api/v1/spoolman/inventory/spools")
  1734. assert resp.status_code == 400
  1735. assert "unsupported scheme" in resp.json()["detail"]
  1736. class TestBulkCreateWithPriceFailure:
  1737. """Test that bulk create handles price-update failures per C1/C8 semantics."""
  1738. @pytest.mark.asyncio
  1739. @pytest.mark.integration
  1740. async def test_bulk_create_price_503_moves_spool_to_failures(
  1741. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1742. ):
  1743. """When price update fails (503), the spool goes to failures — overall returns 207 if at least one succeeds."""
  1744. from backend.app.services.spoolman import SpoolmanUnavailableError
  1745. # First price update fails (SpoolmanUnavailableError → 503), second succeeds
  1746. mock_spoolman_client.update_spool_full = AsyncMock(
  1747. side_effect=[SpoolmanUnavailableError("price server down"), SAMPLE_SPOOLMAN_SPOOL]
  1748. )
  1749. mock_spoolman_client.create_spool = AsyncMock(return_value=SAMPLE_SPOOLMAN_SPOOL)
  1750. payload = {
  1751. "spool": {
  1752. "material": "PLA",
  1753. "brand": "Bambu Lab",
  1754. "label_weight": 1000,
  1755. "cost_per_kg": 19.99,
  1756. },
  1757. "quantity": 2,
  1758. }
  1759. resp = await async_client.post("/api/v1/spoolman/inventory/spools/bulk", json=payload)
  1760. # One spool succeeded, one failed (price 503) → 207 Partial
  1761. assert resp.status_code == 207
  1762. data = resp.json()
  1763. assert len(data["created"]) == 1
  1764. assert data["failed_count"] == 1
  1765. # Both Spoolman creates were attempted
  1766. assert mock_spoolman_client.create_spool.call_count == 2
  1767. # Both price updates were attempted
  1768. assert mock_spoolman_client.update_spool_full.call_count == 2
  1769. class TestSpoolTagLinkValidation:
  1770. """NEW-B1: /spools/{id}/tag endpoint validates tag_uid length and content."""
  1771. @pytest.mark.asyncio
  1772. @pytest.mark.integration
  1773. async def test_tag_uid_6_chars_rejected(self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client):
  1774. """tag_uid with 6 hex chars is rejected — minimum is 8 chars (4-byte UID)."""
  1775. resp = await async_client.patch(
  1776. "/api/v1/spoolman/inventory/spools/42/tag",
  1777. json={"tag_uid": "AABBCC"}, # 6 chars — below new minimum
  1778. )
  1779. assert resp.status_code == 422
  1780. @pytest.mark.asyncio
  1781. @pytest.mark.integration
  1782. async def test_tag_uid_all_zeros_rejected(self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client):
  1783. """tag_uid that is all-zero bytes is rejected as an unwritten/blank tag."""
  1784. resp = await async_client.patch(
  1785. "/api/v1/spoolman/inventory/spools/42/tag",
  1786. json={"tag_uid": "00000000000000"}, # 14 zeros
  1787. )
  1788. assert resp.status_code == 422
  1789. @pytest.mark.asyncio
  1790. @pytest.mark.integration
  1791. async def test_tag_uid_valid_14_chars_accepted(
  1792. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1793. ):
  1794. """tag_uid with 14 valid hex chars (7-byte UID) is accepted."""
  1795. # This tag is not in SAMPLE_SPOOLMAN_SPOOL so no duplicate conflict.
  1796. resp = await async_client.patch(
  1797. "/api/v1/spoolman/inventory/spools/42/tag",
  1798. json={"tag_uid": "AABBCCDD112233"}, # 14 chars, valid, not all-zeros
  1799. )
  1800. assert resp.status_code == 200
  1801. @pytest.mark.asyncio
  1802. @pytest.mark.integration
  1803. async def test_tag_uid_8_chars_accepted(self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client):
  1804. """tag_uid with 8 hex chars (4-byte Bambu Lab NFC UID) is accepted after min_length fix."""
  1805. resp = await async_client.patch(
  1806. "/api/v1/spoolman/inventory/spools/42/tag",
  1807. json={"tag_uid": "2728C17B"}, # 8 chars — real Bambu Lab 4-byte hardware UID
  1808. )
  1809. assert resp.status_code == 200
  1810. @pytest.mark.asyncio
  1811. @pytest.mark.integration
  1812. async def test_tag_uid_8_zeros_rejected(self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client):
  1813. """tag_uid with 8 zero chars is rejected — all-zeros validator applies at the new minimum."""
  1814. resp = await async_client.patch(
  1815. "/api/v1/spoolman/inventory/spools/42/tag",
  1816. json={"tag_uid": "00000000"}, # 8 zeros — meets min_length but is a blank/unwritten tag
  1817. )
  1818. assert resp.status_code == 422
  1819. class TestLinkTagDuplicate:
  1820. """NEW-I1: /spools/{id}/tag returns 409 when another spool already has the same tag."""
  1821. @pytest.mark.asyncio
  1822. @pytest.mark.integration
  1823. async def test_link_tag_returns_200_when_tag_not_on_another_spool(
  1824. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1825. ):
  1826. """Linking a fresh tag to spool 42 returns 200 — no duplicate in Spoolman."""
  1827. resp = await async_client.patch(
  1828. "/api/v1/spoolman/inventory/spools/42/tag",
  1829. json={"tag_uid": "AABBCCDD112233"}, # not in SAMPLE_SPOOLMAN_SPOOL
  1830. )
  1831. assert resp.status_code == 200
  1832. mock_spoolman_client.update_spool_full.assert_called_once()
  1833. @pytest.mark.asyncio
  1834. @pytest.mark.integration
  1835. async def test_link_tag_returns_409_when_same_tag_on_different_spool(
  1836. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1837. ):
  1838. """Linking spool 99 to a tag that spool 42 already carries must return 409."""
  1839. # SAMPLE_SPOOLMAN_SPOOL (id=42) has extra.tag = '"AABBCCDDEEFF0011AABBCCDDEEFF0011"'.
  1840. # Attempting to assign the same tag to spool 99 must be rejected.
  1841. resp = await async_client.patch(
  1842. "/api/v1/spoolman/inventory/spools/99/tag",
  1843. json={"tray_uuid": "AABBCCDDEEFF0011AABBCCDDEEFF0011"}, # 32-char tray UUID
  1844. )
  1845. assert resp.status_code == 409
  1846. detail = resp.json()["detail"]
  1847. assert "42" in str(detail)
  1848. class TestSpoolmanInventoryUpdateCoreWeight:
  1849. """core_weight is accepted for schema parity but not persisted — any value should be accepted."""
  1850. @pytest.mark.asyncio
  1851. @pytest.mark.integration
  1852. async def test_patch_core_weight_other_than_250_accepted(
  1853. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1854. ):
  1855. """PATCH with core_weight != 250 is accepted (field is ignored server-side, not rejected)."""
  1856. resp = await async_client.patch(
  1857. "/api/v1/spoolman/inventory/spools/42",
  1858. json={"core_weight": 100},
  1859. )
  1860. assert resp.status_code == 200
  1861. @pytest.mark.asyncio
  1862. @pytest.mark.integration
  1863. async def test_patch_core_weight_250_explicitly_is_accepted(
  1864. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1865. ):
  1866. """PATCH with core_weight=250 (the default) is valid and returns 200."""
  1867. resp = await async_client.patch(
  1868. "/api/v1/spoolman/inventory/spools/42",
  1869. json={"core_weight": 250},
  1870. )
  1871. assert resp.status_code == 200
  1872. @pytest.mark.asyncio
  1873. @pytest.mark.integration
  1874. async def test_patch_without_core_weight_is_accepted(
  1875. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1876. ):
  1877. """PATCH without core_weight (omitted) must not trigger the validator — returns 200."""
  1878. resp = await async_client.patch(
  1879. "/api/v1/spoolman/inventory/spools/42",
  1880. json={"note": "no core_weight key"},
  1881. )
  1882. assert resp.status_code == 200
  1883. class TestUnlinkSpool:
  1884. """POST /spoolman/spools/{id}/unlink clears Spoolman tag without re-entrant lock deadlock.
  1885. Spoolman PATCHes the extra dict by MERGING — popping a key + sending the
  1886. rest doesn't clear the popped key. The endpoint sends the JSON empty-string
  1887. sentinel ('""') which the read-side filters strip. (#1114)
  1888. The endpoint uses merge_spool_extra (not update_spool_full directly)
  1889. because (a) merge_spool_extra owns the per-spool extra_lock for atomic
  1890. read-modify-write semantics, and (b) wrapping it in another extra_lock
  1891. would deadlock — asyncio.Lock is not re-entrant.
  1892. """
  1893. @pytest.fixture
  1894. def mock_unlink_client(self):
  1895. """Mock Spoolman client for the spoolman.py (non-inventory) route."""
  1896. spool_with_tag = {
  1897. **SAMPLE_SPOOLMAN_SPOOL,
  1898. "extra": {"tag": '"AABBCCDDEEFF0011AABBCCDDEEFF0011"', "custom": "keep"},
  1899. }
  1900. mock_client = MagicMock()
  1901. mock_client.base_url = "http://localhost:7912"
  1902. mock_client.health_check = AsyncMock(return_value=True)
  1903. mock_client.get_spool = AsyncMock(return_value=spool_with_tag)
  1904. # merge_spool_extra returns the spool with the tag cleared (and custom
  1905. # preserved) — that's what the read-side will see after the fix.
  1906. mock_client.merge_spool_extra = AsyncMock(
  1907. return_value={**spool_with_tag, "extra": {"tag": '""', "custom": "keep"}}
  1908. )
  1909. with (
  1910. patch(
  1911. "backend.app.api.routes.spoolman.get_spoolman_client",
  1912. AsyncMock(return_value=mock_client),
  1913. ),
  1914. patch(
  1915. "backend.app.api.routes.spoolman.init_spoolman_client",
  1916. AsyncMock(return_value=mock_client),
  1917. ),
  1918. ):
  1919. yield mock_client
  1920. @pytest.mark.asyncio
  1921. @pytest.mark.integration
  1922. async def test_unlink_sets_tag_to_json_empty_string(
  1923. self,
  1924. async_client: AsyncClient,
  1925. spoolman_settings,
  1926. mock_unlink_client,
  1927. ):
  1928. """Unlink calls merge_spool_extra with the JSON-empty-string sentinel.
  1929. Pre-fix the endpoint did `cur_extra.pop("tag")` then PATCHed the rest.
  1930. Spoolman silently kept the previous tag because the key wasn't in the
  1931. payload (PATCH merges). Now the endpoint sends `{"tag": '""'}` and
  1932. the read-side .strip('"') resolves it to "" → spool drops out of
  1933. get_linked_spools.
  1934. """
  1935. import json as _json
  1936. resp = await async_client.post("/api/v1/spoolman/spools/42/unlink")
  1937. assert resp.status_code == 200
  1938. mock_unlink_client.merge_spool_extra.assert_called_once_with(42, {"tag": _json.dumps("")})
  1939. @pytest.mark.asyncio
  1940. @pytest.mark.integration
  1941. async def test_unlink_preserves_other_extra_keys(
  1942. self,
  1943. async_client: AsyncClient,
  1944. spoolman_settings,
  1945. mock_unlink_client,
  1946. ):
  1947. """Unrelated extra keys must survive unlink.
  1948. merge_spool_extra is responsible for the merge (read current → merge
  1949. new fields → PATCH). The unlink endpoint only sends `{"tag": ...}`,
  1950. so any other extra key on the spool is automatically preserved by
  1951. merge_spool_extra's read-merge-write semantics.
  1952. """
  1953. resp = await async_client.post("/api/v1/spoolman/spools/42/unlink")
  1954. assert resp.status_code == 200
  1955. # The endpoint passes only the tag key — merge_spool_extra does the
  1956. # rest. We don't assert anything about `custom` on the call args
  1957. # because the route doesn't see / pass it.
  1958. _, args, _ = mock_unlink_client.merge_spool_extra.mock_calls[0]
  1959. sent_fields = args[1] if len(args) >= 2 else {}
  1960. assert sent_fields == {"tag": '""'}, "unlink should only send the tag key — merge_spool_extra does the merge"
  1961. # ---------------------------------------------------------------------------
  1962. # B1: GET /spoolman/inventory/filaments
  1963. # B2: POST /spools with spoolman_filament_id bypasses find_or_create_filament
  1964. # ---------------------------------------------------------------------------
  1965. SAMPLE_FILAMENT_DICT = {
  1966. "id": 7,
  1967. "name": "PLA Basic",
  1968. "material": "PLA",
  1969. "color_hex": "FF0000",
  1970. "color_name": "Red",
  1971. "weight": 1000,
  1972. "spool_weight": 196,
  1973. "vendor": {"id": 3, "name": "Bambu Lab"},
  1974. }
  1975. class TestListSpoolmanFilaments:
  1976. """Tests for GET /api/v1/spoolman/inventory/filaments (B1)."""
  1977. @pytest.mark.asyncio
  1978. @pytest.mark.integration
  1979. async def test_list_filaments_disabled_returns_400(self, async_client: AsyncClient):
  1980. """Without Spoolman enabled the endpoint returns 400."""
  1981. resp = await async_client.get("/api/v1/spoolman/inventory/filaments")
  1982. assert resp.status_code == 400
  1983. @pytest.mark.asyncio
  1984. @pytest.mark.integration
  1985. async def test_list_filaments_unreachable_returns_503(self, async_client: AsyncClient, spoolman_settings):
  1986. """503 is returned when _get_client raises HTTPException(503)."""
  1987. with patch(
  1988. "backend.app.api.routes.spoolman_inventory._get_client",
  1989. AsyncMock(side_effect=HTTPException(status_code=503, detail="Spoolman server is not reachable")),
  1990. ):
  1991. resp = await async_client.get("/api/v1/spoolman/inventory/filaments")
  1992. assert resp.status_code == 503
  1993. @pytest.mark.asyncio
  1994. @pytest.mark.integration
  1995. async def test_list_filaments_success(self, async_client: AsyncClient, spoolman_settings):
  1996. """Success path returns normalised filament list including spool_weight."""
  1997. mock_client = MagicMock()
  1998. mock_client.get_filaments = AsyncMock(return_value=[SAMPLE_FILAMENT_DICT])
  1999. with patch(
  2000. "backend.app.api.routes.spoolman_inventory._get_client",
  2001. AsyncMock(return_value=mock_client),
  2002. ):
  2003. resp = await async_client.get("/api/v1/spoolman/inventory/filaments")
  2004. assert resp.status_code == 200
  2005. data = resp.json()
  2006. assert isinstance(data, list)
  2007. assert len(data) == 1
  2008. entry = data[0]
  2009. assert entry["id"] == 7
  2010. assert entry["material"] == "PLA"
  2011. assert entry["spool_weight"] == 196
  2012. assert entry["vendor"]["name"] == "Bambu Lab"
  2013. class TestCreateSpoolWithFilamentId:
  2014. """Tests for POST /api/v1/spoolman/inventory/spools with spoolman_filament_id (B2)."""
  2015. @pytest.mark.asyncio
  2016. @pytest.mark.integration
  2017. async def test_create_with_filament_id_skips_find_or_create(self, async_client: AsyncClient, spoolman_settings):
  2018. """When spoolman_filament_id is provided, find_or_create_filament must NOT be called."""
  2019. mock_client = MagicMock()
  2020. mock_client.find_or_create_filament = AsyncMock(return_value=7)
  2021. mock_client.create_spool = AsyncMock(return_value=SAMPLE_SPOOLMAN_SPOOL)
  2022. mock_client.update_spool_full = AsyncMock(return_value=SAMPLE_SPOOLMAN_SPOOL)
  2023. with patch(
  2024. "backend.app.api.routes.spoolman_inventory._get_client",
  2025. AsyncMock(return_value=mock_client),
  2026. ):
  2027. resp = await async_client.post(
  2028. "/api/v1/spoolman/inventory/spools",
  2029. json={"spoolman_filament_id": 7},
  2030. )
  2031. assert resp.status_code == 200
  2032. mock_client.find_or_create_filament.assert_not_called()
  2033. mock_client.create_spool.assert_called_once()
  2034. _, kwargs = mock_client.create_spool.call_args
  2035. assert kwargs.get("filament_id") == 7
  2036. @pytest.mark.asyncio
  2037. @pytest.mark.integration
  2038. async def test_create_with_invalid_filament_id_returns_404(self, async_client: AsyncClient, spoolman_settings):
  2039. """An invalid spoolman_filament_id (not in Spoolman) must return 404."""
  2040. from backend.app.services.spoolman import SpoolmanNotFoundError
  2041. mock_client = MagicMock()
  2042. mock_client.create_spool = AsyncMock(side_effect=SpoolmanNotFoundError("filament not found"))
  2043. with patch(
  2044. "backend.app.api.routes.spoolman_inventory._get_client",
  2045. AsyncMock(return_value=mock_client),
  2046. ):
  2047. resp = await async_client.post(
  2048. "/api/v1/spoolman/inventory/spools",
  2049. json={"spoolman_filament_id": 9999},
  2050. )
  2051. assert resp.status_code == 404
  2052. assert "9999" in resp.json()["detail"]
  2053. # ---------------------------------------------------------------------------
  2054. # WICHTIG-12: Additional edge-case tests
  2055. # ---------------------------------------------------------------------------
  2056. class TestBulkCreateWithFilamentId:
  2057. """Bulk create with spoolman_filament_id skips find_or_create_filament."""
  2058. @pytest.mark.asyncio
  2059. @pytest.mark.integration
  2060. async def test_bulk_create_with_filament_id_skips_find_or_create(
  2061. self, async_client: AsyncClient, spoolman_settings
  2062. ):
  2063. """Bulk POST with spoolman_filament_id must NOT call find_or_create_filament."""
  2064. mock_client = MagicMock()
  2065. mock_client.find_or_create_filament = AsyncMock(return_value=7)
  2066. mock_client.create_spool = AsyncMock(return_value=SAMPLE_SPOOLMAN_SPOOL)
  2067. mock_client.update_spool_full = AsyncMock(return_value=SAMPLE_SPOOLMAN_SPOOL)
  2068. with patch(
  2069. "backend.app.api.routes.spoolman_inventory._get_client",
  2070. AsyncMock(return_value=mock_client),
  2071. ):
  2072. resp = await async_client.post(
  2073. "/api/v1/spoolman/inventory/spools/bulk",
  2074. json={"spool": {"spoolman_filament_id": 7}, "quantity": 2},
  2075. )
  2076. assert resp.status_code == 200
  2077. mock_client.find_or_create_filament.assert_not_called()
  2078. assert mock_client.create_spool.call_count == 2
  2079. for call in mock_client.create_spool.call_args_list:
  2080. _, kwargs = call
  2081. assert kwargs.get("filament_id") == 7
  2082. class TestCreateSpoolValidation:
  2083. """Validation edge cases for SpoolmanInventoryCreate."""
  2084. @pytest.mark.asyncio
  2085. @pytest.mark.integration
  2086. async def test_create_spool_filament_id_zero_returns_422(self, async_client: AsyncClient, spoolman_settings):
  2087. """spoolman_filament_id=0 must fail Field(gt=0) validation → 422."""
  2088. resp = await async_client.post(
  2089. "/api/v1/spoolman/inventory/spools",
  2090. json={"spoolman_filament_id": 0},
  2091. )
  2092. assert resp.status_code == 422
  2093. @pytest.mark.asyncio
  2094. @pytest.mark.integration
  2095. async def test_create_spool_without_material_or_filament_id_returns_422(
  2096. self, async_client: AsyncClient, spoolman_settings
  2097. ):
  2098. """Neither material nor spoolman_filament_id → model_validator must reject → 422."""
  2099. resp = await async_client.post(
  2100. "/api/v1/spoolman/inventory/spools",
  2101. json={"label_weight": 1000},
  2102. )
  2103. assert resp.status_code == 422
  2104. class TestNormalizeFilament:
  2105. """Unit-style tests for _normalize_filament helper (imported directly)."""
  2106. def test_normalize_filament_null_vendor(self):
  2107. from backend.app.api.routes.spoolman_inventory import _normalize_filament
  2108. result = _normalize_filament({"id": 5, "name": "PLA", "vendor": None})
  2109. assert result is not None
  2110. assert result["vendor"] is None
  2111. def test_normalize_filament_null_id_returns_none(self):
  2112. from backend.app.api.routes.spoolman_inventory import _normalize_filament
  2113. result = _normalize_filament({"id": None, "name": "PLA"})
  2114. assert result is None
  2115. def test_normalize_filament_zero_id_returns_none(self):
  2116. from backend.app.api.routes.spoolman_inventory import _normalize_filament
  2117. result = _normalize_filament({"id": 0, "name": "PLA"})
  2118. assert result is None
  2119. # ---------------------------------------------------------------------------
  2120. # F1: TestTranslateSpoolmanErrors — 502/404/503 paths through _translate_spoolman_errors
  2121. # ---------------------------------------------------------------------------
  2122. class TestTranslateSpoolmanErrors:
  2123. """F1: _translate_spoolman_errors() maps Spoolman exceptions to HTTP codes."""
  2124. @pytest.mark.asyncio
  2125. @pytest.mark.integration
  2126. async def test_spoolman_not_found_returns_404(
  2127. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2128. ):
  2129. """SpoolmanNotFoundError from get_spool → 404."""
  2130. from backend.app.services.spoolman import SpoolmanNotFoundError
  2131. mock_spoolman_client.get_spool.side_effect = SpoolmanNotFoundError("spool 999 not found")
  2132. resp = await async_client.get("/api/v1/spoolman/inventory/spools/999")
  2133. assert resp.status_code == 404
  2134. @pytest.mark.asyncio
  2135. @pytest.mark.integration
  2136. async def test_spoolman_unavailable_returns_503(
  2137. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2138. ):
  2139. """SpoolmanUnavailableError from get_spool → 503."""
  2140. from backend.app.services.spoolman import SpoolmanUnavailableError
  2141. mock_spoolman_client.get_spool.side_effect = SpoolmanUnavailableError("network error")
  2142. resp = await async_client.get("/api/v1/spoolman/inventory/spools/42")
  2143. assert resp.status_code == 503
  2144. @pytest.mark.asyncio
  2145. @pytest.mark.integration
  2146. async def test_spoolman_client_error_returns_502_with_upstream_status(
  2147. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2148. ):
  2149. """SpoolmanClientError from get_spool → 502 with upstream_status in body."""
  2150. from backend.app.services.spoolman import SpoolmanClientError
  2151. mock_spoolman_client.get_spool.side_effect = SpoolmanClientError("Spoolman rejected", 422, "filament not found")
  2152. resp = await async_client.get("/api/v1/spoolman/inventory/spools/42")
  2153. assert resp.status_code == 502
  2154. body = resp.json()
  2155. assert body["detail"]["upstream_status"] == 422
  2156. assert body["detail"]["upstream_body"] == "filament not found"
  2157. # ---------------------------------------------------------------------------
  2158. # F2: _get_client health_check returns False → 503
  2159. # ---------------------------------------------------------------------------
  2160. class TestGetClientHealthCheckFalse:
  2161. """F2: _get_client raises 503 when health_check() returns False."""
  2162. @pytest.mark.asyncio
  2163. @pytest.mark.integration
  2164. async def test_returns_503_when_health_check_returns_false(
  2165. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2166. ):
  2167. """health_check() → False should produce 503 on any inventory call."""
  2168. import time
  2169. import backend.app.api.routes.spoolman_inventory as inv_module
  2170. mock_spoolman_client.health_check = AsyncMock(return_value=False)
  2171. # Clear the TTL cache so health_check is actually called
  2172. inv_module._health_check_cache.clear()
  2173. resp = await async_client.get("/api/v1/spoolman/inventory/spools")
  2174. assert resp.status_code == 503
  2175. # ---------------------------------------------------------------------------
  2176. # F3: SpoolTagLinkRequest both fields null → 422
  2177. # ---------------------------------------------------------------------------
  2178. class TestSpoolTagLinkBothNull:
  2179. """F3: /spools/{id}/tag with both tag_uid and tray_uuid null → 422."""
  2180. @pytest.mark.asyncio
  2181. @pytest.mark.integration
  2182. async def test_both_null_returns_422(self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client):
  2183. """Sending {} (both fields absent) → at_least_one validator → 422."""
  2184. resp = await async_client.patch(
  2185. "/api/v1/spoolman/inventory/spools/42/tag",
  2186. json={},
  2187. )
  2188. assert resp.status_code == 422
  2189. @pytest.mark.asyncio
  2190. @pytest.mark.integration
  2191. async def test_both_explicitly_null_returns_422(
  2192. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2193. ):
  2194. """Sending {tag_uid: null, tray_uuid: null} → at_least_one validator → 422."""
  2195. resp = await async_client.patch(
  2196. "/api/v1/spoolman/inventory/spools/42/tag",
  2197. json={"tag_uid": None, "tray_uuid": None},
  2198. )
  2199. assert resp.status_code == 422
  2200. # ---------------------------------------------------------------------------
  2201. # F5: RBAC lists — missing endpoints
  2202. # ---------------------------------------------------------------------------
  2203. class TestSpoolmanInventoryAuthExtended:
  2204. """F5: Additional endpoints in RBAC auth/403 parametrize lists."""
  2205. @pytest.fixture
  2206. async def auth_and_spoolman_settings(self, db_session):
  2207. from backend.app.models.settings import Settings
  2208. db_session.add(Settings(key="spoolman_enabled", value="true"))
  2209. db_session.add(Settings(key="spoolman_url", value="http://localhost:7912"))
  2210. db_session.add(Settings(key="auth_enabled", value="true"))
  2211. await db_session.commit()
  2212. @pytest.mark.asyncio
  2213. @pytest.mark.integration
  2214. @pytest.mark.parametrize(
  2215. "method,path,payload",
  2216. [
  2217. ("PATCH", "/api/v1/spoolman/inventory/spools/42/tag", {"tag_uid": "AABBCCDDEE112233"}),
  2218. ("POST", "/api/v1/spoolman/inventory/sync-ams-weights", {"printer_id": 1, "ams_data": []}),
  2219. ("PATCH", "/api/v1/spoolman/inventory/filaments/7", {"spool_weight": 196.0}),
  2220. ],
  2221. )
  2222. async def test_extended_write_endpoints_require_auth(
  2223. self,
  2224. async_client: AsyncClient,
  2225. auth_and_spoolman_settings,
  2226. method: str,
  2227. path: str,
  2228. payload: dict | None,
  2229. ):
  2230. """Additional write endpoints return 401 when auth is enabled and no token is provided."""
  2231. resp = await async_client.request(method, path, json=payload)
  2232. assert resp.status_code == 401, f"{method} {path} should require auth but got {resp.status_code}: {resp.json()}"
  2233. @pytest.mark.asyncio
  2234. @pytest.mark.integration
  2235. @pytest.mark.parametrize(
  2236. "method,path",
  2237. [
  2238. ("GET", "/api/v1/spoolman/inventory/filaments"),
  2239. ],
  2240. )
  2241. async def test_extended_read_endpoints_require_auth(
  2242. self,
  2243. async_client: AsyncClient,
  2244. auth_and_spoolman_settings,
  2245. method: str,
  2246. path: str,
  2247. ):
  2248. """Additional read endpoints return 401 when auth is enabled and no token is provided."""
  2249. resp = await async_client.request(method, path)
  2250. assert resp.status_code == 401, f"{method} {path} should require auth but got {resp.status_code}: {resp.json()}"
  2251. # ---------------------------------------------------------------------------
  2252. # F8: _normalize_filament negative ID returns None
  2253. # ---------------------------------------------------------------------------
  2254. class TestNormalizeFilamentNegativeId:
  2255. """F8: _normalize_filament with negative id → None (was only checking == 0)."""
  2256. def test_normalize_filament_negative_id_returns_none(self):
  2257. from backend.app.api.routes.spoolman_inventory import _normalize_filament
  2258. result = _normalize_filament({"id": -1, "name": "PLA"})
  2259. assert result is None
  2260. def test_normalize_filament_large_negative_id_returns_none(self):
  2261. from backend.app.api.routes.spoolman_inventory import _normalize_filament
  2262. result = _normalize_filament({"id": -999, "name": "PLA"})
  2263. assert result is None
  2264. # ---------------------------------------------------------------------------
  2265. # F9: weight_used > label_weight cross-field validator integration test
  2266. # ---------------------------------------------------------------------------
  2267. class TestCreateSpoolWeightValidation:
  2268. """F9: SpoolmanInventoryCreate.validate_weight_consistency cross-field validator."""
  2269. @pytest.mark.asyncio
  2270. @pytest.mark.integration
  2271. async def test_weight_used_exceeds_label_weight_returns_422(self, async_client: AsyncClient, spoolman_settings):
  2272. """weight_used > label_weight → cross-field validator → 422."""
  2273. resp = await async_client.post(
  2274. "/api/v1/spoolman/inventory/spools",
  2275. json={"material": "PLA", "label_weight": 500, "weight_used": 600},
  2276. )
  2277. assert resp.status_code == 422
  2278. @pytest.mark.asyncio
  2279. @pytest.mark.integration
  2280. async def test_weight_used_equals_label_weight_accepted(
  2281. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2282. ):
  2283. """weight_used == label_weight is exactly at the boundary → should pass (201)."""
  2284. resp = await async_client.post(
  2285. "/api/v1/spoolman/inventory/spools",
  2286. json={"material": "PLA", "label_weight": 1000, "weight_used": 1000},
  2287. )
  2288. # 201 or 200 (spool created)
  2289. assert resp.status_code in (200, 201)
  2290. @pytest.mark.asyncio
  2291. @pytest.mark.integration
  2292. async def test_create_spool_with_non_default_core_weight_accepted(
  2293. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2294. ):
  2295. """A3: core_weight != 250 must no longer be rejected → 201."""
  2296. resp = await async_client.post(
  2297. "/api/v1/spoolman/inventory/spools",
  2298. json={"material": "PLA", "label_weight": 1000, "weight_used": 0, "core_weight": 196},
  2299. )
  2300. assert resp.status_code in (200, 201)
  2301. @pytest.mark.asyncio
  2302. @pytest.mark.integration
  2303. async def test_update_spool_with_non_default_core_weight_accepted(
  2304. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2305. ):
  2306. """A3: PATCH with core_weight != 250 must no longer return 422."""
  2307. resp = await async_client.patch(
  2308. "/api/v1/spoolman/inventory/spools/42",
  2309. json={"core_weight": 300},
  2310. )
  2311. assert resp.status_code == 200
  2312. # ---------------------------------------------------------------------------
  2313. # P8-T1: /slot-assignments/all enriches with printer_name + ams_label
  2314. # ---------------------------------------------------------------------------
  2315. class TestGetAllSlotAssignmentsEnriched:
  2316. """P8-T1: /slot-assignments/all enriches with printer_name + ams_label.
  2317. Regression for InventoryPage LOCATION column showing '-' for Spoolman
  2318. spools because the endpoint only returned 4 raw fields without the
  2319. printer_name + ams_label needed by the UI.
  2320. """
  2321. @pytest.mark.asyncio
  2322. @pytest.mark.integration
  2323. async def test_returns_printer_name_for_existing_printer(
  2324. self, async_client: AsyncClient, db_session, spoolman_settings
  2325. ):
  2326. """printer_name is enriched from the joined Printer relationship."""
  2327. from backend.app.models.printer import Printer
  2328. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2329. db_session.add(
  2330. Printer(
  2331. id=1,
  2332. name="Sully",
  2333. model="X1C",
  2334. serial_number="SN1",
  2335. ip_address="1.2.3.4",
  2336. access_code="",
  2337. )
  2338. )
  2339. db_session.add(
  2340. SpoolmanSlotAssignment(
  2341. printer_id=1,
  2342. ams_id=0,
  2343. tray_id=2,
  2344. spoolman_spool_id=216,
  2345. )
  2346. )
  2347. await db_session.commit()
  2348. with patch("backend.app.api.routes.spoolman_inventory.printer_manager") as mock_pm:
  2349. mock_pm.get_all_statuses.return_value = {}
  2350. resp = await async_client.get("/api/v1/spoolman/inventory/slot-assignments/all")
  2351. assert resp.status_code == 200
  2352. data = resp.json()
  2353. assert len(data) == 1
  2354. assert data[0]["printer_name"] == "Sully"
  2355. assert data[0]["spoolman_spool_id"] == 216
  2356. assert data[0]["ams_id"] == 0
  2357. assert data[0]["tray_id"] == 2
  2358. assert data[0]["ams_label"] is None
  2359. @pytest.mark.asyncio
  2360. @pytest.mark.integration
  2361. async def test_returns_ams_label_when_label_configured(
  2362. self, async_client: AsyncClient, db_session, spoolman_settings
  2363. ):
  2364. """ams_label is enriched from AmsLabel via printer MQTT serial map."""
  2365. from backend.app.models.ams_label import AmsLabel
  2366. from backend.app.models.printer import Printer
  2367. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2368. db_session.add(
  2369. Printer(
  2370. id=1,
  2371. name="Sully",
  2372. model="X1C",
  2373. serial_number="SN1",
  2374. ip_address="1.2.3.4",
  2375. access_code="",
  2376. )
  2377. )
  2378. db_session.add(AmsLabel(ams_serial_number="ABC123", label="Top Shelf"))
  2379. db_session.add(
  2380. SpoolmanSlotAssignment(
  2381. printer_id=1,
  2382. ams_id=0,
  2383. tray_id=2,
  2384. spoolman_spool_id=216,
  2385. )
  2386. )
  2387. await db_session.commit()
  2388. mock_state = MagicMock(raw_data={"ams": [{"id": 0, "sn": "ABC123"}]})
  2389. with patch("backend.app.api.routes.spoolman_inventory.printer_manager") as mock_pm:
  2390. mock_pm.get_all_statuses.return_value = {1: mock_state}
  2391. resp = await async_client.get("/api/v1/spoolman/inventory/slot-assignments/all")
  2392. assert resp.status_code == 200
  2393. assert resp.json()[0]["ams_label"] == "Top Shelf"
  2394. @pytest.mark.asyncio
  2395. @pytest.mark.integration
  2396. async def test_synthetic_ams_label_fallback(self, async_client: AsyncClient, db_session, spoolman_settings):
  2397. """Falls back to synthetic 'p{pid}a{ams_id}' key when no MQTT serial available."""
  2398. from backend.app.models.ams_label import AmsLabel
  2399. from backend.app.models.printer import Printer
  2400. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2401. db_session.add(
  2402. Printer(
  2403. id=1,
  2404. name="Sully",
  2405. model="X1C",
  2406. serial_number="SN1",
  2407. ip_address="1.2.3.4",
  2408. access_code="",
  2409. )
  2410. )
  2411. db_session.add(AmsLabel(ams_serial_number="p1a0", label="Synthetic Label"))
  2412. db_session.add(
  2413. SpoolmanSlotAssignment(
  2414. printer_id=1,
  2415. ams_id=0,
  2416. tray_id=2,
  2417. spoolman_spool_id=216,
  2418. )
  2419. )
  2420. await db_session.commit()
  2421. with patch("backend.app.api.routes.spoolman_inventory.printer_manager") as mock_pm:
  2422. mock_pm.get_all_statuses.return_value = {} # No live state -> synthetic key
  2423. resp = await async_client.get("/api/v1/spoolman/inventory/slot-assignments/all")
  2424. assert resp.json()[0]["ams_label"] == "Synthetic Label"
  2425. @pytest.mark.asyncio
  2426. @pytest.mark.integration
  2427. async def test_filter_by_printer_id_still_works(self, async_client: AsyncClient, db_session, spoolman_settings):
  2428. """Regression: ?printer_id=N still filters and enriches."""
  2429. from backend.app.models.printer import Printer
  2430. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2431. for pid in (1, 2):
  2432. db_session.add(
  2433. Printer(
  2434. id=pid,
  2435. name=f"P{pid}",
  2436. model="X1C",
  2437. serial_number=f"SN{pid}",
  2438. ip_address=f"1.2.3.{pid}",
  2439. access_code="",
  2440. )
  2441. )
  2442. db_session.add(
  2443. SpoolmanSlotAssignment(
  2444. printer_id=pid,
  2445. ams_id=0,
  2446. tray_id=0,
  2447. spoolman_spool_id=200 + pid,
  2448. )
  2449. )
  2450. await db_session.commit()
  2451. with patch("backend.app.api.routes.spoolman_inventory.printer_manager") as mock_pm:
  2452. mock_pm.get_all_statuses.return_value = {}
  2453. resp = await async_client.get("/api/v1/spoolman/inventory/slot-assignments/all?printer_id=1")
  2454. data = resp.json()
  2455. assert len(data) == 1
  2456. assert data[0]["printer_id"] == 1
  2457. assert data[0]["printer_name"] == "P1"
  2458. assert data[0]["spoolman_spool_id"] == 201