test_labels.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. """Integration tests for the spool-label routes (#809).
  2. Covers both ``POST /inventory/labels`` (local DB) and ``POST /spoolman/labels``
  3. (Spoolman-backed). The renderer itself has its own unit tests; these tests
  4. focus on auth, request validation, mode gating, and the wiring between route
  5. and renderer.
  6. """
  7. from __future__ import annotations
  8. from unittest.mock import AsyncMock, MagicMock, patch
  9. import pytest
  10. from httpx import AsyncClient
  11. from sqlalchemy.ext.asyncio import AsyncSession
  12. from backend.app.models.spool import Spool
  13. @pytest.fixture
  14. async def spool_factory(db_session: AsyncSession):
  15. """Factory to create test spools."""
  16. _counter = [0]
  17. async def _create_spool(**kwargs):
  18. _counter[0] += 1
  19. defaults = {
  20. "material": "PLA",
  21. "subtype": "Basic",
  22. "brand": "Polymaker",
  23. "color_name": f"Test {_counter[0]}",
  24. "rgba": "FF8800FF",
  25. "label_weight": 1000,
  26. "weight_used": 0,
  27. }
  28. defaults.update(kwargs)
  29. spool = Spool(**defaults)
  30. db_session.add(spool)
  31. await db_session.commit()
  32. await db_session.refresh(spool)
  33. return spool
  34. return _create_spool
  35. # ── /inventory/labels (local DB) ─────────────────────────────────────────────
  36. class TestLocalInventoryLabels:
  37. @pytest.mark.asyncio
  38. @pytest.mark.integration
  39. async def test_renders_pdf_for_local_spools(self, async_client: AsyncClient, spool_factory):
  40. s1 = await spool_factory()
  41. s2 = await spool_factory(material="PETG", brand="Sunlu")
  42. resp = await async_client.post(
  43. "/api/v1/inventory/labels",
  44. json={"spool_ids": [s1.id, s2.id], "template": "box_62x29"},
  45. )
  46. assert resp.status_code == 200
  47. assert resp.headers["content-type"] == "application/pdf"
  48. assert resp.content.startswith(b"%PDF")
  49. assert int(resp.headers["content-length"]) == len(resp.content)
  50. @pytest.mark.asyncio
  51. @pytest.mark.integration
  52. async def test_all_four_templates_succeed(self, async_client: AsyncClient, spool_factory):
  53. s = await spool_factory()
  54. for template in (
  55. "ams_holder_74x33",
  56. "ams_holder_75x55",
  57. "box_62x29",
  58. "avery_5160",
  59. "avery_l7160",
  60. ):
  61. resp = await async_client.post(
  62. "/api/v1/inventory/labels",
  63. json={"spool_ids": [s.id], "template": template},
  64. )
  65. assert resp.status_code == 200, f"{template} returned {resp.status_code}: {resp.text}"
  66. assert resp.content.startswith(b"%PDF")
  67. @pytest.mark.asyncio
  68. @pytest.mark.integration
  69. async def test_unknown_template_rejected(self, async_client: AsyncClient, spool_factory):
  70. s = await spool_factory()
  71. resp = await async_client.post(
  72. "/api/v1/inventory/labels",
  73. json={"spool_ids": [s.id], "template": "totally_made_up"},
  74. )
  75. # Pydantic Literal validation → 422
  76. assert resp.status_code in (400, 422)
  77. @pytest.mark.asyncio
  78. @pytest.mark.integration
  79. async def test_empty_spool_ids_rejected(self, async_client: AsyncClient):
  80. resp = await async_client.post(
  81. "/api/v1/inventory/labels",
  82. json={"spool_ids": [], "template": "box_62x29"},
  83. )
  84. assert resp.status_code == 422
  85. @pytest.mark.asyncio
  86. @pytest.mark.integration
  87. async def test_unknown_spool_id_returns_404(self, async_client: AsyncClient, spool_factory):
  88. s = await spool_factory()
  89. resp = await async_client.post(
  90. "/api/v1/inventory/labels",
  91. json={"spool_ids": [s.id, 99999], "template": "ams_holder_74x33"},
  92. )
  93. assert resp.status_code == 404
  94. assert "99999" in resp.text
  95. @pytest.mark.asyncio
  96. @pytest.mark.integration
  97. async def test_preserves_request_order(self, async_client: AsyncClient, spool_factory):
  98. """Caller's `spool_ids` order should match the on-screen list — important
  99. for Avery sheet layouts where users curate the layout via filtering."""
  100. s1 = await spool_factory()
  101. s2 = await spool_factory()
  102. s3 = await spool_factory()
  103. # Reverse order; assert the route doesn't sort them. We can't peek
  104. # inside the PDF for assertion, but we can call render_labels directly
  105. # under the same patches and compare bytes deterministically.
  106. from backend.app.api.routes import labels as labels_module
  107. captured = {}
  108. original = labels_module.render_labels
  109. def _capture(template, data_list, **kwargs):
  110. captured["ids"] = [d.spool_id for d in data_list]
  111. return original(template, data_list, **kwargs)
  112. with patch.object(labels_module, "render_labels", side_effect=_capture):
  113. resp = await async_client.post(
  114. "/api/v1/inventory/labels",
  115. json={"spool_ids": [s3.id, s1.id, s2.id], "template": "avery_l7160"},
  116. )
  117. assert resp.status_code == 200
  118. assert captured["ids"] == [s3.id, s1.id, s2.id]
  119. @pytest.mark.asyncio
  120. @pytest.mark.integration
  121. async def test_forwards_sheet_starting_position(self, async_client: AsyncClient, spool_factory):
  122. spool = await spool_factory()
  123. from backend.app.api.routes import labels as labels_module
  124. captured = {}
  125. original = labels_module.render_labels
  126. def _capture(template, data_list, **kwargs):
  127. captured["starting_position"] = kwargs["starting_position"]
  128. return original(template, data_list, **kwargs)
  129. with patch.object(labels_module, "render_labels", side_effect=_capture):
  130. resp = await async_client.post(
  131. "/api/v1/inventory/labels",
  132. json={"spool_ids": [spool.id], "template": "avery_5160", "starting_position": 8},
  133. )
  134. assert resp.status_code == 200
  135. assert captured["starting_position"] == 8
  136. # ── /spoolman/labels (Spoolman-backed) ───────────────────────────────────────
  137. class TestSpoolmanLabels:
  138. @pytest.mark.asyncio
  139. @pytest.mark.integration
  140. async def test_returns_400_when_spoolman_disabled(self, async_client: AsyncClient):
  141. # Default state in tests: spoolman_enabled is unset / "false"
  142. resp = await async_client.post(
  143. "/api/v1/spoolman/labels",
  144. json={"spool_ids": [1], "template": "box_62x29"},
  145. )
  146. assert resp.status_code == 400
  147. assert "Spoolman" in resp.text
  148. @pytest.mark.asyncio
  149. @pytest.mark.integration
  150. async def test_returns_503_when_spoolman_unreachable(self, async_client: AsyncClient, db_session: AsyncSession):
  151. from backend.app.models.settings import Settings
  152. db_session.add(Settings(key="spoolman_enabled", value="true"))
  153. await db_session.commit()
  154. with patch("backend.app.api.routes.labels.get_spoolman_client", AsyncMock(return_value=None)):
  155. resp = await async_client.post(
  156. "/api/v1/spoolman/labels",
  157. json={"spool_ids": [1], "template": "box_62x29"},
  158. )
  159. assert resp.status_code == 503
  160. @pytest.mark.asyncio
  161. @pytest.mark.integration
  162. async def test_renders_pdf_from_spoolman_data(self, async_client: AsyncClient, db_session: AsyncSession):
  163. from backend.app.models.settings import Settings
  164. db_session.add(Settings(key="spoolman_enabled", value="true"))
  165. await db_session.commit()
  166. spoolman_spool = {
  167. "id": 42,
  168. "filament": {
  169. "name": "PolyTerra Sapphire Blue",
  170. "material": "PLA",
  171. "color_hex": "0033AA",
  172. "vendor": {"name": "Polymaker"},
  173. },
  174. "location": "Shelf 5, slot C",
  175. }
  176. mock_client = MagicMock()
  177. mock_client.is_connected = True
  178. mock_client.get_spools = AsyncMock(return_value=[spoolman_spool])
  179. with patch(
  180. "backend.app.api.routes.labels.get_spoolman_client",
  181. AsyncMock(return_value=mock_client),
  182. ):
  183. resp = await async_client.post(
  184. "/api/v1/spoolman/labels",
  185. json={"spool_ids": [42], "template": "avery_l7160"},
  186. )
  187. assert resp.status_code == 200
  188. assert resp.headers["content-type"] == "application/pdf"
  189. assert resp.content.startswith(b"%PDF")
  190. @pytest.mark.asyncio
  191. @pytest.mark.integration
  192. async def test_returns_404_when_spool_missing_from_spoolman(
  193. self, async_client: AsyncClient, db_session: AsyncSession
  194. ):
  195. from backend.app.models.settings import Settings
  196. db_session.add(Settings(key="spoolman_enabled", value="true"))
  197. await db_session.commit()
  198. mock_client = MagicMock()
  199. mock_client.is_connected = True
  200. mock_client.get_spools = AsyncMock(return_value=[{"id": 1, "filament": {"name": "X", "material": "PLA"}}])
  201. with patch(
  202. "backend.app.api.routes.labels.get_spoolman_client",
  203. AsyncMock(return_value=mock_client),
  204. ):
  205. resp = await async_client.post(
  206. "/api/v1/spoolman/labels",
  207. json={"spool_ids": [99], "template": "box_62x29"},
  208. )
  209. assert resp.status_code == 404
  210. assert "99" in resp.text
  211. # ── Validation cross-cutting ─────────────────────────────────────────────────
  212. class TestValidation:
  213. @pytest.mark.asyncio
  214. @pytest.mark.integration
  215. @pytest.mark.parametrize(
  216. ("template", "starting_position"),
  217. (("avery_5160", 0), ("avery_5160", 31), ("avery_l7160", 22), ("box_62x29", 2)),
  218. )
  219. async def test_invalid_starting_position_rejected(
  220. self,
  221. async_client: AsyncClient,
  222. template: str,
  223. starting_position: int,
  224. ):
  225. resp = await async_client.post(
  226. "/api/v1/inventory/labels",
  227. json={"spool_ids": [1], "template": template, "starting_position": starting_position},
  228. )
  229. assert resp.status_code == 422
  230. @pytest.mark.asyncio
  231. @pytest.mark.integration
  232. async def test_request_body_size_capped(self, async_client: AsyncClient):
  233. """spool_ids is bounded to MAX_LABELS_PER_REQUEST so a runaway client
  234. can't flood the renderer."""
  235. from backend.app.api.routes.labels import MAX_LABELS_PER_REQUEST
  236. resp = await async_client.post(
  237. "/api/v1/inventory/labels",
  238. json={
  239. "spool_ids": list(range(1, MAX_LABELS_PER_REQUEST + 2)),
  240. "template": "box_62x29",
  241. },
  242. )
  243. assert resp.status_code == 422
  244. # ── Fields, PNG and preview (#2981) ──────────────────────────────────────────
  245. def _spoolman_on(db_session: AsyncSession):
  246. from backend.app.models.settings import Settings
  247. db_session.add(Settings(key="spoolman_enabled", value="true"))
  248. def _spoolman_client(spools: list[dict]) -> MagicMock:
  249. client = MagicMock()
  250. client.is_connected = True
  251. client.get_spools = AsyncMock(return_value=spools)
  252. return client
  253. class TestLabelFieldsAndFormats:
  254. @pytest.mark.asyncio
  255. @pytest.mark.integration
  256. async def test_omitted_fields_print_the_default_set(self, async_client: AsyncClient, spool_factory):
  257. from backend.app.api.routes import labels as labels_module
  258. from backend.app.services.label_renderer import DEFAULT_LABEL_FIELDS
  259. spool = await spool_factory()
  260. captured = {}
  261. original = labels_module.render_labels
  262. def _capture(template, data_list, **kwargs):
  263. captured["fields"] = kwargs["fields"]
  264. return original(template, data_list, **kwargs)
  265. with patch.object(labels_module, "render_labels", side_effect=_capture):
  266. resp = await async_client.post(
  267. "/api/v1/inventory/labels", json={"spool_ids": [spool.id], "template": "box_40x30"}
  268. )
  269. assert resp.status_code == 200
  270. assert captured["fields"] == DEFAULT_LABEL_FIELDS
  271. @pytest.mark.asyncio
  272. @pytest.mark.integration
  273. async def test_chosen_fields_and_new_spool_data_reach_the_renderer(self, async_client: AsyncClient, spool_factory):
  274. from backend.app.api.routes import labels as labels_module
  275. spool = await spool_factory(material_number="MN-15", nozzle_temp_min=190, nozzle_temp_max=230, note="Dry first")
  276. captured = {}
  277. original = labels_module.render_labels
  278. def _capture(template, data_list, **kwargs):
  279. captured["fields"] = kwargs["fields"]
  280. captured["data"] = data_list[0]
  281. return original(template, data_list, **kwargs)
  282. with patch.object(labels_module, "render_labels", side_effect=_capture):
  283. resp = await async_client.post(
  284. "/api/v1/inventory/labels",
  285. json={
  286. "spool_ids": [spool.id],
  287. "template": "box_40x30",
  288. "fields": ["temps", "material_number", "temps"],
  289. },
  290. )
  291. assert resp.status_code == 200
  292. assert captured["fields"] == {"temps", "material_number"}
  293. data = captured["data"]
  294. assert (data.material_number, data.nozzle_temp_min, data.nozzle_temp_max) == ("MN-15", 190, 230)
  295. assert (data.label_weight, data.note) == (1000, "Dry first")
  296. assert data.added is not None
  297. @pytest.mark.asyncio
  298. @pytest.mark.integration
  299. async def test_unknown_field_rejected(self, async_client: AsyncClient, spool_factory):
  300. spool = await spool_factory()
  301. resp = await async_client.post(
  302. "/api/v1/inventory/labels",
  303. json={"spool_ids": [spool.id], "template": "box_40x30", "fields": ["brand", "password"]},
  304. )
  305. assert resp.status_code == 422
  306. @pytest.mark.asyncio
  307. @pytest.mark.integration
  308. @pytest.mark.parametrize("body", [{"format": "gif"}, {"format": "png", "dpi": 72}, {"spool_ids": [0]}])
  309. async def test_invalid_output_options_rejected(self, async_client: AsyncClient, body: dict):
  310. resp = await async_client.post(
  311. "/api/v1/inventory/labels", json={"spool_ids": [1], "template": "box_40x30", **body}
  312. )
  313. assert resp.status_code == 422
  314. @pytest.mark.asyncio
  315. @pytest.mark.integration
  316. async def test_one_label_as_png(self, async_client: AsyncClient, spool_factory):
  317. spool = await spool_factory()
  318. resp = await async_client.post(
  319. "/api/v1/inventory/labels",
  320. json={"spool_ids": [spool.id], "template": "box_40x30", "format": "png", "dpi": 203},
  321. )
  322. assert resp.status_code == 200
  323. assert resp.headers["content-type"] == "image/png"
  324. assert "bambuddy-labels-box_40x30.png" in resp.headers["content-disposition"]
  325. assert resp.content.startswith(b"\x89PNG")
  326. @pytest.mark.asyncio
  327. @pytest.mark.integration
  328. async def test_several_roll_labels_come_as_a_zip_named_by_spool(self, async_client: AsyncClient, spool_factory):
  329. import io
  330. import zipfile
  331. s1 = await spool_factory()
  332. s2 = await spool_factory()
  333. resp = await async_client.post(
  334. "/api/v1/inventory/labels",
  335. json={"spool_ids": [s2.id, s1.id], "template": "box_62x29", "format": "png"},
  336. )
  337. assert resp.status_code == 200
  338. assert resp.headers["content-type"] == "application/zip"
  339. with zipfile.ZipFile(io.BytesIO(resp.content)) as zf:
  340. assert zf.namelist() == [f"label-{s2.id}.png", f"label-{s1.id}.png"]
  341. assert all(zf.read(n).startswith(b"\x89PNG") for n in zf.namelist())
  342. @pytest.mark.asyncio
  343. @pytest.mark.integration
  344. async def test_sheet_pngs_are_numbered_by_page(self, async_client: AsyncClient, spool_factory):
  345. import io
  346. import zipfile
  347. s1 = await spool_factory()
  348. s2 = await spool_factory()
  349. resp = await async_client.post(
  350. "/api/v1/inventory/labels",
  351. # 21 per L7160 page; starting at 21 puts the second label on page two.
  352. json={
  353. "spool_ids": [s1.id, s2.id],
  354. "template": "avery_l7160",
  355. "format": "png",
  356. "starting_position": 21,
  357. },
  358. )
  359. assert resp.status_code == 200
  360. with zipfile.ZipFile(io.BytesIO(resp.content)) as zf:
  361. assert zf.namelist() == ["sheet-1.png", "sheet-2.png"]
  362. @pytest.mark.asyncio
  363. @pytest.mark.integration
  364. async def test_preview_is_one_png(self, async_client: AsyncClient, spool_factory):
  365. spool = await spool_factory()
  366. resp = await async_client.post(
  367. "/api/v1/inventory/labels/preview",
  368. json={"spool_id": spool.id, "template": "avery_5160", "fields": ["brand", "qr"]},
  369. )
  370. assert resp.status_code == 200
  371. assert resp.headers["content-type"] == "image/png"
  372. assert resp.headers["cache-control"] == "no-store"
  373. assert resp.content.startswith(b"\x89PNG")
  374. @pytest.mark.asyncio
  375. @pytest.mark.integration
  376. async def test_preview_of_unknown_spool_is_404(self, async_client: AsyncClient):
  377. resp = await async_client.post(
  378. "/api/v1/inventory/labels/preview", json={"spool_id": 99999, "template": "box_40x30"}
  379. )
  380. assert resp.status_code == 404
  381. class TestSpoolmanLabelParity:
  382. """A Spoolman spool's label is built from the same mapping the inventory
  383. page shows, so it carries what a built-in spool's label does."""
  384. SPOOL = {
  385. "id": 7,
  386. "filament": {
  387. "name": "PLA Matte",
  388. "material": "PLA",
  389. "color_hex": "000000",
  390. "vendor": {"name": "Bambu Lab"},
  391. "article_number": "MN-15",
  392. "settings_extruder_temp": 220,
  393. "weight": 1000,
  394. },
  395. "extra": {"bambu_color_name": '"Charcoal"'},
  396. "comment": "Dry first",
  397. "registered": "2026-09-01T10:00:00Z",
  398. "location": "Shelf 2",
  399. }
  400. async def _captured(self, async_client: AsyncClient, db_session: AsyncSession, spool: dict):
  401. from backend.app.api.routes import labels as labels_module
  402. _spoolman_on(db_session)
  403. await db_session.commit()
  404. captured = {}
  405. original = labels_module.render_labels
  406. def _capture(template, data_list, **kwargs):
  407. captured["data"] = data_list[0]
  408. return original(template, data_list, **kwargs)
  409. with (
  410. patch.object(labels_module, "render_labels", side_effect=_capture),
  411. patch(
  412. "backend.app.api.routes.labels.get_spoolman_client",
  413. AsyncMock(return_value=_spoolman_client([spool])),
  414. ),
  415. ):
  416. resp = await async_client.post(
  417. "/api/v1/spoolman/labels", json={"spool_ids": [spool["id"]], "template": "box_40x30"}
  418. )
  419. assert resp.status_code == 200
  420. return captured["data"]
  421. @pytest.mark.asyncio
  422. @pytest.mark.integration
  423. async def test_carries_subtype_colour_name_and_the_new_fields(
  424. self, async_client: AsyncClient, db_session: AsyncSession
  425. ):
  426. from datetime import date
  427. data = await self._captured(async_client, db_session, self.SPOOL)
  428. assert (data.material, data.subtype, data.name, data.brand) == ("PLA", "Matte", "Charcoal", "Bambu Lab")
  429. assert (data.material_number, data.nozzle_temp_min, data.label_weight) == ("MN-15", 220, 1000)
  430. assert (data.note, data.added, data.storage_location) == ("Dry first", date(2026, 9, 1), "Shelf 2")
  431. @pytest.mark.asyncio
  432. @pytest.mark.integration
  433. async def test_without_a_colour_name_the_filament_name_is_used(
  434. self, async_client: AsyncClient, db_session: AsyncSession
  435. ):
  436. """As before: the name line falls back to the filament name, not to the
  437. subtype the mapping synthesises as a colour name."""
  438. spool = {**self.SPOOL, "extra": {}}
  439. data = await self._captured(async_client, db_session, spool)
  440. assert data.name == "PLA Matte"
  441. @pytest.mark.asyncio
  442. @pytest.mark.integration
  443. async def test_preview_uses_spoolman(self, async_client: AsyncClient, db_session: AsyncSession):
  444. _spoolman_on(db_session)
  445. await db_session.commit()
  446. with patch(
  447. "backend.app.api.routes.labels.get_spoolman_client",
  448. AsyncMock(return_value=_spoolman_client([self.SPOOL])),
  449. ):
  450. resp = await async_client.post(
  451. "/api/v1/spoolman/labels/preview", json={"spool_id": 7, "template": "box_40x30"}
  452. )
  453. assert resp.status_code == 200
  454. assert resp.content.startswith(b"\x89PNG")
  455. @pytest.mark.asyncio
  456. @pytest.mark.integration
  457. async def test_preview_refused_when_spoolman_is_off(self, async_client: AsyncClient):
  458. resp = await async_client.post("/api/v1/spoolman/labels/preview", json={"spool_id": 7, "template": "box_40x30"})
  459. assert resp.status_code == 400