test_spoolbuddy.py 112 KB

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