test_spoolbuddy.py 113 KB

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