test_spoolbuddy.py 112 KB

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