test_spoolman_inventory_api.py 125 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128
  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. mock_spoolman_client.ensure_extra_field = AsyncMock(return_value=True)
  746. response = await async_client.patch(
  747. "/api/v1/spoolman/inventory/spools/42",
  748. json={
  749. "slicer_filament": "PFUSf543b298f8ea66",
  750. "slicer_filament_name": "Devil Design PLA Basic @Bambu Lab H2D 0.4 nozzle (Custom)",
  751. },
  752. )
  753. assert response.status_code == 200
  754. # Field registration is idempotent — must be called for each key
  755. ensure_calls = [c.args[0] for c in mock_spoolman_client.ensure_extra_field.call_args_list]
  756. assert "bambu_slicer_filament" in ensure_calls
  757. assert "bambu_slicer_filament_name" in ensure_calls
  758. # Values must be JSON-encoded so read-side can json.loads + .strip('"')
  759. mock_spoolman_client.merge_spool_extra.assert_called_once_with(
  760. 42,
  761. {
  762. "bambu_slicer_filament": _json.dumps("PFUSf543b298f8ea66"),
  763. "bambu_slicer_filament_name": _json.dumps("Devil Design PLA Basic @Bambu Lab H2D 0.4 nozzle (Custom)"),
  764. },
  765. )
  766. @pytest.mark.asyncio
  767. @pytest.mark.integration
  768. async def test_update_without_slicer_filament_skips_merge(
  769. self,
  770. async_client: AsyncClient,
  771. spoolman_settings,
  772. mock_spoolman_client,
  773. ):
  774. """PATCH without slicer_filament fields must not call merge_spool_extra.
  775. Avoids overwriting an existing preset with empty/null when the user
  776. just changed an unrelated field (e.g. note, weight).
  777. """
  778. response = await async_client.patch(
  779. "/api/v1/spoolman/inventory/spools/42",
  780. json={"note": "just changing the note"},
  781. )
  782. assert response.status_code == 200
  783. mock_spoolman_client.merge_spool_extra.assert_not_called()
  784. @pytest.mark.asyncio
  785. @pytest.mark.integration
  786. async def test_update_clears_slicer_filament_with_empty_string(
  787. self,
  788. async_client: AsyncClient,
  789. spoolman_settings,
  790. mock_spoolman_client,
  791. ):
  792. """Empty-string slicer_filament writes the JSON-encoded "" sentinel.
  793. The read-side strip('"') resolves it to an empty string and falls
  794. back to filament.name — matches the user-facing "clear preset" flow.
  795. """
  796. import json as _json
  797. mock_spoolman_client.ensure_extra_field = AsyncMock(return_value=True)
  798. response = await async_client.patch(
  799. "/api/v1/spoolman/inventory/spools/42",
  800. json={"slicer_filament": "", "slicer_filament_name": ""},
  801. )
  802. assert response.status_code == 200
  803. mock_spoolman_client.merge_spool_extra.assert_called_once_with(
  804. 42,
  805. {
  806. "bambu_slicer_filament": _json.dumps(""),
  807. "bambu_slicer_filament_name": _json.dumps(""),
  808. },
  809. )
  810. class TestSpoolmanInventoryCostPerKg:
  811. """Tests for the two-step cost_per_kg create path (PT-C2)."""
  812. @pytest.mark.asyncio
  813. @pytest.mark.integration
  814. async def test_create_spool_with_cost_per_kg_calls_price_update(
  815. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  816. ):
  817. """POST with cost_per_kg calls update_spool_full with price= after creation."""
  818. from unittest.mock import AsyncMock
  819. mock_spoolman_client.update_spool_full = AsyncMock(return_value=SAMPLE_SPOOLMAN_SPOOL)
  820. payload = {
  821. "material": "PLA",
  822. "brand": "Bambu Lab",
  823. "label_weight": 1000,
  824. "cost_per_kg": 24.99,
  825. }
  826. resp = await async_client.post("/api/v1/spoolman/inventory/spools", json=payload)
  827. assert resp.status_code == 200
  828. # update_spool_full must have been called with price=24.99
  829. calls = [
  830. c
  831. for c in mock_spoolman_client.update_spool_full.call_args_list
  832. if c.kwargs.get("price") == 24.99 or (c.args and 24.99 in c.args)
  833. ]
  834. assert len(calls) >= 1
  835. @pytest.mark.asyncio
  836. @pytest.mark.integration
  837. async def test_create_spool_without_cost_per_kg_skips_price_update(
  838. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  839. ):
  840. """POST without cost_per_kg does not call update_spool_full."""
  841. from unittest.mock import AsyncMock
  842. mock_spoolman_client.update_spool_full = AsyncMock(return_value=SAMPLE_SPOOLMAN_SPOOL)
  843. payload = {"material": "PLA", "brand": "Bambu Lab", "label_weight": 1000}
  844. resp = await async_client.post("/api/v1/spoolman/inventory/spools", json=payload)
  845. assert resp.status_code == 200
  846. mock_spoolman_client.update_spool_full.assert_not_called()
  847. class TestSpoolmanInventoryInputValidation:
  848. """Tests for input validation added as security hardening."""
  849. @pytest.mark.asyncio
  850. @pytest.mark.integration
  851. async def test_create_rejects_material_too_long(
  852. self,
  853. async_client: AsyncClient,
  854. spoolman_settings,
  855. mock_spoolman_client,
  856. ):
  857. """material longer than 64 chars is rejected with 422."""
  858. payload = {"material": "A" * 65, "label_weight": 1000, "weight_used": 0}
  859. response = await async_client.post("/api/v1/spoolman/inventory/spools", json=payload)
  860. assert response.status_code == 422
  861. @pytest.mark.asyncio
  862. @pytest.mark.integration
  863. async def test_create_rejects_note_too_long(
  864. self,
  865. async_client: AsyncClient,
  866. spoolman_settings,
  867. mock_spoolman_client,
  868. ):
  869. """note longer than 1000 chars is rejected with 422."""
  870. payload = {
  871. "material": "PLA",
  872. "label_weight": 1000,
  873. "weight_used": 0,
  874. "note": "x" * 1001,
  875. }
  876. response = await async_client.post("/api/v1/spoolman/inventory/spools", json=payload)
  877. assert response.status_code == 422
  878. @pytest.mark.asyncio
  879. @pytest.mark.integration
  880. async def test_create_rejects_negative_weight_used(
  881. self,
  882. async_client: AsyncClient,
  883. spoolman_settings,
  884. mock_spoolman_client,
  885. ):
  886. """Negative weight_used is rejected with 422."""
  887. payload = {"material": "PLA", "label_weight": 1000, "weight_used": -1.0}
  888. response = await async_client.post("/api/v1/spoolman/inventory/spools", json=payload)
  889. assert response.status_code == 422
  890. @pytest.mark.asyncio
  891. @pytest.mark.integration
  892. async def test_create_rejects_zero_label_weight(
  893. self,
  894. async_client: AsyncClient,
  895. spoolman_settings,
  896. mock_spoolman_client,
  897. ):
  898. """label_weight of 0 is rejected (minimum is 1)."""
  899. payload = {"material": "PLA", "label_weight": 0, "weight_used": 0}
  900. response = await async_client.post("/api/v1/spoolman/inventory/spools", json=payload)
  901. assert response.status_code == 422
  902. @pytest.mark.asyncio
  903. @pytest.mark.integration
  904. async def test_create_rejects_invalid_rgba(
  905. self,
  906. async_client: AsyncClient,
  907. spoolman_settings,
  908. mock_spoolman_client,
  909. ):
  910. """Non-hex rgba string is rejected with 422."""
  911. payload = {"material": "PLA", "label_weight": 1000, "weight_used": 0, "rgba": "GGGGGGFF"}
  912. response = await async_client.post("/api/v1/spoolman/inventory/spools", json=payload)
  913. assert response.status_code == 422
  914. @pytest.mark.asyncio
  915. @pytest.mark.integration
  916. async def test_create_accepts_valid_6char_rgba(
  917. self,
  918. async_client: AsyncClient,
  919. spoolman_settings,
  920. mock_spoolman_client,
  921. ):
  922. """A valid 6-char hex rgba is accepted."""
  923. payload = {"material": "PLA", "label_weight": 1000, "weight_used": 0, "rgba": "FF0000"}
  924. response = await async_client.post("/api/v1/spoolman/inventory/spools", json=payload)
  925. assert response.status_code == 200
  926. @pytest.mark.asyncio
  927. @pytest.mark.integration
  928. async def test_weight_update_rejects_negative_grams(
  929. self,
  930. async_client: AsyncClient,
  931. spoolman_settings,
  932. mock_spoolman_client,
  933. ):
  934. """Negative weight_grams on weight sync endpoint is rejected with 422."""
  935. response = await async_client.patch(
  936. "/api/v1/spoolman/inventory/spools/42/weight",
  937. json={"weight_grams": -50.0},
  938. )
  939. assert response.status_code == 422
  940. @pytest.mark.asyncio
  941. @pytest.mark.integration
  942. async def test_update_rejects_tag_uid_too_long(
  943. self,
  944. async_client: AsyncClient,
  945. spoolman_settings,
  946. mock_spoolman_client,
  947. ):
  948. """tag_uid longer than 30 chars is rejected with 422 (NFC UID max 10 bytes = 20 hex chars, capped at 30)."""
  949. payload = {"tag_uid": "A" * 65}
  950. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  951. assert response.status_code == 422
  952. @pytest.mark.asyncio
  953. @pytest.mark.integration
  954. async def test_update_rejects_tray_uuid_too_long(
  955. self,
  956. async_client: AsyncClient,
  957. spoolman_settings,
  958. mock_spoolman_client,
  959. ):
  960. """tray_uuid longer than 32 chars is rejected with 422."""
  961. payload = {"tray_uuid": "B" * 65}
  962. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  963. assert response.status_code == 422
  964. @pytest.mark.asyncio
  965. @pytest.mark.integration
  966. @pytest.mark.parametrize("uuid_len", [16, 31])
  967. async def test_update_rejects_tray_uuid_too_short(
  968. self,
  969. async_client: AsyncClient,
  970. spoolman_settings,
  971. mock_spoolman_client,
  972. uuid_len: int,
  973. ):
  974. """tray_uuid shorter than 32 chars is rejected (min_length=max_length=32)."""
  975. payload = {"tray_uuid": "A" * uuid_len}
  976. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  977. assert response.status_code == 422
  978. @pytest.mark.asyncio
  979. @pytest.mark.integration
  980. async def test_update_rejects_rgba_nine_chars(
  981. self,
  982. async_client: AsyncClient,
  983. spoolman_settings,
  984. mock_spoolman_client,
  985. ):
  986. """rgba must be max 8 hex chars; 9-char value is rejected with 422."""
  987. payload = {"rgba": "FF0000FFA"} # 9 chars
  988. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  989. assert response.status_code == 422
  990. @pytest.mark.asyncio
  991. @pytest.mark.integration
  992. async def test_tag_uid_below_min_length_rejected(
  993. self,
  994. async_client: AsyncClient,
  995. spoolman_settings,
  996. mock_spoolman_client,
  997. ):
  998. """tag_uid shorter than 8 hex chars is rejected with 422 (PT-I5)."""
  999. payload = {"tag_uid": "AABBCC"} # 6 chars, below min_length=8
  1000. resp = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  1001. assert resp.status_code == 422
  1002. @pytest.mark.asyncio
  1003. @pytest.mark.integration
  1004. async def test_invalid_spoolman_url_scheme_returns_400(
  1005. self,
  1006. async_client: AsyncClient,
  1007. db_session,
  1008. mock_spoolman_client,
  1009. ):
  1010. """A spoolman_url with a non-http(s) scheme is rejected."""
  1011. from backend.app.models.settings import Settings
  1012. db_session.add(Settings(key="spoolman_enabled", value="true"))
  1013. db_session.add(Settings(key="spoolman_url", value="ftp://evil.internal/"))
  1014. await db_session.commit()
  1015. response = await async_client.get("/api/v1/spoolman/inventory/spools")
  1016. assert response.status_code == 400
  1017. assert "http" in response.json()["detail"].lower()
  1018. @pytest.mark.asyncio
  1019. @pytest.mark.integration
  1020. @pytest.mark.parametrize(
  1021. "evil_url",
  1022. [
  1023. "file:///etc/passwd",
  1024. "gopher://127.0.0.1:70/",
  1025. "dict://internal.corp/",
  1026. "javascript:alert(1)",
  1027. "http://169.254.169.254/latest/meta-data/", # AWS IMDS
  1028. "http://100.100.100.200/", # Alibaba Cloud metadata
  1029. "http://[fd00:ec2::254]/", # AWS IMDS IPv6
  1030. "http://0.0.0.0/", # unspecified
  1031. "http://224.0.0.1/", # IPv4 multicast
  1032. "http://[ff02::1]/", # IPv6 multicast
  1033. "http://[::ffff:169.254.169.254]/", # IPv4-mapped IPv6 IMDS bypass
  1034. "http://2130706433/", # decimal-encoded 127.0.0.1
  1035. "http://0x7f000001/", # hex-encoded 127.0.0.1
  1036. ],
  1037. )
  1038. async def test_ssrf_blocked_schemes_and_addresses(
  1039. self,
  1040. async_client: AsyncClient,
  1041. db_session,
  1042. mock_spoolman_client,
  1043. evil_url: str,
  1044. ):
  1045. """SSRF: dangerous schemes, cloud metadata IPs, multicast, unspecified,
  1046. and numeric-encoded IPs must be rejected with 400. Loopback and
  1047. RFC-1918 private ranges are allowed — they are legitimate Spoolman
  1048. topologies for self-hosted Bambuddy deployments."""
  1049. from backend.app.models.settings import Settings
  1050. db_session.add(Settings(key="spoolman_enabled", value="true"))
  1051. db_session.add(Settings(key="spoolman_url", value=evil_url))
  1052. await db_session.commit()
  1053. response = await async_client.get("/api/v1/spoolman/inventory/spools")
  1054. assert response.status_code == 400, (
  1055. f"Expected 400 for SSRF URL {evil_url!r} but got {response.status_code}: {response.json()}"
  1056. )
  1057. @pytest.mark.asyncio
  1058. @pytest.mark.integration
  1059. @pytest.mark.parametrize(
  1060. "lan_url",
  1061. [
  1062. "http://127.0.0.1:7912/", # loopback
  1063. "http://[::1]:7912/", # IPv6 loopback
  1064. "http://192.168.1.50:7912/", # RFC-1918 /16
  1065. "http://10.0.0.5:7912/", # RFC-1918 /8
  1066. "http://172.20.0.3:7912/", # RFC-1918 /12
  1067. ],
  1068. )
  1069. async def test_ssrf_allows_lan_spoolman_topologies(
  1070. self,
  1071. async_client: AsyncClient,
  1072. db_session,
  1073. mock_spoolman_client,
  1074. lan_url: str,
  1075. ):
  1076. """Regression: Bambuddy's normal deployment is LAN-local Spoolman.
  1077. Loopback and RFC-1918 private addresses must NOT be rejected as SSRF."""
  1078. from backend.app.models.settings import Settings
  1079. db_session.add(Settings(key="spoolman_enabled", value="true"))
  1080. db_session.add(Settings(key="spoolman_url", value=lan_url))
  1081. await db_session.commit()
  1082. response = await async_client.get("/api/v1/spoolman/inventory/spools")
  1083. assert response.status_code != 400, f"LAN URL {lan_url!r} was incorrectly blocked as SSRF: {response.json()}"
  1084. @pytest.mark.asyncio
  1085. @pytest.mark.integration
  1086. async def test_create_rejects_storage_location_too_long(
  1087. self,
  1088. async_client: AsyncClient,
  1089. spoolman_settings,
  1090. mock_spoolman_client,
  1091. ):
  1092. """storage_location longer than 255 chars is rejected with 422."""
  1093. payload = {
  1094. "material": "PLA",
  1095. "label_weight": 1000,
  1096. "weight_used": 0,
  1097. "storage_location": "x" * 256,
  1098. }
  1099. response = await async_client.post("/api/v1/spoolman/inventory/spools", json=payload)
  1100. assert response.status_code == 422
  1101. @pytest.mark.asyncio
  1102. @pytest.mark.integration
  1103. async def test_update_rejects_storage_location_too_long(
  1104. self,
  1105. async_client: AsyncClient,
  1106. spoolman_settings,
  1107. mock_spoolman_client,
  1108. ):
  1109. """storage_location longer than 255 chars on PATCH is rejected with 422."""
  1110. payload = {"storage_location": "y" * 256}
  1111. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  1112. assert response.status_code == 422
  1113. class TestStorageLocationPassthrough:
  1114. """Tests that storage_location is correctly passed to and from Spoolman."""
  1115. @pytest.mark.asyncio
  1116. @pytest.mark.integration
  1117. async def test_list_spools_maps_spoolman_location_to_storage_location(
  1118. self,
  1119. async_client: AsyncClient,
  1120. spoolman_settings,
  1121. mock_spoolman_client,
  1122. ):
  1123. """Spoolman's location field is exposed as storage_location in the response."""
  1124. response = await async_client.get("/api/v1/spoolman/inventory/spools")
  1125. spool = response.json()[0]
  1126. assert spool["storage_location"] == "Printer1 - AMS A1"
  1127. @pytest.mark.asyncio
  1128. @pytest.mark.integration
  1129. async def test_list_spools_null_location_gives_null_storage_location(
  1130. self,
  1131. async_client: AsyncClient,
  1132. spoolman_settings,
  1133. mock_spoolman_client,
  1134. ):
  1135. """A Spoolman spool with no location gives null storage_location."""
  1136. spool_no_loc = {**SAMPLE_SPOOLMAN_SPOOL, "location": None}
  1137. mock_spoolman_client.get_all_spools.return_value = [spool_no_loc]
  1138. response = await async_client.get("/api/v1/spoolman/inventory/spools")
  1139. spool = response.json()[0]
  1140. assert spool["storage_location"] is None
  1141. @pytest.mark.asyncio
  1142. @pytest.mark.integration
  1143. async def test_create_passes_storage_location_to_spoolman(
  1144. self,
  1145. async_client: AsyncClient,
  1146. spoolman_settings,
  1147. mock_spoolman_client,
  1148. ):
  1149. """storage_location is forwarded as location when creating a Spoolman spool."""
  1150. payload = {
  1151. "material": "PLA",
  1152. "label_weight": 1000,
  1153. "weight_used": 0,
  1154. "storage_location": "Shelf B",
  1155. }
  1156. response = await async_client.post("/api/v1/spoolman/inventory/spools", json=payload)
  1157. assert response.status_code == 200
  1158. mock_spoolman_client.create_spool.assert_called_once()
  1159. _, kwargs = mock_spoolman_client.create_spool.call_args
  1160. assert kwargs.get("location") == "Shelf B"
  1161. @pytest.mark.asyncio
  1162. @pytest.mark.integration
  1163. async def test_update_passes_storage_location_to_spoolman(
  1164. self,
  1165. async_client: AsyncClient,
  1166. spoolman_settings,
  1167. mock_spoolman_client,
  1168. ):
  1169. """storage_location is forwarded as location when updating a Spoolman spool."""
  1170. payload = {"storage_location": "Drawer 3"}
  1171. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  1172. assert response.status_code == 200
  1173. mock_spoolman_client.update_spool_full.assert_called_once()
  1174. _, kwargs = mock_spoolman_client.update_spool_full.call_args
  1175. assert kwargs.get("location") == "Drawer 3"
  1176. assert kwargs.get("clear_location") is False
  1177. @pytest.mark.asyncio
  1178. @pytest.mark.integration
  1179. async def test_update_clears_storage_location_when_null_sent(
  1180. self,
  1181. async_client: AsyncClient,
  1182. spoolman_settings,
  1183. mock_spoolman_client,
  1184. ):
  1185. """Explicitly sending null storage_location clears the Spoolman location."""
  1186. payload = {"storage_location": None}
  1187. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  1188. assert response.status_code == 200
  1189. _, kwargs = mock_spoolman_client.update_spool_full.call_args
  1190. assert kwargs.get("clear_location") is True
  1191. @pytest.mark.asyncio
  1192. @pytest.mark.integration
  1193. async def test_update_clears_storage_location_when_empty_string_sent(
  1194. self,
  1195. async_client: AsyncClient,
  1196. spoolman_settings,
  1197. mock_spoolman_client,
  1198. ):
  1199. """Sending an empty string for storage_location also clears the Spoolman location."""
  1200. payload = {"storage_location": ""}
  1201. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  1202. assert response.status_code == 200
  1203. _, kwargs = mock_spoolman_client.update_spool_full.call_args
  1204. assert kwargs.get("clear_location") is True
  1205. @pytest.mark.asyncio
  1206. @pytest.mark.integration
  1207. async def test_update_omitting_storage_location_does_not_write_location_to_spoolman(
  1208. self,
  1209. async_client: AsyncClient,
  1210. spoolman_settings,
  1211. mock_spoolman_client,
  1212. ):
  1213. """PATCH without storage_location in the payload must not touch Spoolman's location field.
  1214. Regression test for the round-trip bug: opening the edit modal and saving without
  1215. changing the location would previously echo the current Spoolman value back
  1216. (storage_location_changed=False branch used current.get("location") instead of None).
  1217. """
  1218. # Payload deliberately omits storage_location — simulates saving the modal
  1219. # without touching that field.
  1220. payload = {"note": "just updating the note"}
  1221. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  1222. assert response.status_code == 200
  1223. mock_spoolman_client.update_spool_full.assert_called_once()
  1224. _, kwargs = mock_spoolman_client.update_spool_full.call_args
  1225. # location must be None so update_spool_full skips writing the field entirely
  1226. assert kwargs.get("location") is None
  1227. # clear_location must also be False — we are not explicitly clearing it either
  1228. assert kwargs.get("clear_location") is False
  1229. class TestColorNamePassthrough:
  1230. """color_name persistence via spool.extra.bambu_color_name (#1357).
  1231. Spoolman 0.23.1 has no `color_name` field on Filament, so Bambuddy owns
  1232. the round-trip via the spool's extra dict — same shape as the existing
  1233. bambu_slicer_filament storage. These tests pin that the create/update
  1234. routes register the extra field and write to merge_spool_extra, NOT to
  1235. find_or_create_filament's color_name parameter.
  1236. """
  1237. @pytest.mark.asyncio
  1238. @pytest.mark.integration
  1239. async def test_create_writes_color_name_to_spool_extra(
  1240. self,
  1241. async_client: AsyncClient,
  1242. spoolman_settings,
  1243. mock_spoolman_client,
  1244. ):
  1245. """color_name from create payload lands in spool.extra.bambu_color_name."""
  1246. import json as _json
  1247. payload = {
  1248. "material": "PLA",
  1249. "label_weight": 1000,
  1250. "weight_used": 0,
  1251. "color_name": "Bambu Green",
  1252. }
  1253. response = await async_client.post("/api/v1/spoolman/inventory/spools", json=payload)
  1254. assert response.status_code == 200
  1255. mock_spoolman_client.ensure_extra_field.assert_any_call("bambu_color_name")
  1256. mock_spoolman_client.merge_spool_extra.assert_called_once()
  1257. args = mock_spoolman_client.merge_spool_extra.call_args.args
  1258. extra_patch = args[1]
  1259. assert _json.loads(extra_patch["bambu_color_name"]) == "Bambu Green"
  1260. @pytest.mark.asyncio
  1261. @pytest.mark.integration
  1262. async def test_update_writes_color_name_to_spool_extra(
  1263. self,
  1264. async_client: AsyncClient,
  1265. spoolman_settings,
  1266. mock_spoolman_client,
  1267. ):
  1268. """color_name from update payload lands in spool.extra.bambu_color_name —
  1269. this is the #1357 reproduction: previously the value went to
  1270. filament.color_name which Spoolman silently dropped."""
  1271. import json as _json
  1272. payload = {"color_name": "Jade White"}
  1273. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  1274. assert response.status_code == 200
  1275. mock_spoolman_client.ensure_extra_field.assert_any_call("bambu_color_name")
  1276. mock_spoolman_client.merge_spool_extra.assert_called_once()
  1277. args = mock_spoolman_client.merge_spool_extra.call_args.args
  1278. extra_patch = args[1]
  1279. assert _json.loads(extra_patch["bambu_color_name"]) == "Jade White"
  1280. @pytest.mark.asyncio
  1281. @pytest.mark.integration
  1282. async def test_update_omits_color_name_skips_extra_write(
  1283. self,
  1284. async_client: AsyncClient,
  1285. spoolman_settings,
  1286. mock_spoolman_client,
  1287. ):
  1288. """When color_name is absent from the PATCH body, the route must not
  1289. write to spool.extra at all (preserves any existing value)."""
  1290. payload = {"note": "no color_name here"}
  1291. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  1292. assert response.status_code == 200
  1293. color_name_calls = [
  1294. c
  1295. for c in mock_spoolman_client.ensure_extra_field.call_args_list
  1296. if c.args and c.args[0] == "bambu_color_name"
  1297. ]
  1298. assert color_name_calls == []
  1299. class TestSpoolmanInventoryAuth:
  1300. """Write/delete endpoints require INVENTORY_UPDATE when auth is enabled."""
  1301. @pytest.fixture
  1302. async def auth_and_spoolman_settings(self, db_session):
  1303. """Enable both Spoolman and auth."""
  1304. from backend.app.models.settings import Settings
  1305. db_session.add(Settings(key="spoolman_enabled", value="true"))
  1306. db_session.add(Settings(key="spoolman_url", value="http://localhost:7912"))
  1307. db_session.add(Settings(key="auth_enabled", value="true"))
  1308. await db_session.commit()
  1309. @pytest.mark.asyncio
  1310. @pytest.mark.integration
  1311. @pytest.mark.parametrize(
  1312. "method,path,payload",
  1313. [
  1314. ("POST", "/api/v1/spoolman/inventory/spools", {"material": "PLA", "label_weight": 1000, "weight_used": 0}),
  1315. (
  1316. "POST",
  1317. "/api/v1/spoolman/inventory/spools/bulk",
  1318. {"spool": {"material": "PLA", "label_weight": 1000, "weight_used": 0}, "quantity": 1},
  1319. ),
  1320. ("PATCH", "/api/v1/spoolman/inventory/spools/42", {"note": "x"}),
  1321. ("DELETE", "/api/v1/spoolman/inventory/spools/42", None),
  1322. ("POST", "/api/v1/spoolman/inventory/spools/42/archive", None),
  1323. ("POST", "/api/v1/spoolman/inventory/spools/42/restore", None),
  1324. ("PATCH", "/api/v1/spoolman/inventory/spools/42/weight", {"weight_grams": 100.0}),
  1325. ],
  1326. )
  1327. async def test_write_endpoints_require_auth(
  1328. self,
  1329. async_client: AsyncClient,
  1330. auth_and_spoolman_settings,
  1331. method: str,
  1332. path: str,
  1333. payload: dict | None,
  1334. ):
  1335. """All write/delete endpoints return 401 when auth is enabled and no token is provided."""
  1336. response = await async_client.request(method, path, json=payload)
  1337. assert response.status_code == 401, (
  1338. f"{method} {path} should require auth but got {response.status_code}: {response.json()}"
  1339. )
  1340. @pytest.mark.asyncio
  1341. @pytest.mark.integration
  1342. @pytest.mark.parametrize(
  1343. "method,path",
  1344. [
  1345. ("GET", "/api/v1/spoolman/inventory/spools"),
  1346. ("GET", "/api/v1/spoolman/inventory/spools/42"),
  1347. ],
  1348. )
  1349. async def test_read_endpoints_require_auth(
  1350. self,
  1351. async_client: AsyncClient,
  1352. auth_and_spoolman_settings,
  1353. method: str,
  1354. path: str,
  1355. ):
  1356. """Read endpoints also require auth when auth is enabled."""
  1357. response = await async_client.request(method, path)
  1358. assert response.status_code == 401, (
  1359. f"{method} {path} should require auth but got {response.status_code}: {response.json()}"
  1360. )
  1361. @pytest.fixture
  1362. async def viewer_token(self, db_session):
  1363. """Create a Viewer-group user (INVENTORY_READ only, no INVENTORY_UPDATE)."""
  1364. from sqlalchemy import select
  1365. from backend.app.core.auth import create_access_token, get_password_hash
  1366. from backend.app.models.group import Group
  1367. from backend.app.models.settings import Settings
  1368. from backend.app.models.user import User
  1369. db_session.add(Settings(key="spoolman_enabled", value="true"))
  1370. db_session.add(Settings(key="spoolman_url", value="http://localhost:7912"))
  1371. db_session.add(Settings(key="auth_enabled", value="true"))
  1372. await db_session.commit()
  1373. viewer_group = (await db_session.execute(select(Group).where(Group.name == "Viewers"))).scalar_one()
  1374. viewer = User(
  1375. username="sm_inv_viewer",
  1376. password_hash=get_password_hash("pw"),
  1377. is_active=True,
  1378. )
  1379. viewer.groups.append(viewer_group)
  1380. db_session.add(viewer)
  1381. await db_session.commit()
  1382. return create_access_token(data={"sub": viewer.username})
  1383. @pytest.mark.asyncio
  1384. @pytest.mark.integration
  1385. @pytest.mark.parametrize(
  1386. "method,path,payload",
  1387. [
  1388. ("POST", "/api/v1/spoolman/inventory/spools", {"material": "PLA", "label_weight": 1000, "weight_used": 0}),
  1389. (
  1390. "POST",
  1391. "/api/v1/spoolman/inventory/spools/bulk",
  1392. {"spool": {"material": "PLA", "label_weight": 1000, "weight_used": 0}, "quantity": 1},
  1393. ),
  1394. ("PATCH", "/api/v1/spoolman/inventory/spools/42", {"note": "x"}),
  1395. ("DELETE", "/api/v1/spoolman/inventory/spools/42", None),
  1396. ("POST", "/api/v1/spoolman/inventory/spools/42/archive", None),
  1397. ("POST", "/api/v1/spoolman/inventory/spools/42/restore", None),
  1398. ("PATCH", "/api/v1/spoolman/inventory/spools/42/weight", {"weight_grams": 100.0}),
  1399. ],
  1400. )
  1401. async def test_write_endpoints_return_403_for_viewer(
  1402. self,
  1403. async_client: AsyncClient,
  1404. viewer_token,
  1405. method: str,
  1406. path: str,
  1407. payload: dict | None,
  1408. ):
  1409. """Viewer-group users (INVENTORY_READ, no INVENTORY_UPDATE) get 403 on write endpoints."""
  1410. response = await async_client.request(
  1411. method,
  1412. path,
  1413. json=payload,
  1414. headers={"Authorization": f"Bearer {viewer_token}"},
  1415. )
  1416. assert response.status_code == 403, (
  1417. f"{method} {path} should return 403 for read-only user but got {response.status_code}: {response.json()}"
  1418. )
  1419. # Error body must mention the permission string so a "banned-user middleware"
  1420. # regression (generic 403 with no permission context) doesn't pass silently.
  1421. detail = response.json().get("detail", "")
  1422. assert "inventory:update" in detail, f"Expected 'inventory:update' in 403 detail but got: {detail!r}"
  1423. # ---------------------------------------------------------------------------
  1424. # Additional regression tests for second-round review items
  1425. # ---------------------------------------------------------------------------
  1426. class TestSpoolmanInventorySecurityExtras:
  1427. """Additional security/validation tests added in second review round."""
  1428. @pytest.mark.asyncio
  1429. @pytest.mark.integration
  1430. async def test_create_rejects_double_hash_rgba(
  1431. self,
  1432. async_client: AsyncClient,
  1433. spoolman_settings,
  1434. mock_spoolman_client,
  1435. ):
  1436. """SEC-3: rgba like '##FF0000' (double hash) must be rejected with 422."""
  1437. payload = {"material": "PLA", "label_weight": 1000, "weight_used": 0, "rgba": "##FF0000"}
  1438. response = await async_client.post("/api/v1/spoolman/inventory/spools", json=payload)
  1439. assert response.status_code == 422
  1440. @pytest.mark.asyncio
  1441. @pytest.mark.integration
  1442. @pytest.mark.parametrize("spool_id", [0, -1])
  1443. async def test_path_param_non_positive_spool_id_returns_422(
  1444. self,
  1445. async_client: AsyncClient,
  1446. spoolman_settings,
  1447. mock_spoolman_client,
  1448. spool_id: int,
  1449. ):
  1450. """SEC-5: /spools/0 and /spools/-1 must be rejected with 422 (Path gt=0)."""
  1451. response = await async_client.get(f"/api/v1/spoolman/inventory/spools/{spool_id}")
  1452. assert response.status_code == 422, f"Expected 422 for spool_id={spool_id} but got {response.status_code}"
  1453. @pytest.mark.asyncio
  1454. @pytest.mark.integration
  1455. @pytest.mark.parametrize(
  1456. "tag_uid,expected_status",
  1457. [
  1458. # After B1 fix: non-null tag_uid on PATCH /spools/{id} is rejected (use /tag endpoint)
  1459. ("A" * 30, 422), # non-null → 422 (use /tag endpoint instead)
  1460. ("DEADBEEF12345678", 422), # non-null → 422 regardless of length
  1461. ("A" * 31, 422), # exceeds max_length — also 422
  1462. ("A" * 32, 422), # tray_uuid-length value — also 422
  1463. ],
  1464. )
  1465. async def test_tag_uid_length_boundary(
  1466. self,
  1467. async_client: AsyncClient,
  1468. spoolman_settings,
  1469. mock_spoolman_client,
  1470. tag_uid: str,
  1471. expected_status: int,
  1472. ):
  1473. """tag_uid on PATCH /spools/{id} — all non-null values are rejected (B1 fix; use /tag endpoint)."""
  1474. payload = {"tag_uid": tag_uid}
  1475. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload)
  1476. assert response.status_code == expected_status, (
  1477. f"tag_uid len={len(tag_uid)}: expected {expected_status} but got {response.status_code}"
  1478. )
  1479. @pytest.mark.asyncio
  1480. @pytest.mark.integration
  1481. async def test_bulk_create_partial_failure_returns_207(
  1482. self,
  1483. async_client: AsyncClient,
  1484. spoolman_settings,
  1485. mock_spoolman_client,
  1486. ):
  1487. """I9: bulk create with quantity=3 where middle call fails → 207 Multi-Status."""
  1488. from backend.app.services.spoolman import SpoolmanUnavailableError
  1489. results = [SAMPLE_SPOOLMAN_SPOOL, SpoolmanUnavailableError("Spoolman down"), SAMPLE_SPOOLMAN_SPOOL]
  1490. mock_spoolman_client.create_spool.side_effect = results
  1491. payload = {
  1492. "spool": {"material": "PLA", "label_weight": 1000, "weight_used": 0},
  1493. "quantity": 3,
  1494. }
  1495. response = await async_client.post("/api/v1/spoolman/inventory/spools/bulk", json=payload)
  1496. assert response.status_code == 207, (
  1497. f"Expected 207 Multi-Status for partial failure but got {response.status_code}"
  1498. )
  1499. body = response.json()
  1500. assert isinstance(body, dict)
  1501. assert body["requested_count"] == 3
  1502. assert body["failed_count"] == 1
  1503. assert len(body["created"]) == 2
  1504. class TestTagClearPreservesExtraKeys:
  1505. """Regression test: clearing tag_uid must not wipe unrelated Spoolman extra fields."""
  1506. @pytest.mark.asyncio
  1507. @pytest.mark.integration
  1508. async def test_tag_clear_preserves_custom_extra_key(
  1509. self,
  1510. async_client: AsyncClient,
  1511. spoolman_settings,
  1512. mock_spoolman_client,
  1513. ):
  1514. """PATCH tag_uid=None clears tag without dropping unrelated extra keys.
  1515. Spoolman PATCHes the extra dict by MERGING — popping a key from the
  1516. dict and sending the rest doesn't actually clear it. The endpoint
  1517. sets tag = json.dumps("") explicitly; read-side filters strip the
  1518. wrapping quotes and treat the empty string as "no tag" (#1114).
  1519. """
  1520. import json as _json
  1521. spool_with_extra = {
  1522. **SAMPLE_SPOOLMAN_SPOOL,
  1523. "extra": {"tag": '"AABBCCDDEEFF0011AABBCCDDEEFF0011"', "custom_key": "keep_me"},
  1524. }
  1525. mock_spoolman_client.get_spool = AsyncMock(return_value=spool_with_extra)
  1526. mock_spoolman_client.update_spool_full = AsyncMock(return_value=spool_with_extra)
  1527. response = await async_client.patch(
  1528. "/api/v1/spoolman/inventory/spools/42",
  1529. json={"tag_uid": None},
  1530. )
  1531. assert response.status_code == 200
  1532. mock_spoolman_client.update_spool_full.assert_called_once()
  1533. _, kwargs = mock_spoolman_client.update_spool_full.call_args
  1534. sent_extra = kwargs.get("extra")
  1535. assert sent_extra is not None, "extra must be sent when tag is cleared"
  1536. assert sent_extra.get("tag") == _json.dumps(""), (
  1537. "tag must be set to JSON empty-string sentinel (Spoolman PATCH merges; "
  1538. "popping the key would leave the previous value in place)"
  1539. )
  1540. assert sent_extra.get("custom_key") == "keep_me", "unrelated extra keys must survive"
  1541. @pytest.mark.asyncio
  1542. @pytest.mark.integration
  1543. async def test_tag_clear_refetches_spool_inside_lock(
  1544. self,
  1545. async_client: AsyncClient,
  1546. spoolman_settings,
  1547. mock_spoolman_client,
  1548. ):
  1549. """B7: tag-clear does a fresh get_spool() re-fetch inside the lock, not the stale one.
  1550. Simulates a write that changes extra between the initial get_spool (used for
  1551. other field resolution) and the lock acquisition. The extra sent to
  1552. update_spool_full must come from the second (in-lock) fetch, not the first.
  1553. """
  1554. stale_extra = {"tag": '"AABBCCDD"', "custom_key": "stale_value"}
  1555. fresh_extra = {"tag": '"AABBCCDD"', "custom_key": "fresh_value"}
  1556. stale_spool = {**SAMPLE_SPOOLMAN_SPOOL, "extra": stale_extra}
  1557. fresh_spool = {**SAMPLE_SPOOLMAN_SPOOL, "extra": fresh_extra}
  1558. # First call returns stale; second call (inside lock) returns fresh
  1559. mock_spoolman_client.get_spool = AsyncMock(side_effect=[stale_spool, fresh_spool])
  1560. mock_spoolman_client.update_spool_full = AsyncMock(return_value=fresh_spool)
  1561. response = await async_client.patch(
  1562. "/api/v1/spoolman/inventory/spools/42",
  1563. json={"tag_uid": None, "tray_uuid": None},
  1564. )
  1565. assert response.status_code == 200
  1566. # get_spool called twice: once for field resolution, once for fresh extra fetch
  1567. assert mock_spoolman_client.get_spool.call_count == 2
  1568. import json as _json
  1569. _, kwargs = mock_spoolman_client.update_spool_full.call_args
  1570. sent_extra = kwargs.get("extra")
  1571. assert sent_extra is not None
  1572. # Tag is set to the JSON empty-string sentinel (not popped) — Spoolman
  1573. # PATCH merges, so popping the key would leave the previous value.
  1574. assert sent_extra.get("tag") == _json.dumps("")
  1575. # custom_key must come from the fresh re-fetch, not the stale first fetch
  1576. assert sent_extra.get("custom_key") == "fresh_value"
  1577. class TestSpoolmanInventorySSRFSpoolBuddyPath:
  1578. """SSRF tests for _get_spoolman_client_or_none (nfc/* and scale/ endpoints)."""
  1579. @pytest.mark.asyncio
  1580. @pytest.mark.integration
  1581. @pytest.mark.parametrize(
  1582. "evil_url",
  1583. [
  1584. "file:///etc/passwd",
  1585. "http://169.254.169.254/latest/meta-data/", # AWS IMDS
  1586. "http://0.0.0.0/", # unspecified
  1587. "http://[::ffff:169.254.169.254]/", # IPv4-mapped IMDS bypass
  1588. ],
  1589. )
  1590. async def test_nfc_tag_scanned_with_ssrf_url_ignores_spoolman(
  1591. self,
  1592. async_client: AsyncClient,
  1593. db_session,
  1594. evil_url: str,
  1595. ):
  1596. """SSRF: _get_spoolman_client_or_none silently disables Spoolman for unsafe URLs
  1597. on the SpoolBuddy NFC path (tag-scanned broadcasts unknown_tag, not 400)."""
  1598. from backend.app.models.settings import Settings
  1599. db_session.add(Settings(key="spoolman_enabled", value="true"))
  1600. db_session.add(Settings(key="spoolman_url", value=evil_url))
  1601. await db_session.commit()
  1602. from unittest.mock import AsyncMock, patch
  1603. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  1604. mock_ws.broadcast = AsyncMock()
  1605. resp = await async_client.post(
  1606. "/api/v1/spoolbuddy/nfc/tag-scanned",
  1607. json={"device_id": "sb-ssrf", "tag_uid": "AABBCCDD"},
  1608. )
  1609. # Must not crash or proxy the SSRF URL — unknown_tag is the safe degraded response
  1610. assert resp.status_code == 200
  1611. if mock_ws.broadcast.called:
  1612. msg = mock_ws.broadcast.call_args[0][0]
  1613. assert msg["type"] == "spoolbuddy_unknown_tag"
  1614. @pytest.mark.asyncio
  1615. @pytest.mark.integration
  1616. @pytest.mark.parametrize(
  1617. "evil_url",
  1618. [
  1619. "http://169.254.169.254/latest/meta-data/", # AWS IMDS
  1620. "http://[::ffff:169.254.169.254]/", # IPv4-mapped IMDS bypass
  1621. ],
  1622. )
  1623. async def test_nfc_write_result_with_ssrf_url_degrades_gracefully(
  1624. self,
  1625. async_client: AsyncClient,
  1626. db_session,
  1627. evil_url: str,
  1628. ):
  1629. """SSRF: write-result with unsafe Spoolman URL must not proxy to the evil host.
  1630. write-result calls Spoolman to write-back the tag UID when data_origin='spoolman'.
  1631. With an SSRF URL, _get_spoolman_client_or_none returns None so the call is skipped
  1632. and the route returns 502 (tag written but link not persisted — not a server crash).
  1633. """
  1634. import json as _json
  1635. from backend.app.models.settings import Settings
  1636. from backend.app.models.spoolbuddy_device import SpoolBuddyDevice
  1637. db_session.add(Settings(key="spoolman_enabled", value="true"))
  1638. db_session.add(Settings(key="spoolman_url", value=evil_url))
  1639. # Register the device so the route doesn't 404 before reaching the SSRF guard.
  1640. db_session.add(
  1641. SpoolBuddyDevice(
  1642. device_id="sb-ssrf-wr",
  1643. hostname="sb-ssrf-wr.local",
  1644. ip_address="127.0.0.1",
  1645. pending_command="write_tag",
  1646. pending_write_payload=_json.dumps({"spool_id": 99, "ndef_data_hex": "DEAD", "data_origin": "spoolman"}),
  1647. )
  1648. )
  1649. await db_session.commit()
  1650. from unittest.mock import AsyncMock, patch
  1651. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  1652. mock_ws.broadcast = AsyncMock()
  1653. resp = await async_client.post(
  1654. "/api/v1/spoolbuddy/nfc/write-result",
  1655. json={
  1656. "device_id": "sb-ssrf-wr",
  1657. "spool_id": 99,
  1658. "tag_uid": "AABBCCDD",
  1659. "success": True,
  1660. },
  1661. )
  1662. # 502 = tag written to NFC but Spoolman link not persisted (SSRF guard blocked it).
  1663. # Must not be 500 (crash) and must not have proxied to the evil host.
  1664. assert resp.status_code == 502
  1665. @pytest.mark.asyncio
  1666. @pytest.mark.integration
  1667. @pytest.mark.parametrize(
  1668. "evil_url",
  1669. [
  1670. "http://169.254.169.254/latest/meta-data/", # AWS IMDS
  1671. ],
  1672. )
  1673. async def test_scale_update_weight_with_ssrf_url_degrades_gracefully(
  1674. self,
  1675. async_client: AsyncClient,
  1676. db_session,
  1677. evil_url: str,
  1678. ):
  1679. """SSRF: scale weight update with unsafe Spoolman URL must not proxy to the evil host."""
  1680. from backend.app.models.settings import Settings
  1681. db_session.add(Settings(key="spoolman_enabled", value="true"))
  1682. db_session.add(Settings(key="spoolman_url", value=evil_url))
  1683. await db_session.commit()
  1684. from unittest.mock import AsyncMock, patch
  1685. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  1686. mock_ws.broadcast = AsyncMock()
  1687. resp = await async_client.post(
  1688. "/api/v1/spoolbuddy/scale/update-spool-weight",
  1689. json={"device_id": "sb-ssrf-scale", "spool_id": 1, "weight_grams": 500.0},
  1690. )
  1691. # Must not crash or proxy to an SSRF host
  1692. assert resp.status_code in (200, 404, 422)
  1693. class TestMergeSpoolExtraPreservesKeys:
  1694. """Unit-level test for merge_spool_extra key preservation (via mocked Spoolman)."""
  1695. @pytest.mark.asyncio
  1696. @pytest.mark.integration
  1697. async def test_merge_preserves_unrelated_extra_keys(
  1698. self,
  1699. async_client: AsyncClient,
  1700. spoolman_settings,
  1701. mock_spoolman_client,
  1702. ):
  1703. """merge_spool_extra must deep-merge rather than overwrite the extra dict.
  1704. Seed extra={"custom_key": "keep_me", "tag": "old"}.
  1705. After merging {"tag": "new"}, the PATCH payload must still contain custom_key.
  1706. """
  1707. from unittest.mock import AsyncMock, patch
  1708. existing_spool = {
  1709. **SAMPLE_SPOOLMAN_SPOOL,
  1710. "extra": {"custom_key": "keep_me", "tag": '"old"'},
  1711. }
  1712. updated_spool = {**existing_spool, "extra": {"custom_key": "keep_me", "tag": '"new"'}}
  1713. mock_client = mock_spoolman_client
  1714. mock_client.get_spool = AsyncMock(return_value=existing_spool)
  1715. mock_client.update_spool_full = AsyncMock(return_value=updated_spool)
  1716. # Call merge_spool_extra directly through the service
  1717. from backend.app.services.spoolman import SpoolmanClient
  1718. client = SpoolmanClient.__new__(SpoolmanClient)
  1719. client.base_url = "http://localhost:7912"
  1720. client.api_url = "http://localhost:7912/api/v1"
  1721. client._extra_locks = {}
  1722. async def _mock_get(spool_id):
  1723. return existing_spool
  1724. async def _mock_update(spool_id, **kwargs):
  1725. # Capture what was actually sent
  1726. _mock_update.captured_extra = kwargs.get("extra")
  1727. return updated_spool
  1728. _mock_update.captured_extra = None
  1729. client.get_spool = _mock_get
  1730. client.update_spool_full = _mock_update
  1731. result = await client.merge_spool_extra(42, {"tag": '"new"'})
  1732. # The merged extra must include the unrelated key
  1733. assert _mock_update.captured_extra is not None
  1734. assert _mock_update.captured_extra.get("custom_key") == "keep_me"
  1735. assert _mock_update.captured_extra.get("tag") == '"new"'
  1736. assert result is not None
  1737. class TestGetClientValueError:
  1738. """Test the ValueError branch in _get_client when init_spoolman_client fails (Gap 5)."""
  1739. @pytest.mark.asyncio
  1740. @pytest.mark.integration
  1741. async def test_returns_400_when_init_spoolman_client_raises_value_error(
  1742. self, async_client: AsyncClient, spoolman_settings
  1743. ):
  1744. """If init_spoolman_client raises ValueError after SSRF check passes, return HTTP 400."""
  1745. with (
  1746. patch(
  1747. "backend.app.api.routes.spoolman_inventory.get_spoolman_client",
  1748. AsyncMock(return_value=None),
  1749. ),
  1750. patch(
  1751. "backend.app.api.routes.spoolman_inventory.init_spoolman_client",
  1752. AsyncMock(side_effect=ValueError("unsupported scheme")),
  1753. ),
  1754. ):
  1755. resp = await async_client.get("/api/v1/spoolman/inventory/spools")
  1756. assert resp.status_code == 400
  1757. assert "unsupported scheme" in resp.json()["detail"]
  1758. class TestBulkCreateWithPriceFailure:
  1759. """Test that bulk create handles price-update failures per C1/C8 semantics."""
  1760. @pytest.mark.asyncio
  1761. @pytest.mark.integration
  1762. async def test_bulk_create_price_503_moves_spool_to_failures(
  1763. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1764. ):
  1765. """When price update fails (503), the spool goes to failures — overall returns 207 if at least one succeeds."""
  1766. from backend.app.services.spoolman import SpoolmanUnavailableError
  1767. # First price update fails (SpoolmanUnavailableError → 503), second succeeds
  1768. mock_spoolman_client.update_spool_full = AsyncMock(
  1769. side_effect=[SpoolmanUnavailableError("price server down"), SAMPLE_SPOOLMAN_SPOOL]
  1770. )
  1771. mock_spoolman_client.create_spool = AsyncMock(return_value=SAMPLE_SPOOLMAN_SPOOL)
  1772. payload = {
  1773. "spool": {
  1774. "material": "PLA",
  1775. "brand": "Bambu Lab",
  1776. "label_weight": 1000,
  1777. "cost_per_kg": 19.99,
  1778. },
  1779. "quantity": 2,
  1780. }
  1781. resp = await async_client.post("/api/v1/spoolman/inventory/spools/bulk", json=payload)
  1782. # One spool succeeded, one failed (price 503) → 207 Partial
  1783. assert resp.status_code == 207
  1784. data = resp.json()
  1785. assert len(data["created"]) == 1
  1786. assert data["failed_count"] == 1
  1787. # Both Spoolman creates were attempted
  1788. assert mock_spoolman_client.create_spool.call_count == 2
  1789. # Both price updates were attempted
  1790. assert mock_spoolman_client.update_spool_full.call_count == 2
  1791. class TestSpoolTagLinkValidation:
  1792. """NEW-B1: /spools/{id}/tag endpoint validates tag_uid length and content."""
  1793. @pytest.mark.asyncio
  1794. @pytest.mark.integration
  1795. async def test_tag_uid_6_chars_rejected(self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client):
  1796. """tag_uid with 6 hex chars is rejected — minimum is 8 chars (4-byte UID)."""
  1797. resp = await async_client.patch(
  1798. "/api/v1/spoolman/inventory/spools/42/tag",
  1799. json={"tag_uid": "AABBCC"}, # 6 chars — below new minimum
  1800. )
  1801. assert resp.status_code == 422
  1802. @pytest.mark.asyncio
  1803. @pytest.mark.integration
  1804. async def test_tag_uid_all_zeros_rejected(self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client):
  1805. """tag_uid that is all-zero bytes is rejected as an unwritten/blank tag."""
  1806. resp = await async_client.patch(
  1807. "/api/v1/spoolman/inventory/spools/42/tag",
  1808. json={"tag_uid": "00000000000000"}, # 14 zeros
  1809. )
  1810. assert resp.status_code == 422
  1811. @pytest.mark.asyncio
  1812. @pytest.mark.integration
  1813. async def test_tag_uid_valid_14_chars_accepted(
  1814. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1815. ):
  1816. """tag_uid with 14 valid hex chars (7-byte UID) is accepted."""
  1817. # This tag is not in SAMPLE_SPOOLMAN_SPOOL so no duplicate conflict.
  1818. resp = await async_client.patch(
  1819. "/api/v1/spoolman/inventory/spools/42/tag",
  1820. json={"tag_uid": "AABBCCDD112233"}, # 14 chars, valid, not all-zeros
  1821. )
  1822. assert resp.status_code == 200
  1823. @pytest.mark.asyncio
  1824. @pytest.mark.integration
  1825. async def test_tag_uid_8_chars_accepted(self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client):
  1826. """tag_uid with 8 hex chars (4-byte Bambu Lab NFC UID) is accepted after min_length fix."""
  1827. resp = await async_client.patch(
  1828. "/api/v1/spoolman/inventory/spools/42/tag",
  1829. json={"tag_uid": "2728C17B"}, # 8 chars — real Bambu Lab 4-byte hardware UID
  1830. )
  1831. assert resp.status_code == 200
  1832. @pytest.mark.asyncio
  1833. @pytest.mark.integration
  1834. async def test_tag_uid_8_zeros_rejected(self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client):
  1835. """tag_uid with 8 zero chars is rejected — all-zeros validator applies at the new minimum."""
  1836. resp = await async_client.patch(
  1837. "/api/v1/spoolman/inventory/spools/42/tag",
  1838. json={"tag_uid": "00000000"}, # 8 zeros — meets min_length but is a blank/unwritten tag
  1839. )
  1840. assert resp.status_code == 422
  1841. class TestLinkTagDuplicate:
  1842. """NEW-I1: /spools/{id}/tag returns 409 when another spool already has the same tag."""
  1843. @pytest.mark.asyncio
  1844. @pytest.mark.integration
  1845. async def test_link_tag_returns_200_when_tag_not_on_another_spool(
  1846. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1847. ):
  1848. """Linking a fresh tag to spool 42 returns 200 — no duplicate in Spoolman."""
  1849. resp = await async_client.patch(
  1850. "/api/v1/spoolman/inventory/spools/42/tag",
  1851. json={"tag_uid": "AABBCCDD112233"}, # not in SAMPLE_SPOOLMAN_SPOOL
  1852. )
  1853. assert resp.status_code == 200
  1854. mock_spoolman_client.update_spool_full.assert_called_once()
  1855. @pytest.mark.asyncio
  1856. @pytest.mark.integration
  1857. async def test_link_tag_returns_409_when_same_tag_on_different_spool(
  1858. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1859. ):
  1860. """Linking spool 99 to a tag that spool 42 already carries must return 409."""
  1861. # SAMPLE_SPOOLMAN_SPOOL (id=42) has extra.tag = '"AABBCCDDEEFF0011AABBCCDDEEFF0011"'.
  1862. # Attempting to assign the same tag to spool 99 must be rejected.
  1863. resp = await async_client.patch(
  1864. "/api/v1/spoolman/inventory/spools/99/tag",
  1865. json={"tray_uuid": "AABBCCDDEEFF0011AABBCCDDEEFF0011"}, # 32-char tray UUID
  1866. )
  1867. assert resp.status_code == 409
  1868. detail = resp.json()["detail"]
  1869. assert "42" in str(detail)
  1870. @pytest.mark.asyncio
  1871. @pytest.mark.integration
  1872. async def test_the_409_is_the_same_structured_detail_as_the_built_in_route(
  1873. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1874. ):
  1875. """#3110: one shape for both inventory modes, not two prose sentences.
  1876. The built-in route said "already linked to another active spool" and
  1877. named nobody; this one named the spool but only inside a sentence. A
  1878. client had to parse prose, and a different sentence per mode.
  1879. """
  1880. resp = await async_client.patch(
  1881. "/api/v1/spoolman/inventory/spools/99/tag",
  1882. json={"tray_uuid": "AABBCCDDEEFF0011AABBCCDDEEFF0011"},
  1883. )
  1884. assert resp.status_code == 409
  1885. detail = resp.json()["detail"]
  1886. assert detail["code"] == "tag_already_linked"
  1887. assert detail["spool_id"] == 42
  1888. assert detail["field"] == "tray_uuid"
  1889. @pytest.mark.asyncio
  1890. @pytest.mark.integration
  1891. async def test_the_field_follows_the_precedence_the_tag_itself_uses(
  1892. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1893. ):
  1894. """tray_uuid wins over tag_uid when both are sent, so `field` says so."""
  1895. mock_spoolman_client.get_all_spools.return_value = [
  1896. {**SAMPLE_SPOOLMAN_SPOOL, "id": 42, "extra": {"tag": '"AABBCCDDEEFF0011"'}}
  1897. ]
  1898. resp = await async_client.patch(
  1899. "/api/v1/spoolman/inventory/spools/99/tag",
  1900. json={"tag_uid": "AABBCCDDEEFF0011"},
  1901. )
  1902. assert resp.status_code == 409
  1903. assert resp.json()["detail"]["field"] == "tag_uid"
  1904. @pytest.mark.asyncio
  1905. @pytest.mark.integration
  1906. async def test_duplicate_holders_yield_the_lowest_id(
  1907. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1908. ):
  1909. """Spoolman has no unique constraint on extra.tag either.
  1910. Whichever row the scan reached first was an arbitrary answer; the
  1911. built-in route names the lowest id, so this one does too.
  1912. """
  1913. tag = '"AABBCCDDEEFF0011AABBCCDDEEFF0011"'
  1914. mock_spoolman_client.get_all_spools.return_value = [
  1915. {**SAMPLE_SPOOLMAN_SPOOL, "id": 77, "extra": {"tag": tag}},
  1916. {**SAMPLE_SPOOLMAN_SPOOL, "id": 42, "extra": {"tag": tag}},
  1917. ]
  1918. resp = await async_client.patch(
  1919. "/api/v1/spoolman/inventory/spools/99/tag",
  1920. json={"tray_uuid": "AABBCCDDEEFF0011AABBCCDDEEFF0011"},
  1921. )
  1922. assert resp.status_code == 409
  1923. assert resp.json()["detail"]["spool_id"] == 42
  1924. @pytest.mark.asyncio
  1925. @pytest.mark.integration
  1926. async def test_a_malformed_row_after_the_holder_does_not_sink_the_request(
  1927. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1928. ):
  1929. """extra is free-form and edited outside Bambuddy.
  1930. Naming the lowest id means reading every row, where the old loop
  1931. stopped at its first match -- so a row whose extra.tag is a JSON null
  1932. (which .get("tag", "") hands back as None, not the default) sits
  1933. between the caller and their 409 in a way it never used to.
  1934. """
  1935. tag = '"AABBCCDDEEFF0011AABBCCDDEEFF0011"'
  1936. mock_spoolman_client.get_all_spools.return_value = [
  1937. {**SAMPLE_SPOOLMAN_SPOOL, "id": 42, "extra": {"tag": tag}},
  1938. {**SAMPLE_SPOOLMAN_SPOOL, "id": 55, "extra": {"tag": None}},
  1939. {**SAMPLE_SPOOLMAN_SPOOL, "id": 56, "extra": {"tag": 12345}},
  1940. {**SAMPLE_SPOOLMAN_SPOOL, "id": 57, "extra": None},
  1941. {**SAMPLE_SPOOLMAN_SPOOL, "id": 58, "extra": []},
  1942. ]
  1943. resp = await async_client.patch(
  1944. "/api/v1/spoolman/inventory/spools/99/tag",
  1945. json={"tray_uuid": "AABBCCDDEEFF0011AABBCCDDEEFF0011"},
  1946. )
  1947. assert resp.status_code == 409
  1948. assert resp.json()["detail"]["spool_id"] == 42
  1949. @pytest.mark.asyncio
  1950. @pytest.mark.integration
  1951. async def test_a_malformed_row_is_not_itself_read_as_a_holder(
  1952. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1953. ):
  1954. """A link with no real conflict still succeeds past those rows."""
  1955. mock_spoolman_client.get_all_spools.return_value = [
  1956. {**SAMPLE_SPOOLMAN_SPOOL, "id": 55, "extra": {"tag": None}},
  1957. {**SAMPLE_SPOOLMAN_SPOOL, "id": 56, "extra": {"tag": 12345}},
  1958. {**SAMPLE_SPOOLMAN_SPOOL, "id": 57, "extra": None},
  1959. ]
  1960. resp = await async_client.patch(
  1961. "/api/v1/spoolman/inventory/spools/42/tag",
  1962. json={"tag_uid": "AABBCCDD112233"},
  1963. )
  1964. assert resp.status_code == 200
  1965. mock_spoolman_client.update_spool_full.assert_called_once()
  1966. class TestSpoolmanInventoryUpdateCoreWeight:
  1967. """core_weight is forwarded to Spoolman when sent — any value should be accepted."""
  1968. @pytest.mark.asyncio
  1969. @pytest.mark.integration
  1970. async def test_patch_core_weight_other_than_250_accepted(
  1971. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1972. ):
  1973. """PATCH with core_weight != 250 is accepted and carried through, not rejected."""
  1974. resp = await async_client.patch(
  1975. "/api/v1/spoolman/inventory/spools/42",
  1976. json={"core_weight": 100},
  1977. )
  1978. assert resp.status_code == 200
  1979. @pytest.mark.asyncio
  1980. @pytest.mark.integration
  1981. async def test_patch_core_weight_250_explicitly_is_accepted(
  1982. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1983. ):
  1984. """PATCH with core_weight=250 (the default) is valid and returns 200."""
  1985. resp = await async_client.patch(
  1986. "/api/v1/spoolman/inventory/spools/42",
  1987. json={"core_weight": 250},
  1988. )
  1989. assert resp.status_code == 200
  1990. @pytest.mark.asyncio
  1991. @pytest.mark.integration
  1992. async def test_patch_without_core_weight_is_accepted(
  1993. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1994. ):
  1995. """PATCH without core_weight (omitted) must not trigger the validator — returns 200."""
  1996. resp = await async_client.patch(
  1997. "/api/v1/spoolman/inventory/spools/42",
  1998. json={"note": "no core_weight key"},
  1999. )
  2000. assert resp.status_code == 200
  2001. class TestUnlinkSpool:
  2002. """POST /spoolman/spools/{id}/unlink clears Spoolman tag without re-entrant lock deadlock.
  2003. Spoolman PATCHes the extra dict by MERGING — popping a key + sending the
  2004. rest doesn't clear the popped key. The endpoint sends the JSON empty-string
  2005. sentinel ('""') which the read-side filters strip. (#1114)
  2006. The endpoint uses merge_spool_extra (not update_spool_full directly)
  2007. because (a) merge_spool_extra owns the per-spool extra_lock for atomic
  2008. read-modify-write semantics, and (b) wrapping it in another extra_lock
  2009. would deadlock — asyncio.Lock is not re-entrant.
  2010. """
  2011. @pytest.fixture
  2012. def mock_unlink_client(self):
  2013. """Mock Spoolman client for the spoolman.py (non-inventory) route."""
  2014. spool_with_tag = {
  2015. **SAMPLE_SPOOLMAN_SPOOL,
  2016. "extra": {"tag": '"AABBCCDDEEFF0011AABBCCDDEEFF0011"', "custom": "keep"},
  2017. }
  2018. mock_client = MagicMock()
  2019. mock_client.has_tag_api = AsyncMock(return_value=False)
  2020. mock_client.add_native_tags = AsyncMock(return_value=0)
  2021. mock_client.unlink_all_native_tags = AsyncMock()
  2022. mock_client.base_url = "http://localhost:7912"
  2023. mock_client.health_check = AsyncMock(return_value=True)
  2024. mock_client.get_spool = AsyncMock(return_value=spool_with_tag)
  2025. # merge_spool_extra returns the spool with the tag cleared (and custom
  2026. # preserved) — that's what the read-side will see after the fix.
  2027. mock_client.merge_spool_extra = AsyncMock(
  2028. return_value={**spool_with_tag, "extra": {"tag": '""', "custom": "keep"}}
  2029. )
  2030. with (
  2031. patch(
  2032. "backend.app.api.routes.spoolman.get_spoolman_client",
  2033. AsyncMock(return_value=mock_client),
  2034. ),
  2035. patch(
  2036. "backend.app.api.routes.spoolman.init_spoolman_client",
  2037. AsyncMock(return_value=mock_client),
  2038. ),
  2039. ):
  2040. yield mock_client
  2041. @pytest.mark.asyncio
  2042. @pytest.mark.integration
  2043. async def test_unlink_sets_tag_to_json_empty_string(
  2044. self,
  2045. async_client: AsyncClient,
  2046. spoolman_settings,
  2047. mock_unlink_client,
  2048. ):
  2049. """Unlink calls merge_spool_extra with the JSON-empty-string sentinel.
  2050. Pre-fix the endpoint did `cur_extra.pop("tag")` then PATCHed the rest.
  2051. Spoolman silently kept the previous tag because the key wasn't in the
  2052. payload (PATCH merges). Now the endpoint sends `{"tag": '""'}` and
  2053. the read-side .strip('"') resolves it to "" → spool drops out of
  2054. get_linked_spools.
  2055. """
  2056. import json as _json
  2057. resp = await async_client.post("/api/v1/spoolman/spools/42/unlink")
  2058. assert resp.status_code == 200
  2059. mock_unlink_client.merge_spool_extra.assert_called_once_with(42, {"tag": _json.dumps("")})
  2060. @pytest.mark.asyncio
  2061. @pytest.mark.integration
  2062. async def test_unlink_preserves_other_extra_keys(
  2063. self,
  2064. async_client: AsyncClient,
  2065. spoolman_settings,
  2066. mock_unlink_client,
  2067. ):
  2068. """Unrelated extra keys must survive unlink.
  2069. merge_spool_extra is responsible for the merge (read current → merge
  2070. new fields → PATCH). The unlink endpoint only sends `{"tag": ...}`,
  2071. so any other extra key on the spool is automatically preserved by
  2072. merge_spool_extra's read-merge-write semantics.
  2073. """
  2074. resp = await async_client.post("/api/v1/spoolman/spools/42/unlink")
  2075. assert resp.status_code == 200
  2076. # The endpoint passes only the tag key — merge_spool_extra does the
  2077. # rest. We don't assert anything about `custom` on the call args
  2078. # because the route doesn't see / pass it.
  2079. _, args, _ = mock_unlink_client.merge_spool_extra.mock_calls[0]
  2080. sent_fields = args[1] if len(args) >= 2 else {}
  2081. assert sent_fields == {"tag": '""'}, "unlink should only send the tag key — merge_spool_extra does the merge"
  2082. # ---------------------------------------------------------------------------
  2083. # B1: GET /spoolman/inventory/filaments
  2084. # B2: POST /spools with spoolman_filament_id bypasses find_or_create_filament
  2085. # ---------------------------------------------------------------------------
  2086. SAMPLE_FILAMENT_DICT = {
  2087. "id": 7,
  2088. "name": "PLA Basic",
  2089. "material": "PLA",
  2090. "color_hex": "FF0000",
  2091. "color_name": "Red",
  2092. "weight": 1000,
  2093. "spool_weight": 196,
  2094. "vendor": {"id": 3, "name": "Bambu Lab"},
  2095. }
  2096. class TestListSpoolmanFilaments:
  2097. """Tests for GET /api/v1/spoolman/inventory/filaments (B1)."""
  2098. @pytest.mark.asyncio
  2099. @pytest.mark.integration
  2100. async def test_list_filaments_disabled_returns_400(self, async_client: AsyncClient):
  2101. """Without Spoolman enabled the endpoint returns 400."""
  2102. resp = await async_client.get("/api/v1/spoolman/inventory/filaments")
  2103. assert resp.status_code == 400
  2104. @pytest.mark.asyncio
  2105. @pytest.mark.integration
  2106. async def test_list_filaments_unreachable_returns_503(self, async_client: AsyncClient, spoolman_settings):
  2107. """503 is returned when _get_client raises HTTPException(503)."""
  2108. with patch(
  2109. "backend.app.api.routes.spoolman_inventory._get_client",
  2110. AsyncMock(side_effect=HTTPException(status_code=503, detail="Spoolman server is not reachable")),
  2111. ):
  2112. resp = await async_client.get("/api/v1/spoolman/inventory/filaments")
  2113. assert resp.status_code == 503
  2114. @pytest.mark.asyncio
  2115. @pytest.mark.integration
  2116. async def test_list_filaments_success(self, async_client: AsyncClient, spoolman_settings):
  2117. """Success path returns normalised filament list including spool_weight."""
  2118. mock_client = MagicMock()
  2119. mock_client.get_filaments = AsyncMock(return_value=[SAMPLE_FILAMENT_DICT])
  2120. with patch(
  2121. "backend.app.api.routes.spoolman_inventory._get_client",
  2122. AsyncMock(return_value=mock_client),
  2123. ):
  2124. resp = await async_client.get("/api/v1/spoolman/inventory/filaments")
  2125. assert resp.status_code == 200
  2126. data = resp.json()
  2127. assert isinstance(data, list)
  2128. assert len(data) == 1
  2129. entry = data[0]
  2130. assert entry["id"] == 7
  2131. assert entry["material"] == "PLA"
  2132. assert entry["spool_weight"] == 196
  2133. assert entry["vendor"]["name"] == "Bambu Lab"
  2134. class TestCreateSpoolWithFilamentId:
  2135. """Tests for POST /api/v1/spoolman/inventory/spools with spoolman_filament_id (B2)."""
  2136. @pytest.mark.asyncio
  2137. @pytest.mark.integration
  2138. async def test_create_with_filament_id_skips_find_or_create(self, async_client: AsyncClient, spoolman_settings):
  2139. """When spoolman_filament_id is provided, find_or_create_filament must NOT be called."""
  2140. mock_client = MagicMock()
  2141. mock_client.has_tag_api = AsyncMock(return_value=False)
  2142. mock_client.add_native_tags = AsyncMock(return_value=0)
  2143. mock_client.unlink_all_native_tags = AsyncMock()
  2144. mock_client.find_or_create_filament = AsyncMock(return_value=7)
  2145. mock_client.create_spool = AsyncMock(return_value=SAMPLE_SPOOLMAN_SPOOL)
  2146. mock_client.update_spool_full = AsyncMock(return_value=SAMPLE_SPOOLMAN_SPOOL)
  2147. with patch(
  2148. "backend.app.api.routes.spoolman_inventory._get_client",
  2149. AsyncMock(return_value=mock_client),
  2150. ):
  2151. resp = await async_client.post(
  2152. "/api/v1/spoolman/inventory/spools",
  2153. json={"spoolman_filament_id": 7},
  2154. )
  2155. assert resp.status_code == 200
  2156. mock_client.find_or_create_filament.assert_not_called()
  2157. mock_client.create_spool.assert_called_once()
  2158. _, kwargs = mock_client.create_spool.call_args
  2159. assert kwargs.get("filament_id") == 7
  2160. @pytest.mark.asyncio
  2161. @pytest.mark.integration
  2162. async def test_create_with_invalid_filament_id_returns_404(self, async_client: AsyncClient, spoolman_settings):
  2163. """An invalid spoolman_filament_id (not in Spoolman) must return 404."""
  2164. from backend.app.services.spoolman import SpoolmanNotFoundError
  2165. mock_client = MagicMock()
  2166. mock_client.has_tag_api = AsyncMock(return_value=False)
  2167. mock_client.add_native_tags = AsyncMock(return_value=0)
  2168. mock_client.unlink_all_native_tags = AsyncMock()
  2169. mock_client.create_spool = AsyncMock(side_effect=SpoolmanNotFoundError("filament not found"))
  2170. with patch(
  2171. "backend.app.api.routes.spoolman_inventory._get_client",
  2172. AsyncMock(return_value=mock_client),
  2173. ):
  2174. resp = await async_client.post(
  2175. "/api/v1/spoolman/inventory/spools",
  2176. json={"spoolman_filament_id": 9999},
  2177. )
  2178. assert resp.status_code == 404
  2179. assert "9999" in resp.json()["detail"]
  2180. # ---------------------------------------------------------------------------
  2181. # WICHTIG-12: Additional edge-case tests
  2182. # ---------------------------------------------------------------------------
  2183. class TestBulkCreateWithFilamentId:
  2184. """Bulk create with spoolman_filament_id skips find_or_create_filament."""
  2185. @pytest.mark.asyncio
  2186. @pytest.mark.integration
  2187. async def test_bulk_create_with_filament_id_skips_find_or_create(
  2188. self, async_client: AsyncClient, spoolman_settings
  2189. ):
  2190. """Bulk POST with spoolman_filament_id must NOT call find_or_create_filament."""
  2191. mock_client = MagicMock()
  2192. mock_client.has_tag_api = AsyncMock(return_value=False)
  2193. mock_client.add_native_tags = AsyncMock(return_value=0)
  2194. mock_client.unlink_all_native_tags = AsyncMock()
  2195. mock_client.find_or_create_filament = AsyncMock(return_value=7)
  2196. mock_client.create_spool = AsyncMock(return_value=SAMPLE_SPOOLMAN_SPOOL)
  2197. mock_client.update_spool_full = AsyncMock(return_value=SAMPLE_SPOOLMAN_SPOOL)
  2198. with patch(
  2199. "backend.app.api.routes.spoolman_inventory._get_client",
  2200. AsyncMock(return_value=mock_client),
  2201. ):
  2202. resp = await async_client.post(
  2203. "/api/v1/spoolman/inventory/spools/bulk",
  2204. json={"spool": {"spoolman_filament_id": 7}, "quantity": 2},
  2205. )
  2206. assert resp.status_code == 200
  2207. mock_client.find_or_create_filament.assert_not_called()
  2208. assert mock_client.create_spool.call_count == 2
  2209. for call in mock_client.create_spool.call_args_list:
  2210. _, kwargs = call
  2211. assert kwargs.get("filament_id") == 7
  2212. class TestCreateSpoolValidation:
  2213. """Validation edge cases for SpoolmanInventoryCreate."""
  2214. @pytest.mark.asyncio
  2215. @pytest.mark.integration
  2216. async def test_create_spool_filament_id_zero_returns_422(self, async_client: AsyncClient, spoolman_settings):
  2217. """spoolman_filament_id=0 must fail Field(gt=0) validation → 422."""
  2218. resp = await async_client.post(
  2219. "/api/v1/spoolman/inventory/spools",
  2220. json={"spoolman_filament_id": 0},
  2221. )
  2222. assert resp.status_code == 422
  2223. @pytest.mark.asyncio
  2224. @pytest.mark.integration
  2225. async def test_create_spool_without_material_or_filament_id_returns_422(
  2226. self, async_client: AsyncClient, spoolman_settings
  2227. ):
  2228. """Neither material nor spoolman_filament_id → model_validator must reject → 422."""
  2229. resp = await async_client.post(
  2230. "/api/v1/spoolman/inventory/spools",
  2231. json={"label_weight": 1000},
  2232. )
  2233. assert resp.status_code == 422
  2234. class TestNormalizeFilament:
  2235. """Unit-style tests for _normalize_filament helper (imported directly)."""
  2236. def test_normalize_filament_null_vendor(self):
  2237. from backend.app.api.routes.spoolman_inventory import _normalize_filament
  2238. result = _normalize_filament({"id": 5, "name": "PLA", "vendor": None})
  2239. assert result is not None
  2240. assert result["vendor"] is None
  2241. def test_normalize_filament_null_id_returns_none(self):
  2242. from backend.app.api.routes.spoolman_inventory import _normalize_filament
  2243. result = _normalize_filament({"id": None, "name": "PLA"})
  2244. assert result is None
  2245. def test_normalize_filament_zero_id_returns_none(self):
  2246. from backend.app.api.routes.spoolman_inventory import _normalize_filament
  2247. result = _normalize_filament({"id": 0, "name": "PLA"})
  2248. assert result is None
  2249. # ---------------------------------------------------------------------------
  2250. # F1: TestTranslateSpoolmanErrors — 502/404/503 paths through _translate_spoolman_errors
  2251. # ---------------------------------------------------------------------------
  2252. class TestTranslateSpoolmanErrors:
  2253. """F1: _translate_spoolman_errors() maps Spoolman exceptions to HTTP codes."""
  2254. @pytest.mark.asyncio
  2255. @pytest.mark.integration
  2256. async def test_spoolman_not_found_returns_404(
  2257. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2258. ):
  2259. """SpoolmanNotFoundError from get_spool → 404."""
  2260. from backend.app.services.spoolman import SpoolmanNotFoundError
  2261. mock_spoolman_client.get_spool.side_effect = SpoolmanNotFoundError("spool 999 not found")
  2262. resp = await async_client.get("/api/v1/spoolman/inventory/spools/999")
  2263. assert resp.status_code == 404
  2264. @pytest.mark.asyncio
  2265. @pytest.mark.integration
  2266. async def test_spoolman_unavailable_returns_503(
  2267. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2268. ):
  2269. """SpoolmanUnavailableError from get_spool → 503."""
  2270. from backend.app.services.spoolman import SpoolmanUnavailableError
  2271. mock_spoolman_client.get_spool.side_effect = SpoolmanUnavailableError("network error")
  2272. resp = await async_client.get("/api/v1/spoolman/inventory/spools/42")
  2273. assert resp.status_code == 503
  2274. @pytest.mark.asyncio
  2275. @pytest.mark.integration
  2276. async def test_spoolman_client_error_returns_502_with_upstream_status(
  2277. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2278. ):
  2279. """SpoolmanClientError from get_spool → 502 with upstream_status in body."""
  2280. from backend.app.services.spoolman import SpoolmanClientError
  2281. mock_spoolman_client.get_spool.side_effect = SpoolmanClientError("Spoolman rejected", 422, "filament not found")
  2282. resp = await async_client.get("/api/v1/spoolman/inventory/spools/42")
  2283. assert resp.status_code == 502
  2284. body = resp.json()
  2285. assert body["detail"]["upstream_status"] == 422
  2286. assert body["detail"]["upstream_body"] == "filament not found"
  2287. # ---------------------------------------------------------------------------
  2288. # F2: _get_client health_check returns False → 503
  2289. # ---------------------------------------------------------------------------
  2290. class TestGetClientHealthCheckFalse:
  2291. """F2: _get_client raises 503 when health_check() returns False."""
  2292. @pytest.mark.asyncio
  2293. @pytest.mark.integration
  2294. async def test_returns_503_when_health_check_returns_false(
  2295. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2296. ):
  2297. """health_check() → False should produce 503 on any inventory call."""
  2298. import time
  2299. import backend.app.api.routes.spoolman_inventory as inv_module
  2300. mock_spoolman_client.health_check = AsyncMock(return_value=False)
  2301. # Clear the TTL cache so health_check is actually called
  2302. inv_module._health_check_cache.clear()
  2303. resp = await async_client.get("/api/v1/spoolman/inventory/spools")
  2304. assert resp.status_code == 503
  2305. # ---------------------------------------------------------------------------
  2306. # F3: SpoolTagLinkRequest both fields null → 422
  2307. # ---------------------------------------------------------------------------
  2308. class TestSpoolTagLinkBothNull:
  2309. """F3: /spools/{id}/tag with both tag_uid and tray_uuid null → 422."""
  2310. @pytest.mark.asyncio
  2311. @pytest.mark.integration
  2312. async def test_both_null_returns_422(self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client):
  2313. """Sending {} (both fields absent) → at_least_one validator → 422."""
  2314. resp = await async_client.patch(
  2315. "/api/v1/spoolman/inventory/spools/42/tag",
  2316. json={},
  2317. )
  2318. assert resp.status_code == 422
  2319. @pytest.mark.asyncio
  2320. @pytest.mark.integration
  2321. async def test_both_explicitly_null_returns_422(
  2322. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2323. ):
  2324. """Sending {tag_uid: null, tray_uuid: null} → at_least_one validator → 422."""
  2325. resp = await async_client.patch(
  2326. "/api/v1/spoolman/inventory/spools/42/tag",
  2327. json={"tag_uid": None, "tray_uuid": None},
  2328. )
  2329. assert resp.status_code == 422
  2330. # ---------------------------------------------------------------------------
  2331. # F5: RBAC lists — missing endpoints
  2332. # ---------------------------------------------------------------------------
  2333. class TestSpoolmanInventoryAuthExtended:
  2334. """F5: Additional endpoints in RBAC auth/403 parametrize lists."""
  2335. @pytest.fixture
  2336. async def auth_and_spoolman_settings(self, db_session):
  2337. from backend.app.models.settings import Settings
  2338. db_session.add(Settings(key="spoolman_enabled", value="true"))
  2339. db_session.add(Settings(key="spoolman_url", value="http://localhost:7912"))
  2340. db_session.add(Settings(key="auth_enabled", value="true"))
  2341. await db_session.commit()
  2342. @pytest.mark.asyncio
  2343. @pytest.mark.integration
  2344. @pytest.mark.parametrize(
  2345. "method,path,payload",
  2346. [
  2347. ("PATCH", "/api/v1/spoolman/inventory/spools/42/tag", {"tag_uid": "AABBCCDDEE112233"}),
  2348. ("POST", "/api/v1/spoolman/inventory/sync-ams-weights", {"printer_id": 1, "ams_data": []}),
  2349. ("PATCH", "/api/v1/spoolman/inventory/filaments/7", {"spool_weight": 196.0}),
  2350. ],
  2351. )
  2352. async def test_extended_write_endpoints_require_auth(
  2353. self,
  2354. async_client: AsyncClient,
  2355. auth_and_spoolman_settings,
  2356. method: str,
  2357. path: str,
  2358. payload: dict | None,
  2359. ):
  2360. """Additional write endpoints return 401 when auth is enabled and no token is provided."""
  2361. resp = await async_client.request(method, path, json=payload)
  2362. assert resp.status_code == 401, f"{method} {path} should require auth but got {resp.status_code}: {resp.json()}"
  2363. @pytest.mark.asyncio
  2364. @pytest.mark.integration
  2365. @pytest.mark.parametrize(
  2366. "method,path",
  2367. [
  2368. ("GET", "/api/v1/spoolman/inventory/filaments"),
  2369. ],
  2370. )
  2371. async def test_extended_read_endpoints_require_auth(
  2372. self,
  2373. async_client: AsyncClient,
  2374. auth_and_spoolman_settings,
  2375. method: str,
  2376. path: str,
  2377. ):
  2378. """Additional read endpoints return 401 when auth is enabled and no token is provided."""
  2379. resp = await async_client.request(method, path)
  2380. assert resp.status_code == 401, f"{method} {path} should require auth but got {resp.status_code}: {resp.json()}"
  2381. # ---------------------------------------------------------------------------
  2382. # F8: _normalize_filament negative ID returns None
  2383. # ---------------------------------------------------------------------------
  2384. class TestNormalizeFilamentNegativeId:
  2385. """F8: _normalize_filament with negative id → None (was only checking == 0)."""
  2386. def test_normalize_filament_negative_id_returns_none(self):
  2387. from backend.app.api.routes.spoolman_inventory import _normalize_filament
  2388. result = _normalize_filament({"id": -1, "name": "PLA"})
  2389. assert result is None
  2390. def test_normalize_filament_large_negative_id_returns_none(self):
  2391. from backend.app.api.routes.spoolman_inventory import _normalize_filament
  2392. result = _normalize_filament({"id": -999, "name": "PLA"})
  2393. assert result is None
  2394. # ---------------------------------------------------------------------------
  2395. # F9: weight_used > label_weight cross-field validator integration test
  2396. # ---------------------------------------------------------------------------
  2397. class TestCreateSpoolWeightValidation:
  2398. """F9: SpoolmanInventoryCreate.validate_weight_consistency cross-field validator."""
  2399. @pytest.mark.asyncio
  2400. @pytest.mark.integration
  2401. async def test_weight_used_exceeds_label_weight_returns_422(self, async_client: AsyncClient, spoolman_settings):
  2402. """weight_used > label_weight → cross-field validator → 422."""
  2403. resp = await async_client.post(
  2404. "/api/v1/spoolman/inventory/spools",
  2405. json={"material": "PLA", "label_weight": 500, "weight_used": 600},
  2406. )
  2407. assert resp.status_code == 422
  2408. @pytest.mark.asyncio
  2409. @pytest.mark.integration
  2410. async def test_weight_used_equals_label_weight_accepted(
  2411. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2412. ):
  2413. """weight_used == label_weight is exactly at the boundary → should pass (201)."""
  2414. resp = await async_client.post(
  2415. "/api/v1/spoolman/inventory/spools",
  2416. json={"material": "PLA", "label_weight": 1000, "weight_used": 1000},
  2417. )
  2418. # 201 or 200 (spool created)
  2419. assert resp.status_code in (200, 201)
  2420. @pytest.mark.asyncio
  2421. @pytest.mark.integration
  2422. async def test_create_spool_with_non_default_core_weight_accepted(
  2423. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2424. ):
  2425. """A3: core_weight != 250 is accepted and reaches Spoolman → 201."""
  2426. resp = await async_client.post(
  2427. "/api/v1/spoolman/inventory/spools",
  2428. json={"material": "PLA", "label_weight": 1000, "weight_used": 0, "core_weight": 196},
  2429. )
  2430. assert resp.status_code in (200, 201)
  2431. @pytest.mark.asyncio
  2432. @pytest.mark.integration
  2433. async def test_update_spool_with_non_default_core_weight_accepted(
  2434. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2435. ):
  2436. """A3: PATCH with core_weight != 250 must no longer return 422."""
  2437. resp = await async_client.patch(
  2438. "/api/v1/spoolman/inventory/spools/42",
  2439. json={"core_weight": 300},
  2440. )
  2441. assert resp.status_code == 200
  2442. # ---------------------------------------------------------------------------
  2443. # P8-T1: /slot-assignments/all enriches with printer_name + ams_label
  2444. # ---------------------------------------------------------------------------
  2445. class TestGetAllSlotAssignmentsEnriched:
  2446. """P8-T1: /slot-assignments/all enriches with printer_name + ams_label.
  2447. Regression for InventoryPage LOCATION column showing '-' for Spoolman
  2448. spools because the endpoint only returned 4 raw fields without the
  2449. printer_name + ams_label needed by the UI.
  2450. """
  2451. @pytest.mark.asyncio
  2452. @pytest.mark.integration
  2453. async def test_returns_printer_name_for_existing_printer(
  2454. self, async_client: AsyncClient, db_session, spoolman_settings
  2455. ):
  2456. """printer_name is enriched from the joined Printer relationship."""
  2457. from backend.app.models.printer import Printer
  2458. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2459. db_session.add(
  2460. Printer(
  2461. id=1,
  2462. name="Sully",
  2463. model="X1C",
  2464. serial_number="SN1",
  2465. ip_address="1.2.3.4",
  2466. access_code="",
  2467. )
  2468. )
  2469. db_session.add(
  2470. SpoolmanSlotAssignment(
  2471. printer_id=1,
  2472. ams_id=0,
  2473. tray_id=2,
  2474. spoolman_spool_id=216,
  2475. )
  2476. )
  2477. await db_session.commit()
  2478. with patch("backend.app.api.routes.spoolman_inventory.printer_manager") as mock_pm:
  2479. mock_pm.get_all_statuses.return_value = {}
  2480. resp = await async_client.get("/api/v1/spoolman/inventory/slot-assignments/all")
  2481. assert resp.status_code == 200
  2482. data = resp.json()
  2483. assert len(data) == 1
  2484. assert data[0]["printer_name"] == "Sully"
  2485. assert data[0]["spoolman_spool_id"] == 216
  2486. assert data[0]["ams_id"] == 0
  2487. assert data[0]["tray_id"] == 2
  2488. assert data[0]["ams_label"] is None
  2489. @pytest.mark.asyncio
  2490. @pytest.mark.integration
  2491. async def test_returns_ams_label_when_label_configured(
  2492. self, async_client: AsyncClient, db_session, spoolman_settings
  2493. ):
  2494. """ams_label is enriched from AmsLabel via printer MQTT serial map."""
  2495. from backend.app.models.ams_label import AmsLabel
  2496. from backend.app.models.printer import Printer
  2497. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2498. db_session.add(
  2499. Printer(
  2500. id=1,
  2501. name="Sully",
  2502. model="X1C",
  2503. serial_number="SN1",
  2504. ip_address="1.2.3.4",
  2505. access_code="",
  2506. )
  2507. )
  2508. db_session.add(AmsLabel(ams_serial_number="ABC123", label="Top Shelf"))
  2509. db_session.add(
  2510. SpoolmanSlotAssignment(
  2511. printer_id=1,
  2512. ams_id=0,
  2513. tray_id=2,
  2514. spoolman_spool_id=216,
  2515. )
  2516. )
  2517. await db_session.commit()
  2518. mock_state = MagicMock(raw_data={"ams": [{"id": 0, "sn": "ABC123"}]})
  2519. with patch("backend.app.api.routes.spoolman_inventory.printer_manager") as mock_pm:
  2520. mock_pm.get_all_statuses.return_value = {1: mock_state}
  2521. resp = await async_client.get("/api/v1/spoolman/inventory/slot-assignments/all")
  2522. assert resp.status_code == 200
  2523. assert resp.json()[0]["ams_label"] == "Top Shelf"
  2524. @pytest.mark.asyncio
  2525. @pytest.mark.integration
  2526. async def test_synthetic_ams_label_fallback(self, async_client: AsyncClient, db_session, spoolman_settings):
  2527. """Falls back to synthetic 'p{pid}a{ams_id}' key when no MQTT serial available."""
  2528. from backend.app.models.ams_label import AmsLabel
  2529. from backend.app.models.printer import Printer
  2530. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2531. db_session.add(
  2532. Printer(
  2533. id=1,
  2534. name="Sully",
  2535. model="X1C",
  2536. serial_number="SN1",
  2537. ip_address="1.2.3.4",
  2538. access_code="",
  2539. )
  2540. )
  2541. db_session.add(AmsLabel(ams_serial_number="p1a0", label="Synthetic Label"))
  2542. db_session.add(
  2543. SpoolmanSlotAssignment(
  2544. printer_id=1,
  2545. ams_id=0,
  2546. tray_id=2,
  2547. spoolman_spool_id=216,
  2548. )
  2549. )
  2550. await db_session.commit()
  2551. with patch("backend.app.api.routes.spoolman_inventory.printer_manager") as mock_pm:
  2552. mock_pm.get_all_statuses.return_value = {} # No live state -> synthetic key
  2553. resp = await async_client.get("/api/v1/spoolman/inventory/slot-assignments/all")
  2554. assert resp.json()[0]["ams_label"] == "Synthetic Label"
  2555. @pytest.mark.asyncio
  2556. @pytest.mark.integration
  2557. async def test_filter_by_printer_id_still_works(self, async_client: AsyncClient, db_session, spoolman_settings):
  2558. """Regression: ?printer_id=N still filters and enriches."""
  2559. from backend.app.models.printer import Printer
  2560. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2561. for pid in (1, 2):
  2562. db_session.add(
  2563. Printer(
  2564. id=pid,
  2565. name=f"P{pid}",
  2566. model="X1C",
  2567. serial_number=f"SN{pid}",
  2568. ip_address=f"1.2.3.{pid}",
  2569. access_code="",
  2570. )
  2571. )
  2572. db_session.add(
  2573. SpoolmanSlotAssignment(
  2574. printer_id=pid,
  2575. ams_id=0,
  2576. tray_id=0,
  2577. spoolman_spool_id=200 + pid,
  2578. )
  2579. )
  2580. await db_session.commit()
  2581. with patch("backend.app.api.routes.spoolman_inventory.printer_manager") as mock_pm:
  2582. mock_pm.get_all_statuses.return_value = {}
  2583. resp = await async_client.get("/api/v1/spoolman/inventory/slot-assignments/all?printer_id=1")
  2584. data = resp.json()
  2585. assert len(data) == 1
  2586. assert data[0]["printer_id"] == 1
  2587. assert data[0]["printer_name"] == "P1"
  2588. assert data[0]["spoolman_spool_id"] == 201
  2589. class TestPerSpoolCoreWeight:
  2590. """The per-spool tare reaches Spoolman now (#2908).
  2591. `core_weight` was declared on both write schemas and dropped after
  2592. validation, with a comment saying so. The read path never showed it: it
  2593. derives the value from ``spool.spool_weight ?? filament.spool_weight ?? 250``
  2594. (_spoolman_helpers.py), so an edit that went nowhere came back as the
  2595. inherited value and looked like it had simply not changed.
  2596. It is not cosmetic, because the same resolution is the tare the weigh
  2597. endpoint subtracts. A spool whose real empty weight differs from its
  2598. filament's produced a wrong remaining weight on every weigh-in -- 70 g for
  2599. the reporter's third-party spools against Bambu's 250 g reusable ones.
  2600. Spoolman already has the field and already gives it priority. Only the
  2601. write was missing.
  2602. """
  2603. @pytest.mark.asyncio
  2604. @pytest.mark.integration
  2605. async def test_an_edited_tare_is_written_to_the_spools_own_field(
  2606. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2607. ):
  2608. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json={"core_weight": 180})
  2609. assert response.status_code == 200
  2610. assert mock_spoolman_client.update_spool_full.call_args.kwargs["spool_weight"] == 180
  2611. @pytest.mark.asyncio
  2612. @pytest.mark.integration
  2613. async def test_an_edit_that_does_not_mention_the_tare_leaves_it_inheriting(
  2614. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2615. ):
  2616. """The reason this keys off model_fields_set rather than the value.
  2617. `core_weight` carries a default, so a PATCH that never mentions it still
  2618. arrives at the handler holding one. Writing that would stamp an explicit
  2619. tare on every spool the user edits for any reason, silently detaching it
  2620. from its filament -- a worse bug than the one being fixed, and an
  2621. invisible one, since the number displayed would not change.
  2622. """
  2623. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json={"note": "just a note"})
  2624. assert response.status_code == 200
  2625. assert mock_spoolman_client.update_spool_full.call_args.kwargs["spool_weight"] is None
  2626. @pytest.mark.asyncio
  2627. @pytest.mark.integration
  2628. async def test_a_tare_given_at_creation_is_written(
  2629. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2630. ):
  2631. response = await async_client.post(
  2632. "/api/v1/spoolman/inventory/spools",
  2633. json={"material": "PLA", "label_weight": 1000, "core_weight": 180},
  2634. )
  2635. assert response.status_code == 200
  2636. assert mock_spoolman_client.create_spool.call_args.kwargs["spool_weight"] == 180
  2637. @pytest.mark.asyncio
  2638. @pytest.mark.integration
  2639. async def test_a_creation_that_omits_the_tare_leaves_the_spool_inheriting(
  2640. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2641. ):
  2642. """Same defaulting hazard as the update, and the commoner path: the
  2643. form posts without a tare far more often than with one."""
  2644. response = await async_client.post(
  2645. "/api/v1/spoolman/inventory/spools",
  2646. json={"material": "PLA", "label_weight": 1000},
  2647. )
  2648. assert response.status_code == 200
  2649. assert mock_spoolman_client.create_spool.call_args.kwargs["spool_weight"] is None
  2650. @pytest.mark.asyncio
  2651. @pytest.mark.integration
  2652. async def test_bulk_creation_persists_the_tare_on_every_spool(
  2653. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2654. ):
  2655. """Bulk create takes the same schema, so it dropped the field the same way."""
  2656. response = await async_client.post(
  2657. "/api/v1/spoolman/inventory/spools/bulk",
  2658. json={"spool": {"material": "PLA", "label_weight": 1000, "core_weight": 180}, "quantity": 3},
  2659. )
  2660. assert response.status_code in (200, 201)
  2661. assert mock_spoolman_client.create_spool.await_count == 3
  2662. assert all(c.kwargs["spool_weight"] == 180 for c in mock_spoolman_client.create_spool.await_args_list)
  2663. @pytest.mark.asyncio
  2664. @pytest.mark.integration
  2665. async def test_a_zero_tare_is_a_value_not_an_absence(
  2666. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2667. ):
  2668. """0 g is a real answer -- a coil with no spool -- and the schema allows
  2669. it (``ge=0``). Guarding the write on truthiness rather than ``is not
  2670. None`` would silently turn it into "inherit", which resolves to 250."""
  2671. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json={"core_weight": 0})
  2672. assert response.status_code == 200
  2673. assert mock_spoolman_client.update_spool_full.call_args.kwargs["spool_weight"] == 0
  2674. @pytest.mark.asyncio
  2675. @pytest.mark.integration
  2676. async def test_the_written_tare_is_the_one_the_weigh_endpoint_subtracts(
  2677. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2678. ):
  2679. """What the fix is actually for.
  2680. The weigh endpoint resolves the tare exactly as the read path does, so
  2681. once the per-spool value is stored it is the number a measured gross
  2682. weight is reduced by. With a 180 g spool inheriting the filament's 250 g
  2683. this same weigh-in would have recorded 550 g remaining instead of 620 --
  2684. the 70 g error from the report, on every weigh-in.
  2685. """
  2686. mock_spoolman_client.get_spool.return_value = {
  2687. **SAMPLE_SPOOLMAN_SPOOL,
  2688. "spool_weight": 180.0,
  2689. }
  2690. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42/weight", json={"weight_grams": 800.0})
  2691. assert response.status_code == 200
  2692. assert mock_spoolman_client.update_spool_full.call_args.kwargs["remaining_weight"] == 620.0
  2693. class TestSpoolmanLastDried:
  2694. """#2863 — a drying date set by hand round-trips through spool.extra."""
  2695. @pytest.mark.asyncio
  2696. @pytest.mark.integration
  2697. async def test_hand_set_date_writes_utc_and_clears_temperature_and_hours(
  2698. self,
  2699. async_client: AsyncClient,
  2700. spoolman_settings,
  2701. mock_spoolman_client,
  2702. ):
  2703. response = await async_client.patch(
  2704. "/api/v1/spoolman/inventory/spools/42", json={"last_dried_at": "2026-10-06T14:30:00+02:00"}
  2705. )
  2706. assert response.status_code == 200
  2707. mock_spoolman_client.merge_spool_extra.assert_called_once_with(
  2708. 42,
  2709. {
  2710. "bambu_last_dried_at": json.dumps("2026-10-06T12:30:00"),
  2711. "bambu_last_dried_temp": json.dumps(""),
  2712. "bambu_last_dried_hours": json.dumps(""),
  2713. },
  2714. )
  2715. @pytest.mark.asyncio
  2716. @pytest.mark.integration
  2717. async def test_null_clears_the_date(
  2718. self,
  2719. async_client: AsyncClient,
  2720. spoolman_settings,
  2721. mock_spoolman_client,
  2722. ):
  2723. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json={"last_dried_at": None})
  2724. assert response.status_code == 200
  2725. fields = mock_spoolman_client.merge_spool_extra.call_args.args[1]
  2726. assert fields["bambu_last_dried_at"] == json.dumps("")