test_makerworld_routes.py 29 KB

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