test_spoolman_inventory_api.py 108 KB

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