test_spoolman_inventory_api.py 126 KB

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