test_spoolbuddy.py 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838
  1. """Integration tests for SpoolBuddy API endpoints."""
  2. from datetime import datetime, timedelta, timezone
  3. from unittest.mock import AsyncMock, MagicMock, patch
  4. import pytest
  5. from httpx import AsyncClient
  6. from sqlalchemy.ext.asyncio import AsyncSession
  7. import backend.app.services.spoolbuddy_ssh # noqa: F401 — ensures patch() can resolve the dotted path
  8. from backend.app.api.routes import spoolbuddy as spoolbuddy_routes
  9. from backend.app.models.spool import Spool
  10. from backend.app.models.spoolbuddy_device import SpoolBuddyDevice
  11. from backend.app.services.spoolman import SpoolmanNotFoundError, SpoolmanUnavailableError
  12. API = "/api/v1/spoolbuddy"
  13. @pytest.fixture
  14. def device_factory(db_session: AsyncSession):
  15. """Factory to create SpoolBuddyDevice records."""
  16. _counter = [0]
  17. async def _create(**kwargs):
  18. _counter[0] += 1
  19. n = _counter[0]
  20. defaults = {
  21. "device_id": f"sb-{n:04d}",
  22. "hostname": f"spoolbuddy-{n}",
  23. "ip_address": f"10.0.0.{n}",
  24. "firmware_version": "1.0.0",
  25. "has_nfc": True,
  26. "has_scale": True,
  27. "tare_offset": 0,
  28. "calibration_factor": 1.0,
  29. "last_seen": datetime.now(timezone.utc),
  30. }
  31. defaults.update(kwargs)
  32. device = SpoolBuddyDevice(**defaults)
  33. db_session.add(device)
  34. await db_session.commit()
  35. await db_session.refresh(device)
  36. return device
  37. return _create
  38. @pytest.fixture
  39. def spool_factory(db_session: AsyncSession):
  40. """Factory to create Spool records."""
  41. _counter = [0]
  42. async def _create(**kwargs):
  43. _counter[0] += 1
  44. defaults = {
  45. "material": "PLA",
  46. "subtype": "Basic",
  47. "brand": "Polymaker",
  48. "color_name": "Red",
  49. "rgba": "FF0000FF",
  50. "label_weight": 1000,
  51. "core_weight": 250,
  52. "weight_used": 0,
  53. }
  54. defaults.update(kwargs)
  55. spool = Spool(**defaults)
  56. db_session.add(spool)
  57. await db_session.commit()
  58. await db_session.refresh(spool)
  59. return spool
  60. return _create
  61. # ============================================================================
  62. # Device endpoints
  63. # ============================================================================
  64. class TestDeviceEndpoints:
  65. @pytest.mark.asyncio
  66. @pytest.mark.integration
  67. async def test_register_new_device(self, async_client: AsyncClient):
  68. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  69. mock_ws.broadcast = AsyncMock()
  70. resp = await async_client.post(
  71. f"{API}/devices/register",
  72. json={
  73. "device_id": "sb-new",
  74. "hostname": "spoolbuddy-new",
  75. "ip_address": "10.0.0.99",
  76. "firmware_version": "1.2.0",
  77. },
  78. )
  79. assert resp.status_code == 200
  80. data = resp.json()
  81. assert data["device_id"] == "sb-new"
  82. assert data["hostname"] == "spoolbuddy-new"
  83. assert data["online"] is True
  84. mock_ws.broadcast.assert_called_once()
  85. msg = mock_ws.broadcast.call_args[0][0]
  86. assert msg["type"] == "spoolbuddy_online"
  87. @pytest.mark.asyncio
  88. @pytest.mark.integration
  89. async def test_re_register_existing_device(self, async_client: AsyncClient, device_factory):
  90. device = await device_factory(
  91. device_id="sb-exist",
  92. tare_offset=12345,
  93. calibration_factor=0.0042,
  94. )
  95. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  96. mock_ws.broadcast = AsyncMock()
  97. resp = await async_client.post(
  98. f"{API}/devices/register",
  99. json={
  100. "device_id": "sb-exist",
  101. "hostname": "updated-host",
  102. "ip_address": "10.0.0.200",
  103. "firmware_version": "2.0.0",
  104. },
  105. )
  106. assert resp.status_code == 200
  107. data = resp.json()
  108. assert data["id"] == device.id
  109. assert data["hostname"] == "updated-host"
  110. assert data["ip_address"] == "10.0.0.200"
  111. assert data["firmware_version"] == "2.0.0"
  112. # Calibration preserved on re-register
  113. assert data["tare_offset"] == 12345
  114. assert data["calibration_factor"] == pytest.approx(0.0042)
  115. @pytest.mark.asyncio
  116. @pytest.mark.integration
  117. async def test_list_devices_empty(self, async_client: AsyncClient):
  118. resp = await async_client.get(f"{API}/devices")
  119. assert resp.status_code == 200
  120. assert resp.json() == []
  121. @pytest.mark.asyncio
  122. @pytest.mark.integration
  123. async def test_list_devices(self, async_client: AsyncClient, device_factory):
  124. await device_factory(device_id="sb-a", hostname="alpha")
  125. await device_factory(device_id="sb-b", hostname="beta")
  126. resp = await async_client.get(f"{API}/devices")
  127. assert resp.status_code == 200
  128. devices = resp.json()
  129. assert len(devices) == 2
  130. hostnames = {d["hostname"] for d in devices}
  131. assert hostnames == {"alpha", "beta"}
  132. @pytest.mark.asyncio
  133. @pytest.mark.integration
  134. async def test_unregister_device(self, async_client: AsyncClient, device_factory, db_session):
  135. await device_factory(device_id="sb-keep", hostname="keep")
  136. await device_factory(device_id="sb-drop", hostname="drop")
  137. spoolbuddy_routes._spoolbuddy_online_last_broadcast["sb-drop"] = 123.0
  138. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  139. mock_ws.broadcast = AsyncMock()
  140. resp = await async_client.delete(f"{API}/devices/sb-drop")
  141. assert resp.status_code == 200
  142. assert resp.json() == {"status": "deleted", "device_id": "sb-drop"}
  143. assert "sb-drop" not in spoolbuddy_routes._spoolbuddy_online_last_broadcast
  144. mock_ws.broadcast.assert_called_once()
  145. msg = mock_ws.broadcast.call_args[0][0]
  146. assert msg["type"] == "spoolbuddy_unregistered"
  147. assert msg["device_id"] == "sb-drop"
  148. # Other device still present
  149. resp = await async_client.get(f"{API}/devices")
  150. remaining = {d["device_id"] for d in resp.json()}
  151. assert remaining == {"sb-keep"}
  152. @pytest.mark.asyncio
  153. @pytest.mark.integration
  154. async def test_unregister_device_not_found(self, async_client: AsyncClient):
  155. resp = await async_client.delete(f"{API}/devices/sb-ghost")
  156. assert resp.status_code == 404
  157. @pytest.mark.asyncio
  158. @pytest.mark.integration
  159. async def test_heartbeat_updates_status(self, async_client: AsyncClient, device_factory):
  160. device = await device_factory(device_id="sb-hb")
  161. spoolbuddy_routes._spoolbuddy_online_last_broadcast.clear()
  162. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  163. mock_ws.broadcast = AsyncMock()
  164. resp = await async_client.post(
  165. f"{API}/devices/sb-hb/heartbeat",
  166. json={"nfc_ok": True, "scale_ok": True, "uptime_s": 600},
  167. )
  168. assert resp.status_code == 200
  169. data = resp.json()
  170. assert data["tare_offset"] == device.tare_offset
  171. assert data["calibration_factor"] == pytest.approx(device.calibration_factor)
  172. mock_ws.broadcast.assert_called_once()
  173. msg = mock_ws.broadcast.call_args[0][0]
  174. assert msg["type"] == "spoolbuddy_online"
  175. assert msg["device_id"] == "sb-hb"
  176. @pytest.mark.asyncio
  177. @pytest.mark.integration
  178. async def test_heartbeat_returns_ssh_public_key(self, async_client: AsyncClient, device_factory):
  179. """Heartbeat response carries the current SSH public key so the daemon
  180. can re-deploy it whenever Bambuddy's keypair rotates without waiting
  181. for a service restart."""
  182. await device_factory(device_id="sb-ssh-hb")
  183. fake_key = "ssh-ed25519 AAAATESTKEY bambuddy-spoolbuddy"
  184. with (
  185. patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws,
  186. patch(
  187. "backend.app.services.spoolbuddy_ssh.get_public_key",
  188. AsyncMock(return_value=fake_key),
  189. ),
  190. ):
  191. mock_ws.broadcast = AsyncMock()
  192. resp = await async_client.post(
  193. f"{API}/devices/sb-ssh-hb/heartbeat",
  194. json={"nfc_ok": True, "scale_ok": True, "uptime_s": 5},
  195. )
  196. assert resp.status_code == 200
  197. assert resp.json()["ssh_public_key"] == fake_key
  198. @pytest.mark.asyncio
  199. @pytest.mark.integration
  200. async def test_heartbeat_ssh_key_failure_does_not_break_heartbeat(self, async_client: AsyncClient, device_factory):
  201. """If the backend can't read its own SSH key, the heartbeat must still
  202. succeed — telemetry/commands are far more critical than key sync."""
  203. await device_factory(device_id="sb-ssh-fail")
  204. with (
  205. patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws,
  206. patch(
  207. "backend.app.services.spoolbuddy_ssh.get_public_key",
  208. AsyncMock(side_effect=OSError("disk full")),
  209. ),
  210. ):
  211. mock_ws.broadcast = AsyncMock()
  212. resp = await async_client.post(
  213. f"{API}/devices/sb-ssh-fail/heartbeat",
  214. json={"nfc_ok": True, "scale_ok": True, "uptime_s": 5},
  215. )
  216. assert resp.status_code == 200
  217. assert resp.json()["ssh_public_key"] is None
  218. @pytest.mark.asyncio
  219. @pytest.mark.integration
  220. async def test_heartbeat_returns_pending_command(self, async_client: AsyncClient, device_factory):
  221. await device_factory(device_id="sb-cmd", pending_command="tare")
  222. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  223. mock_ws.broadcast = AsyncMock()
  224. resp = await async_client.post(
  225. f"{API}/devices/sb-cmd/heartbeat",
  226. json={"nfc_ok": True, "scale_ok": True, "uptime_s": 10},
  227. )
  228. assert resp.status_code == 200
  229. assert resp.json()["pending_command"] == "tare"
  230. # Second heartbeat should have no pending command (cleared)
  231. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  232. mock_ws.broadcast = AsyncMock()
  233. resp2 = await async_client.post(
  234. f"{API}/devices/sb-cmd/heartbeat",
  235. json={"nfc_ok": True, "scale_ok": True, "uptime_s": 20},
  236. )
  237. assert resp2.json()["pending_command"] is None
  238. @pytest.mark.asyncio
  239. @pytest.mark.integration
  240. async def test_heartbeat_unknown_device_404(self, async_client: AsyncClient):
  241. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  242. mock_ws.broadcast = AsyncMock()
  243. resp = await async_client.post(
  244. f"{API}/devices/nonexistent/heartbeat",
  245. json={"nfc_ok": False, "scale_ok": False, "uptime_s": 0},
  246. )
  247. assert resp.status_code == 404
  248. @pytest.mark.asyncio
  249. @pytest.mark.integration
  250. async def test_heartbeat_broadcasts_online_when_was_offline(self, async_client: AsyncClient, device_factory):
  251. # Create device with last_seen far in the past (offline)
  252. spoolbuddy_routes._spoolbuddy_online_last_broadcast.clear()
  253. await device_factory(
  254. device_id="sb-offline",
  255. last_seen=datetime.now(timezone.utc) - timedelta(seconds=120),
  256. )
  257. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  258. mock_ws.broadcast = AsyncMock()
  259. resp = await async_client.post(
  260. f"{API}/devices/sb-offline/heartbeat",
  261. json={"nfc_ok": True, "scale_ok": True, "uptime_s": 5},
  262. )
  263. assert resp.status_code == 200
  264. # Should broadcast online since device was offline
  265. mock_ws.broadcast.assert_called_once()
  266. msg = mock_ws.broadcast.call_args[0][0]
  267. assert msg["type"] == "spoolbuddy_online"
  268. assert msg["device_id"] == "sb-offline"
  269. @pytest.mark.asyncio
  270. @pytest.mark.integration
  271. async def test_heartbeat_broadcasts_online_when_already_online(self, async_client: AsyncClient, device_factory):
  272. spoolbuddy_routes._spoolbuddy_online_last_broadcast.clear()
  273. await device_factory(
  274. device_id="sb-already-online",
  275. last_seen=datetime.now(timezone.utc),
  276. )
  277. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  278. mock_ws.broadcast = AsyncMock()
  279. resp = await async_client.post(
  280. f"{API}/devices/sb-already-online/heartbeat",
  281. json={"nfc_ok": True, "scale_ok": True, "uptime_s": 42},
  282. )
  283. assert resp.status_code == 200
  284. mock_ws.broadcast.assert_called_once()
  285. msg = mock_ws.broadcast.call_args[0][0]
  286. assert msg["type"] == "spoolbuddy_online"
  287. assert msg["device_id"] == "sb-already-online"
  288. @pytest.mark.asyncio
  289. @pytest.mark.integration
  290. async def test_heartbeat_online_broadcast_is_throttled(self, async_client: AsyncClient, device_factory):
  291. spoolbuddy_routes._spoolbuddy_online_last_broadcast.clear()
  292. await device_factory(
  293. device_id="sb-throttle",
  294. last_seen=datetime.now(timezone.utc),
  295. )
  296. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  297. mock_ws.broadcast = AsyncMock()
  298. resp1 = await async_client.post(
  299. f"{API}/devices/sb-throttle/heartbeat",
  300. json={"nfc_ok": True, "scale_ok": True, "uptime_s": 10},
  301. )
  302. resp2 = await async_client.post(
  303. f"{API}/devices/sb-throttle/heartbeat",
  304. json={"nfc_ok": True, "scale_ok": True, "uptime_s": 11},
  305. )
  306. assert resp1.status_code == 200
  307. assert resp2.status_code == 200
  308. mock_ws.broadcast.assert_called_once()
  309. msg = mock_ws.broadcast.call_args[0][0]
  310. assert msg["type"] == "spoolbuddy_online"
  311. assert msg["device_id"] == "sb-throttle"
  312. # ============================================================================
  313. # NFC endpoints
  314. # ============================================================================
  315. class TestNfcEndpoints:
  316. @pytest.mark.asyncio
  317. @pytest.mark.integration
  318. async def test_tag_scanned_matched(self, async_client: AsyncClient, spool_factory):
  319. spool = await spool_factory(tag_uid="AABB1122", material="PLA")
  320. mock_spool = MagicMock()
  321. mock_spool.id = spool.id
  322. mock_spool.material = spool.material
  323. mock_spool.subtype = spool.subtype
  324. mock_spool.color_name = spool.color_name
  325. mock_spool.rgba = spool.rgba
  326. mock_spool.brand = spool.brand
  327. mock_spool.label_weight = spool.label_weight
  328. mock_spool.core_weight = spool.core_weight
  329. mock_spool.weight_used = spool.weight_used
  330. with (
  331. patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws,
  332. patch("backend.app.api.routes.spoolbuddy.get_spool_by_tag", new_callable=AsyncMock) as mock_lookup,
  333. ):
  334. mock_ws.broadcast = AsyncMock()
  335. mock_lookup.return_value = mock_spool
  336. resp = await async_client.post(
  337. f"{API}/nfc/tag-scanned",
  338. json={"device_id": "sb-1", "tag_uid": "AABB1122"},
  339. )
  340. assert resp.status_code == 200
  341. data = resp.json()
  342. assert data["matched"] is True
  343. assert data["spool_id"] == spool.id
  344. msg = mock_ws.broadcast.call_args[0][0]
  345. assert msg["type"] == "spoolbuddy_tag_matched"
  346. assert msg["spool"]["id"] == spool.id
  347. @pytest.mark.asyncio
  348. @pytest.mark.integration
  349. async def test_tag_scanned_unmatched(self, async_client: AsyncClient):
  350. with (
  351. patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws,
  352. patch("backend.app.api.routes.spoolbuddy.get_spool_by_tag", new_callable=AsyncMock) as mock_lookup,
  353. ):
  354. mock_ws.broadcast = AsyncMock()
  355. mock_lookup.return_value = None
  356. resp = await async_client.post(
  357. f"{API}/nfc/tag-scanned",
  358. json={"device_id": "sb-1", "tag_uid": "DEADBEEF"},
  359. )
  360. assert resp.status_code == 200
  361. data = resp.json()
  362. assert data["matched"] is False
  363. assert data["spool_id"] is None
  364. msg = mock_ws.broadcast.call_args[0][0]
  365. assert msg["type"] == "spoolbuddy_unknown_tag"
  366. @pytest.mark.asyncio
  367. @pytest.mark.integration
  368. async def test_tag_scanned_spoolman_mode_skips_local_lookup(self, async_client: AsyncClient, db_session):
  369. """When spoolman_enabled=true, /nfc/tag-scanned must use Spoolman
  370. exclusively — local DB lookup must not be consulted at all. The
  371. previous always-local-first behaviour caused stale local rows to
  372. win over the authoritative Spoolman data (#1228 follow-up).
  373. """
  374. from backend.app.models.settings import Settings
  375. db_session.add(Settings(key="spoolman_enabled", value="true"))
  376. db_session.add(Settings(key="spoolman_url", value="http://127.0.0.1:7912"))
  377. await db_session.commit()
  378. # Mock Spoolman match and verify get_spool_by_tag (the local-DB lookup)
  379. # is never called in Spoolman-enabled mode.
  380. sm_match = {
  381. "id": 7,
  382. "filament": {
  383. "material": "PLA",
  384. "name": "PLA Basic Red",
  385. "color_hex": "FF0000",
  386. "weight": 1000.0,
  387. "vendor": {"name": "Bambu Lab"},
  388. },
  389. "extra": {"tag": '"AABB1122"'},
  390. "used_weight": 0.0,
  391. }
  392. mock_client = MagicMock()
  393. mock_client.has_tag_api = AsyncMock(return_value=False)
  394. mock_client.add_native_tags = AsyncMock(return_value=0)
  395. mock_client.unlink_all_native_tags = AsyncMock()
  396. mock_client.get_spools = AsyncMock(return_value=[sm_match])
  397. mock_client.find_spool_by_tag = AsyncMock(return_value=sm_match)
  398. with (
  399. patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws,
  400. patch(
  401. "backend.app.api.routes.spoolbuddy._get_spoolman_client_or_none",
  402. new_callable=AsyncMock,
  403. ) as mock_get_client,
  404. patch(
  405. "backend.app.api.routes.spoolbuddy.get_spool_by_tag",
  406. new_callable=AsyncMock,
  407. ) as mock_local_lookup,
  408. ):
  409. mock_ws.broadcast = AsyncMock()
  410. mock_get_client.return_value = mock_client
  411. # Sentinel so a misrouted call would surface as a wrong spool_id.
  412. mock_local_lookup.return_value = MagicMock(id=999)
  413. resp = await async_client.post(
  414. f"{API}/nfc/tag-scanned",
  415. json={"device_id": "sb-1", "tag_uid": "AABB1122"},
  416. )
  417. assert resp.status_code == 200
  418. data = resp.json()
  419. assert data["matched"] is True
  420. # Spoolman result, not local DB sentinel — proves the local lookup was skipped.
  421. assert data["spool_id"] == 7
  422. mock_local_lookup.assert_not_called()
  423. @pytest.mark.asyncio
  424. @pytest.mark.integration
  425. async def test_write_result_clears_duplicate_tag_binding(
  426. self, async_client: AsyncClient, db_session, device_factory
  427. ):
  428. """Writing a tag for spool B must clear the same tag binding from any
  429. other spool that currently has it. Without this guard, find_spool_by_tag
  430. returns whichever spool comes first in the cached list (typically the
  431. older one), so the dashboard shows the wrong spool when the tag is
  432. scanned.
  433. """
  434. import json as _json
  435. from backend.app.models.settings import Settings
  436. from backend.app.models.spoolbuddy_device import SpoolBuddyDevice
  437. db_session.add(Settings(key="spoolman_enabled", value="true"))
  438. db_session.add(Settings(key="spoolman_url", value="http://127.0.0.1:7912"))
  439. await device_factory(
  440. device_id="sb-write",
  441. pending_command="write_tag",
  442. pending_write_payload=_json.dumps({"spool_id": 22, "ndef_data_hex": "DEAD", "data_origin": "spoolman"}),
  443. )
  444. await db_session.commit()
  445. # Spool A (id=11) currently holds the tag we're about to bind to spool B (id=22).
  446. spool_a_with_tag = {
  447. "id": 11,
  448. "filament": {"material": "PLA", "name": "PLA Old", "color_hex": "AAAAAA", "weight": 1000.0},
  449. "extra": {"tag": '"DEADBEEF"'},
  450. }
  451. mock_client = MagicMock()
  452. mock_client.has_tag_api = AsyncMock(return_value=False)
  453. mock_client.add_native_tags = AsyncMock(return_value=0)
  454. mock_client.unlink_all_native_tags = AsyncMock()
  455. mock_client.get_spools = AsyncMock(return_value=[spool_a_with_tag])
  456. mock_client.find_spool_by_tag = AsyncMock(return_value=spool_a_with_tag)
  457. mock_client.merge_spool_extra = AsyncMock(return_value={})
  458. with (
  459. patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws,
  460. patch(
  461. "backend.app.api.routes.spoolbuddy._get_spoolman_client_or_none",
  462. new_callable=AsyncMock,
  463. ) as mock_get_client,
  464. ):
  465. mock_ws.broadcast = AsyncMock()
  466. mock_get_client.return_value = mock_client
  467. resp = await async_client.post(
  468. f"{API}/nfc/write-result",
  469. json={
  470. "device_id": "sb-write",
  471. "spool_id": 22,
  472. "tag_uid": "DEADBEEF",
  473. "success": True,
  474. },
  475. )
  476. assert resp.status_code == 200
  477. # merge_spool_extra was called twice:
  478. # 1. clear tag from spool A (id=11) — JSON-encoded "", as Spoolman
  479. # refuses a bare "" (#3312)
  480. # 2. set tag on spool B (id=22) — set tag to "DEADBEEF" (JSON-encoded)
  481. assert mock_client.merge_spool_extra.await_count == 2
  482. clear_call, bind_call = mock_client.merge_spool_extra.await_args_list
  483. assert clear_call.args[0] == 11
  484. assert clear_call.args[1] == {"tag": _json.dumps("")}
  485. assert bind_call.args[0] == 22
  486. assert bind_call.args[1] == {"tag": '"DEADBEEF"'}
  487. @pytest.mark.asyncio
  488. @pytest.mark.integration
  489. async def test_tag_scanned_other_tag_matches_ams_spool_by_tray_uuid(self, async_client: AsyncClient, spool_factory):
  490. """A Bambu spool has two tags with different UIDs but one block-9 tray UUID.
  491. The AMS created the spool from one tag; scanning the other tag on
  492. SpoolBuddy must find that spool through the tray UUID, not offer a
  493. duplicate (#984).
  494. """
  495. spool = await spool_factory(tag_uid="1E783DA000000100", tray_uuid="5E5498918CBF4B94A25EF669C24DECC3")
  496. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  497. mock_ws.broadcast = AsyncMock()
  498. resp = await async_client.post(
  499. f"{API}/nfc/tag-scanned",
  500. json={"device_id": "sb-1", "tag_uid": "8E3A00A2", "tray_uuid": "5E5498918CBF4B94A25EF669C24DECC3"},
  501. )
  502. assert resp.status_code == 200
  503. assert resp.json()["spool_id"] == spool.id
  504. msg = mock_ws.broadcast.call_args[0][0]
  505. assert msg["type"] == "spoolbuddy_tag_matched"
  506. assert msg["tray_uuid"] == "5E5498918CBF4B94A25EF669C24DECC3"
  507. @pytest.mark.asyncio
  508. @pytest.mark.integration
  509. async def test_tag_scanned_unknown_tag_carries_tray_uuid(self, async_client: AsyncClient):
  510. """The kiosk saves the tray UUID from the unknown-tag event on quick-add and link."""
  511. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  512. mock_ws.broadcast = AsyncMock()
  513. resp = await async_client.post(
  514. f"{API}/nfc/tag-scanned",
  515. json={"device_id": "sb-1", "tag_uid": "8E3A00A2", "tray_uuid": "9e0b0717bee94d7887eb1d8dfd1a14f3"},
  516. )
  517. assert resp.json()["matched"] is False
  518. msg = mock_ws.broadcast.call_args[0][0]
  519. assert msg["type"] == "spoolbuddy_unknown_tag"
  520. assert msg["tray_uuid"] == "9E0B0717BEE94D7887EB1D8DFD1A14F3"
  521. @pytest.mark.asyncio
  522. @pytest.mark.integration
  523. async def test_tag_scanned_drops_filament_type_sent_as_tray_uuid(self, async_client: AsyncClient, spool_factory):
  524. """Daemons before #984 sent blocks 4-5 -- the filament type -- as tray_uuid.
  525. That value is the same for every spool of one type, so it must neither
  526. match a spool nor reach the kiosk, where quick-add would save it.
  527. """
  528. pla_matte = "504C41204D6174746500000000000000" # "PLA Matte"
  529. await spool_factory(tag_uid="11111111", tray_uuid=pla_matte)
  530. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  531. mock_ws.broadcast = AsyncMock()
  532. resp = await async_client.post(
  533. f"{API}/nfc/tag-scanned",
  534. json={"device_id": "sb-1", "tag_uid": "22222222", "tray_uuid": pla_matte},
  535. )
  536. assert resp.json()["matched"] is False
  537. msg = mock_ws.broadcast.call_args[0][0]
  538. assert msg["type"] == "spoolbuddy_unknown_tag"
  539. assert msg["tray_uuid"] is None
  540. @pytest.mark.asyncio
  541. @pytest.mark.integration
  542. async def test_tag_scanned_drops_invalid_tray_uuid_but_matches_tag_uid(
  543. self, async_client: AsyncClient, spool_factory
  544. ):
  545. """An old daemon still matches by tag_uid, as before the fix."""
  546. spool = await spool_factory(tag_uid="22222222")
  547. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  548. mock_ws.broadcast = AsyncMock()
  549. resp = await async_client.post(
  550. f"{API}/nfc/tag-scanned",
  551. json={"device_id": "sb-1", "tag_uid": "22222222", "tray_uuid": "504C41204D6174746500000000000000"},
  552. )
  553. assert resp.json()["spool_id"] == spool.id
  554. assert mock_ws.broadcast.call_args[0][0]["tray_uuid"] is None
  555. # Spools added on the kiosk before #984 carry only one tag's UID. A scan that
  556. # matches one by that exact UID saves the tray UUID read from the same tag.
  557. TRAY = "9E0B0717BEE94D7887EB1D8DFD1A14F3"
  558. async def _scan(self, async_client: AsyncClient, tag_uid: str, tray_uuid: str | None, sak: int | None = None):
  559. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  560. mock_ws.broadcast = AsyncMock()
  561. resp = await async_client.post(
  562. f"{API}/nfc/tag-scanned",
  563. json={"device_id": "sb-1", "tag_uid": tag_uid, "tray_uuid": tray_uuid, "sak": sak},
  564. )
  565. assert resp.status_code == 200
  566. return resp.json()
  567. async def _tray_uuid_of(self, db_session: AsyncSession, spool_id: int) -> str | None:
  568. from sqlalchemy import select
  569. db_session.expire_all()
  570. return (await db_session.execute(select(Spool.tray_uuid).where(Spool.id == spool_id))).scalar_one()
  571. @pytest.mark.asyncio
  572. @pytest.mark.integration
  573. async def test_exact_tag_match_saves_tray_uuid(self, async_client: AsyncClient, spool_factory, db_session):
  574. spool_id = (await spool_factory(tag_uid="AABB1122")).id
  575. data = await self._scan(async_client, "AABB1122", self.TRAY)
  576. assert data["spool_id"] == spool_id
  577. assert await self._tray_uuid_of(db_session, spool_id) == self.TRAY
  578. # The spool's other tag now finds it.
  579. assert (await self._scan(async_client, "8E3A00A2", self.TRAY))["spool_id"] == spool_id
  580. @pytest.mark.asyncio
  581. @pytest.mark.integration
  582. async def test_fuzzy_tag_match_saves_nothing(self, async_client: AsyncClient, spool_factory, db_session):
  583. """A first-byte-variance match may be another spool's tag."""
  584. spool = await spool_factory(tag_uid="BABB1122")
  585. data = await self._scan(async_client, "AABB1122", self.TRAY)
  586. assert data["spool_id"] == spool.id
  587. assert await self._tray_uuid_of(db_session, spool.id) is None
  588. @pytest.mark.asyncio
  589. @pytest.mark.integration
  590. async def test_tray_uuid_held_by_another_spool_is_not_copied(
  591. self, async_client: AsyncClient, spool_factory, db_session
  592. ):
  593. from datetime import datetime, timezone
  594. await spool_factory(tag_uid="11111111", tray_uuid=self.TRAY, archived_at=datetime.now(timezone.utc))
  595. spool = await spool_factory(tag_uid="AABB1122")
  596. await self._scan(async_client, "AABB1122", self.TRAY)
  597. assert await self._tray_uuid_of(db_session, spool.id) is None
  598. @pytest.mark.asyncio
  599. @pytest.mark.integration
  600. async def test_existing_tray_uuid_is_kept(self, async_client: AsyncClient, spool_factory, db_session):
  601. other = "5E5498918CBF4B94A25EF669C24DECC3"
  602. spool = await spool_factory(tag_uid="AABB1122", tray_uuid=other)
  603. await self._scan(async_client, "AABB1122", self.TRAY)
  604. assert await self._tray_uuid_of(db_session, spool.id) == other
  605. @pytest.mark.asyncio
  606. @pytest.mark.integration
  607. async def test_full_uid_scan_saves_full_uid_over_cascade_level_1_link(
  608. self, async_client: AsyncClient, spool_factory, db_session
  609. ):
  610. """A spool linked from a level-1 read (#3258) gets the full UID on its first full scan."""
  611. from sqlalchemy import select
  612. spool_id = (await spool_factory(tag_uid="8804ECE6")).id
  613. data = await self._scan(async_client, "04ECE673D32A81", None)
  614. assert data["spool_id"] == spool_id
  615. db_session.expire_all()
  616. stored = (await db_session.execute(select(Spool.tag_uid).where(Spool.id == spool_id))).scalar_one()
  617. assert stored == "04ECE673D32A81"
  618. # A daemon not updated yet still finds it.
  619. assert (await self._scan(async_client, "8804ECE6", None))["spool_id"] == spool_id
  620. @pytest.mark.asyncio
  621. @pytest.mark.integration
  622. async def test_complete_uid_beginning_with_88_is_no_cascade_level_1_read(
  623. self, async_client: AsyncClient, spool_factory
  624. ):
  625. """An old daemon's level-1 read comes with SAK 0x04; a 4-byte clone card's 88 UID with 0x08 (#3258)."""
  626. spool_id = (await spool_factory(tag_uid="04ECE673D32A81")).id
  627. assert (await self._scan(async_client, "8804ECE6", None, sak=0x04))["spool_id"] == spool_id
  628. assert (await self._scan(async_client, "8804ECE6", None, sak=0x08))["matched"] is False
  629. @pytest.mark.asyncio
  630. @pytest.mark.integration
  631. async def test_spoolman_exact_tag_match_stores_tray_uuid_as_tag(self, async_client: AsyncClient):
  632. sm_spool = {
  633. "id": 7,
  634. "filament": {"material": "PLA", "name": "PLA Matte", "color_hex": "008080", "weight": 1000.0},
  635. "extra": {"tag": '"AABB1122"'},
  636. "used_weight": 0.0,
  637. }
  638. mock_client = MagicMock()
  639. mock_client.has_tag_api = AsyncMock(return_value=False)
  640. mock_client.add_native_tags = AsyncMock(return_value=0)
  641. mock_client.unlink_all_native_tags = AsyncMock()
  642. mock_client.get_spools = AsyncMock(return_value=[sm_spool])
  643. mock_client.find_spool_by_tag = AsyncMock(
  644. side_effect=lambda tag, cached_spools=None: sm_spool if tag == "AABB1122" else None
  645. )
  646. mock_client.merge_spool_extra = AsyncMock(return_value={})
  647. with patch(
  648. "backend.app.api.routes.spoolbuddy._get_spoolman_client_or_none",
  649. new_callable=AsyncMock,
  650. return_value=mock_client,
  651. ):
  652. data = await self._scan(async_client, "AABB1122", self.TRAY)
  653. assert data["spool_id"] == 7
  654. mock_client.merge_spool_extra.assert_awaited_once_with(7, {"tag": f'"{self.TRAY}"'})
  655. @pytest.mark.asyncio
  656. @pytest.mark.integration
  657. async def test_spoolman_match_by_tray_uuid_writes_nothing(self, async_client: AsyncClient):
  658. sm_spool = {
  659. "id": 7,
  660. "filament": {"material": "PLA", "name": "PLA Matte", "color_hex": "008080", "weight": 1000.0},
  661. "extra": {"tag": f'"{self.TRAY}"'},
  662. "used_weight": 0.0,
  663. }
  664. mock_client = MagicMock()
  665. mock_client.has_tag_api = AsyncMock(return_value=False)
  666. mock_client.add_native_tags = AsyncMock(return_value=0)
  667. mock_client.unlink_all_native_tags = AsyncMock()
  668. mock_client.get_spools = AsyncMock(return_value=[sm_spool])
  669. mock_client.find_spool_by_tag = AsyncMock(return_value=sm_spool)
  670. mock_client.merge_spool_extra = AsyncMock(return_value={})
  671. with patch(
  672. "backend.app.api.routes.spoolbuddy._get_spoolman_client_or_none",
  673. new_callable=AsyncMock,
  674. return_value=mock_client,
  675. ):
  676. data = await self._scan(async_client, "AABB1122", self.TRAY)
  677. assert data["spool_id"] == 7
  678. mock_client.merge_spool_extra.assert_not_awaited()
  679. @pytest.mark.asyncio
  680. @pytest.mark.integration
  681. async def test_spoolman_write_failure_still_reports_the_match(self, async_client: AsyncClient):
  682. sm_spool = {
  683. "id": 7,
  684. "filament": {"material": "PLA", "name": "PLA Matte", "color_hex": "008080", "weight": 1000.0},
  685. "extra": {"tag": '"AABB1122"'},
  686. "used_weight": 0.0,
  687. }
  688. mock_client = MagicMock()
  689. mock_client.has_tag_api = AsyncMock(return_value=False)
  690. mock_client.add_native_tags = AsyncMock(return_value=0)
  691. mock_client.unlink_all_native_tags = AsyncMock()
  692. mock_client.get_spools = AsyncMock(return_value=[sm_spool])
  693. mock_client.find_spool_by_tag = AsyncMock(
  694. side_effect=lambda tag, cached_spools=None: sm_spool if tag == "AABB1122" else None
  695. )
  696. mock_client.merge_spool_extra = AsyncMock(side_effect=SpoolmanUnavailableError("down"))
  697. with patch(
  698. "backend.app.api.routes.spoolbuddy._get_spoolman_client_or_none",
  699. new_callable=AsyncMock,
  700. return_value=mock_client,
  701. ):
  702. data = await self._scan(async_client, "AABB1122", self.TRAY)
  703. assert data["matched"] is True
  704. assert data["spool_id"] == 7
  705. @pytest.mark.asyncio
  706. @pytest.mark.integration
  707. async def test_tag_removed(self, async_client: AsyncClient):
  708. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  709. mock_ws.broadcast = AsyncMock()
  710. resp = await async_client.post(
  711. f"{API}/nfc/tag-removed",
  712. json={"device_id": "sb-1", "tag_uid": "AABB1122"},
  713. )
  714. assert resp.status_code == 200
  715. msg = mock_ws.broadcast.call_args[0][0]
  716. assert msg["type"] == "spoolbuddy_tag_removed"
  717. assert msg["device_id"] == "sb-1"
  718. assert msg["tag_uid"] == "AABB1122"
  719. # ============================================================================
  720. # NFC write-tag endpoints
  721. # ============================================================================
  722. class TestWriteTagEndpoints:
  723. @pytest.mark.asyncio
  724. @pytest.mark.integration
  725. async def test_write_tag_queues_command(self, async_client: AsyncClient, device_factory, spool_factory):
  726. device = await device_factory(device_id="sb-wt")
  727. spool = await spool_factory(material="PLA", brand="Polymaker", color_name="Red", rgba="FF0000FF")
  728. resp = await async_client.post(
  729. f"{API}/nfc/write-tag",
  730. json={"device_id": device.device_id, "spool_id": spool.id},
  731. )
  732. assert resp.status_code == 200
  733. assert resp.json()["status"] == "queued"
  734. # Verify heartbeat returns write_tag command with payload
  735. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  736. mock_ws.broadcast = AsyncMock()
  737. hb = await async_client.post(
  738. f"{API}/devices/{device.device_id}/heartbeat",
  739. json={"nfc_ok": True, "scale_ok": True, "uptime_s": 10},
  740. )
  741. hb_data = hb.json()
  742. assert hb_data["pending_command"] == "write_tag"
  743. assert hb_data["pending_write_payload"] is not None
  744. assert hb_data["pending_write_payload"]["spool_id"] == spool.id
  745. assert "ndef_data_hex" in hb_data["pending_write_payload"]
  746. @pytest.mark.asyncio
  747. @pytest.mark.integration
  748. async def test_write_tag_heartbeat_not_cleared(self, async_client: AsyncClient, device_factory, spool_factory):
  749. """write_tag command persists across heartbeats until write-result clears it."""
  750. device = await device_factory(device_id="sb-wt-persist")
  751. spool = await spool_factory(material="PETG")
  752. await async_client.post(
  753. f"{API}/nfc/write-tag",
  754. json={"device_id": device.device_id, "spool_id": spool.id},
  755. )
  756. # First heartbeat — command present
  757. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  758. mock_ws.broadcast = AsyncMock()
  759. hb1 = await async_client.post(
  760. f"{API}/devices/{device.device_id}/heartbeat",
  761. json={"nfc_ok": True, "scale_ok": True, "uptime_s": 10},
  762. )
  763. assert hb1.json()["pending_command"] == "write_tag"
  764. # Second heartbeat — should still be present (not cleared like tare)
  765. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  766. mock_ws.broadcast = AsyncMock()
  767. hb2 = await async_client.post(
  768. f"{API}/devices/{device.device_id}/heartbeat",
  769. json={"nfc_ok": True, "scale_ok": True, "uptime_s": 20},
  770. )
  771. assert hb2.json()["pending_command"] == "write_tag"
  772. @pytest.mark.asyncio
  773. @pytest.mark.integration
  774. async def test_write_tag_missing_spool_404(self, async_client: AsyncClient, device_factory):
  775. device = await device_factory(device_id="sb-wt-nospool")
  776. resp = await async_client.post(
  777. f"{API}/nfc/write-tag",
  778. json={"device_id": device.device_id, "spool_id": 99999},
  779. )
  780. assert resp.status_code == 404
  781. @pytest.mark.asyncio
  782. @pytest.mark.integration
  783. async def test_write_tag_missing_device_404(self, async_client: AsyncClient, spool_factory):
  784. spool = await spool_factory()
  785. resp = await async_client.post(
  786. f"{API}/nfc/write-tag",
  787. json={"device_id": "nonexistent", "spool_id": spool.id},
  788. )
  789. assert resp.status_code == 404
  790. @pytest.mark.asyncio
  791. @pytest.mark.integration
  792. async def test_write_result_success_links_tag(self, async_client: AsyncClient, device_factory, spool_factory):
  793. device = await device_factory(device_id="sb-wr", pending_command="write_tag")
  794. spool = await spool_factory(material="PLA", tag_uid=None)
  795. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  796. mock_ws.broadcast = AsyncMock()
  797. resp = await async_client.post(
  798. f"{API}/nfc/write-result",
  799. json={
  800. "device_id": device.device_id,
  801. "spool_id": spool.id,
  802. "tag_uid": "04AABB11223344",
  803. "success": True,
  804. },
  805. )
  806. assert resp.status_code == 200
  807. msg = mock_ws.broadcast.call_args[0][0]
  808. assert msg["type"] == "spoolbuddy_tag_written"
  809. assert msg["spool_id"] == spool.id
  810. assert msg["tag_uid"] == "04AABB11223344"
  811. # Verify spool got tag linked
  812. spool_resp = await async_client.get(f"/api/v1/inventory/spools/{spool.id}")
  813. spool_data = spool_resp.json()
  814. assert spool_data["tag_uid"] == "04AABB11223344"
  815. assert spool_data["tag_type"] == "ntag"
  816. assert spool_data["data_origin"] == "opentag3d"
  817. assert spool_data["encode_time"] is not None
  818. @pytest.mark.asyncio
  819. @pytest.mark.integration
  820. async def test_write_result_failure_broadcasts_error(
  821. self, async_client: AsyncClient, device_factory, spool_factory
  822. ):
  823. device = await device_factory(device_id="sb-wr-fail", pending_command="write_tag")
  824. spool = await spool_factory(material="PLA", tag_uid=None)
  825. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  826. mock_ws.broadcast = AsyncMock()
  827. resp = await async_client.post(
  828. f"{API}/nfc/write-result",
  829. json={
  830. "device_id": device.device_id,
  831. "spool_id": spool.id,
  832. "tag_uid": "04AABBCC",
  833. "success": False,
  834. "message": "Write or verification failed",
  835. },
  836. )
  837. assert resp.status_code == 200
  838. msg = mock_ws.broadcast.call_args[0][0]
  839. assert msg["type"] == "spoolbuddy_tag_write_failed"
  840. assert msg["message"] == "Write or verification failed"
  841. # Verify spool NOT linked
  842. spool_resp = await async_client.get(f"/api/v1/inventory/spools/{spool.id}")
  843. assert spool_resp.json()["tag_uid"] is None
  844. @pytest.mark.asyncio
  845. @pytest.mark.integration
  846. async def test_write_result_clears_pending_command(self, async_client: AsyncClient, device_factory, spool_factory):
  847. device = await device_factory(
  848. device_id="sb-wr-clear",
  849. pending_command="write_tag",
  850. pending_write_payload='{"spool_id": 1, "ndef_data_hex": "E110120003"}',
  851. )
  852. spool = await spool_factory()
  853. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  854. mock_ws.broadcast = AsyncMock()
  855. await async_client.post(
  856. f"{API}/nfc/write-result",
  857. json={
  858. "device_id": device.device_id,
  859. "spool_id": spool.id,
  860. "tag_uid": "AABBCCDD",
  861. "success": True,
  862. },
  863. )
  864. # Heartbeat should have no pending command
  865. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  866. mock_ws.broadcast = AsyncMock()
  867. hb = await async_client.post(
  868. f"{API}/devices/{device.device_id}/heartbeat",
  869. json={"nfc_ok": True, "scale_ok": True, "uptime_s": 30},
  870. )
  871. assert hb.json()["pending_command"] is None
  872. assert hb.json()["pending_write_payload"] is None
  873. @pytest.mark.asyncio
  874. @pytest.mark.integration
  875. async def test_cancel_write(self, async_client: AsyncClient, device_factory, spool_factory):
  876. device = await device_factory(device_id="sb-cancel")
  877. spool = await spool_factory()
  878. # Queue a write
  879. await async_client.post(
  880. f"{API}/nfc/write-tag",
  881. json={"device_id": device.device_id, "spool_id": spool.id},
  882. )
  883. # Cancel it
  884. resp = await async_client.post(f"{API}/devices/{device.device_id}/cancel-write", json={})
  885. assert resp.status_code == 200
  886. # Heartbeat should have no pending command
  887. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  888. mock_ws.broadcast = AsyncMock()
  889. hb = await async_client.post(
  890. f"{API}/devices/{device.device_id}/heartbeat",
  891. json={"nfc_ok": True, "scale_ok": True, "uptime_s": 10},
  892. )
  893. assert hb.json()["pending_command"] is None
  894. @pytest.mark.asyncio
  895. @pytest.mark.integration
  896. async def test_cancel_write_unknown_device_404(self, async_client: AsyncClient):
  897. resp = await async_client.post(f"{API}/devices/ghost/cancel-write", json={})
  898. assert resp.status_code == 404
  899. @pytest.mark.asyncio
  900. @pytest.mark.integration
  901. async def test_write_tag_ndef_data_is_valid(self, async_client: AsyncClient, device_factory, spool_factory):
  902. """Verify the NDEF data in the heartbeat is a valid OpenTag3D message."""
  903. device = await device_factory(device_id="sb-wt-ndef")
  904. spool = await spool_factory(
  905. material="PLA",
  906. brand="Polymaker",
  907. color_name="White",
  908. rgba="FFFFFFFF",
  909. label_weight=1000,
  910. )
  911. await async_client.post(
  912. f"{API}/nfc/write-tag",
  913. json={"device_id": device.device_id, "spool_id": spool.id},
  914. )
  915. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  916. mock_ws.broadcast = AsyncMock()
  917. hb = await async_client.post(
  918. f"{API}/devices/{device.device_id}/heartbeat",
  919. json={"nfc_ok": True, "scale_ok": True, "uptime_s": 10},
  920. )
  921. payload = hb.json()["pending_write_payload"]
  922. ndef_bytes = bytes.fromhex(payload["ndef_data_hex"])
  923. # CC bytes
  924. assert ndef_bytes[:4] == bytes([0xE1, 0x10, 0x12, 0x00])
  925. # TLV type
  926. assert ndef_bytes[4] == 0x03
  927. # NDEF record: TNF=MIME, type=application/opentag3d
  928. assert ndef_bytes[6] == 0xD2
  929. assert ndef_bytes[9:30] == b"application/opentag3d"
  930. # Terminator
  931. assert ndef_bytes[-1] == 0xFE
  932. # Total size fits NTAG213
  933. assert len(ndef_bytes) <= 144
  934. # ============================================================================
  935. # Scale endpoints
  936. # ============================================================================
  937. class TestScaleEndpoints:
  938. @pytest.mark.asyncio
  939. @pytest.mark.integration
  940. async def test_scale_reading_broadcast(self, async_client: AsyncClient):
  941. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  942. mock_ws.broadcast = AsyncMock()
  943. resp = await async_client.post(
  944. f"{API}/scale/reading",
  945. json={
  946. "device_id": "sb-1",
  947. "weight_grams": 823.5,
  948. "stable": True,
  949. "raw_adc": 456789,
  950. },
  951. )
  952. assert resp.status_code == 200
  953. msg = mock_ws.broadcast.call_args[0][0]
  954. assert msg["type"] == "spoolbuddy_weight"
  955. assert msg["device_id"] == "sb-1"
  956. assert msg["weight_grams"] == 823.5
  957. assert msg["stable"] is True
  958. assert msg["raw_adc"] == 456789
  959. @pytest.mark.asyncio
  960. @pytest.mark.integration
  961. async def test_update_spool_weight_calculates_correctly(self, async_client: AsyncClient, spool_factory):
  962. # label=1000g, core=250g, scale reads 750g
  963. # net_filament = max(0, 750 - 250) = 500
  964. # weight_used = max(0, 1000 - 500) = 500
  965. spool = await spool_factory(label_weight=1000, core_weight=250, weight_used=0)
  966. resp = await async_client.post(
  967. f"{API}/scale/update-spool-weight",
  968. json={"spool_id": spool.id, "weight_grams": 750},
  969. )
  970. assert resp.status_code == 200
  971. data = resp.json()
  972. assert data["weight_used"] == 500
  973. @pytest.mark.asyncio
  974. @pytest.mark.integration
  975. async def test_update_spool_weight_full_spool(self, async_client: AsyncClient, spool_factory):
  976. # label=1000g, core=250g, scale reads 1250g (full spool)
  977. # net_filament = max(0, 1250 - 250) = 1000
  978. # weight_used = max(0, 1000 - 1000) = 0
  979. spool = await spool_factory(label_weight=1000, core_weight=250, weight_used=200)
  980. resp = await async_client.post(
  981. f"{API}/scale/update-spool-weight",
  982. json={"spool_id": spool.id, "weight_grams": 1250},
  983. )
  984. assert resp.status_code == 200
  985. data = resp.json()
  986. assert data["weight_used"] == 0
  987. @pytest.mark.asyncio
  988. @pytest.mark.integration
  989. async def test_update_spool_weight_stores_scale_reading(self, async_client: AsyncClient, spool_factory):
  990. """Verify last_scale_weight and last_weighed_at are stored after weight sync."""
  991. spool = await spool_factory(label_weight=1000, core_weight=250, weight_used=0)
  992. resp = await async_client.post(
  993. f"{API}/scale/update-spool-weight",
  994. json={"spool_id": spool.id, "weight_grams": 750},
  995. )
  996. assert resp.status_code == 200
  997. # Fetch the spool via inventory API to verify stored fields
  998. spool_resp = await async_client.get(f"/api/v1/inventory/spools/{spool.id}")
  999. assert spool_resp.status_code == 200
  1000. spool_data = spool_resp.json()
  1001. assert spool_data["last_scale_weight"] == 750
  1002. assert spool_data["last_weighed_at"] is not None
  1003. @pytest.mark.asyncio
  1004. @pytest.mark.integration
  1005. async def test_update_spool_weight_missing_spool_404(self, async_client: AsyncClient):
  1006. resp = await async_client.post(
  1007. f"{API}/scale/update-spool-weight",
  1008. json={"spool_id": 99999, "weight_grams": 500},
  1009. )
  1010. assert resp.status_code == 404
  1011. # ============================================================================
  1012. # Calibration endpoints
  1013. # ============================================================================
  1014. class TestCalibrationEndpoints:
  1015. @pytest.mark.asyncio
  1016. @pytest.mark.integration
  1017. async def test_tare_queues_command(self, async_client: AsyncClient, device_factory):
  1018. await device_factory(device_id="sb-tare")
  1019. resp = await async_client.post(f"{API}/devices/sb-tare/calibration/tare", json={})
  1020. assert resp.status_code == 200
  1021. assert resp.json()["status"] == "ok"
  1022. # Verify pending_command via heartbeat
  1023. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  1024. mock_ws.broadcast = AsyncMock()
  1025. hb = await async_client.post(
  1026. f"{API}/devices/sb-tare/heartbeat",
  1027. json={"nfc_ok": True, "scale_ok": True, "uptime_s": 1},
  1028. )
  1029. assert hb.json()["pending_command"] == "tare"
  1030. @pytest.mark.asyncio
  1031. @pytest.mark.integration
  1032. async def test_tare_unknown_device_404(self, async_client: AsyncClient):
  1033. resp = await async_client.post(f"{API}/devices/ghost/calibration/tare", json={})
  1034. assert resp.status_code == 404
  1035. @pytest.mark.asyncio
  1036. @pytest.mark.integration
  1037. async def test_set_tare_offset(self, async_client: AsyncClient, device_factory):
  1038. await device_factory(device_id="sb-st", calibration_factor=0.005)
  1039. resp = await async_client.post(
  1040. f"{API}/devices/sb-st/calibration/set-tare",
  1041. json={"tare_offset": 54321},
  1042. )
  1043. assert resp.status_code == 200
  1044. data = resp.json()
  1045. assert data["tare_offset"] == 54321
  1046. assert data["calibration_factor"] == pytest.approx(0.005)
  1047. @pytest.mark.asyncio
  1048. @pytest.mark.integration
  1049. async def test_set_calibration_factor(self, async_client: AsyncClient, device_factory):
  1050. # known_weight=200g, raw_adc=50000, tare=10000 → factor=200/(50000-10000)=0.005
  1051. await device_factory(device_id="sb-cf", tare_offset=10000)
  1052. resp = await async_client.post(
  1053. f"{API}/devices/sb-cf/calibration/set-factor",
  1054. json={"known_weight_grams": 200, "raw_adc": 50000},
  1055. )
  1056. assert resp.status_code == 200
  1057. data = resp.json()
  1058. assert data["calibration_factor"] == pytest.approx(0.005)
  1059. assert data["tare_offset"] == 10000
  1060. @pytest.mark.asyncio
  1061. @pytest.mark.integration
  1062. async def test_set_calibration_factor_zero_delta_400(self, async_client: AsyncClient, device_factory):
  1063. # raw_adc == tare_offset → delta is 0 → 400 error
  1064. await device_factory(device_id="sb-zero", tare_offset=5000)
  1065. resp = await async_client.post(
  1066. f"{API}/devices/sb-zero/calibration/set-factor",
  1067. json={"known_weight_grams": 100, "raw_adc": 5000},
  1068. )
  1069. assert resp.status_code == 400
  1070. @pytest.mark.asyncio
  1071. @pytest.mark.integration
  1072. async def test_get_calibration(self, async_client: AsyncClient, device_factory):
  1073. await device_factory(
  1074. device_id="sb-gcal",
  1075. tare_offset=11111,
  1076. calibration_factor=0.0042,
  1077. )
  1078. resp = await async_client.get(f"{API}/devices/sb-gcal/calibration")
  1079. assert resp.status_code == 200
  1080. data = resp.json()
  1081. assert data["tare_offset"] == 11111
  1082. assert data["calibration_factor"] == pytest.approx(0.0042)
  1083. # ============================================================================
  1084. # Display endpoints
  1085. # ============================================================================
  1086. class TestDisplayEndpoints:
  1087. @pytest.mark.asyncio
  1088. @pytest.mark.integration
  1089. async def test_update_display_settings(self, async_client: AsyncClient, device_factory):
  1090. await device_factory(device_id="sb-disp", display_brightness=100, display_blank_timeout=0)
  1091. resp = await async_client.put(
  1092. f"{API}/devices/sb-disp/display",
  1093. json={"brightness": 75, "blank_timeout": 300},
  1094. )
  1095. assert resp.status_code == 200
  1096. data = resp.json()
  1097. assert data["brightness"] == 75
  1098. assert data["blank_timeout"] == 300
  1099. @pytest.mark.asyncio
  1100. @pytest.mark.integration
  1101. async def test_update_display_persists_via_heartbeat(self, async_client: AsyncClient, device_factory):
  1102. await device_factory(device_id="sb-disp-hb")
  1103. await async_client.put(
  1104. f"{API}/devices/sb-disp-hb/display",
  1105. json={"brightness": 50, "blank_timeout": 600},
  1106. )
  1107. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  1108. mock_ws.broadcast = AsyncMock()
  1109. hb = await async_client.post(
  1110. f"{API}/devices/sb-disp-hb/heartbeat",
  1111. json={"nfc_ok": True, "scale_ok": True, "uptime_s": 10},
  1112. )
  1113. assert hb.json()["display_brightness"] == 50
  1114. assert hb.json()["display_blank_timeout"] == 600
  1115. @pytest.mark.asyncio
  1116. @pytest.mark.integration
  1117. async def test_update_display_unknown_device_404(self, async_client: AsyncClient):
  1118. resp = await async_client.put(
  1119. f"{API}/devices/ghost/display",
  1120. json={"brightness": 50, "blank_timeout": 60},
  1121. )
  1122. assert resp.status_code == 404
  1123. @pytest.mark.asyncio
  1124. @pytest.mark.integration
  1125. async def test_update_display_validates_brightness(self, async_client: AsyncClient, device_factory):
  1126. await device_factory(device_id="sb-disp-val")
  1127. resp = await async_client.put(
  1128. f"{API}/devices/sb-disp-val/display",
  1129. json={"brightness": 150, "blank_timeout": 0},
  1130. )
  1131. assert resp.status_code == 422 # Validation error: brightness > 100
  1132. @pytest.mark.asyncio
  1133. @pytest.mark.integration
  1134. async def test_get_display_settings(self, async_client: AsyncClient, device_factory):
  1135. """The kiosk idle watchdog (install/spoolbuddy-idle.sh) reads this
  1136. endpoint on autostart to configure swayidle with the user-selected
  1137. blank timeout before launching. See issue #937."""
  1138. await device_factory(device_id="sb-disp-get", display_brightness=60, display_blank_timeout=450)
  1139. resp = await async_client.get(f"{API}/devices/sb-disp-get/display")
  1140. assert resp.status_code == 200
  1141. data = resp.json()
  1142. assert data["brightness"] == 60
  1143. assert data["blank_timeout"] == 450
  1144. @pytest.mark.asyncio
  1145. @pytest.mark.integration
  1146. async def test_get_display_unknown_device_404(self, async_client: AsyncClient):
  1147. resp = await async_client.get(f"{API}/devices/ghost/display")
  1148. assert resp.status_code == 404
  1149. # ============================================================================
  1150. # Update endpoints
  1151. # ============================================================================
  1152. class TestUpdateEndpoints:
  1153. @pytest.mark.asyncio
  1154. @pytest.mark.integration
  1155. async def test_trigger_update_starts_ssh_update(self, async_client: AsyncClient, device_factory):
  1156. await device_factory(device_id="sb-upd")
  1157. with (
  1158. patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws,
  1159. patch("backend.app.services.spoolbuddy_ssh.perform_ssh_update", new_callable=AsyncMock),
  1160. ):
  1161. mock_ws.broadcast = AsyncMock()
  1162. resp = await async_client.post(f"{API}/devices/sb-upd/update")
  1163. assert resp.status_code == 200
  1164. assert resp.json()["status"] == "ok"
  1165. @pytest.mark.asyncio
  1166. @pytest.mark.integration
  1167. async def test_trigger_update_offline_device_409(self, async_client: AsyncClient, device_factory):
  1168. await device_factory(
  1169. device_id="sb-upd-off",
  1170. last_seen=datetime.now(timezone.utc) - timedelta(seconds=120),
  1171. )
  1172. resp = await async_client.post(f"{API}/devices/sb-upd-off/update")
  1173. assert resp.status_code == 409
  1174. @pytest.mark.asyncio
  1175. @pytest.mark.integration
  1176. async def test_trigger_update_unknown_device_404(self, async_client: AsyncClient):
  1177. resp = await async_client.post(f"{API}/devices/ghost/update")
  1178. assert resp.status_code == 404
  1179. @pytest.mark.asyncio
  1180. @pytest.mark.integration
  1181. async def test_trigger_update_already_updating(self, async_client: AsyncClient, device_factory):
  1182. await device_factory(device_id="sb-upd-dup", update_status="updating")
  1183. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  1184. mock_ws.broadcast = AsyncMock()
  1185. resp = await async_client.post(f"{API}/devices/sb-upd-dup/update")
  1186. assert resp.status_code == 200
  1187. assert resp.json()["status"] == "already_updating"
  1188. @pytest.mark.asyncio
  1189. @pytest.mark.integration
  1190. async def test_ssh_public_key_error_does_not_leak_exception_text(self, async_client: AsyncClient):
  1191. """SSH public-key 500 must not expose raw exception details (M3)."""
  1192. from backend.app.services.spoolbuddy_ssh import get_public_key
  1193. with patch(
  1194. "backend.app.services.spoolbuddy_ssh.get_public_key",
  1195. AsyncMock(side_effect=RuntimeError("REDACT_ME internal path /data/keys/id_ed25519")),
  1196. ):
  1197. resp = await async_client.get(f"{API}/ssh/public-key")
  1198. assert resp.status_code == 500
  1199. body = resp.json()["detail"]
  1200. assert "REDACT_ME" not in body
  1201. assert "/data/keys" not in body
  1202. assert "id_ed25519" not in body
  1203. @pytest.mark.asyncio
  1204. @pytest.mark.integration
  1205. async def test_device_response_includes_update_fields(self, async_client: AsyncClient, device_factory):
  1206. await device_factory(device_id="sb-upd-resp", update_status="complete", update_message="Done!")
  1207. resp = await async_client.get(f"{API}/devices")
  1208. assert resp.status_code == 200
  1209. device = next(d for d in resp.json() if d["device_id"] == "sb-upd-resp")
  1210. assert device["update_status"] == "complete"
  1211. assert device["update_message"] == "Done!"
  1212. @pytest.mark.asyncio
  1213. @pytest.mark.integration
  1214. async def test_update_check_returns_version_info(self, async_client: AsyncClient, device_factory):
  1215. """GET /devices/{id}/update-check compares device version against APP_VERSION."""
  1216. await device_factory(device_id="sb-uc", firmware_version="0.1.0")
  1217. resp = await async_client.get(f"{API}/devices/sb-uc/update-check")
  1218. assert resp.status_code == 200
  1219. data = resp.json()
  1220. assert data["current_version"] == "0.1.0"
  1221. assert data["latest_version"] is not None
  1222. assert data["update_available"] is True
  1223. @pytest.mark.asyncio
  1224. @pytest.mark.integration
  1225. async def test_update_check_up_to_date(self, async_client: AsyncClient, device_factory):
  1226. from backend.app.core.config import APP_VERSION
  1227. await device_factory(device_id="sb-uc2", firmware_version=APP_VERSION)
  1228. resp = await async_client.get(f"{API}/devices/sb-uc2/update-check")
  1229. assert resp.status_code == 200
  1230. assert resp.json()["update_available"] is False
  1231. @pytest.mark.asyncio
  1232. @pytest.mark.integration
  1233. async def test_update_check_unknown_device_404(self, async_client: AsyncClient):
  1234. resp = await async_client.get(f"{API}/devices/ghost/update-check")
  1235. assert resp.status_code == 404
  1236. @pytest.mark.asyncio
  1237. @pytest.mark.integration
  1238. async def test_trigger_update_broadcasts_websocket(self, async_client: AsyncClient, device_factory):
  1239. await device_factory(device_id="sb-upd-ws")
  1240. with (
  1241. patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws,
  1242. patch("backend.app.services.spoolbuddy_ssh.perform_ssh_update", new_callable=AsyncMock),
  1243. ):
  1244. mock_ws.broadcast = AsyncMock()
  1245. await async_client.post(f"{API}/devices/sb-upd-ws/update")
  1246. mock_ws.broadcast.assert_called_once()
  1247. msg = mock_ws.broadcast.call_args[0][0]
  1248. assert msg["type"] == "spoolbuddy_update"
  1249. assert msg["device_id"] == "sb-upd-ws"
  1250. assert msg["update_status"] == "pending"
  1251. # ============================================================================
  1252. # System command endpoints
  1253. # ============================================================================
  1254. class TestSystemCommandEndpoints:
  1255. @pytest.mark.asyncio
  1256. @pytest.mark.integration
  1257. async def test_queue_reboot(self, async_client: AsyncClient, device_factory):
  1258. await device_factory(device_id="sb-reboot")
  1259. resp = await async_client.post(
  1260. f"{API}/devices/sb-reboot/system/command",
  1261. json={"command": "reboot"},
  1262. )
  1263. assert resp.status_code == 200
  1264. data = resp.json()
  1265. assert data["status"] == "queued"
  1266. assert data["command"] == "reboot"
  1267. @pytest.mark.asyncio
  1268. @pytest.mark.integration
  1269. async def test_queue_shutdown(self, async_client: AsyncClient, device_factory):
  1270. await device_factory(device_id="sb-shutdown")
  1271. resp = await async_client.post(
  1272. f"{API}/devices/sb-shutdown/system/command",
  1273. json={"command": "shutdown"},
  1274. )
  1275. assert resp.status_code == 200
  1276. assert resp.json()["command"] == "shutdown"
  1277. @pytest.mark.asyncio
  1278. @pytest.mark.integration
  1279. async def test_queue_restart_daemon(self, async_client: AsyncClient, device_factory):
  1280. await device_factory(device_id="sb-rd")
  1281. resp = await async_client.post(
  1282. f"{API}/devices/sb-rd/system/command",
  1283. json={"command": "restart_daemon"},
  1284. )
  1285. assert resp.status_code == 200
  1286. assert resp.json()["command"] == "restart_daemon"
  1287. @pytest.mark.asyncio
  1288. @pytest.mark.integration
  1289. async def test_queue_restart_browser(self, async_client: AsyncClient, device_factory):
  1290. await device_factory(device_id="sb-rb")
  1291. resp = await async_client.post(
  1292. f"{API}/devices/sb-rb/system/command",
  1293. json={"command": "restart_browser"},
  1294. )
  1295. assert resp.status_code == 200
  1296. assert resp.json()["command"] == "restart_browser"
  1297. @pytest.mark.asyncio
  1298. @pytest.mark.integration
  1299. async def test_invalid_command_rejected(self, async_client: AsyncClient, device_factory):
  1300. await device_factory(device_id="sb-invalid")
  1301. resp = await async_client.post(
  1302. f"{API}/devices/sb-invalid/system/command",
  1303. json={"command": "format_disk"},
  1304. )
  1305. assert resp.status_code == 400
  1306. assert "Invalid command" in resp.json()["detail"]
  1307. @pytest.mark.asyncio
  1308. @pytest.mark.integration
  1309. async def test_command_unknown_device_404(self, async_client: AsyncClient):
  1310. resp = await async_client.post(
  1311. f"{API}/devices/ghost/system/command",
  1312. json={"command": "reboot"},
  1313. )
  1314. assert resp.status_code == 404
  1315. @pytest.mark.asyncio
  1316. @pytest.mark.integration
  1317. async def test_command_offline_device_409(self, async_client: AsyncClient, device_factory):
  1318. await device_factory(
  1319. device_id="sb-offline-cmd",
  1320. last_seen=datetime.now(timezone.utc) - timedelta(seconds=120),
  1321. )
  1322. resp = await async_client.post(
  1323. f"{API}/devices/sb-offline-cmd/system/command",
  1324. json={"command": "reboot"},
  1325. )
  1326. assert resp.status_code == 409
  1327. assert "offline" in resp.json()["detail"].lower()
  1328. @pytest.mark.asyncio
  1329. @pytest.mark.integration
  1330. async def test_command_sets_pending_command(self, async_client: AsyncClient, device_factory, db_session):
  1331. device = await device_factory(device_id="sb-pending")
  1332. await async_client.post(
  1333. f"{API}/devices/sb-pending/system/command",
  1334. json={"command": "restart_daemon"},
  1335. )
  1336. await db_session.refresh(device)
  1337. assert device.pending_command == "restart_daemon"
  1338. @pytest.mark.asyncio
  1339. @pytest.mark.integration
  1340. async def test_heartbeat_clears_system_command(self, async_client: AsyncClient, device_factory):
  1341. """System commands (reboot/shutdown/restart_*) are fire-and-forget — heartbeat clears them."""
  1342. await device_factory(device_id="sb-hb-clear")
  1343. # Queue a command
  1344. await async_client.post(
  1345. f"{API}/devices/sb-hb-clear/system/command",
  1346. json={"command": "restart_browser"},
  1347. )
  1348. # Heartbeat should return the command and clear it
  1349. resp = await async_client.post(
  1350. f"{API}/devices/sb-hb-clear/heartbeat",
  1351. json={"nfc_ok": True, "scale_ok": True, "uptime_s": 100},
  1352. )
  1353. assert resp.status_code == 200
  1354. data = resp.json()
  1355. assert data["pending_command"] == "restart_browser"
  1356. # ============================================================================
  1357. # Spoolman-aware SpoolBuddy endpoints
  1358. # ============================================================================
  1359. @pytest.fixture
  1360. async def spoolman_settings(db_session: AsyncSession):
  1361. """Create Spoolman settings in the database (enabled with URL)."""
  1362. from backend.app.models.settings import Settings
  1363. settings = [
  1364. Settings(key="spoolman_enabled", value="true"),
  1365. Settings(key="spoolman_url", value="http://spoolman.local:7912"),
  1366. ]
  1367. for s in settings:
  1368. db_session.add(s)
  1369. await db_session.commit()
  1370. return settings
  1371. def _mock_spoolman_client(base_url: str = "http://spoolman.local:7912") -> MagicMock:
  1372. client = MagicMock()
  1373. client.has_tag_api = AsyncMock(return_value=False)
  1374. client.add_native_tags = AsyncMock(return_value=0)
  1375. client.unlink_all_native_tags = AsyncMock()
  1376. client.base_url = base_url
  1377. client.get_spools = AsyncMock(return_value=[])
  1378. client.get_spool = AsyncMock(return_value={})
  1379. client.find_spool_by_tag = AsyncMock(return_value=None)
  1380. client.update_spool = AsyncMock(return_value=None)
  1381. client.merge_spool_extra = AsyncMock(return_value={"id": 0})
  1382. return client
  1383. def _spoolman_spool_fixture(
  1384. spool_id: int,
  1385. spool_weight: float = 196.0,
  1386. filament_weight: float = 1000.0,
  1387. spool_level_spool_weight=None,
  1388. ) -> dict:
  1389. """Build a minimal Spoolman spool dict with realistic core weight from filament.spool_weight."""
  1390. raw = {
  1391. "id": spool_id,
  1392. "filament": {"weight": filament_weight, "spool_weight": spool_weight},
  1393. "used_weight": 0.0,
  1394. }
  1395. if spool_level_spool_weight is not None:
  1396. raw["spool_weight"] = spool_level_spool_weight
  1397. return raw
  1398. class TestUpdateSpoolWeightSpoolman:
  1399. """update-spool-weight routes to Spoolman when Spoolman mode is active."""
  1400. @pytest.mark.asyncio
  1401. @pytest.mark.integration
  1402. async def test_spoolman_mode_uses_filament_spool_weight(self, async_client: AsyncClient, spoolman_settings):
  1403. """core_weight comes from filament.spool_weight, not a hardcoded constant."""
  1404. sm_spool = _spoolman_spool_fixture(42, spool_weight=196.0, filament_weight=1000.0)
  1405. mock_client = _mock_spoolman_client()
  1406. mock_client.get_spool = AsyncMock(return_value=sm_spool)
  1407. mock_client.update_spool = AsyncMock(return_value=sm_spool)
  1408. with (
  1409. patch(
  1410. "backend.app.services.spoolman.get_spoolman_client",
  1411. AsyncMock(return_value=mock_client),
  1412. ),
  1413. patch(
  1414. "backend.app.services.spoolman.init_spoolman_client",
  1415. AsyncMock(return_value=mock_client),
  1416. ),
  1417. ):
  1418. resp = await async_client.post(
  1419. f"{API}/scale/update-spool-weight",
  1420. json={"spool_id": 42, "weight_grams": 750},
  1421. )
  1422. assert resp.status_code == 200
  1423. data = resp.json()
  1424. assert data["status"] == "ok"
  1425. # remaining = max(0, 750 - 196) = 554 → weight_used = 1000 - 554 = 446
  1426. assert data["weight_used"] == pytest.approx(446.0)
  1427. mock_client.update_spool.assert_called_once_with(spool_id=42, remaining_weight=pytest.approx(554.0))
  1428. @pytest.mark.asyncio
  1429. @pytest.mark.integration
  1430. async def test_spoolman_mode_announces_the_weight(self, async_client: AsyncClient, spoolman_settings):
  1431. """WU-9: other open Inventory tabs refresh only on inventory_changed."""
  1432. sm_spool = _spoolman_spool_fixture(42, spool_weight=196.0, filament_weight=1000.0)
  1433. mock_client = _mock_spoolman_client()
  1434. mock_client.get_spool = AsyncMock(return_value=sm_spool)
  1435. mock_client.update_spool = AsyncMock(return_value=sm_spool)
  1436. with (
  1437. patch("backend.app.services.spoolman.get_spoolman_client", AsyncMock(return_value=mock_client)),
  1438. patch("backend.app.services.spoolman.init_spoolman_client", AsyncMock(return_value=mock_client)),
  1439. patch("backend.app.api.routes.spoolbuddy.ws_manager") as ws,
  1440. ):
  1441. ws.broadcast = AsyncMock()
  1442. await async_client.post(f"{API}/scale/update-spool-weight", json={"spool_id": 42, "weight_grams": 750})
  1443. assert {"type": "inventory_changed"} in [c.args[0] for c in ws.broadcast.call_args_list]
  1444. @pytest.mark.asyncio
  1445. @pytest.mark.integration
  1446. async def test_spoolman_mode_clamps_remaining_to_zero(self, async_client: AsyncClient, spoolman_settings):
  1447. """Scale weight below core weight → remaining_weight = 0."""
  1448. sm_spool = _spoolman_spool_fixture(7, spool_weight=196.0, filament_weight=1000.0)
  1449. mock_client = _mock_spoolman_client()
  1450. mock_client.get_spool = AsyncMock(return_value=sm_spool)
  1451. mock_client.update_spool = AsyncMock(return_value=sm_spool)
  1452. with (
  1453. patch(
  1454. "backend.app.services.spoolman.get_spoolman_client",
  1455. AsyncMock(return_value=mock_client),
  1456. ),
  1457. patch(
  1458. "backend.app.services.spoolman.init_spoolman_client",
  1459. AsyncMock(return_value=mock_client),
  1460. ),
  1461. ):
  1462. resp = await async_client.post(
  1463. f"{API}/scale/update-spool-weight",
  1464. json={"spool_id": 7, "weight_grams": 100},
  1465. )
  1466. assert resp.status_code == 200
  1467. mock_client.update_spool.assert_called_once_with(spool_id=7, remaining_weight=0.0)
  1468. @pytest.mark.asyncio
  1469. @pytest.mark.integration
  1470. async def test_spoolman_mode_404_when_spool_not_found(self, async_client: AsyncClient, spoolman_settings):
  1471. """404 when Spoolman doesn't know the spool."""
  1472. mock_client = _mock_spoolman_client()
  1473. mock_client.get_spool = AsyncMock(side_effect=SpoolmanNotFoundError("Spool 9999 not found"))
  1474. with (
  1475. patch(
  1476. "backend.app.services.spoolman.get_spoolman_client",
  1477. AsyncMock(return_value=mock_client),
  1478. ),
  1479. patch(
  1480. "backend.app.services.spoolman.init_spoolman_client",
  1481. AsyncMock(return_value=mock_client),
  1482. ),
  1483. ):
  1484. resp = await async_client.post(
  1485. f"{API}/scale/update-spool-weight",
  1486. json={"spool_id": 9999, "weight_grams": 500},
  1487. )
  1488. assert resp.status_code == 404
  1489. @pytest.mark.asyncio
  1490. @pytest.mark.integration
  1491. async def test_spoolman_mode_503_on_client_failure(self, async_client: AsyncClient, spoolman_settings):
  1492. """503 is returned when Spoolman is unreachable during weight update."""
  1493. sm_spool = _spoolman_spool_fixture(99)
  1494. mock_client = _mock_spoolman_client()
  1495. mock_client.get_spool = AsyncMock(return_value=sm_spool)
  1496. mock_client.update_spool = AsyncMock(side_effect=SpoolmanUnavailableError("Spoolman down"))
  1497. with (
  1498. patch(
  1499. "backend.app.services.spoolman.get_spoolman_client",
  1500. AsyncMock(return_value=mock_client),
  1501. ),
  1502. patch(
  1503. "backend.app.services.spoolman.init_spoolman_client",
  1504. AsyncMock(return_value=mock_client),
  1505. ),
  1506. ):
  1507. resp = await async_client.post(
  1508. f"{API}/scale/update-spool-weight",
  1509. json={"spool_id": 99, "weight_grams": 500},
  1510. )
  1511. assert resp.status_code == 503
  1512. @pytest.mark.asyncio
  1513. @pytest.mark.integration
  1514. async def test_local_mode_unchanged(self, async_client: AsyncClient, spool_factory):
  1515. """When Spoolman is NOT enabled, local DB update still works."""
  1516. spool = await spool_factory(label_weight=1000, core_weight=250, weight_used=0)
  1517. resp = await async_client.post(
  1518. f"{API}/scale/update-spool-weight",
  1519. json={"spool_id": spool.id, "weight_grams": 750},
  1520. )
  1521. assert resp.status_code == 200
  1522. assert resp.json()["weight_used"] == 500
  1523. @pytest.mark.asyncio
  1524. @pytest.mark.integration
  1525. async def test_stale_local_row_does_not_shadow_spoolman(
  1526. self, async_client: AsyncClient, db_session, spool_factory, spoolman_settings
  1527. ):
  1528. """Regression for #1530: when Spoolman mode is on, a stale local Spool
  1529. sharing the same numeric id must NOT absorb the update — Spoolman is
  1530. the authoritative target."""
  1531. local_spool = await spool_factory(label_weight=1000, core_weight=250, weight_used=0)
  1532. # Spoolman spool with the SAME numeric id as the local stale row.
  1533. sm_spool = _spoolman_spool_fixture(local_spool.id, spool_weight=250.0, filament_weight=1000.0)
  1534. mock_client = _mock_spoolman_client()
  1535. mock_client.get_spool = AsyncMock(return_value=sm_spool)
  1536. mock_client.update_spool = AsyncMock(return_value=sm_spool)
  1537. with (
  1538. patch("backend.app.services.spoolman.get_spoolman_client", AsyncMock(return_value=mock_client)),
  1539. patch("backend.app.services.spoolman.init_spoolman_client", AsyncMock(return_value=mock_client)),
  1540. ):
  1541. resp = await async_client.post(
  1542. f"{API}/scale/update-spool-weight",
  1543. json={"spool_id": local_spool.id, "weight_grams": 750},
  1544. )
  1545. assert resp.status_code == 200
  1546. # Spoolman got the update.
  1547. mock_client.update_spool.assert_called_once_with(spool_id=local_spool.id, remaining_weight=pytest.approx(500.0))
  1548. # Local row is untouched — the bug was that the local update silently
  1549. # absorbed the request while Spoolman stayed stale.
  1550. await db_session.refresh(local_spool)
  1551. assert local_spool.weight_used == 0
  1552. assert local_spool.last_scale_weight is None
  1553. @pytest.mark.asyncio
  1554. @pytest.mark.integration
  1555. async def test_spool_level_spool_weight_takes_priority(self, async_client: AsyncClient, spoolman_settings):
  1556. """spool.spool_weight overrides filament.spool_weight for tare calculation."""
  1557. sm_spool = _spoolman_spool_fixture(42, spool_weight=196.0, filament_weight=1000.0, spool_level_spool_weight=300)
  1558. mock_client = _mock_spoolman_client()
  1559. mock_client.get_spool = AsyncMock(return_value=sm_spool)
  1560. mock_client.update_spool = AsyncMock(return_value=sm_spool)
  1561. with (
  1562. patch("backend.app.services.spoolman.get_spoolman_client", AsyncMock(return_value=mock_client)),
  1563. patch("backend.app.services.spoolman.init_spoolman_client", AsyncMock(return_value=mock_client)),
  1564. ):
  1565. resp = await async_client.post(
  1566. f"{API}/scale/update-spool-weight",
  1567. json={"spool_id": 42, "weight_grams": 750},
  1568. )
  1569. assert resp.status_code == 200
  1570. # remaining = 750 - 300 = 450; weight_used = 1000 - 450 = 550
  1571. assert resp.json()["weight_used"] == pytest.approx(550.0)
  1572. mock_client.update_spool.assert_called_once_with(spool_id=42, remaining_weight=pytest.approx(450.0))
  1573. @pytest.mark.asyncio
  1574. @pytest.mark.integration
  1575. async def test_spool_level_zero_spool_weight_not_treated_as_missing(
  1576. self, async_client: AsyncClient, spoolman_settings
  1577. ):
  1578. """spool.spool_weight=0 is valid (0g tare), not treated as missing/fallback."""
  1579. sm_spool = _spoolman_spool_fixture(42, spool_weight=196.0, filament_weight=1000.0, spool_level_spool_weight=0)
  1580. mock_client = _mock_spoolman_client()
  1581. mock_client.get_spool = AsyncMock(return_value=sm_spool)
  1582. mock_client.update_spool = AsyncMock(return_value=sm_spool)
  1583. with (
  1584. patch("backend.app.services.spoolman.get_spoolman_client", AsyncMock(return_value=mock_client)),
  1585. patch("backend.app.services.spoolman.init_spoolman_client", AsyncMock(return_value=mock_client)),
  1586. ):
  1587. resp = await async_client.post(
  1588. f"{API}/scale/update-spool-weight",
  1589. json={"spool_id": 42, "weight_grams": 750},
  1590. )
  1591. assert resp.status_code == 200
  1592. # remaining = 750 - 0 = 750; weight_used = 1000 - 750 = 250
  1593. assert resp.json()["weight_used"] == pytest.approx(250.0)
  1594. mock_client.update_spool.assert_called_once_with(spool_id=42, remaining_weight=pytest.approx(750.0))
  1595. @pytest.mark.asyncio
  1596. @pytest.mark.integration
  1597. async def test_both_levels_none_uses_250g_fallback_and_warns(self, async_client: AsyncClient, spoolman_settings):
  1598. """When both spool_weight and filament.spool_weight are None, 250g fallback is used with a warning."""
  1599. sm_spool = {"id": 42, "filament": {"weight": 1000.0, "spool_weight": None}, "used_weight": 0.0}
  1600. mock_client = _mock_spoolman_client()
  1601. mock_client.get_spool = AsyncMock(return_value=sm_spool)
  1602. mock_client.update_spool = AsyncMock(return_value=sm_spool)
  1603. with (
  1604. patch("backend.app.services.spoolman.get_spoolman_client", AsyncMock(return_value=mock_client)),
  1605. patch("backend.app.services.spoolman.init_spoolman_client", AsyncMock(return_value=mock_client)),
  1606. ):
  1607. resp = await async_client.post(
  1608. f"{API}/scale/update-spool-weight",
  1609. json={"spool_id": 42, "weight_grams": 750},
  1610. )
  1611. assert resp.status_code == 200
  1612. # remaining = 750 - 250 = 500; weight_used = 1000 - 500 = 500
  1613. assert resp.json()["weight_used"] == pytest.approx(500.0)
  1614. assert resp.json().get("warnings")
  1615. class TestTagScannedSpoolmanFallback:
  1616. """nfc/tag-scanned falls back to Spoolman when local DB has no match."""
  1617. @pytest.mark.asyncio
  1618. @pytest.mark.integration
  1619. async def test_spoolman_fallback_on_local_miss(self, async_client: AsyncClient, spoolman_settings):
  1620. raw_spool = {
  1621. "id": 5,
  1622. "filament": {
  1623. "material": "PETG",
  1624. "name": "PETG Basic",
  1625. "color_hex": "00FF00",
  1626. "weight": 1000,
  1627. "vendor": {"name": "Polymaker"},
  1628. },
  1629. "used_weight": 100.0,
  1630. "archived": False,
  1631. "registered": "2024-01-01T00:00:00+00:00",
  1632. "extra": {"tag": '"DEADBEEF12345678"'},
  1633. }
  1634. mock_client = _mock_spoolman_client()
  1635. mock_client.get_spools = AsyncMock(return_value=[raw_spool])
  1636. mock_client.find_spool_by_tag = AsyncMock(return_value=raw_spool)
  1637. with (
  1638. patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws,
  1639. patch(
  1640. "backend.app.api.routes.spoolbuddy.get_spool_by_tag",
  1641. new_callable=AsyncMock,
  1642. return_value=None,
  1643. ),
  1644. patch(
  1645. "backend.app.services.spoolman.get_spoolman_client",
  1646. AsyncMock(return_value=mock_client),
  1647. ),
  1648. patch(
  1649. "backend.app.services.spoolman.init_spoolman_client",
  1650. AsyncMock(return_value=mock_client),
  1651. ),
  1652. ):
  1653. mock_ws.broadcast = AsyncMock()
  1654. resp = await async_client.post(
  1655. f"{API}/nfc/tag-scanned",
  1656. json={"device_id": "sb-1", "tag_uid": "DEADBEEF12345678"},
  1657. )
  1658. assert resp.status_code == 200
  1659. data = resp.json()
  1660. assert data["matched"] is True
  1661. assert data["spool_id"] == 5
  1662. mock_ws.broadcast.assert_called_once()
  1663. msg = mock_ws.broadcast.call_args[0][0]
  1664. assert msg["type"] == "spoolbuddy_tag_matched"
  1665. assert msg["spool"]["id"] == 5
  1666. assert msg["spool"]["material"] == "PETG"
  1667. @pytest.mark.asyncio
  1668. @pytest.mark.integration
  1669. async def test_spoolman_fallback_unknown_when_no_spoolman_match(self, async_client: AsyncClient, spoolman_settings):
  1670. """Unknown tag broadcast when both local DB and Spoolman miss."""
  1671. mock_client = _mock_spoolman_client()
  1672. mock_client.get_spools = AsyncMock(return_value=[])
  1673. mock_client.find_spool_by_tag = AsyncMock(return_value=None)
  1674. with (
  1675. patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws,
  1676. patch(
  1677. "backend.app.api.routes.spoolbuddy.get_spool_by_tag",
  1678. new_callable=AsyncMock,
  1679. return_value=None,
  1680. ),
  1681. patch(
  1682. "backend.app.services.spoolman.get_spoolman_client",
  1683. AsyncMock(return_value=mock_client),
  1684. ),
  1685. patch(
  1686. "backend.app.services.spoolman.init_spoolman_client",
  1687. AsyncMock(return_value=mock_client),
  1688. ),
  1689. ):
  1690. mock_ws.broadcast = AsyncMock()
  1691. resp = await async_client.post(
  1692. f"{API}/nfc/tag-scanned",
  1693. json={"device_id": "sb-1", "tag_uid": "UNKNOWN0000000FF"},
  1694. )
  1695. assert resp.status_code == 200
  1696. data = resp.json()
  1697. assert data["matched"] is False
  1698. assert data["spool_id"] is None
  1699. mock_ws.broadcast.assert_called_once()
  1700. msg = mock_ws.broadcast.call_args[0][0]
  1701. assert msg["type"] == "spoolbuddy_unknown_tag"
  1702. @pytest.mark.asyncio
  1703. @pytest.mark.integration
  1704. async def test_malformed_spoolman_data_degrades_gracefully(self, async_client: AsyncClient, spoolman_settings):
  1705. """ValueError from _map_spoolman_spool (e.g. spool_id=0) must return matched=False without broadcasting unknown_tag."""
  1706. bad_spool = {
  1707. "id": 0, # _map_spoolman_spool raises ValueError for id <= 0
  1708. "filament": {"material": "PLA", "name": "PLA Basic", "color_hex": "FF0000", "weight": 1000},
  1709. "used_weight": 0.0,
  1710. "archived": False,
  1711. "registered": "2024-01-01T00:00:00Z",
  1712. "extra": {"tag": '"DEADBEEF12345678"'},
  1713. }
  1714. mock_client = _mock_spoolman_client()
  1715. mock_client.find_spool_by_tag = AsyncMock(return_value=bad_spool)
  1716. with (
  1717. patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws,
  1718. patch(
  1719. "backend.app.api.routes.spoolbuddy.get_spool_by_tag",
  1720. new_callable=AsyncMock,
  1721. return_value=None,
  1722. ),
  1723. patch(
  1724. "backend.app.services.spoolman.get_spoolman_client",
  1725. AsyncMock(return_value=mock_client),
  1726. ),
  1727. patch(
  1728. "backend.app.services.spoolman.init_spoolman_client",
  1729. AsyncMock(return_value=mock_client),
  1730. ),
  1731. ):
  1732. mock_ws.broadcast = AsyncMock()
  1733. resp = await async_client.post(
  1734. f"{API}/nfc/tag-scanned",
  1735. json={"device_id": "sb-1", "tag_uid": "DEADBEEF12345678"},
  1736. )
  1737. assert resp.status_code == 200
  1738. data = resp.json()
  1739. assert data["matched"] is False
  1740. assert data["spool_id"] is None
  1741. # No broadcast: UI must not get a spurious unknown_tag event on Spoolman data errors
  1742. mock_ws.broadcast.assert_not_called()
  1743. @pytest.mark.asyncio
  1744. @pytest.mark.integration
  1745. async def test_local_match_skips_spoolman(self, async_client: AsyncClient, spool_factory):
  1746. """When local DB matches, Spoolman is never queried."""
  1747. spool = await spool_factory(tag_uid="AABB1122", material="PLA")
  1748. mock_spool = MagicMock()
  1749. mock_spool.id = spool.id
  1750. mock_spool.material = spool.material
  1751. mock_spool.subtype = spool.subtype
  1752. mock_spool.color_name = spool.color_name
  1753. mock_spool.rgba = spool.rgba
  1754. mock_spool.brand = spool.brand
  1755. mock_spool.label_weight = spool.label_weight
  1756. mock_spool.core_weight = spool.core_weight
  1757. mock_spool.weight_used = spool.weight_used
  1758. with (
  1759. patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws,
  1760. patch(
  1761. "backend.app.api.routes.spoolbuddy.get_spool_by_tag",
  1762. new_callable=AsyncMock,
  1763. return_value=mock_spool,
  1764. ),
  1765. ):
  1766. mock_ws.broadcast = AsyncMock()
  1767. resp = await async_client.post(
  1768. f"{API}/nfc/tag-scanned",
  1769. json={"device_id": "sb-1", "tag_uid": "AABB1122"},
  1770. )
  1771. assert resp.status_code == 200
  1772. data = resp.json()
  1773. assert data["matched"] is True
  1774. assert data["spool_id"] == spool.id
  1775. # ============================================================================
  1776. # NFC write-tag / write-result — Spoolman-aware
  1777. # ============================================================================
  1778. def _full_spoolman_spool(spool_id: int) -> dict:
  1779. """Complete Spoolman spool dict sufficient for NDEF encoding."""
  1780. return {
  1781. "id": spool_id,
  1782. "filament": {
  1783. "material": "PLA",
  1784. "name": "PLA Basic",
  1785. "color_hex": "FF0000",
  1786. "weight": 1000.0,
  1787. "spool_weight": 196.0,
  1788. "vendor": {"name": "Bambu Lab"},
  1789. },
  1790. "used_weight": 0.0,
  1791. "archived": False,
  1792. "registered": "2024-01-01T00:00:00Z",
  1793. }
  1794. class TestNfcWriteTagSpoolman:
  1795. """nfc/write-tag encodes the Spoolman spool in Spoolman mode."""
  1796. @pytest.mark.asyncio
  1797. @pytest.mark.integration
  1798. async def test_spoolman_spool_queued_when_local_miss(
  1799. self, async_client: AsyncClient, device_factory, spoolman_settings
  1800. ):
  1801. """write-tag encodes NDEF from Spoolman data when spool not in local DB."""
  1802. await device_factory(device_id="sb-write-sm")
  1803. sm_spool = _full_spoolman_spool(77)
  1804. mock_client = _mock_spoolman_client()
  1805. mock_client.get_spool = AsyncMock(return_value=sm_spool)
  1806. with (
  1807. patch(
  1808. "backend.app.services.spoolman.get_spoolman_client",
  1809. AsyncMock(return_value=mock_client),
  1810. ),
  1811. patch(
  1812. "backend.app.services.spoolman.init_spoolman_client",
  1813. AsyncMock(return_value=mock_client),
  1814. ),
  1815. ):
  1816. resp = await async_client.post(
  1817. f"{API}/nfc/write-tag",
  1818. json={"device_id": "sb-write-sm", "spool_id": 77},
  1819. )
  1820. assert resp.status_code == 200
  1821. assert resp.json()["status"] == "queued"
  1822. mock_client.get_spool.assert_called_once_with(77)
  1823. @pytest.mark.asyncio
  1824. @pytest.mark.integration
  1825. async def test_data_origin_spoolman_stored_in_payload(
  1826. self, async_client: AsyncClient, device_factory, db_session, spoolman_settings
  1827. ):
  1828. """Pending write payload records data_origin=spoolman for Spoolman spools."""
  1829. import json as _json
  1830. device = await device_factory(device_id="sb-origin")
  1831. sm_spool = _full_spoolman_spool(88)
  1832. mock_client = _mock_spoolman_client()
  1833. mock_client.get_spool = AsyncMock(return_value=sm_spool)
  1834. with (
  1835. patch(
  1836. "backend.app.services.spoolman.get_spoolman_client",
  1837. AsyncMock(return_value=mock_client),
  1838. ),
  1839. patch(
  1840. "backend.app.services.spoolman.init_spoolman_client",
  1841. AsyncMock(return_value=mock_client),
  1842. ),
  1843. ):
  1844. await async_client.post(
  1845. f"{API}/nfc/write-tag",
  1846. json={"device_id": "sb-origin", "spool_id": 88},
  1847. )
  1848. await db_session.refresh(device)
  1849. payload = _json.loads(device.pending_write_payload)
  1850. assert payload["data_origin"] == "spoolman"
  1851. assert payload["spool_id"] == 88
  1852. assert "ndef_data_hex" in payload
  1853. @pytest.mark.asyncio
  1854. @pytest.mark.integration
  1855. async def test_404_when_spoolman_has_no_such_spool(
  1856. self, async_client: AsyncClient, device_factory, spoolman_settings
  1857. ):
  1858. """404 returned when the spool is missing from Spoolman."""
  1859. await device_factory(device_id="sb-miss")
  1860. mock_client = _mock_spoolman_client()
  1861. mock_client.get_spool = AsyncMock(side_effect=SpoolmanNotFoundError("Spool 9999 not found"))
  1862. with (
  1863. patch(
  1864. "backend.app.services.spoolman.get_spoolman_client",
  1865. AsyncMock(return_value=mock_client),
  1866. ),
  1867. patch(
  1868. "backend.app.services.spoolman.init_spoolman_client",
  1869. AsyncMock(return_value=mock_client),
  1870. ),
  1871. ):
  1872. resp = await async_client.post(
  1873. f"{API}/nfc/write-tag",
  1874. json={"device_id": "sb-miss", "spool_id": 9999},
  1875. )
  1876. assert resp.status_code == 404
  1877. @pytest.mark.asyncio
  1878. @pytest.mark.integration
  1879. async def test_spoolman_spool_wins_over_a_leftover_built_in_spool(
  1880. self, async_client: AsyncClient, device_factory, db_session, spool_factory, spoolman_settings
  1881. ):
  1882. """Built-in spools are kept after switching to Spoolman; one with the
  1883. same id as the Spoolman spool must not be the one written to the tag."""
  1884. import json as _json
  1885. leftover = await spool_factory(material="PETG")
  1886. device = await device_factory(device_id="sb-leftover")
  1887. mock_client = _mock_spoolman_client()
  1888. mock_client.get_spool = AsyncMock(return_value=_full_spoolman_spool(leftover.id))
  1889. with (
  1890. patch("backend.app.services.spoolman.get_spoolman_client", AsyncMock(return_value=mock_client)),
  1891. patch("backend.app.services.spoolman.init_spoolman_client", AsyncMock(return_value=mock_client)),
  1892. ):
  1893. resp = await async_client.post(
  1894. f"{API}/nfc/write-tag",
  1895. json={"device_id": "sb-leftover", "spool_id": leftover.id},
  1896. )
  1897. assert resp.status_code == 200, resp.text
  1898. mock_client.get_spool.assert_called_once_with(leftover.id)
  1899. await db_session.refresh(device)
  1900. assert _json.loads(device.pending_write_payload)["data_origin"] == "spoolman"
  1901. @pytest.mark.asyncio
  1902. @pytest.mark.integration
  1903. async def test_local_spool_used_when_present(self, async_client: AsyncClient, device_factory, spool_factory):
  1904. """Local DB spool is encoded directly without contacting Spoolman."""
  1905. await device_factory(device_id="sb-local-write")
  1906. spool = await spool_factory(material="PETG")
  1907. resp = await async_client.post(
  1908. f"{API}/nfc/write-tag",
  1909. json={"device_id": "sb-local-write", "spool_id": spool.id},
  1910. )
  1911. assert resp.status_code == 200
  1912. assert resp.json()["status"] == "queued"
  1913. class TestNfcWriteResultSpoolman:
  1914. """nfc/write-result updates Spoolman extra.tag on success for Spoolman spools."""
  1915. @pytest.mark.asyncio
  1916. @pytest.mark.integration
  1917. async def test_success_updates_spoolman_extra_tag(
  1918. self, async_client: AsyncClient, device_factory, spoolman_settings
  1919. ):
  1920. """Successful write for a Spoolman spool calls merge_spool_extra with extra.tag."""
  1921. import json as _json
  1922. await device_factory(
  1923. device_id="sb-wr-sm",
  1924. pending_command="write_tag",
  1925. pending_write_payload=_json.dumps({"spool_id": 55, "ndef_data_hex": "deadbeef", "data_origin": "spoolman"}),
  1926. )
  1927. mock_client = _mock_spoolman_client()
  1928. mock_client.merge_spool_extra = AsyncMock(return_value={"id": 55})
  1929. with (
  1930. patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws,
  1931. patch(
  1932. "backend.app.services.spoolman.get_spoolman_client",
  1933. AsyncMock(return_value=mock_client),
  1934. ),
  1935. patch(
  1936. "backend.app.services.spoolman.init_spoolman_client",
  1937. AsyncMock(return_value=mock_client),
  1938. ),
  1939. ):
  1940. mock_ws.broadcast = AsyncMock()
  1941. resp = await async_client.post(
  1942. f"{API}/nfc/write-result",
  1943. json={
  1944. "device_id": "sb-wr-sm",
  1945. "spool_id": 55,
  1946. "tag_uid": "AABBCCDD11223344",
  1947. "success": True,
  1948. },
  1949. )
  1950. assert resp.status_code == 200
  1951. mock_client.merge_spool_extra.assert_called_once_with(55, {"tag": '"AABBCCDD11223344"'})
  1952. msg = mock_ws.broadcast.call_args[0][0]
  1953. assert msg["type"] == "spoolbuddy_tag_written"
  1954. assert msg["tag_uid"] == "AABBCCDD11223344"
  1955. @pytest.mark.asyncio
  1956. @pytest.mark.integration
  1957. async def test_failure_does_not_call_spoolman(self, async_client: AsyncClient, device_factory, spoolman_settings):
  1958. """Failed write never calls Spoolman update."""
  1959. import json as _json
  1960. await device_factory(
  1961. device_id="sb-wr-fail",
  1962. pending_command="write_tag",
  1963. pending_write_payload=_json.dumps({"spool_id": 66, "ndef_data_hex": "deadbeef", "data_origin": "spoolman"}),
  1964. )
  1965. mock_client = _mock_spoolman_client()
  1966. with (
  1967. patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws,
  1968. patch(
  1969. "backend.app.services.spoolman.get_spoolman_client",
  1970. AsyncMock(return_value=mock_client),
  1971. ),
  1972. ):
  1973. mock_ws.broadcast = AsyncMock()
  1974. resp = await async_client.post(
  1975. f"{API}/nfc/write-result",
  1976. json={
  1977. "device_id": "sb-wr-fail",
  1978. "spool_id": 66,
  1979. "tag_uid": "AABBCCDD11223344",
  1980. "success": False,
  1981. "message": "write timeout",
  1982. },
  1983. )
  1984. assert resp.status_code == 200
  1985. mock_client.update_spool.assert_not_called()
  1986. msg = mock_ws.broadcast.call_args[0][0]
  1987. assert msg["type"] == "spoolbuddy_tag_write_failed"
  1988. @pytest.mark.asyncio
  1989. @pytest.mark.integration
  1990. async def test_success_local_spool_writes_to_db(
  1991. self, async_client: AsyncClient, device_factory, spool_factory, db_session
  1992. ):
  1993. """Successful write for a local spool still updates local DB tag_uid."""
  1994. import json as _json
  1995. spool = await spool_factory()
  1996. await device_factory(
  1997. device_id="sb-wr-local",
  1998. pending_command="write_tag",
  1999. pending_write_payload=_json.dumps(
  2000. {"spool_id": spool.id, "ndef_data_hex": "deadbeef", "data_origin": "local"}
  2001. ),
  2002. )
  2003. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  2004. mock_ws.broadcast = AsyncMock()
  2005. resp = await async_client.post(
  2006. f"{API}/nfc/write-result",
  2007. json={
  2008. "device_id": "sb-wr-local",
  2009. "spool_id": spool.id,
  2010. "tag_uid": "DEADBEEF12345678",
  2011. "success": True,
  2012. },
  2013. )
  2014. assert resp.status_code == 200
  2015. await db_session.refresh(spool)
  2016. assert spool.tag_uid == "DEADBEEF12345678"
  2017. assert spool.tag_type == "ntag"
  2018. # ============================================================================
  2019. # Security fix tests — write-tag ValueError + write-result exception safety
  2020. # ============================================================================
  2021. class TestNfcWriteTagSpoolmanSecurityFixes:
  2022. """Regression tests for security fixes in nfc/write-tag Spoolman path."""
  2023. @pytest.mark.asyncio
  2024. @pytest.mark.integration
  2025. async def test_invalid_spoolman_spool_id_returns_502(
  2026. self, async_client: AsyncClient, device_factory, spoolman_settings
  2027. ):
  2028. """Malformed Spoolman spool (invalid id=0) raises 502, not 404 — spool exists but is bad data."""
  2029. await device_factory(device_id="sb-invalid-id")
  2030. # Spoolman returns spool with id=0 (invalid — caught by _map_spoolman_spool guard)
  2031. bad_spool = {**_full_spoolman_spool(1), "id": 0}
  2032. mock_client = _mock_spoolman_client()
  2033. mock_client.get_spool = AsyncMock(return_value=bad_spool)
  2034. with (
  2035. patch(
  2036. "backend.app.services.spoolman.get_spoolman_client",
  2037. AsyncMock(return_value=mock_client),
  2038. ),
  2039. patch(
  2040. "backend.app.services.spoolman.init_spoolman_client",
  2041. AsyncMock(return_value=mock_client),
  2042. ),
  2043. ):
  2044. resp = await async_client.post(
  2045. f"{API}/nfc/write-tag",
  2046. json={"device_id": "sb-invalid-id", "spool_id": 99},
  2047. )
  2048. # 502: spool exists in Spoolman but its data is malformed — not a "not found"
  2049. assert resp.status_code == 502
  2050. @pytest.mark.asyncio
  2051. @pytest.mark.integration
  2052. async def test_oversized_label_weight_does_not_crash(
  2053. self, async_client: AsyncClient, device_factory, spoolman_settings
  2054. ):
  2055. """label_weight > 65535 from Spoolman must not crash with struct.error."""
  2056. await device_factory(device_id="sb-overflow")
  2057. big_weight_spool = {
  2058. **_full_spoolman_spool(42),
  2059. "filament": {**_full_spoolman_spool(42)["filament"], "weight": 70000},
  2060. }
  2061. mock_client = _mock_spoolman_client()
  2062. mock_client.get_spool = AsyncMock(return_value=big_weight_spool)
  2063. with (
  2064. patch(
  2065. "backend.app.services.spoolman.get_spoolman_client",
  2066. AsyncMock(return_value=mock_client),
  2067. ),
  2068. patch(
  2069. "backend.app.services.spoolman.init_spoolman_client",
  2070. AsyncMock(return_value=mock_client),
  2071. ),
  2072. ):
  2073. resp = await async_client.post(
  2074. f"{API}/nfc/write-tag",
  2075. json={"device_id": "sb-overflow", "spool_id": 42},
  2076. )
  2077. assert resp.status_code == 200
  2078. assert resp.json()["status"] == "queued"
  2079. class TestNfcWriteResultSpoolmanSecurityFixes:
  2080. """Regression tests for transaction safety in nfc/write-result Spoolman path."""
  2081. @pytest.mark.asyncio
  2082. @pytest.mark.integration
  2083. async def test_spoolman_client_exception_still_clears_device_state(
  2084. self, async_client: AsyncClient, device_factory, db_session, spoolman_settings
  2085. ):
  2086. """If Spoolman client raises, device pending_command is still cleared in DB."""
  2087. import json as _json
  2088. device = await device_factory(
  2089. device_id="sb-exc-safe",
  2090. pending_command="write_tag",
  2091. pending_write_payload=_json.dumps({"spool_id": 77, "ndef_data_hex": "deadbeef", "data_origin": "spoolman"}),
  2092. )
  2093. mock_client = _mock_spoolman_client()
  2094. mock_client.merge_spool_extra = AsyncMock(side_effect=Exception("connection refused"))
  2095. with (
  2096. patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws,
  2097. patch(
  2098. "backend.app.services.spoolman.get_spoolman_client",
  2099. AsyncMock(return_value=mock_client),
  2100. ),
  2101. patch(
  2102. "backend.app.services.spoolman.init_spoolman_client",
  2103. AsyncMock(return_value=mock_client),
  2104. ),
  2105. ):
  2106. mock_ws.broadcast = AsyncMock()
  2107. resp = await async_client.post(
  2108. f"{API}/nfc/write-result",
  2109. json={
  2110. "device_id": "sb-exc-safe",
  2111. "spool_id": 77,
  2112. "tag_uid": "AABBCCDD11223344",
  2113. "success": True,
  2114. },
  2115. )
  2116. # 502: tag written to NFC but Spoolman link failed (not best-effort — caller must retry)
  2117. assert resp.status_code == 502
  2118. # Device state must be cleared despite the exception (no spurious re-write)
  2119. await db_session.refresh(device)
  2120. assert device.pending_command is None
  2121. assert device.pending_write_payload is None
  2122. # Failure broadcast fires so the UI can show the error
  2123. msg = mock_ws.broadcast.call_args[0][0]
  2124. assert msg["type"] == "spoolbuddy_tag_link_failed"
  2125. assert msg["reason"] == "spoolman_link_failed"
  2126. @pytest.mark.asyncio
  2127. @pytest.mark.integration
  2128. async def test_spoolman_not_found_error_broadcasts_link_failed(
  2129. self, async_client: AsyncClient, device_factory, db_session, spoolman_settings
  2130. ):
  2131. """SpoolmanNotFoundError from merge_spool_extra must clear device state and broadcast link_failed."""
  2132. import json as _json
  2133. device = await device_factory(
  2134. device_id="sb-notfound",
  2135. pending_command="write_tag",
  2136. pending_write_payload=_json.dumps({"spool_id": 55, "ndef_data_hex": "deadbeef", "data_origin": "spoolman"}),
  2137. )
  2138. mock_client = _mock_spoolman_client()
  2139. mock_client.merge_spool_extra = AsyncMock(side_effect=SpoolmanNotFoundError("Spool 55 not found"))
  2140. with (
  2141. patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws,
  2142. patch(
  2143. "backend.app.services.spoolman.get_spoolman_client",
  2144. AsyncMock(return_value=mock_client),
  2145. ),
  2146. patch(
  2147. "backend.app.services.spoolman.init_spoolman_client",
  2148. AsyncMock(return_value=mock_client),
  2149. ),
  2150. ):
  2151. mock_ws.broadcast = AsyncMock()
  2152. resp = await async_client.post(
  2153. f"{API}/nfc/write-result",
  2154. json={
  2155. "device_id": "sb-notfound",
  2156. "spool_id": 55,
  2157. "tag_uid": "AABBCCDD11223344",
  2158. "success": True,
  2159. },
  2160. )
  2161. assert resp.status_code == 502
  2162. await db_session.refresh(device)
  2163. assert device.pending_command is None
  2164. assert device.pending_write_payload is None
  2165. msg = mock_ws.broadcast.call_args[0][0]
  2166. assert msg["type"] == "spoolbuddy_tag_link_failed"
  2167. assert msg["spool_id"] == 55
  2168. assert msg["reason"] == "spoolman_link_failed"
  2169. class TestNfcWriteResultOrphanedSpool:
  2170. """nfc/write-result when the local spool was deleted between write-queue and write-result."""
  2171. @pytest.mark.asyncio
  2172. @pytest.mark.integration
  2173. async def test_local_spool_deleted_before_write_back(self, async_client: AsyncClient, device_factory, db_session):
  2174. """When local spool is deleted between write-queue and write-result, return linked=False and broadcast link_failed."""
  2175. import json as _json
  2176. device = await device_factory(
  2177. device_id="sb-orphan",
  2178. pending_command="write_tag",
  2179. pending_write_payload=_json.dumps(
  2180. {
  2181. "spool_id": 99999, # non-existent spool
  2182. "ndef_data_hex": "aabbccdd",
  2183. "data_origin": "local",
  2184. }
  2185. ),
  2186. )
  2187. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  2188. mock_ws.broadcast = AsyncMock()
  2189. resp = await async_client.post(
  2190. f"{API}/nfc/write-result",
  2191. json={"device_id": device.device_id, "spool_id": 99999, "success": True, "tag_uid": "AABBCCDD"},
  2192. )
  2193. assert resp.status_code == 200
  2194. data = resp.json()
  2195. assert data["linked"] is False
  2196. # pending command should be cleared
  2197. await db_session.refresh(device)
  2198. assert device.pending_command is None
  2199. # broadcast should be spoolbuddy_tag_link_failed
  2200. broadcast_calls = mock_ws.broadcast.call_args_list
  2201. link_failed = [c[0][0] for c in broadcast_calls if c[0][0].get("type") == "spoolbuddy_tag_link_failed"]
  2202. assert len(link_failed) >= 1
  2203. assert link_failed[0]["reason"] == "spool_not_found"
  2204. class TestNfcWriteResultInputValidation:
  2205. """Input validation and JSON safety for nfc/write-result."""
  2206. @pytest.mark.asyncio
  2207. @pytest.mark.integration
  2208. async def test_tag_uid_too_long_rejected(self, async_client: AsyncClient, device_factory):
  2209. """tag_uid longer than 32 chars must be rejected with 422."""
  2210. import json as _json
  2211. await device_factory(
  2212. device_id="sb-uid-long",
  2213. pending_command="write_tag",
  2214. pending_write_payload=_json.dumps({"spool_id": 1, "ndef_data_hex": "dead", "data_origin": "local"}),
  2215. )
  2216. resp = await async_client.post(
  2217. f"{API}/nfc/write-result",
  2218. json={
  2219. "device_id": "sb-uid-long",
  2220. "spool_id": 1,
  2221. "tag_uid": "A" * 65,
  2222. "success": True,
  2223. },
  2224. )
  2225. assert resp.status_code == 422
  2226. @pytest.mark.asyncio
  2227. @pytest.mark.integration
  2228. async def test_malformed_pending_payload_falls_back_to_local(
  2229. self, async_client: AsyncClient, device_factory, spool_factory, db_session
  2230. ):
  2231. """Corrupted pending_write_payload JSON falls back to local mode gracefully."""
  2232. spool = await spool_factory()
  2233. await device_factory(
  2234. device_id="sb-corrupt-json",
  2235. pending_command="write_tag",
  2236. pending_write_payload="{not valid json!!!",
  2237. )
  2238. with patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws:
  2239. mock_ws.broadcast = AsyncMock()
  2240. resp = await async_client.post(
  2241. f"{API}/nfc/write-result",
  2242. json={
  2243. "device_id": "sb-corrupt-json",
  2244. "spool_id": spool.id,
  2245. "tag_uid": "DEADBEEF12345678",
  2246. "success": True,
  2247. },
  2248. )
  2249. # Must return 200, not 500
  2250. assert resp.status_code == 200
  2251. # Falls back to local mode — tag written to DB
  2252. await db_session.refresh(spool)
  2253. assert spool.tag_uid == "DEADBEEF12345678"
  2254. # ============================================================================
  2255. # B1: NFC write-tag warnings appear in response body
  2256. # ============================================================================
  2257. class TestNfcWriteTagWarningsBody:
  2258. """B1: resp.json()['warnings'] is populated when Spoolman fields are absent."""
  2259. @pytest.mark.asyncio
  2260. @pytest.mark.integration
  2261. async def test_warnings_returned_for_missing_color_and_temp(
  2262. self, async_client: AsyncClient, device_factory, spoolman_settings
  2263. ):
  2264. """Both color_name=None and settings_extruder_temp=None produce 2 warnings."""
  2265. await device_factory(device_id="sb-warn-b1")
  2266. # Spoolman spool with no color_name or nozzle temp
  2267. sparse_spool = {
  2268. "id": 99,
  2269. "filament": {
  2270. "material": "PLA",
  2271. "name": "PLA Basic",
  2272. "color_hex": "808080",
  2273. # color_name absent → None after mapping
  2274. # settings_extruder_temp absent → nozzle_temp_min=None
  2275. "weight": 1000.0,
  2276. "vendor": {"name": "Bambu Lab"},
  2277. },
  2278. "used_weight": 0.0,
  2279. "archived": False,
  2280. "registered": "2024-01-01T00:00:00Z",
  2281. }
  2282. mock_client = _mock_spoolman_client()
  2283. mock_client.get_spool = AsyncMock(return_value=sparse_spool)
  2284. with (
  2285. patch(
  2286. "backend.app.services.spoolman.get_spoolman_client",
  2287. AsyncMock(return_value=mock_client),
  2288. ),
  2289. patch(
  2290. "backend.app.services.spoolman.init_spoolman_client",
  2291. AsyncMock(return_value=mock_client),
  2292. ),
  2293. ):
  2294. resp = await async_client.post(
  2295. f"{API}/nfc/write-tag",
  2296. json={"device_id": "sb-warn-b1", "spool_id": 99},
  2297. )
  2298. assert resp.status_code == 200
  2299. body = resp.json()
  2300. assert "warnings" in body, "Response should contain 'warnings' key when fields are absent"
  2301. warnings = body["warnings"]
  2302. assert len(warnings) >= 2, f"Expected at least 2 warnings for missing color_name + nozzle_temp, got: {warnings}"
  2303. # Confirm the specific fields are mentioned
  2304. warn_text = " ".join(warnings)
  2305. assert "color_name" in warn_text
  2306. assert "nozzle_temp" in warn_text
  2307. @pytest.mark.asyncio
  2308. @pytest.mark.integration
  2309. async def test_no_warnings_key_when_all_fields_present(
  2310. self, async_client: AsyncClient, device_factory, spoolman_settings
  2311. ):
  2312. """No 'warnings' key in response when all fields are populated."""
  2313. await device_factory(device_id="sb-nowarn")
  2314. full_spool = _full_spoolman_spool(100)
  2315. # Add color_name and extruder temp
  2316. full_spool["filament"]["color_name"] = "Red"
  2317. full_spool["filament"]["settings_extruder_temp"] = 220
  2318. mock_client = _mock_spoolman_client()
  2319. mock_client.get_spool = AsyncMock(return_value=full_spool)
  2320. with (
  2321. patch(
  2322. "backend.app.services.spoolman.get_spoolman_client",
  2323. AsyncMock(return_value=mock_client),
  2324. ),
  2325. patch(
  2326. "backend.app.services.spoolman.init_spoolman_client",
  2327. AsyncMock(return_value=mock_client),
  2328. ),
  2329. ):
  2330. resp = await async_client.post(
  2331. f"{API}/nfc/write-tag",
  2332. json={"device_id": "sb-nowarn", "spool_id": 100},
  2333. )
  2334. assert resp.status_code == 200
  2335. body = resp.json()
  2336. assert "warnings" not in body or body["warnings"] == []
  2337. # ============================================================================
  2338. # B5: Exception text scrubbed from WebSocket broadcast message
  2339. # ============================================================================
  2340. class TestNfcWriteResultExceptionScrubbing:
  2341. """B5: Internal exception details must not appear in WebSocket 'message' field."""
  2342. @pytest.mark.asyncio
  2343. @pytest.mark.integration
  2344. async def test_exception_text_not_leaked_in_ws_message(
  2345. self, async_client: AsyncClient, device_factory, db_session, spoolman_settings
  2346. ):
  2347. """When Spoolman merge raises, WS message is generic; 'connection refused' absent."""
  2348. import json as _json
  2349. await device_factory(
  2350. device_id="sb-scrub-b5",
  2351. pending_command="write_tag",
  2352. pending_write_payload=_json.dumps({"spool_id": 77, "ndef_data_hex": "deadbeef", "data_origin": "spoolman"}),
  2353. )
  2354. mock_client = _mock_spoolman_client()
  2355. mock_client.merge_spool_extra = AsyncMock(side_effect=Exception("connection refused to 192.168.1.1:7912"))
  2356. with (
  2357. patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws,
  2358. patch(
  2359. "backend.app.services.spoolman.get_spoolman_client",
  2360. AsyncMock(return_value=mock_client),
  2361. ),
  2362. patch(
  2363. "backend.app.services.spoolman.init_spoolman_client",
  2364. AsyncMock(return_value=mock_client),
  2365. ),
  2366. ):
  2367. mock_ws.broadcast = AsyncMock()
  2368. resp = await async_client.post(
  2369. f"{API}/nfc/write-result",
  2370. json={
  2371. "device_id": "sb-scrub-b5",
  2372. "spool_id": 77,
  2373. "tag_uid": "AABBCCDD11223344",
  2374. "success": True,
  2375. },
  2376. )
  2377. assert resp.status_code == 502
  2378. msg = mock_ws.broadcast.call_args[0][0]
  2379. assert msg["type"] == "spoolbuddy_tag_link_failed"
  2380. # Generic message — no internal exception details leaked
  2381. assert msg["message"] == "Spoolman link failed", f"Expected generic message but got: {msg['message']!r}"
  2382. assert msg["reason"] == "spoolman_link_failed"
  2383. assert "connection refused" not in str(msg), f"Exception text must not appear in WS message: {msg}"
  2384. assert "192.168.1" not in str(msg), f"Internal IP must not appear in WS message: {msg}"
  2385. # ============================================================================
  2386. # _get_spoolman_client_or_none: graceful degradation on ValueError during reinit
  2387. # ============================================================================
  2388. class TestSpoolmanClientOrNoneGraceful:
  2389. """_get_spoolman_client_or_none returns None when init_spoolman_client raises ValueError."""
  2390. @pytest.mark.asyncio
  2391. @pytest.mark.integration
  2392. async def test_returns_none_when_init_raises_value_error(self, async_client: AsyncClient, db_session):
  2393. """_get_spoolman_client_or_none returns None when init_spoolman_client raises ValueError,
  2394. so the device endpoint degrades gracefully instead of propagating a 500 error."""
  2395. from backend.app.models.settings import Settings
  2396. db_session.add(Settings(key="spoolman_enabled", value="true"))
  2397. db_session.add(Settings(key="spoolman_url", value="http://spoolman.local:7912"))
  2398. await db_session.commit()
  2399. with (
  2400. patch("backend.app.api.routes._spoolman_helpers.assert_safe_spoolman_url"),
  2401. patch(
  2402. "backend.app.services.spoolman.get_spoolman_client",
  2403. AsyncMock(return_value=None),
  2404. ),
  2405. patch(
  2406. "backend.app.services.spoolman.init_spoolman_client",
  2407. AsyncMock(side_effect=ValueError("invalid URL")),
  2408. ),
  2409. patch("backend.app.api.routes.spoolbuddy.ws_manager") as mock_ws,
  2410. ):
  2411. mock_ws.broadcast = AsyncMock()
  2412. # nfc/tag-scanned calls _get_spoolman_client_or_none; with None returned it
  2413. # must broadcast unknown_tag (not raise 500 due to ValueError propagating).
  2414. resp = await async_client.post(
  2415. f"{API}/nfc/tag-scanned",
  2416. json={"device_id": "sb-vale", "tag_uid": "AABBCCDD"},
  2417. )
  2418. # Must not be 500 — ValueError is caught and client returns None, degrading gracefully
  2419. assert resp.status_code == 200
  2420. data = resp.json()
  2421. assert data["matched"] is False