test_makerworld_routes.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. """Tests for the /makerworld/* route handlers.
  2. Mocks ``MakerWorldService`` so tests don't hit the real MakerWorld API. We
  3. still cover: URL validation, metadata passthrough, already-imported detection,
  4. source-URL-based dedupe on import, auto-creation of the MakerWorld default
  5. folder, canonical URL shape, filename basenaming, and the ``/recent-imports``
  6. listing endpoint.
  7. """
  8. from __future__ import annotations
  9. from datetime import datetime, timedelta
  10. from unittest.mock import AsyncMock, patch
  11. import pytest
  12. from backend.app.api.routes.makerworld import _canonical_url
  13. from backend.app.models.library import LibraryFile, LibraryFolder
  14. def _fake_service(**stubs):
  15. """Build an AsyncMock MakerWorldService with the given async method stubs."""
  16. svc = AsyncMock()
  17. svc.close = AsyncMock()
  18. for name, value in stubs.items():
  19. if callable(value) and not isinstance(value, AsyncMock):
  20. setattr(svc, name, AsyncMock(side_effect=value))
  21. else:
  22. setattr(svc, name, AsyncMock(return_value=value))
  23. return svc
  24. def _default_design(alphanumeric: str = "US2bb73b106683e5", model_id: int = 1400373):
  25. """Shape the backend needs from ``/design/{id}``: the alphanumeric
  26. ``modelId`` field that iot-service requires, plus at least one instance
  27. so the importer has a ``profile_id`` to fall back on."""
  28. return {
  29. "id": model_id,
  30. "modelId": alphanumeric,
  31. "title": "Seed Starter",
  32. "instances": [{"profileId": 298919107, "title": "9 cells"}],
  33. }
  34. def _default_manifest(name: str = "benchy.3mf"):
  35. return {
  36. "name": name,
  37. "url": "https://makerworld.bblmw.com/makerworld/model/X/Y/f.3mf?exp=1&key=k",
  38. }
  39. class TestCanonicalUrl:
  40. """Unit test the dedupe-key builder directly — regressions break dedupe
  41. silently so it's worth pinning the exact shape."""
  42. def test_without_profile_id(self):
  43. assert _canonical_url(1400373) == "https://makerworld.com/models/1400373"
  44. def test_without_profile_id_when_none(self):
  45. assert _canonical_url(1400373, None) == "https://makerworld.com/models/1400373"
  46. def test_with_profile_id(self):
  47. assert _canonical_url(1400373, 298919107) == ("https://makerworld.com/models/1400373#profileId-298919107")
  48. class TestStatus:
  49. @pytest.mark.asyncio
  50. async def test_status_reports_no_token_by_default(self, async_client, db_session):
  51. resp = await async_client.get("/api/v1/makerworld/status")
  52. assert resp.status_code == 200
  53. body = resp.json()
  54. # Fresh in-memory DB has no stored token, so can_download must be false
  55. assert body == {"has_cloud_token": False, "can_download": False}
  56. class TestResolve:
  57. @pytest.mark.asyncio
  58. async def test_rejects_non_makerworld_url(self, async_client):
  59. resp = await async_client.post(
  60. "/api/v1/makerworld/resolve",
  61. json={"url": "https://thingiverse.com/thing/1"},
  62. )
  63. assert resp.status_code == 400
  64. assert "makerworld" in resp.json()["detail"].lower()
  65. @pytest.mark.asyncio
  66. async def test_happy_path_returns_design_and_instances(self, async_client):
  67. design_payload = {"id": 1400373, "title": "Seed Starter"}
  68. instances_payload = {
  69. "total": 2,
  70. "hits": [
  71. {"id": 1452154, "profileId": 298919107, "title": "9 cells"},
  72. {"id": 1452158, "profileId": 298919564, "title": "12 cells"},
  73. ],
  74. }
  75. svc = _fake_service(get_design=design_payload, get_design_instances=instances_payload)
  76. with patch("backend.app.api.routes.makerworld._build_service", AsyncMock(return_value=svc)):
  77. resp = await async_client.post(
  78. "/api/v1/makerworld/resolve",
  79. json={"url": "https://makerworld.com/en/models/1400373-slug#profileId-1452154"},
  80. )
  81. assert resp.status_code == 200, resp.text
  82. body = resp.json()
  83. assert body["model_id"] == 1400373
  84. assert body["profile_id"] == 1452154
  85. assert body["design"] == design_payload
  86. assert len(body["instances"]) == 2
  87. assert body["already_imported_library_ids"] == []
  88. @pytest.mark.asyncio
  89. async def test_flags_already_imported_library_ids(self, async_client, db_session):
  90. # Seed a matching LibraryFile so resolve() reports it back
  91. existing = LibraryFile(
  92. filename="prev.3mf",
  93. file_path="library/files/prev.3mf",
  94. file_type="3mf",
  95. file_size=100,
  96. source_type="makerworld",
  97. source_url="https://makerworld.com/models/1400373",
  98. )
  99. db_session.add(existing)
  100. await db_session.commit()
  101. await db_session.refresh(existing)
  102. svc = _fake_service(
  103. get_design={"id": 1400373},
  104. get_design_instances={"total": 0, "hits": []},
  105. )
  106. with patch("backend.app.api.routes.makerworld._build_service", AsyncMock(return_value=svc)):
  107. resp = await async_client.post(
  108. "/api/v1/makerworld/resolve",
  109. json={"url": "https://makerworld.com/en/models/1400373"},
  110. )
  111. assert resp.status_code == 200, resp.text
  112. assert resp.json()["already_imported_library_ids"] == [existing.id]
  113. @pytest.mark.asyncio
  114. async def test_merges_compatibility_from_design_into_instances(self, async_client):
  115. """Per-instance printer compatibility info lives on
  116. ``design.instances[].extention.modelInfo`` but not on
  117. ``/instances/hits``. Resolve enriches each hit with both
  118. ``compatibility`` (primary printer the instance was sliced for) and
  119. ``otherCompatibility`` (extra printers the uploader marked it
  120. compatible with) so the frontend can show "sliced for A1 / also
  121. marked compatible with: H2D, P1S".
  122. """
  123. design_payload = {
  124. "id": 1400373,
  125. "title": "Seed Starter",
  126. "instances": [
  127. {
  128. "id": 1452154,
  129. "extention": {
  130. "modelInfo": {
  131. "compatibility": ["A1"],
  132. "otherCompatibility": ["H2D", "P1S"],
  133. }
  134. },
  135. },
  136. {
  137. "id": 1452158,
  138. "extention": {
  139. "modelInfo": {
  140. "compatibility": ["X1 Carbon"],
  141. "otherCompatibility": [],
  142. }
  143. },
  144. },
  145. ],
  146. }
  147. instances_payload = {
  148. "total": 2,
  149. "hits": [
  150. {"id": 1452154, "profileId": 298919107, "title": "9 cells"},
  151. {"id": 1452158, "profileId": 298919564, "title": "12 cells"},
  152. ],
  153. }
  154. svc = _fake_service(get_design=design_payload, get_design_instances=instances_payload)
  155. with patch("backend.app.api.routes.makerworld._build_service", AsyncMock(return_value=svc)):
  156. resp = await async_client.post(
  157. "/api/v1/makerworld/resolve",
  158. json={"url": "https://makerworld.com/en/models/1400373"},
  159. )
  160. assert resp.status_code == 200, resp.text
  161. instances = resp.json()["instances"]
  162. by_id = {i["id"]: i for i in instances}
  163. assert by_id[1452154]["compatibility"] == ["A1"]
  164. assert by_id[1452154]["otherCompatibility"] == ["H2D", "P1S"]
  165. assert by_id[1452158]["compatibility"] == ["X1 Carbon"]
  166. assert by_id[1452158]["otherCompatibility"] == []
  167. @pytest.mark.asyncio
  168. async def test_resolve_handles_missing_compatibility_gracefully(self, async_client):
  169. """Older designs (or hits without a matching design.instances entry)
  170. must not crash the resolve response — they just don't get the
  171. compat fields."""
  172. design_payload = {"id": 1400373, "instances": [{"id": 1452154}]} # no extention
  173. instances_payload = {
  174. "total": 2,
  175. "hits": [
  176. {"id": 1452154, "profileId": 298919107},
  177. {"id": 9999999, "profileId": 298919999}, # no design.instances match
  178. ],
  179. }
  180. svc = _fake_service(get_design=design_payload, get_design_instances=instances_payload)
  181. with patch("backend.app.api.routes.makerworld._build_service", AsyncMock(return_value=svc)):
  182. resp = await async_client.post(
  183. "/api/v1/makerworld/resolve",
  184. json={"url": "https://makerworld.com/en/models/1400373"},
  185. )
  186. assert resp.status_code == 200, resp.text
  187. instances = resp.json()["instances"]
  188. # First instance: design entry exists but no extention → fields absent or None.
  189. first = next(i for i in instances if i["id"] == 1452154)
  190. assert first.get("compatibility") is None
  191. assert first.get("otherCompatibility") is None
  192. # Second instance: no design entry at all → no enrichment, no crash.
  193. second = next(i for i in instances if i["id"] == 9999999)
  194. assert "compatibility" not in second or second["compatibility"] is None
  195. class TestImport:
  196. """End-to-end of POST /makerworld/import — mocks the service but exercises
  197. real DB writes, real ``save_3mf_bytes_to_library``, real folder auto-creation."""
  198. _FAKE_3MF_BYTES = b"PK\x03\x04not-a-real-3mf"
  199. @pytest.mark.asyncio
  200. async def test_returns_existing_on_source_url_match(self, async_client, db_session):
  201. """Re-importing a model we already have must NOT re-download.
  202. Dedupe key is ``{model_id}#profileId-{profile_id}`` — matches the
  203. canonical URL the route constructs, not the legacy model-only shape.
  204. """
  205. existing = LibraryFile(
  206. filename="already-here.3mf",
  207. file_path="library/files/already.3mf",
  208. file_type="3mf",
  209. file_size=500,
  210. source_type="makerworld",
  211. source_url="https://makerworld.com/models/1400373#profileId-298919107",
  212. )
  213. db_session.add(existing)
  214. await db_session.commit()
  215. await db_session.refresh(existing)
  216. svc = _fake_service(
  217. get_design=_default_design(),
  218. get_profile_download=_default_manifest(),
  219. )
  220. svc.download_3mf = AsyncMock() # must remain uncalled
  221. with patch("backend.app.api.routes.makerworld._build_service", AsyncMock(return_value=svc)):
  222. resp = await async_client.post(
  223. "/api/v1/makerworld/import",
  224. json={"model_id": 1400373, "profile_id": 298919107},
  225. )
  226. assert resp.status_code == 200, resp.text
  227. body = resp.json()
  228. assert body["library_file_id"] == existing.id
  229. assert body["was_existing"] is True
  230. assert body["profile_id"] == 298919107
  231. svc.download_3mf.assert_not_called()
  232. @pytest.mark.asyncio
  233. async def test_autocreates_makerworld_folder_when_folder_id_none(self, async_client, db_session):
  234. """Default destination — a top-level "MakerWorld" folder — is created
  235. on first import so users don't have to set it up."""
  236. svc = _fake_service(
  237. get_design=_default_design(),
  238. get_profile_download=_default_manifest(),
  239. download_3mf=(self._FAKE_3MF_BYTES, "benchy.3mf"),
  240. )
  241. with patch("backend.app.api.routes.makerworld._build_service", AsyncMock(return_value=svc)):
  242. resp = await async_client.post(
  243. "/api/v1/makerworld/import",
  244. json={"model_id": 1400373, "profile_id": 298919107, "folder_id": None},
  245. )
  246. assert resp.status_code == 200, resp.text
  247. # The new folder should exist, at the root.
  248. from sqlalchemy import select
  249. result = await db_session.execute(
  250. select(LibraryFolder).where(LibraryFolder.name == "MakerWorld", LibraryFolder.parent_id.is_(None))
  251. )
  252. folder = result.scalar_one()
  253. assert resp.json()["folder_id"] == folder.id
  254. @pytest.mark.asyncio
  255. async def test_uses_existing_folder_when_folder_id_provided(self, async_client, db_session):
  256. """Caller-supplied ``folder_id`` must be honoured even if the default
  257. ``MakerWorld`` folder also exists — no silent hijacking."""
  258. folder = LibraryFolder(name="MyCustomFolder", parent_id=None)
  259. db_session.add(folder)
  260. await db_session.commit()
  261. await db_session.refresh(folder)
  262. svc = _fake_service(
  263. get_design=_default_design(),
  264. get_profile_download=_default_manifest(),
  265. download_3mf=(self._FAKE_3MF_BYTES, "benchy.3mf"),
  266. )
  267. with patch("backend.app.api.routes.makerworld._build_service", AsyncMock(return_value=svc)):
  268. resp = await async_client.post(
  269. "/api/v1/makerworld/import",
  270. json={"model_id": 1400373, "profile_id": 298919107, "folder_id": folder.id},
  271. )
  272. assert resp.status_code == 200, resp.text
  273. assert resp.json()["folder_id"] == folder.id
  274. @pytest.mark.asyncio
  275. async def test_canonical_source_url_includes_profile_id(self, async_client, db_session):
  276. """The saved row's ``source_url`` must include ``#profileId-`` so two
  277. plates of the same model become two library rows (dedupe is per-plate)."""
  278. svc = _fake_service(
  279. get_design=_default_design(),
  280. get_profile_download=_default_manifest(),
  281. download_3mf=(self._FAKE_3MF_BYTES, "benchy.3mf"),
  282. )
  283. with patch("backend.app.api.routes.makerworld._build_service", AsyncMock(return_value=svc)):
  284. resp = await async_client.post(
  285. "/api/v1/makerworld/import",
  286. json={"model_id": 1400373, "profile_id": 298919107},
  287. )
  288. assert resp.status_code == 200, resp.text
  289. from sqlalchemy import select
  290. row = (
  291. await db_session.execute(select(LibraryFile).where(LibraryFile.id == resp.json()["library_file_id"]))
  292. ).scalar_one()
  293. assert row.source_url == "https://makerworld.com/models/1400373#profileId-298919107"
  294. @pytest.mark.asyncio
  295. async def test_filename_from_upstream_is_basenamed(self, async_client, db_session):
  296. """Defence-in-depth: a malicious ``name`` from the upstream manifest
  297. (e.g. ``"../../evil.3mf"``) must not persist path components into the
  298. library row. On-disk storage uses a UUID already, this is belt-and-
  299. braces protection for the human-readable field."""
  300. svc = _fake_service(
  301. get_design=_default_design(),
  302. get_profile_download={
  303. "name": "../../evil.3mf",
  304. "url": "https://makerworld.bblmw.com/makerworld/model/X/Y/f.3mf?exp=1&key=k",
  305. },
  306. download_3mf=(self._FAKE_3MF_BYTES, "fallback.3mf"),
  307. )
  308. with patch("backend.app.api.routes.makerworld._build_service", AsyncMock(return_value=svc)):
  309. resp = await async_client.post(
  310. "/api/v1/makerworld/import",
  311. json={"model_id": 1400373, "profile_id": 298919107},
  312. )
  313. assert resp.status_code == 200, resp.text
  314. assert resp.json()["filename"] == "evil.3mf"
  315. @pytest.mark.asyncio
  316. async def test_response_includes_profile_id(self, async_client, db_session):
  317. """UI matches imports back to the plate row via ``profile_id`` — the
  318. response field must always be populated, even when the caller provided
  319. it explicitly (rather than the backend falling back to design defaults)."""
  320. svc = _fake_service(
  321. get_design=_default_design(),
  322. get_profile_download=_default_manifest(),
  323. download_3mf=(self._FAKE_3MF_BYTES, "benchy.3mf"),
  324. )
  325. with patch("backend.app.api.routes.makerworld._build_service", AsyncMock(return_value=svc)):
  326. resp = await async_client.post(
  327. "/api/v1/makerworld/import",
  328. json={"model_id": 1400373, "profile_id": 298919107},
  329. )
  330. assert resp.status_code == 200, resp.text
  331. assert resp.json()["profile_id"] == 298919107
  332. @pytest.mark.asyncio
  333. async def test_import_to_writable_external_writes_bytes_to_mount(self, async_client, db_session, tmp_path):
  334. """#1645: importing into a writable external folder writes the bytes to
  335. ``<external_path>/<filename>`` and tags the row ``is_external=True`` —
  336. same shape as the multipart-upload path (#1112). Previously the bytes
  337. landed in the internal library dir under a UUID name while the row
  338. showed up under the external folder in the UI, leaving a NAS/SMB user
  339. unable to find their file on the mount."""
  340. ext_dir = tmp_path / "nas-makerworld"
  341. ext_dir.mkdir()
  342. folder = LibraryFolder(
  343. name="NAS Imports",
  344. parent_id=None,
  345. is_external=True,
  346. external_path=str(ext_dir),
  347. external_readonly=False,
  348. )
  349. db_session.add(folder)
  350. await db_session.commit()
  351. await db_session.refresh(folder)
  352. svc = _fake_service(
  353. get_design=_default_design(),
  354. get_profile_download=_default_manifest("seed-starter.3mf"),
  355. download_3mf=(self._FAKE_3MF_BYTES, "seed-starter.3mf"),
  356. )
  357. with patch("backend.app.api.routes.makerworld._build_service", AsyncMock(return_value=svc)):
  358. resp = await async_client.post(
  359. "/api/v1/makerworld/import",
  360. json={"model_id": 1400373, "profile_id": 298919107, "folder_id": folder.id},
  361. )
  362. assert resp.status_code == 200, resp.text
  363. from sqlalchemy import select
  364. row = (
  365. await db_session.execute(select(LibraryFile).where(LibraryFile.id == resp.json()["library_file_id"]))
  366. ).scalar_one()
  367. assert row.folder_id == folder.id
  368. assert row.is_external is True, "Row must be tagged external so re-scan can reconcile it"
  369. # External rows persist the absolute mount path (matches scan + upload paths).
  370. assert row.file_path == str(ext_dir / "seed-starter.3mf")
  371. on_disk = ext_dir / "seed-starter.3mf"
  372. assert on_disk.is_file(), "Bytes must land on the external mount, not in the internal library dir"
  373. assert on_disk.read_bytes() == self._FAKE_3MF_BYTES
  374. @pytest.mark.asyncio
  375. async def test_import_to_readonly_external_rejected_at_route(self, async_client, db_session, tmp_path):
  376. """The route-layer gate at ``makerworld.py:256-260`` rejects read-only
  377. externals with 403 before any download happens — so MakerWorld
  378. credentials and the upstream download bandwidth aren't wasted."""
  379. ext_dir = tmp_path / "nas-readonly"
  380. ext_dir.mkdir()
  381. folder = LibraryFolder(
  382. name="NAS read-only",
  383. parent_id=None,
  384. is_external=True,
  385. external_path=str(ext_dir),
  386. external_readonly=True,
  387. )
  388. db_session.add(folder)
  389. await db_session.commit()
  390. await db_session.refresh(folder)
  391. svc = _fake_service(
  392. get_design=_default_design(),
  393. get_profile_download=_default_manifest(),
  394. )
  395. svc.download_3mf = AsyncMock()
  396. with patch("backend.app.api.routes.makerworld._build_service", AsyncMock(return_value=svc)):
  397. resp = await async_client.post(
  398. "/api/v1/makerworld/import",
  399. json={"model_id": 1400373, "profile_id": 298919107, "folder_id": folder.id},
  400. )
  401. assert resp.status_code == 403, resp.text
  402. svc.download_3mf.assert_not_called()
  403. @pytest.mark.asyncio
  404. async def test_import_to_external_with_missing_path_returns_400(self, async_client, db_session, tmp_path):
  405. """If the external folder's mount has gone away (NAS unplugged, SMB
  406. share down), ``_resolve_upload_destination`` returns 400 before the
  407. write so we don't silently fall back to the internal library dir."""
  408. missing_dir = tmp_path / "vanished-mount" # NOTE: deliberately not created
  409. folder = LibraryFolder(
  410. name="NAS gone",
  411. parent_id=None,
  412. is_external=True,
  413. external_path=str(missing_dir),
  414. external_readonly=False,
  415. )
  416. db_session.add(folder)
  417. await db_session.commit()
  418. await db_session.refresh(folder)
  419. svc = _fake_service(
  420. get_design=_default_design(),
  421. get_profile_download=_default_manifest(),
  422. download_3mf=(self._FAKE_3MF_BYTES, "benchy.3mf"),
  423. )
  424. with patch("backend.app.api.routes.makerworld._build_service", AsyncMock(return_value=svc)):
  425. resp = await async_client.post(
  426. "/api/v1/makerworld/import",
  427. json={"model_id": 1400373, "profile_id": 298919107, "folder_id": folder.id},
  428. )
  429. assert resp.status_code == 400, resp.text
  430. assert "not accessible" in resp.text.lower()
  431. @pytest.mark.asyncio
  432. async def test_import_to_external_with_name_collision_returns_409(self, async_client, db_session, tmp_path):
  433. """A user-visible 409 fires when the filename already exists on the
  434. external mount, instead of silently overwriting a file the user put
  435. there outside Bambuddy."""
  436. ext_dir = tmp_path / "nas-collide"
  437. ext_dir.mkdir()
  438. (ext_dir / "benchy.3mf").write_bytes(b"pre-existing")
  439. folder = LibraryFolder(
  440. name="NAS collide",
  441. parent_id=None,
  442. is_external=True,
  443. external_path=str(ext_dir),
  444. external_readonly=False,
  445. )
  446. db_session.add(folder)
  447. await db_session.commit()
  448. await db_session.refresh(folder)
  449. svc = _fake_service(
  450. get_design=_default_design(),
  451. get_profile_download=_default_manifest("benchy.3mf"),
  452. download_3mf=(self._FAKE_3MF_BYTES, "benchy.3mf"),
  453. )
  454. with patch("backend.app.api.routes.makerworld._build_service", AsyncMock(return_value=svc)):
  455. resp = await async_client.post(
  456. "/api/v1/makerworld/import",
  457. json={"model_id": 1400373, "profile_id": 298919107, "folder_id": folder.id},
  458. )
  459. assert resp.status_code == 409, resp.text
  460. # Pre-existing file's contents must not be clobbered by the failed write.
  461. assert (ext_dir / "benchy.3mf").read_bytes() == b"pre-existing"
  462. class TestRecentImports:
  463. """GET /makerworld/recent-imports — sidebar feed on the MakerWorld page."""
  464. @pytest.mark.asyncio
  465. async def test_empty_when_no_makerworld_imports(self, async_client):
  466. resp = await async_client.get("/api/v1/makerworld/recent-imports")
  467. assert resp.status_code == 200
  468. assert resp.json() == []
  469. @pytest.mark.asyncio
  470. async def test_returns_items_newest_first(self, async_client, db_session):
  471. # Seed three rows with explicit, decreasing created_at timestamps so
  472. # ordering doesn't depend on auto-increment PK ordering.
  473. base = datetime(2025, 1, 1, 12, 0, 0)
  474. older = LibraryFile(
  475. filename="older.3mf",
  476. file_path="library/older.3mf",
  477. file_type="3mf",
  478. file_size=10,
  479. source_type="makerworld",
  480. source_url="https://makerworld.com/models/1",
  481. created_at=base,
  482. )
  483. middle = LibraryFile(
  484. filename="middle.3mf",
  485. file_path="library/middle.3mf",
  486. file_type="3mf",
  487. file_size=10,
  488. source_type="makerworld",
  489. source_url="https://makerworld.com/models/2",
  490. created_at=base + timedelta(hours=1),
  491. )
  492. newer = LibraryFile(
  493. filename="newer.3mf",
  494. file_path="library/newer.3mf",
  495. file_type="3mf",
  496. file_size=10,
  497. source_type="makerworld",
  498. source_url="https://makerworld.com/models/3",
  499. created_at=base + timedelta(hours=2),
  500. )
  501. # Unrelated non-MakerWorld file must NOT show up.
  502. other = LibraryFile(
  503. filename="manual.3mf",
  504. file_path="library/manual.3mf",
  505. file_type="3mf",
  506. file_size=10,
  507. source_type=None,
  508. source_url=None,
  509. created_at=base + timedelta(hours=3),
  510. )
  511. db_session.add_all([older, middle, newer, other])
  512. await db_session.commit()
  513. resp = await async_client.get("/api/v1/makerworld/recent-imports")
  514. assert resp.status_code == 200, resp.text
  515. body = resp.json()
  516. names = [row["filename"] for row in body]
  517. assert names == ["newer.3mf", "middle.3mf", "older.3mf"]
  518. @pytest.mark.asyncio
  519. async def test_response_matches_pydantic_shape(self, async_client, db_session):
  520. """Lock the exact key set so the frontend's typed ``MakerworldRecentImport``
  521. doesn't silently fall out of sync with the backend schema."""
  522. row = LibraryFile(
  523. filename="x.3mf",
  524. file_path="library/x.3mf",
  525. file_type="3mf",
  526. file_size=10,
  527. source_type="makerworld",
  528. source_url="https://makerworld.com/models/1#profileId-2",
  529. )
  530. db_session.add(row)
  531. await db_session.commit()
  532. resp = await async_client.get("/api/v1/makerworld/recent-imports")
  533. assert resp.status_code == 200, resp.text
  534. item = resp.json()[0]
  535. assert set(item.keys()) == {
  536. "library_file_id",
  537. "filename",
  538. "folder_id",
  539. "thumbnail_path",
  540. "source_url",
  541. "created_at",
  542. }
  543. assert item["source_url"] == "https://makerworld.com/models/1#profileId-2"
  544. @pytest.mark.asyncio
  545. async def test_limit_is_honoured(self, async_client, db_session):
  546. for i in range(5):
  547. db_session.add(
  548. LibraryFile(
  549. filename=f"f{i}.3mf",
  550. file_path=f"library/f{i}.3mf",
  551. file_type="3mf",
  552. file_size=10,
  553. source_type="makerworld",
  554. source_url=f"https://makerworld.com/models/{i}",
  555. )
  556. )
  557. await db_session.commit()
  558. resp = await async_client.get("/api/v1/makerworld/recent-imports?limit=2")
  559. assert resp.status_code == 200
  560. assert len(resp.json()) == 2
  561. @pytest.mark.asyncio
  562. async def test_limit_clamped_to_minimum(self, async_client, db_session):
  563. """``limit=0`` or negative must clamp to 1 — a zero limit would be
  564. silently swallowed by SQL and return nothing, which is surprising."""
  565. db_session.add(
  566. LibraryFile(
  567. filename="one.3mf",
  568. file_path="library/one.3mf",
  569. file_type="3mf",
  570. file_size=10,
  571. source_type="makerworld",
  572. source_url="https://makerworld.com/models/1",
  573. )
  574. )
  575. await db_session.commit()
  576. resp = await async_client.get("/api/v1/makerworld/recent-imports?limit=0")
  577. assert resp.status_code == 200
  578. assert len(resp.json()) == 1
  579. @pytest.mark.asyncio
  580. async def test_limit_clamped_to_maximum(self, async_client, db_session):
  581. """``limit`` is clamped to 50 so a pathological client can't request
  582. the whole table. We seed 60 rows and assert the response is capped."""
  583. for i in range(60):
  584. db_session.add(
  585. LibraryFile(
  586. filename=f"f{i}.3mf",
  587. file_path=f"library/f{i}.3mf",
  588. file_type="3mf",
  589. file_size=10,
  590. source_type="makerworld",
  591. source_url=f"https://makerworld.com/models/{i}",
  592. )
  593. )
  594. await db_session.commit()
  595. resp = await async_client.get("/api/v1/makerworld/recent-imports?limit=9999")
  596. assert resp.status_code == 200
  597. assert len(resp.json()) == 50