test_spoolman_inventory_api.py 125 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131
  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 never builds a client for unsafe URLs on
  1597. the SpoolBuddy NFC path. Spoolman is still the mode, so the scan reports it
  1598. as unavailable rather than looking the tag up in the built-in inventory."""
  1599. from backend.app.models.settings import Settings
  1600. db_session.add(Settings(key="spoolman_enabled", value="true"))
  1601. db_session.add(Settings(key="spoolman_url", value=evil_url))
  1602. await db_session.commit()
  1603. from unittest.mock import AsyncMock, patch
  1604. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  1605. mock_ws.broadcast = AsyncMock()
  1606. resp = await async_client.post(
  1607. "/api/v1/spoolbuddy/nfc/tag-scanned",
  1608. json={"device_id": "sb-ssrf", "tag_uid": "AABBCCDD"},
  1609. )
  1610. # Must not crash or proxy the SSRF URL
  1611. assert resp.status_code == 200
  1612. assert resp.json()["matched"] is False
  1613. sent = {call.args[0]["type"] for call in mock_ws.broadcast.call_args_list}
  1614. assert "spoolman_unavailable" in sent
  1615. assert sent <= {"spoolman_unavailable", "spoolman_ssrf_blocked"}
  1616. @pytest.mark.asyncio
  1617. @pytest.mark.integration
  1618. @pytest.mark.parametrize(
  1619. "evil_url",
  1620. [
  1621. "http://169.254.169.254/latest/meta-data/", # AWS IMDS
  1622. "http://[::ffff:169.254.169.254]/", # IPv4-mapped IMDS bypass
  1623. ],
  1624. )
  1625. async def test_nfc_write_result_with_ssrf_url_degrades_gracefully(
  1626. self,
  1627. async_client: AsyncClient,
  1628. db_session,
  1629. evil_url: str,
  1630. ):
  1631. """SSRF: write-result with unsafe Spoolman URL must not proxy to the evil host.
  1632. write-result calls Spoolman to write-back the tag UID when data_origin='spoolman'.
  1633. With an SSRF URL, _get_spoolman_client_or_none returns None so the call is skipped
  1634. and the route returns 502 (tag written but link not persisted — not a server crash).
  1635. """
  1636. import json as _json
  1637. from backend.app.models.settings import Settings
  1638. from backend.app.models.spoolbuddy_device import SpoolBuddyDevice
  1639. db_session.add(Settings(key="spoolman_enabled", value="true"))
  1640. db_session.add(Settings(key="spoolman_url", value=evil_url))
  1641. # Register the device so the route doesn't 404 before reaching the SSRF guard.
  1642. db_session.add(
  1643. SpoolBuddyDevice(
  1644. device_id="sb-ssrf-wr",
  1645. hostname="sb-ssrf-wr.local",
  1646. ip_address="127.0.0.1",
  1647. pending_command="write_tag",
  1648. pending_write_payload=_json.dumps({"spool_id": 99, "ndef_data_hex": "DEAD", "data_origin": "spoolman"}),
  1649. )
  1650. )
  1651. await db_session.commit()
  1652. from unittest.mock import AsyncMock, patch
  1653. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  1654. mock_ws.broadcast = AsyncMock()
  1655. resp = await async_client.post(
  1656. "/api/v1/spoolbuddy/nfc/write-result",
  1657. json={
  1658. "device_id": "sb-ssrf-wr",
  1659. "spool_id": 99,
  1660. "tag_uid": "AABBCCDD",
  1661. "success": True,
  1662. },
  1663. )
  1664. # 502 = tag written to NFC but Spoolman link not persisted (SSRF guard blocked it).
  1665. # Must not be 500 (crash) and must not have proxied to the evil host.
  1666. assert resp.status_code == 502
  1667. @pytest.mark.asyncio
  1668. @pytest.mark.integration
  1669. @pytest.mark.parametrize(
  1670. "evil_url",
  1671. [
  1672. "http://169.254.169.254/latest/meta-data/", # AWS IMDS
  1673. ],
  1674. )
  1675. async def test_scale_update_weight_with_ssrf_url_degrades_gracefully(
  1676. self,
  1677. async_client: AsyncClient,
  1678. db_session,
  1679. evil_url: str,
  1680. ):
  1681. """SSRF: scale weight update with unsafe Spoolman URL must not proxy to the evil host."""
  1682. from backend.app.models.settings import Settings
  1683. db_session.add(Settings(key="spoolman_enabled", value="true"))
  1684. db_session.add(Settings(key="spoolman_url", value=evil_url))
  1685. await db_session.commit()
  1686. from unittest.mock import AsyncMock, patch
  1687. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  1688. mock_ws.broadcast = AsyncMock()
  1689. resp = await async_client.post(
  1690. "/api/v1/spoolbuddy/scale/update-spool-weight",
  1691. json={"device_id": "sb-ssrf-scale", "spool_id": 1, "weight_grams": 500.0},
  1692. )
  1693. # Must not crash or proxy to an SSRF host; Spoolman is unavailable, and the
  1694. # built-in inventory is not written instead.
  1695. assert resp.status_code == 503
  1696. class TestMergeSpoolExtraPreservesKeys:
  1697. """Unit-level test for merge_spool_extra key preservation (via mocked Spoolman)."""
  1698. @pytest.mark.asyncio
  1699. @pytest.mark.integration
  1700. async def test_merge_preserves_unrelated_extra_keys(
  1701. self,
  1702. async_client: AsyncClient,
  1703. spoolman_settings,
  1704. mock_spoolman_client,
  1705. ):
  1706. """merge_spool_extra must deep-merge rather than overwrite the extra dict.
  1707. Seed extra={"custom_key": "keep_me", "tag": "old"}.
  1708. After merging {"tag": "new"}, the PATCH payload must still contain custom_key.
  1709. """
  1710. from unittest.mock import AsyncMock, patch
  1711. existing_spool = {
  1712. **SAMPLE_SPOOLMAN_SPOOL,
  1713. "extra": {"custom_key": "keep_me", "tag": '"old"'},
  1714. }
  1715. updated_spool = {**existing_spool, "extra": {"custom_key": "keep_me", "tag": '"new"'}}
  1716. mock_client = mock_spoolman_client
  1717. mock_client.get_spool = AsyncMock(return_value=existing_spool)
  1718. mock_client.update_spool_full = AsyncMock(return_value=updated_spool)
  1719. # Call merge_spool_extra directly through the service
  1720. from backend.app.services.spoolman import SpoolmanClient
  1721. client = SpoolmanClient.__new__(SpoolmanClient)
  1722. client.base_url = "http://localhost:7912"
  1723. client.api_url = "http://localhost:7912/api/v1"
  1724. client._extra_locks = {}
  1725. async def _mock_get(spool_id):
  1726. return existing_spool
  1727. async def _mock_update(spool_id, **kwargs):
  1728. # Capture what was actually sent
  1729. _mock_update.captured_extra = kwargs.get("extra")
  1730. return updated_spool
  1731. _mock_update.captured_extra = None
  1732. client.get_spool = _mock_get
  1733. client.update_spool_full = _mock_update
  1734. result = await client.merge_spool_extra(42, {"tag": '"new"'})
  1735. # The merged extra must include the unrelated key
  1736. assert _mock_update.captured_extra is not None
  1737. assert _mock_update.captured_extra.get("custom_key") == "keep_me"
  1738. assert _mock_update.captured_extra.get("tag") == '"new"'
  1739. assert result is not None
  1740. class TestGetClientValueError:
  1741. """Test the ValueError branch in _get_client when init_spoolman_client fails (Gap 5)."""
  1742. @pytest.mark.asyncio
  1743. @pytest.mark.integration
  1744. async def test_returns_400_when_init_spoolman_client_raises_value_error(
  1745. self, async_client: AsyncClient, spoolman_settings
  1746. ):
  1747. """If init_spoolman_client raises ValueError after SSRF check passes, return HTTP 400."""
  1748. with (
  1749. patch(
  1750. "backend.app.api.routes.spoolman_inventory.get_spoolman_client",
  1751. AsyncMock(return_value=None),
  1752. ),
  1753. patch(
  1754. "backend.app.api.routes.spoolman_inventory.init_spoolman_client",
  1755. AsyncMock(side_effect=ValueError("unsupported scheme")),
  1756. ),
  1757. ):
  1758. resp = await async_client.get("/api/v1/spoolman/inventory/spools")
  1759. assert resp.status_code == 400
  1760. assert "unsupported scheme" in resp.json()["detail"]
  1761. class TestBulkCreateWithPriceFailure:
  1762. """Test that bulk create handles price-update failures per C1/C8 semantics."""
  1763. @pytest.mark.asyncio
  1764. @pytest.mark.integration
  1765. async def test_bulk_create_price_503_moves_spool_to_failures(
  1766. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1767. ):
  1768. """When price update fails (503), the spool goes to failures — overall returns 207 if at least one succeeds."""
  1769. from backend.app.services.spoolman import SpoolmanUnavailableError
  1770. # First price update fails (SpoolmanUnavailableError → 503), second succeeds
  1771. mock_spoolman_client.update_spool_full = AsyncMock(
  1772. side_effect=[SpoolmanUnavailableError("price server down"), SAMPLE_SPOOLMAN_SPOOL]
  1773. )
  1774. mock_spoolman_client.create_spool = AsyncMock(return_value=SAMPLE_SPOOLMAN_SPOOL)
  1775. payload = {
  1776. "spool": {
  1777. "material": "PLA",
  1778. "brand": "Bambu Lab",
  1779. "label_weight": 1000,
  1780. "cost_per_kg": 19.99,
  1781. },
  1782. "quantity": 2,
  1783. }
  1784. resp = await async_client.post("/api/v1/spoolman/inventory/spools/bulk", json=payload)
  1785. # One spool succeeded, one failed (price 503) → 207 Partial
  1786. assert resp.status_code == 207
  1787. data = resp.json()
  1788. assert len(data["created"]) == 1
  1789. assert data["failed_count"] == 1
  1790. # Both Spoolman creates were attempted
  1791. assert mock_spoolman_client.create_spool.call_count == 2
  1792. # Both price updates were attempted
  1793. assert mock_spoolman_client.update_spool_full.call_count == 2
  1794. class TestSpoolTagLinkValidation:
  1795. """NEW-B1: /spools/{id}/tag endpoint validates tag_uid length and content."""
  1796. @pytest.mark.asyncio
  1797. @pytest.mark.integration
  1798. async def test_tag_uid_6_chars_rejected(self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client):
  1799. """tag_uid with 6 hex chars is rejected — minimum is 8 chars (4-byte UID)."""
  1800. resp = await async_client.patch(
  1801. "/api/v1/spoolman/inventory/spools/42/tag",
  1802. json={"tag_uid": "AABBCC"}, # 6 chars — below new minimum
  1803. )
  1804. assert resp.status_code == 422
  1805. @pytest.mark.asyncio
  1806. @pytest.mark.integration
  1807. async def test_tag_uid_all_zeros_rejected(self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client):
  1808. """tag_uid that is all-zero bytes is rejected as an unwritten/blank tag."""
  1809. resp = await async_client.patch(
  1810. "/api/v1/spoolman/inventory/spools/42/tag",
  1811. json={"tag_uid": "00000000000000"}, # 14 zeros
  1812. )
  1813. assert resp.status_code == 422
  1814. @pytest.mark.asyncio
  1815. @pytest.mark.integration
  1816. async def test_tag_uid_valid_14_chars_accepted(
  1817. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1818. ):
  1819. """tag_uid with 14 valid hex chars (7-byte UID) is accepted."""
  1820. # This tag is not in SAMPLE_SPOOLMAN_SPOOL so no duplicate conflict.
  1821. resp = await async_client.patch(
  1822. "/api/v1/spoolman/inventory/spools/42/tag",
  1823. json={"tag_uid": "AABBCCDD112233"}, # 14 chars, valid, not all-zeros
  1824. )
  1825. assert resp.status_code == 200
  1826. @pytest.mark.asyncio
  1827. @pytest.mark.integration
  1828. async def test_tag_uid_8_chars_accepted(self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client):
  1829. """tag_uid with 8 hex chars (4-byte Bambu Lab NFC UID) is accepted after min_length fix."""
  1830. resp = await async_client.patch(
  1831. "/api/v1/spoolman/inventory/spools/42/tag",
  1832. json={"tag_uid": "2728C17B"}, # 8 chars — real Bambu Lab 4-byte hardware UID
  1833. )
  1834. assert resp.status_code == 200
  1835. @pytest.mark.asyncio
  1836. @pytest.mark.integration
  1837. async def test_tag_uid_8_zeros_rejected(self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client):
  1838. """tag_uid with 8 zero chars is rejected — all-zeros validator applies at the new minimum."""
  1839. resp = await async_client.patch(
  1840. "/api/v1/spoolman/inventory/spools/42/tag",
  1841. json={"tag_uid": "00000000"}, # 8 zeros — meets min_length but is a blank/unwritten tag
  1842. )
  1843. assert resp.status_code == 422
  1844. class TestLinkTagDuplicate:
  1845. """NEW-I1: /spools/{id}/tag returns 409 when another spool already has the same tag."""
  1846. @pytest.mark.asyncio
  1847. @pytest.mark.integration
  1848. async def test_link_tag_returns_200_when_tag_not_on_another_spool(
  1849. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1850. ):
  1851. """Linking a fresh tag to spool 42 returns 200 — no duplicate in Spoolman."""
  1852. resp = await async_client.patch(
  1853. "/api/v1/spoolman/inventory/spools/42/tag",
  1854. json={"tag_uid": "AABBCCDD112233"}, # not in SAMPLE_SPOOLMAN_SPOOL
  1855. )
  1856. assert resp.status_code == 200
  1857. mock_spoolman_client.update_spool_full.assert_called_once()
  1858. @pytest.mark.asyncio
  1859. @pytest.mark.integration
  1860. async def test_link_tag_returns_409_when_same_tag_on_different_spool(
  1861. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1862. ):
  1863. """Linking spool 99 to a tag that spool 42 already carries must return 409."""
  1864. # SAMPLE_SPOOLMAN_SPOOL (id=42) has extra.tag = '"AABBCCDDEEFF0011AABBCCDDEEFF0011"'.
  1865. # Attempting to assign the same tag to spool 99 must be rejected.
  1866. resp = await async_client.patch(
  1867. "/api/v1/spoolman/inventory/spools/99/tag",
  1868. json={"tray_uuid": "AABBCCDDEEFF0011AABBCCDDEEFF0011"}, # 32-char tray UUID
  1869. )
  1870. assert resp.status_code == 409
  1871. detail = resp.json()["detail"]
  1872. assert "42" in str(detail)
  1873. @pytest.mark.asyncio
  1874. @pytest.mark.integration
  1875. async def test_the_409_is_the_same_structured_detail_as_the_built_in_route(
  1876. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1877. ):
  1878. """#3110: one shape for both inventory modes, not two prose sentences.
  1879. The built-in route said "already linked to another active spool" and
  1880. named nobody; this one named the spool but only inside a sentence. A
  1881. client had to parse prose, and a different sentence per mode.
  1882. """
  1883. resp = await async_client.patch(
  1884. "/api/v1/spoolman/inventory/spools/99/tag",
  1885. json={"tray_uuid": "AABBCCDDEEFF0011AABBCCDDEEFF0011"},
  1886. )
  1887. assert resp.status_code == 409
  1888. detail = resp.json()["detail"]
  1889. assert detail["code"] == "tag_already_linked"
  1890. assert detail["spool_id"] == 42
  1891. assert detail["field"] == "tray_uuid"
  1892. @pytest.mark.asyncio
  1893. @pytest.mark.integration
  1894. async def test_the_field_follows_the_precedence_the_tag_itself_uses(
  1895. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1896. ):
  1897. """tray_uuid wins over tag_uid when both are sent, so `field` says so."""
  1898. mock_spoolman_client.get_all_spools.return_value = [
  1899. {**SAMPLE_SPOOLMAN_SPOOL, "id": 42, "extra": {"tag": '"AABBCCDDEEFF0011"'}}
  1900. ]
  1901. resp = await async_client.patch(
  1902. "/api/v1/spoolman/inventory/spools/99/tag",
  1903. json={"tag_uid": "AABBCCDDEEFF0011"},
  1904. )
  1905. assert resp.status_code == 409
  1906. assert resp.json()["detail"]["field"] == "tag_uid"
  1907. @pytest.mark.asyncio
  1908. @pytest.mark.integration
  1909. async def test_duplicate_holders_yield_the_lowest_id(
  1910. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1911. ):
  1912. """Spoolman has no unique constraint on extra.tag either.
  1913. Whichever row the scan reached first was an arbitrary answer; the
  1914. built-in route names the lowest id, so this one does too.
  1915. """
  1916. tag = '"AABBCCDDEEFF0011AABBCCDDEEFF0011"'
  1917. mock_spoolman_client.get_all_spools.return_value = [
  1918. {**SAMPLE_SPOOLMAN_SPOOL, "id": 77, "extra": {"tag": tag}},
  1919. {**SAMPLE_SPOOLMAN_SPOOL, "id": 42, "extra": {"tag": tag}},
  1920. ]
  1921. resp = await async_client.patch(
  1922. "/api/v1/spoolman/inventory/spools/99/tag",
  1923. json={"tray_uuid": "AABBCCDDEEFF0011AABBCCDDEEFF0011"},
  1924. )
  1925. assert resp.status_code == 409
  1926. assert resp.json()["detail"]["spool_id"] == 42
  1927. @pytest.mark.asyncio
  1928. @pytest.mark.integration
  1929. async def test_a_malformed_row_after_the_holder_does_not_sink_the_request(
  1930. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1931. ):
  1932. """extra is free-form and edited outside Bambuddy.
  1933. Naming the lowest id means reading every row, where the old loop
  1934. stopped at its first match -- so a row whose extra.tag is a JSON null
  1935. (which .get("tag", "") hands back as None, not the default) sits
  1936. between the caller and their 409 in a way it never used to.
  1937. """
  1938. tag = '"AABBCCDDEEFF0011AABBCCDDEEFF0011"'
  1939. mock_spoolman_client.get_all_spools.return_value = [
  1940. {**SAMPLE_SPOOLMAN_SPOOL, "id": 42, "extra": {"tag": tag}},
  1941. {**SAMPLE_SPOOLMAN_SPOOL, "id": 55, "extra": {"tag": None}},
  1942. {**SAMPLE_SPOOLMAN_SPOOL, "id": 56, "extra": {"tag": 12345}},
  1943. {**SAMPLE_SPOOLMAN_SPOOL, "id": 57, "extra": None},
  1944. {**SAMPLE_SPOOLMAN_SPOOL, "id": 58, "extra": []},
  1945. ]
  1946. resp = await async_client.patch(
  1947. "/api/v1/spoolman/inventory/spools/99/tag",
  1948. json={"tray_uuid": "AABBCCDDEEFF0011AABBCCDDEEFF0011"},
  1949. )
  1950. assert resp.status_code == 409
  1951. assert resp.json()["detail"]["spool_id"] == 42
  1952. @pytest.mark.asyncio
  1953. @pytest.mark.integration
  1954. async def test_a_malformed_row_is_not_itself_read_as_a_holder(
  1955. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1956. ):
  1957. """A link with no real conflict still succeeds past those rows."""
  1958. mock_spoolman_client.get_all_spools.return_value = [
  1959. {**SAMPLE_SPOOLMAN_SPOOL, "id": 55, "extra": {"tag": None}},
  1960. {**SAMPLE_SPOOLMAN_SPOOL, "id": 56, "extra": {"tag": 12345}},
  1961. {**SAMPLE_SPOOLMAN_SPOOL, "id": 57, "extra": None},
  1962. ]
  1963. resp = await async_client.patch(
  1964. "/api/v1/spoolman/inventory/spools/42/tag",
  1965. json={"tag_uid": "AABBCCDD112233"},
  1966. )
  1967. assert resp.status_code == 200
  1968. mock_spoolman_client.update_spool_full.assert_called_once()
  1969. class TestSpoolmanInventoryUpdateCoreWeight:
  1970. """core_weight is forwarded to Spoolman when sent — any value should be accepted."""
  1971. @pytest.mark.asyncio
  1972. @pytest.mark.integration
  1973. async def test_patch_core_weight_other_than_250_accepted(
  1974. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1975. ):
  1976. """PATCH with core_weight != 250 is accepted and carried through, not rejected."""
  1977. resp = await async_client.patch(
  1978. "/api/v1/spoolman/inventory/spools/42",
  1979. json={"core_weight": 100},
  1980. )
  1981. assert resp.status_code == 200
  1982. @pytest.mark.asyncio
  1983. @pytest.mark.integration
  1984. async def test_patch_core_weight_250_explicitly_is_accepted(
  1985. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1986. ):
  1987. """PATCH with core_weight=250 (the default) is valid and returns 200."""
  1988. resp = await async_client.patch(
  1989. "/api/v1/spoolman/inventory/spools/42",
  1990. json={"core_weight": 250},
  1991. )
  1992. assert resp.status_code == 200
  1993. @pytest.mark.asyncio
  1994. @pytest.mark.integration
  1995. async def test_patch_without_core_weight_is_accepted(
  1996. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  1997. ):
  1998. """PATCH without core_weight (omitted) must not trigger the validator — returns 200."""
  1999. resp = await async_client.patch(
  2000. "/api/v1/spoolman/inventory/spools/42",
  2001. json={"note": "no core_weight key"},
  2002. )
  2003. assert resp.status_code == 200
  2004. class TestUnlinkSpool:
  2005. """POST /spoolman/spools/{id}/unlink clears Spoolman tag without re-entrant lock deadlock.
  2006. Spoolman PATCHes the extra dict by MERGING — popping a key + sending the
  2007. rest doesn't clear the popped key. The endpoint sends the JSON empty-string
  2008. sentinel ('""') which the read-side filters strip. (#1114)
  2009. The endpoint uses merge_spool_extra (not update_spool_full directly)
  2010. because (a) merge_spool_extra owns the per-spool extra_lock for atomic
  2011. read-modify-write semantics, and (b) wrapping it in another extra_lock
  2012. would deadlock — asyncio.Lock is not re-entrant.
  2013. """
  2014. @pytest.fixture
  2015. def mock_unlink_client(self):
  2016. """Mock Spoolman client for the spoolman.py (non-inventory) route."""
  2017. spool_with_tag = {
  2018. **SAMPLE_SPOOLMAN_SPOOL,
  2019. "extra": {"tag": '"AABBCCDDEEFF0011AABBCCDDEEFF0011"', "custom": "keep"},
  2020. }
  2021. mock_client = MagicMock()
  2022. mock_client.has_tag_api = AsyncMock(return_value=False)
  2023. mock_client.add_native_tags = AsyncMock(return_value=0)
  2024. mock_client.unlink_all_native_tags = AsyncMock()
  2025. mock_client.base_url = "http://localhost:7912"
  2026. mock_client.health_check = AsyncMock(return_value=True)
  2027. mock_client.get_spool = AsyncMock(return_value=spool_with_tag)
  2028. # merge_spool_extra returns the spool with the tag cleared (and custom
  2029. # preserved) — that's what the read-side will see after the fix.
  2030. mock_client.merge_spool_extra = AsyncMock(
  2031. return_value={**spool_with_tag, "extra": {"tag": '""', "custom": "keep"}}
  2032. )
  2033. with (
  2034. patch(
  2035. "backend.app.api.routes.spoolman.get_spoolman_client",
  2036. AsyncMock(return_value=mock_client),
  2037. ),
  2038. patch(
  2039. "backend.app.api.routes.spoolman.init_spoolman_client",
  2040. AsyncMock(return_value=mock_client),
  2041. ),
  2042. ):
  2043. yield mock_client
  2044. @pytest.mark.asyncio
  2045. @pytest.mark.integration
  2046. async def test_unlink_sets_tag_to_json_empty_string(
  2047. self,
  2048. async_client: AsyncClient,
  2049. spoolman_settings,
  2050. mock_unlink_client,
  2051. ):
  2052. """Unlink calls merge_spool_extra with the JSON-empty-string sentinel.
  2053. Pre-fix the endpoint did `cur_extra.pop("tag")` then PATCHed the rest.
  2054. Spoolman silently kept the previous tag because the key wasn't in the
  2055. payload (PATCH merges). Now the endpoint sends `{"tag": '""'}` and
  2056. the read-side .strip('"') resolves it to "" → spool drops out of
  2057. get_linked_spools.
  2058. """
  2059. import json as _json
  2060. resp = await async_client.post("/api/v1/spoolman/spools/42/unlink")
  2061. assert resp.status_code == 200
  2062. mock_unlink_client.merge_spool_extra.assert_called_once_with(42, {"tag": _json.dumps("")})
  2063. @pytest.mark.asyncio
  2064. @pytest.mark.integration
  2065. async def test_unlink_preserves_other_extra_keys(
  2066. self,
  2067. async_client: AsyncClient,
  2068. spoolman_settings,
  2069. mock_unlink_client,
  2070. ):
  2071. """Unrelated extra keys must survive unlink.
  2072. merge_spool_extra is responsible for the merge (read current → merge
  2073. new fields → PATCH). The unlink endpoint only sends `{"tag": ...}`,
  2074. so any other extra key on the spool is automatically preserved by
  2075. merge_spool_extra's read-merge-write semantics.
  2076. """
  2077. resp = await async_client.post("/api/v1/spoolman/spools/42/unlink")
  2078. assert resp.status_code == 200
  2079. # The endpoint passes only the tag key — merge_spool_extra does the
  2080. # rest. We don't assert anything about `custom` on the call args
  2081. # because the route doesn't see / pass it.
  2082. _, args, _ = mock_unlink_client.merge_spool_extra.mock_calls[0]
  2083. sent_fields = args[1] if len(args) >= 2 else {}
  2084. assert sent_fields == {"tag": '""'}, "unlink should only send the tag key — merge_spool_extra does the merge"
  2085. # ---------------------------------------------------------------------------
  2086. # B1: GET /spoolman/inventory/filaments
  2087. # B2: POST /spools with spoolman_filament_id bypasses find_or_create_filament
  2088. # ---------------------------------------------------------------------------
  2089. SAMPLE_FILAMENT_DICT = {
  2090. "id": 7,
  2091. "name": "PLA Basic",
  2092. "material": "PLA",
  2093. "color_hex": "FF0000",
  2094. "color_name": "Red",
  2095. "weight": 1000,
  2096. "spool_weight": 196,
  2097. "vendor": {"id": 3, "name": "Bambu Lab"},
  2098. }
  2099. class TestListSpoolmanFilaments:
  2100. """Tests for GET /api/v1/spoolman/inventory/filaments (B1)."""
  2101. @pytest.mark.asyncio
  2102. @pytest.mark.integration
  2103. async def test_list_filaments_disabled_returns_400(self, async_client: AsyncClient):
  2104. """Without Spoolman enabled the endpoint returns 400."""
  2105. resp = await async_client.get("/api/v1/spoolman/inventory/filaments")
  2106. assert resp.status_code == 400
  2107. @pytest.mark.asyncio
  2108. @pytest.mark.integration
  2109. async def test_list_filaments_unreachable_returns_503(self, async_client: AsyncClient, spoolman_settings):
  2110. """503 is returned when _get_client raises HTTPException(503)."""
  2111. with patch(
  2112. "backend.app.api.routes.spoolman_inventory._get_client",
  2113. AsyncMock(side_effect=HTTPException(status_code=503, detail="Spoolman server is not reachable")),
  2114. ):
  2115. resp = await async_client.get("/api/v1/spoolman/inventory/filaments")
  2116. assert resp.status_code == 503
  2117. @pytest.mark.asyncio
  2118. @pytest.mark.integration
  2119. async def test_list_filaments_success(self, async_client: AsyncClient, spoolman_settings):
  2120. """Success path returns normalised filament list including spool_weight."""
  2121. mock_client = MagicMock()
  2122. mock_client.get_filaments = AsyncMock(return_value=[SAMPLE_FILAMENT_DICT])
  2123. with patch(
  2124. "backend.app.api.routes.spoolman_inventory._get_client",
  2125. AsyncMock(return_value=mock_client),
  2126. ):
  2127. resp = await async_client.get("/api/v1/spoolman/inventory/filaments")
  2128. assert resp.status_code == 200
  2129. data = resp.json()
  2130. assert isinstance(data, list)
  2131. assert len(data) == 1
  2132. entry = data[0]
  2133. assert entry["id"] == 7
  2134. assert entry["material"] == "PLA"
  2135. assert entry["spool_weight"] == 196
  2136. assert entry["vendor"]["name"] == "Bambu Lab"
  2137. class TestCreateSpoolWithFilamentId:
  2138. """Tests for POST /api/v1/spoolman/inventory/spools with spoolman_filament_id (B2)."""
  2139. @pytest.mark.asyncio
  2140. @pytest.mark.integration
  2141. async def test_create_with_filament_id_skips_find_or_create(self, async_client: AsyncClient, spoolman_settings):
  2142. """When spoolman_filament_id is provided, find_or_create_filament must NOT be called."""
  2143. mock_client = MagicMock()
  2144. mock_client.has_tag_api = AsyncMock(return_value=False)
  2145. mock_client.add_native_tags = AsyncMock(return_value=0)
  2146. mock_client.unlink_all_native_tags = AsyncMock()
  2147. mock_client.find_or_create_filament = AsyncMock(return_value=7)
  2148. mock_client.create_spool = AsyncMock(return_value=SAMPLE_SPOOLMAN_SPOOL)
  2149. mock_client.update_spool_full = AsyncMock(return_value=SAMPLE_SPOOLMAN_SPOOL)
  2150. with patch(
  2151. "backend.app.api.routes.spoolman_inventory._get_client",
  2152. AsyncMock(return_value=mock_client),
  2153. ):
  2154. resp = await async_client.post(
  2155. "/api/v1/spoolman/inventory/spools",
  2156. json={"spoolman_filament_id": 7},
  2157. )
  2158. assert resp.status_code == 200
  2159. mock_client.find_or_create_filament.assert_not_called()
  2160. mock_client.create_spool.assert_called_once()
  2161. _, kwargs = mock_client.create_spool.call_args
  2162. assert kwargs.get("filament_id") == 7
  2163. @pytest.mark.asyncio
  2164. @pytest.mark.integration
  2165. async def test_create_with_invalid_filament_id_returns_404(self, async_client: AsyncClient, spoolman_settings):
  2166. """An invalid spoolman_filament_id (not in Spoolman) must return 404."""
  2167. from backend.app.services.spoolman import SpoolmanNotFoundError
  2168. mock_client = MagicMock()
  2169. mock_client.has_tag_api = AsyncMock(return_value=False)
  2170. mock_client.add_native_tags = AsyncMock(return_value=0)
  2171. mock_client.unlink_all_native_tags = AsyncMock()
  2172. mock_client.create_spool = AsyncMock(side_effect=SpoolmanNotFoundError("filament not found"))
  2173. with patch(
  2174. "backend.app.api.routes.spoolman_inventory._get_client",
  2175. AsyncMock(return_value=mock_client),
  2176. ):
  2177. resp = await async_client.post(
  2178. "/api/v1/spoolman/inventory/spools",
  2179. json={"spoolman_filament_id": 9999},
  2180. )
  2181. assert resp.status_code == 404
  2182. assert "9999" in resp.json()["detail"]
  2183. # ---------------------------------------------------------------------------
  2184. # WICHTIG-12: Additional edge-case tests
  2185. # ---------------------------------------------------------------------------
  2186. class TestBulkCreateWithFilamentId:
  2187. """Bulk create with spoolman_filament_id skips find_or_create_filament."""
  2188. @pytest.mark.asyncio
  2189. @pytest.mark.integration
  2190. async def test_bulk_create_with_filament_id_skips_find_or_create(
  2191. self, async_client: AsyncClient, spoolman_settings
  2192. ):
  2193. """Bulk POST with spoolman_filament_id must NOT call find_or_create_filament."""
  2194. mock_client = MagicMock()
  2195. mock_client.has_tag_api = AsyncMock(return_value=False)
  2196. mock_client.add_native_tags = AsyncMock(return_value=0)
  2197. mock_client.unlink_all_native_tags = AsyncMock()
  2198. mock_client.find_or_create_filament = AsyncMock(return_value=7)
  2199. mock_client.create_spool = AsyncMock(return_value=SAMPLE_SPOOLMAN_SPOOL)
  2200. mock_client.update_spool_full = AsyncMock(return_value=SAMPLE_SPOOLMAN_SPOOL)
  2201. with patch(
  2202. "backend.app.api.routes.spoolman_inventory._get_client",
  2203. AsyncMock(return_value=mock_client),
  2204. ):
  2205. resp = await async_client.post(
  2206. "/api/v1/spoolman/inventory/spools/bulk",
  2207. json={"spool": {"spoolman_filament_id": 7}, "quantity": 2},
  2208. )
  2209. assert resp.status_code == 200
  2210. mock_client.find_or_create_filament.assert_not_called()
  2211. assert mock_client.create_spool.call_count == 2
  2212. for call in mock_client.create_spool.call_args_list:
  2213. _, kwargs = call
  2214. assert kwargs.get("filament_id") == 7
  2215. class TestCreateSpoolValidation:
  2216. """Validation edge cases for SpoolmanInventoryCreate."""
  2217. @pytest.mark.asyncio
  2218. @pytest.mark.integration
  2219. async def test_create_spool_filament_id_zero_returns_422(self, async_client: AsyncClient, spoolman_settings):
  2220. """spoolman_filament_id=0 must fail Field(gt=0) validation → 422."""
  2221. resp = await async_client.post(
  2222. "/api/v1/spoolman/inventory/spools",
  2223. json={"spoolman_filament_id": 0},
  2224. )
  2225. assert resp.status_code == 422
  2226. @pytest.mark.asyncio
  2227. @pytest.mark.integration
  2228. async def test_create_spool_without_material_or_filament_id_returns_422(
  2229. self, async_client: AsyncClient, spoolman_settings
  2230. ):
  2231. """Neither material nor spoolman_filament_id → model_validator must reject → 422."""
  2232. resp = await async_client.post(
  2233. "/api/v1/spoolman/inventory/spools",
  2234. json={"label_weight": 1000},
  2235. )
  2236. assert resp.status_code == 422
  2237. class TestNormalizeFilament:
  2238. """Unit-style tests for _normalize_filament helper (imported directly)."""
  2239. def test_normalize_filament_null_vendor(self):
  2240. from backend.app.api.routes.spoolman_inventory import _normalize_filament
  2241. result = _normalize_filament({"id": 5, "name": "PLA", "vendor": None})
  2242. assert result is not None
  2243. assert result["vendor"] is None
  2244. def test_normalize_filament_null_id_returns_none(self):
  2245. from backend.app.api.routes.spoolman_inventory import _normalize_filament
  2246. result = _normalize_filament({"id": None, "name": "PLA"})
  2247. assert result is None
  2248. def test_normalize_filament_zero_id_returns_none(self):
  2249. from backend.app.api.routes.spoolman_inventory import _normalize_filament
  2250. result = _normalize_filament({"id": 0, "name": "PLA"})
  2251. assert result is None
  2252. # ---------------------------------------------------------------------------
  2253. # F1: TestTranslateSpoolmanErrors — 502/404/503 paths through _translate_spoolman_errors
  2254. # ---------------------------------------------------------------------------
  2255. class TestTranslateSpoolmanErrors:
  2256. """F1: _translate_spoolman_errors() maps Spoolman exceptions to HTTP codes."""
  2257. @pytest.mark.asyncio
  2258. @pytest.mark.integration
  2259. async def test_spoolman_not_found_returns_404(
  2260. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2261. ):
  2262. """SpoolmanNotFoundError from get_spool → 404."""
  2263. from backend.app.services.spoolman import SpoolmanNotFoundError
  2264. mock_spoolman_client.get_spool.side_effect = SpoolmanNotFoundError("spool 999 not found")
  2265. resp = await async_client.get("/api/v1/spoolman/inventory/spools/999")
  2266. assert resp.status_code == 404
  2267. @pytest.mark.asyncio
  2268. @pytest.mark.integration
  2269. async def test_spoolman_unavailable_returns_503(
  2270. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2271. ):
  2272. """SpoolmanUnavailableError from get_spool → 503."""
  2273. from backend.app.services.spoolman import SpoolmanUnavailableError
  2274. mock_spoolman_client.get_spool.side_effect = SpoolmanUnavailableError("network error")
  2275. resp = await async_client.get("/api/v1/spoolman/inventory/spools/42")
  2276. assert resp.status_code == 503
  2277. @pytest.mark.asyncio
  2278. @pytest.mark.integration
  2279. async def test_spoolman_client_error_returns_502_with_upstream_status(
  2280. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2281. ):
  2282. """SpoolmanClientError from get_spool → 502 with upstream_status in body."""
  2283. from backend.app.services.spoolman import SpoolmanClientError
  2284. mock_spoolman_client.get_spool.side_effect = SpoolmanClientError("Spoolman rejected", 422, "filament not found")
  2285. resp = await async_client.get("/api/v1/spoolman/inventory/spools/42")
  2286. assert resp.status_code == 502
  2287. body = resp.json()
  2288. assert body["detail"]["upstream_status"] == 422
  2289. assert body["detail"]["upstream_body"] == "filament not found"
  2290. # ---------------------------------------------------------------------------
  2291. # F2: _get_client health_check returns False → 503
  2292. # ---------------------------------------------------------------------------
  2293. class TestGetClientHealthCheckFalse:
  2294. """F2: _get_client raises 503 when health_check() returns False."""
  2295. @pytest.mark.asyncio
  2296. @pytest.mark.integration
  2297. async def test_returns_503_when_health_check_returns_false(
  2298. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2299. ):
  2300. """health_check() → False should produce 503 on any inventory call."""
  2301. import time
  2302. import backend.app.api.routes.spoolman_inventory as inv_module
  2303. mock_spoolman_client.health_check = AsyncMock(return_value=False)
  2304. # Clear the TTL cache so health_check is actually called
  2305. inv_module._health_check_cache.clear()
  2306. resp = await async_client.get("/api/v1/spoolman/inventory/spools")
  2307. assert resp.status_code == 503
  2308. # ---------------------------------------------------------------------------
  2309. # F3: SpoolTagLinkRequest both fields null → 422
  2310. # ---------------------------------------------------------------------------
  2311. class TestSpoolTagLinkBothNull:
  2312. """F3: /spools/{id}/tag with both tag_uid and tray_uuid null → 422."""
  2313. @pytest.mark.asyncio
  2314. @pytest.mark.integration
  2315. async def test_both_null_returns_422(self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client):
  2316. """Sending {} (both fields absent) → at_least_one validator → 422."""
  2317. resp = await async_client.patch(
  2318. "/api/v1/spoolman/inventory/spools/42/tag",
  2319. json={},
  2320. )
  2321. assert resp.status_code == 422
  2322. @pytest.mark.asyncio
  2323. @pytest.mark.integration
  2324. async def test_both_explicitly_null_returns_422(
  2325. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2326. ):
  2327. """Sending {tag_uid: null, tray_uuid: null} → at_least_one validator → 422."""
  2328. resp = await async_client.patch(
  2329. "/api/v1/spoolman/inventory/spools/42/tag",
  2330. json={"tag_uid": None, "tray_uuid": None},
  2331. )
  2332. assert resp.status_code == 422
  2333. # ---------------------------------------------------------------------------
  2334. # F5: RBAC lists — missing endpoints
  2335. # ---------------------------------------------------------------------------
  2336. class TestSpoolmanInventoryAuthExtended:
  2337. """F5: Additional endpoints in RBAC auth/403 parametrize lists."""
  2338. @pytest.fixture
  2339. async def auth_and_spoolman_settings(self, db_session):
  2340. from backend.app.models.settings import Settings
  2341. db_session.add(Settings(key="spoolman_enabled", value="true"))
  2342. db_session.add(Settings(key="spoolman_url", value="http://localhost:7912"))
  2343. db_session.add(Settings(key="auth_enabled", value="true"))
  2344. await db_session.commit()
  2345. @pytest.mark.asyncio
  2346. @pytest.mark.integration
  2347. @pytest.mark.parametrize(
  2348. "method,path,payload",
  2349. [
  2350. ("PATCH", "/api/v1/spoolman/inventory/spools/42/tag", {"tag_uid": "AABBCCDDEE112233"}),
  2351. ("POST", "/api/v1/spoolman/inventory/sync-ams-weights", {"printer_id": 1, "ams_data": []}),
  2352. ("PATCH", "/api/v1/spoolman/inventory/filaments/7", {"spool_weight": 196.0}),
  2353. ],
  2354. )
  2355. async def test_extended_write_endpoints_require_auth(
  2356. self,
  2357. async_client: AsyncClient,
  2358. auth_and_spoolman_settings,
  2359. method: str,
  2360. path: str,
  2361. payload: dict | None,
  2362. ):
  2363. """Additional write endpoints return 401 when auth is enabled and no token is provided."""
  2364. resp = await async_client.request(method, path, json=payload)
  2365. assert resp.status_code == 401, f"{method} {path} should require auth but got {resp.status_code}: {resp.json()}"
  2366. @pytest.mark.asyncio
  2367. @pytest.mark.integration
  2368. @pytest.mark.parametrize(
  2369. "method,path",
  2370. [
  2371. ("GET", "/api/v1/spoolman/inventory/filaments"),
  2372. ],
  2373. )
  2374. async def test_extended_read_endpoints_require_auth(
  2375. self,
  2376. async_client: AsyncClient,
  2377. auth_and_spoolman_settings,
  2378. method: str,
  2379. path: str,
  2380. ):
  2381. """Additional read endpoints return 401 when auth is enabled and no token is provided."""
  2382. resp = await async_client.request(method, path)
  2383. assert resp.status_code == 401, f"{method} {path} should require auth but got {resp.status_code}: {resp.json()}"
  2384. # ---------------------------------------------------------------------------
  2385. # F8: _normalize_filament negative ID returns None
  2386. # ---------------------------------------------------------------------------
  2387. class TestNormalizeFilamentNegativeId:
  2388. """F8: _normalize_filament with negative id → None (was only checking == 0)."""
  2389. def test_normalize_filament_negative_id_returns_none(self):
  2390. from backend.app.api.routes.spoolman_inventory import _normalize_filament
  2391. result = _normalize_filament({"id": -1, "name": "PLA"})
  2392. assert result is None
  2393. def test_normalize_filament_large_negative_id_returns_none(self):
  2394. from backend.app.api.routes.spoolman_inventory import _normalize_filament
  2395. result = _normalize_filament({"id": -999, "name": "PLA"})
  2396. assert result is None
  2397. # ---------------------------------------------------------------------------
  2398. # F9: weight_used > label_weight cross-field validator integration test
  2399. # ---------------------------------------------------------------------------
  2400. class TestCreateSpoolWeightValidation:
  2401. """F9: SpoolmanInventoryCreate.validate_weight_consistency cross-field validator."""
  2402. @pytest.mark.asyncio
  2403. @pytest.mark.integration
  2404. async def test_weight_used_exceeds_label_weight_returns_422(self, async_client: AsyncClient, spoolman_settings):
  2405. """weight_used > label_weight → cross-field validator → 422."""
  2406. resp = await async_client.post(
  2407. "/api/v1/spoolman/inventory/spools",
  2408. json={"material": "PLA", "label_weight": 500, "weight_used": 600},
  2409. )
  2410. assert resp.status_code == 422
  2411. @pytest.mark.asyncio
  2412. @pytest.mark.integration
  2413. async def test_weight_used_equals_label_weight_accepted(
  2414. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2415. ):
  2416. """weight_used == label_weight is exactly at the boundary → should pass (201)."""
  2417. resp = await async_client.post(
  2418. "/api/v1/spoolman/inventory/spools",
  2419. json={"material": "PLA", "label_weight": 1000, "weight_used": 1000},
  2420. )
  2421. # 201 or 200 (spool created)
  2422. assert resp.status_code in (200, 201)
  2423. @pytest.mark.asyncio
  2424. @pytest.mark.integration
  2425. async def test_create_spool_with_non_default_core_weight_accepted(
  2426. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2427. ):
  2428. """A3: core_weight != 250 is accepted and reaches Spoolman → 201."""
  2429. resp = await async_client.post(
  2430. "/api/v1/spoolman/inventory/spools",
  2431. json={"material": "PLA", "label_weight": 1000, "weight_used": 0, "core_weight": 196},
  2432. )
  2433. assert resp.status_code in (200, 201)
  2434. @pytest.mark.asyncio
  2435. @pytest.mark.integration
  2436. async def test_update_spool_with_non_default_core_weight_accepted(
  2437. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2438. ):
  2439. """A3: PATCH with core_weight != 250 must no longer return 422."""
  2440. resp = await async_client.patch(
  2441. "/api/v1/spoolman/inventory/spools/42",
  2442. json={"core_weight": 300},
  2443. )
  2444. assert resp.status_code == 200
  2445. # ---------------------------------------------------------------------------
  2446. # P8-T1: /slot-assignments/all enriches with printer_name + ams_label
  2447. # ---------------------------------------------------------------------------
  2448. class TestGetAllSlotAssignmentsEnriched:
  2449. """P8-T1: /slot-assignments/all enriches with printer_name + ams_label.
  2450. Regression for InventoryPage LOCATION column showing '-' for Spoolman
  2451. spools because the endpoint only returned 4 raw fields without the
  2452. printer_name + ams_label needed by the UI.
  2453. """
  2454. @pytest.mark.asyncio
  2455. @pytest.mark.integration
  2456. async def test_returns_printer_name_for_existing_printer(
  2457. self, async_client: AsyncClient, db_session, spoolman_settings
  2458. ):
  2459. """printer_name is enriched from the joined Printer relationship."""
  2460. from backend.app.models.printer import Printer
  2461. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2462. db_session.add(
  2463. Printer(
  2464. id=1,
  2465. name="Sully",
  2466. model="X1C",
  2467. serial_number="SN1",
  2468. ip_address="1.2.3.4",
  2469. access_code="",
  2470. )
  2471. )
  2472. db_session.add(
  2473. SpoolmanSlotAssignment(
  2474. printer_id=1,
  2475. ams_id=0,
  2476. tray_id=2,
  2477. spoolman_spool_id=216,
  2478. )
  2479. )
  2480. await db_session.commit()
  2481. with patch("backend.app.api.routes.spoolman_inventory.printer_manager") as mock_pm:
  2482. mock_pm.get_all_statuses.return_value = {}
  2483. resp = await async_client.get("/api/v1/spoolman/inventory/slot-assignments/all")
  2484. assert resp.status_code == 200
  2485. data = resp.json()
  2486. assert len(data) == 1
  2487. assert data[0]["printer_name"] == "Sully"
  2488. assert data[0]["spoolman_spool_id"] == 216
  2489. assert data[0]["ams_id"] == 0
  2490. assert data[0]["tray_id"] == 2
  2491. assert data[0]["ams_label"] is None
  2492. @pytest.mark.asyncio
  2493. @pytest.mark.integration
  2494. async def test_returns_ams_label_when_label_configured(
  2495. self, async_client: AsyncClient, db_session, spoolman_settings
  2496. ):
  2497. """ams_label is enriched from AmsLabel via printer MQTT serial map."""
  2498. from backend.app.models.ams_label import AmsLabel
  2499. from backend.app.models.printer import Printer
  2500. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2501. db_session.add(
  2502. Printer(
  2503. id=1,
  2504. name="Sully",
  2505. model="X1C",
  2506. serial_number="SN1",
  2507. ip_address="1.2.3.4",
  2508. access_code="",
  2509. )
  2510. )
  2511. db_session.add(AmsLabel(ams_serial_number="ABC123", label="Top Shelf"))
  2512. db_session.add(
  2513. SpoolmanSlotAssignment(
  2514. printer_id=1,
  2515. ams_id=0,
  2516. tray_id=2,
  2517. spoolman_spool_id=216,
  2518. )
  2519. )
  2520. await db_session.commit()
  2521. mock_state = MagicMock(raw_data={"ams": [{"id": 0, "sn": "ABC123"}]})
  2522. with patch("backend.app.api.routes.spoolman_inventory.printer_manager") as mock_pm:
  2523. mock_pm.get_all_statuses.return_value = {1: mock_state}
  2524. resp = await async_client.get("/api/v1/spoolman/inventory/slot-assignments/all")
  2525. assert resp.status_code == 200
  2526. assert resp.json()[0]["ams_label"] == "Top Shelf"
  2527. @pytest.mark.asyncio
  2528. @pytest.mark.integration
  2529. async def test_synthetic_ams_label_fallback(self, async_client: AsyncClient, db_session, spoolman_settings):
  2530. """Falls back to synthetic 'p{pid}a{ams_id}' key when no MQTT serial available."""
  2531. from backend.app.models.ams_label import AmsLabel
  2532. from backend.app.models.printer import Printer
  2533. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2534. db_session.add(
  2535. Printer(
  2536. id=1,
  2537. name="Sully",
  2538. model="X1C",
  2539. serial_number="SN1",
  2540. ip_address="1.2.3.4",
  2541. access_code="",
  2542. )
  2543. )
  2544. db_session.add(AmsLabel(ams_serial_number="p1a0", label="Synthetic Label"))
  2545. db_session.add(
  2546. SpoolmanSlotAssignment(
  2547. printer_id=1,
  2548. ams_id=0,
  2549. tray_id=2,
  2550. spoolman_spool_id=216,
  2551. )
  2552. )
  2553. await db_session.commit()
  2554. with patch("backend.app.api.routes.spoolman_inventory.printer_manager") as mock_pm:
  2555. mock_pm.get_all_statuses.return_value = {} # No live state -> synthetic key
  2556. resp = await async_client.get("/api/v1/spoolman/inventory/slot-assignments/all")
  2557. assert resp.json()[0]["ams_label"] == "Synthetic Label"
  2558. @pytest.mark.asyncio
  2559. @pytest.mark.integration
  2560. async def test_filter_by_printer_id_still_works(self, async_client: AsyncClient, db_session, spoolman_settings):
  2561. """Regression: ?printer_id=N still filters and enriches."""
  2562. from backend.app.models.printer import Printer
  2563. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2564. for pid in (1, 2):
  2565. db_session.add(
  2566. Printer(
  2567. id=pid,
  2568. name=f"P{pid}",
  2569. model="X1C",
  2570. serial_number=f"SN{pid}",
  2571. ip_address=f"1.2.3.{pid}",
  2572. access_code="",
  2573. )
  2574. )
  2575. db_session.add(
  2576. SpoolmanSlotAssignment(
  2577. printer_id=pid,
  2578. ams_id=0,
  2579. tray_id=0,
  2580. spoolman_spool_id=200 + pid,
  2581. )
  2582. )
  2583. await db_session.commit()
  2584. with patch("backend.app.api.routes.spoolman_inventory.printer_manager") as mock_pm:
  2585. mock_pm.get_all_statuses.return_value = {}
  2586. resp = await async_client.get("/api/v1/spoolman/inventory/slot-assignments/all?printer_id=1")
  2587. data = resp.json()
  2588. assert len(data) == 1
  2589. assert data[0]["printer_id"] == 1
  2590. assert data[0]["printer_name"] == "P1"
  2591. assert data[0]["spoolman_spool_id"] == 201
  2592. class TestPerSpoolCoreWeight:
  2593. """The per-spool tare reaches Spoolman now (#2908).
  2594. `core_weight` was declared on both write schemas and dropped after
  2595. validation, with a comment saying so. The read path never showed it: it
  2596. derives the value from ``spool.spool_weight ?? filament.spool_weight ?? 250``
  2597. (_spoolman_helpers.py), so an edit that went nowhere came back as the
  2598. inherited value and looked like it had simply not changed.
  2599. It is not cosmetic, because the same resolution is the tare the weigh
  2600. endpoint subtracts. A spool whose real empty weight differs from its
  2601. filament's produced a wrong remaining weight on every weigh-in -- 70 g for
  2602. the reporter's third-party spools against Bambu's 250 g reusable ones.
  2603. Spoolman already has the field and already gives it priority. Only the
  2604. write was missing.
  2605. """
  2606. @pytest.mark.asyncio
  2607. @pytest.mark.integration
  2608. async def test_an_edited_tare_is_written_to_the_spools_own_field(
  2609. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2610. ):
  2611. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json={"core_weight": 180})
  2612. assert response.status_code == 200
  2613. assert mock_spoolman_client.update_spool_full.call_args.kwargs["spool_weight"] == 180
  2614. @pytest.mark.asyncio
  2615. @pytest.mark.integration
  2616. async def test_an_edit_that_does_not_mention_the_tare_leaves_it_inheriting(
  2617. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2618. ):
  2619. """The reason this keys off model_fields_set rather than the value.
  2620. `core_weight` carries a default, so a PATCH that never mentions it still
  2621. arrives at the handler holding one. Writing that would stamp an explicit
  2622. tare on every spool the user edits for any reason, silently detaching it
  2623. from its filament -- a worse bug than the one being fixed, and an
  2624. invisible one, since the number displayed would not change.
  2625. """
  2626. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json={"note": "just a note"})
  2627. assert response.status_code == 200
  2628. assert mock_spoolman_client.update_spool_full.call_args.kwargs["spool_weight"] is None
  2629. @pytest.mark.asyncio
  2630. @pytest.mark.integration
  2631. async def test_a_tare_given_at_creation_is_written(
  2632. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2633. ):
  2634. response = await async_client.post(
  2635. "/api/v1/spoolman/inventory/spools",
  2636. json={"material": "PLA", "label_weight": 1000, "core_weight": 180},
  2637. )
  2638. assert response.status_code == 200
  2639. assert mock_spoolman_client.create_spool.call_args.kwargs["spool_weight"] == 180
  2640. @pytest.mark.asyncio
  2641. @pytest.mark.integration
  2642. async def test_a_creation_that_omits_the_tare_leaves_the_spool_inheriting(
  2643. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2644. ):
  2645. """Same defaulting hazard as the update, and the commoner path: the
  2646. form posts without a tare far more often than with one."""
  2647. response = await async_client.post(
  2648. "/api/v1/spoolman/inventory/spools",
  2649. json={"material": "PLA", "label_weight": 1000},
  2650. )
  2651. assert response.status_code == 200
  2652. assert mock_spoolman_client.create_spool.call_args.kwargs["spool_weight"] is None
  2653. @pytest.mark.asyncio
  2654. @pytest.mark.integration
  2655. async def test_bulk_creation_persists_the_tare_on_every_spool(
  2656. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2657. ):
  2658. """Bulk create takes the same schema, so it dropped the field the same way."""
  2659. response = await async_client.post(
  2660. "/api/v1/spoolman/inventory/spools/bulk",
  2661. json={"spool": {"material": "PLA", "label_weight": 1000, "core_weight": 180}, "quantity": 3},
  2662. )
  2663. assert response.status_code in (200, 201)
  2664. assert mock_spoolman_client.create_spool.await_count == 3
  2665. assert all(c.kwargs["spool_weight"] == 180 for c in mock_spoolman_client.create_spool.await_args_list)
  2666. @pytest.mark.asyncio
  2667. @pytest.mark.integration
  2668. async def test_a_zero_tare_is_a_value_not_an_absence(
  2669. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2670. ):
  2671. """0 g is a real answer -- a coil with no spool -- and the schema allows
  2672. it (``ge=0``). Guarding the write on truthiness rather than ``is not
  2673. None`` would silently turn it into "inherit", which resolves to 250."""
  2674. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json={"core_weight": 0})
  2675. assert response.status_code == 200
  2676. assert mock_spoolman_client.update_spool_full.call_args.kwargs["spool_weight"] == 0
  2677. @pytest.mark.asyncio
  2678. @pytest.mark.integration
  2679. async def test_the_written_tare_is_the_one_the_weigh_endpoint_subtracts(
  2680. self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
  2681. ):
  2682. """What the fix is actually for.
  2683. The weigh endpoint resolves the tare exactly as the read path does, so
  2684. once the per-spool value is stored it is the number a measured gross
  2685. weight is reduced by. With a 180 g spool inheriting the filament's 250 g
  2686. this same weigh-in would have recorded 550 g remaining instead of 620 --
  2687. the 70 g error from the report, on every weigh-in.
  2688. """
  2689. mock_spoolman_client.get_spool.return_value = {
  2690. **SAMPLE_SPOOLMAN_SPOOL,
  2691. "spool_weight": 180.0,
  2692. }
  2693. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42/weight", json={"weight_grams": 800.0})
  2694. assert response.status_code == 200
  2695. assert mock_spoolman_client.update_spool_full.call_args.kwargs["remaining_weight"] == 620.0
  2696. class TestSpoolmanLastDried:
  2697. """#2863 — a drying date set by hand round-trips through spool.extra."""
  2698. @pytest.mark.asyncio
  2699. @pytest.mark.integration
  2700. async def test_hand_set_date_writes_utc_and_clears_temperature_and_hours(
  2701. self,
  2702. async_client: AsyncClient,
  2703. spoolman_settings,
  2704. mock_spoolman_client,
  2705. ):
  2706. response = await async_client.patch(
  2707. "/api/v1/spoolman/inventory/spools/42", json={"last_dried_at": "2026-10-06T14:30:00+02:00"}
  2708. )
  2709. assert response.status_code == 200
  2710. mock_spoolman_client.merge_spool_extra.assert_called_once_with(
  2711. 42,
  2712. {
  2713. "bambu_last_dried_at": json.dumps("2026-10-06T12:30:00"),
  2714. "bambu_last_dried_temp": json.dumps(""),
  2715. "bambu_last_dried_hours": json.dumps(""),
  2716. },
  2717. )
  2718. @pytest.mark.asyncio
  2719. @pytest.mark.integration
  2720. async def test_null_clears_the_date(
  2721. self,
  2722. async_client: AsyncClient,
  2723. spoolman_settings,
  2724. mock_spoolman_client,
  2725. ):
  2726. response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json={"last_dried_at": None})
  2727. assert response.status_code == 200
  2728. fields = mock_spoolman_client.merge_spool_extra.call_args.args[1]
  2729. assert fields["bambu_last_dried_at"] == json.dumps("")