test_library_api.py 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939
  1. """Integration tests for Library API endpoints."""
  2. import io
  3. import tempfile
  4. import zipfile
  5. from pathlib import Path
  6. import pytest
  7. from httpx import AsyncClient
  8. from sqlalchemy import select
  9. from backend.app.core.config import settings as app_settings
  10. from backend.app.models.print_queue import PrintQueueItem
  11. async def _read_queue_item(db_session, item_id: int) -> PrintQueueItem:
  12. """Re-read a queue row the route just committed through its own session."""
  13. db_session.expire_all()
  14. return (await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))).scalar_one()
  15. class TestLibraryFoldersAPI:
  16. """Integration tests for library folders endpoints."""
  17. @pytest.fixture
  18. async def folder_factory(self, db_session):
  19. """Factory to create test folders."""
  20. _counter = [0]
  21. async def _create_folder(**kwargs):
  22. from backend.app.models.library import LibraryFolder
  23. _counter[0] += 1
  24. counter = _counter[0]
  25. defaults = {
  26. "name": f"Test Folder {counter}",
  27. }
  28. defaults.update(kwargs)
  29. folder = LibraryFolder(**defaults)
  30. db_session.add(folder)
  31. await db_session.commit()
  32. await db_session.refresh(folder)
  33. return folder
  34. return _create_folder
  35. @pytest.mark.asyncio
  36. @pytest.mark.integration
  37. async def test_list_folders_empty(self, async_client: AsyncClient, db_session):
  38. """Verify empty folder list returns empty array."""
  39. response = await async_client.get("/api/v1/library/folders")
  40. assert response.status_code == 200
  41. assert response.json() == []
  42. @pytest.mark.asyncio
  43. @pytest.mark.integration
  44. async def test_folder_tree_exposes_latest_activity_at_from_files(
  45. self, async_client: AsyncClient, folder_factory, db_session
  46. ):
  47. """#1770: folder list returns latest_activity_at = MAX(folder.updated_at,
  48. MAX(immediate-child file.updated_at)) so the frontend can sort by
  49. recent activity. Adding a file with a later updated_at must bubble it.
  50. """
  51. from datetime import datetime, timedelta
  52. from backend.app.models.library import LibraryFile
  53. folder = await folder_factory(name="Active Folder")
  54. # File whose updated_at is well after the folder's. Activity should
  55. # surface this timestamp, not the folder's stale one.
  56. future = datetime.utcnow() + timedelta(hours=24)
  57. db_session.add(
  58. LibraryFile(
  59. folder_id=folder.id,
  60. filename="model.3mf",
  61. file_path="library/model.3mf",
  62. file_type="3mf",
  63. file_size=123,
  64. updated_at=future,
  65. )
  66. )
  67. await db_session.commit()
  68. response = await async_client.get("/api/v1/library/folders")
  69. assert response.status_code == 200
  70. items = response.json()
  71. assert len(items) == 1
  72. item = items[0]
  73. assert item["id"] == folder.id
  74. assert item["latest_activity_at"] is not None
  75. # latest_activity_at should be at least the future stamp we set.
  76. assert item["latest_activity_at"] >= future.isoformat()
  77. @pytest.mark.asyncio
  78. @pytest.mark.integration
  79. async def test_folder_tree_latest_activity_at_falls_back_to_folder_updated_at(
  80. self, async_client: AsyncClient, folder_factory, db_session
  81. ):
  82. """#1770: a folder with no files reports its own updated_at, not null —
  83. otherwise the activity sort would dump every empty folder to one end."""
  84. await folder_factory(name="Empty Folder")
  85. response = await async_client.get("/api/v1/library/folders")
  86. assert response.status_code == 200
  87. items = response.json()
  88. assert len(items) == 1
  89. item = items[0]
  90. # latest_activity_at == folder.updated_at when there are no files
  91. assert item["latest_activity_at"] is not None
  92. @pytest.mark.asyncio
  93. @pytest.mark.integration
  94. async def test_create_folder(self, async_client: AsyncClient, db_session):
  95. """Verify folder can be created."""
  96. data = {"name": "New Folder"}
  97. response = await async_client.post("/api/v1/library/folders", json=data)
  98. assert response.status_code == 200
  99. result = response.json()
  100. assert result["name"] == "New Folder"
  101. assert result["id"] is not None
  102. @pytest.mark.asyncio
  103. @pytest.mark.integration
  104. async def test_create_nested_folder(self, async_client: AsyncClient, folder_factory, db_session):
  105. """Verify nested folder can be created."""
  106. parent = await folder_factory(name="Parent")
  107. data = {"name": "Child", "parent_id": parent.id}
  108. response = await async_client.post("/api/v1/library/folders", json=data)
  109. assert response.status_code == 200
  110. result = response.json()
  111. assert result["name"] == "Child"
  112. assert result["parent_id"] == parent.id
  113. @pytest.mark.asyncio
  114. @pytest.mark.integration
  115. async def test_get_folder(self, async_client: AsyncClient, folder_factory, db_session):
  116. """Verify single folder can be retrieved."""
  117. folder = await folder_factory(name="Test Folder")
  118. response = await async_client.get(f"/api/v1/library/folders/{folder.id}")
  119. assert response.status_code == 200
  120. result = response.json()
  121. assert result["id"] == folder.id
  122. assert result["name"] == "Test Folder"
  123. @pytest.mark.asyncio
  124. @pytest.mark.integration
  125. async def test_get_folder_not_found(self, async_client: AsyncClient, db_session):
  126. """Verify 404 for non-existent folder."""
  127. response = await async_client.get("/api/v1/library/folders/9999")
  128. assert response.status_code == 404
  129. @pytest.mark.asyncio
  130. @pytest.mark.integration
  131. async def test_update_folder(self, async_client: AsyncClient, folder_factory, db_session):
  132. """Verify folder can be updated."""
  133. folder = await folder_factory(name="Old Name")
  134. data = {"name": "New Name"}
  135. response = await async_client.put(f"/api/v1/library/folders/{folder.id}", json=data)
  136. assert response.status_code == 200
  137. result = response.json()
  138. assert result["name"] == "New Name"
  139. @pytest.mark.asyncio
  140. @pytest.mark.integration
  141. async def test_delete_folder(self, async_client: AsyncClient, folder_factory, db_session):
  142. """Verify folder can be deleted."""
  143. folder = await folder_factory()
  144. response = await async_client.delete(f"/api/v1/library/folders/{folder.id}")
  145. assert response.status_code == 200
  146. result = response.json()
  147. assert result.get("message") or result.get("success", True)
  148. class TestLibraryFilesAPI:
  149. """Integration tests for library files endpoints."""
  150. @pytest.fixture
  151. async def folder_factory(self, db_session):
  152. """Factory to create test folders."""
  153. _counter = [0]
  154. async def _create_folder(**kwargs):
  155. from backend.app.models.library import LibraryFolder
  156. _counter[0] += 1
  157. counter = _counter[0]
  158. defaults = {"name": f"Test Folder {counter}"}
  159. defaults.update(kwargs)
  160. folder = LibraryFolder(**defaults)
  161. db_session.add(folder)
  162. await db_session.commit()
  163. await db_session.refresh(folder)
  164. return folder
  165. return _create_folder
  166. @pytest.fixture
  167. async def file_factory(self, db_session):
  168. """Factory to create test files."""
  169. _counter = [0]
  170. async def _create_file(**kwargs):
  171. from backend.app.models.library import LibraryFile
  172. _counter[0] += 1
  173. counter = _counter[0]
  174. defaults = {
  175. "filename": f"test_file_{counter}.3mf",
  176. "file_path": f"/test/path/test_file_{counter}.3mf",
  177. "file_size": 1024,
  178. "file_type": "3mf",
  179. }
  180. defaults.update(kwargs)
  181. lib_file = LibraryFile(**defaults)
  182. db_session.add(lib_file)
  183. await db_session.commit()
  184. await db_session.refresh(lib_file)
  185. return lib_file
  186. return _create_file
  187. @pytest.mark.asyncio
  188. @pytest.mark.integration
  189. async def test_list_files_empty(self, async_client: AsyncClient, db_session):
  190. """Verify empty file list returns empty array."""
  191. response = await async_client.get("/api/v1/library/files")
  192. assert response.status_code == 200
  193. assert response.json() == []
  194. @pytest.mark.asyncio
  195. @pytest.mark.integration
  196. async def test_list_files_in_folder(self, async_client: AsyncClient, folder_factory, file_factory, db_session):
  197. """Verify files can be filtered by folder."""
  198. folder = await folder_factory()
  199. file1 = await file_factory(folder_id=folder.id)
  200. await file_factory() # File in root (no folder)
  201. response = await async_client.get(f"/api/v1/library/files?folder_id={folder.id}")
  202. assert response.status_code == 200
  203. result = response.json()
  204. assert len(result) == 1
  205. assert result[0]["id"] == file1.id
  206. @pytest.mark.asyncio
  207. @pytest.mark.integration
  208. async def test_list_files_by_project_id(self, async_client: AsyncClient, folder_factory, file_factory, db_session):
  209. """#932: project_id filter returns files across all folders linked to the project.
  210. Replaces the prior N+1 pattern where the frontend fired one request per
  211. linked folder. A single JOIN query must return every file in folders whose
  212. project_id matches, while excluding files from unlinked folders.
  213. """
  214. from backend.app.models.project import Project
  215. project = Project(name="Test Project for Files", color="#00ff00")
  216. db_session.add(project)
  217. await db_session.commit()
  218. await db_session.refresh(project)
  219. folder_a = await folder_factory(name="Folder A", project_id=project.id)
  220. folder_b = await folder_factory(name="Folder B", project_id=project.id)
  221. other_folder = await folder_factory(name="Unlinked")
  222. linked_a = await file_factory(folder_id=folder_a.id, filename="a.3mf")
  223. linked_b = await file_factory(folder_id=folder_b.id, filename="b.3mf")
  224. await file_factory(folder_id=other_folder.id, filename="unlinked.3mf")
  225. await file_factory(filename="root.3mf") # no folder → not part of any project
  226. response = await async_client.get(f"/api/v1/library/files?project_id={project.id}")
  227. assert response.status_code == 200
  228. result = response.json()
  229. ids = {f["id"] for f in result}
  230. assert ids == {linked_a.id, linked_b.id}
  231. @pytest.mark.asyncio
  232. @pytest.mark.integration
  233. async def test_list_files_folder_id_takes_precedence_over_project_id(
  234. self, async_client: AsyncClient, folder_factory, file_factory, db_session
  235. ):
  236. """When both folder_id and project_id are passed, folder_id wins.
  237. Documented precedence in list_files(): folder_id > project_id > include_root.
  238. This guards the behavior so a future refactor can't silently flip it.
  239. """
  240. from backend.app.models.project import Project
  241. project = Project(name="Precedence Project")
  242. db_session.add(project)
  243. await db_session.commit()
  244. await db_session.refresh(project)
  245. folder_linked = await folder_factory(name="Linked", project_id=project.id)
  246. folder_other = await folder_factory(name="Other")
  247. await file_factory(folder_id=folder_linked.id, filename="linked.3mf")
  248. other_file = await file_factory(folder_id=folder_other.id, filename="other.3mf")
  249. # folder_id points at a folder that is NOT in the project — must return
  250. # that folder's contents and ignore project_id entirely.
  251. response = await async_client.get(f"/api/v1/library/files?folder_id={folder_other.id}&project_id={project.id}")
  252. assert response.status_code == 200
  253. result = response.json()
  254. assert len(result) == 1
  255. assert result[0]["id"] == other_file.id
  256. @pytest.mark.asyncio
  257. @pytest.mark.integration
  258. async def test_list_files_internal_only(self, async_client: AsyncClient, folder_factory, file_factory, db_session):
  259. """#1621: `internal_only=true` restricts the listing to files in managed
  260. storage (`is_external=False`) so a linked NAS with hundreds of files
  261. doesn't drown the user's own uploads in the "All Files" sidebar view."""
  262. internal_folder = await folder_factory(name="My uploads")
  263. external_folder = await folder_factory(name="NAS", is_external=True, external_path="/mnt/nas")
  264. internal_file = await file_factory(folder_id=internal_folder.id, filename="mine.3mf", is_external=False)
  265. await file_factory(folder_id=external_folder.id, filename="nas.3mf", is_external=True)
  266. root_file = await file_factory(filename="root.3mf", is_external=False) # Root-uploaded is always internal.
  267. response = await async_client.get("/api/v1/library/files?include_root=false&internal_only=true")
  268. assert response.status_code == 200
  269. ids = {f["id"] for f in response.json()}
  270. assert ids == {internal_file.id, root_file.id}
  271. @pytest.mark.asyncio
  272. @pytest.mark.integration
  273. async def test_list_files_external_only(self, async_client: AsyncClient, folder_factory, file_factory, db_session):
  274. """#1621 symmetric: `external_only=true` returns the combined view
  275. across every linked external folder so users with several mounts can
  276. see all external content in one place without clicking each folder."""
  277. internal_folder = await folder_factory(name="My uploads")
  278. nas_a = await folder_factory(name="NAS A", is_external=True, external_path="/mnt/a")
  279. nas_b = await folder_factory(name="NAS B", is_external=True, external_path="/mnt/b")
  280. await file_factory(folder_id=internal_folder.id, filename="mine.3mf", is_external=False)
  281. ext_a = await file_factory(folder_id=nas_a.id, filename="a.3mf", is_external=True)
  282. ext_b = await file_factory(folder_id=nas_b.id, filename="b.3mf", is_external=True)
  283. response = await async_client.get("/api/v1/library/files?include_root=false&external_only=true")
  284. assert response.status_code == 200
  285. ids = {f["id"] for f in response.json()}
  286. assert ids == {ext_a.id, ext_b.id}
  287. @pytest.mark.asyncio
  288. @pytest.mark.integration
  289. async def test_list_files_internal_and_external_mutually_exclusive(self, async_client: AsyncClient, db_session):
  290. """Both flags together is a caller bug — fail loud (400) rather than
  291. silently picking one, so a frontend regression is caught immediately."""
  292. response = await async_client.get("/api/v1/library/files?internal_only=true&external_only=true")
  293. assert response.status_code == 400
  294. assert "mutually exclusive" in response.json()["detail"]
  295. @pytest.mark.asyncio
  296. @pytest.mark.integration
  297. async def test_get_file(self, async_client: AsyncClient, file_factory, db_session):
  298. """Verify single file can be retrieved."""
  299. lib_file = await file_factory(filename="test.3mf")
  300. response = await async_client.get(f"/api/v1/library/files/{lib_file.id}")
  301. assert response.status_code == 200
  302. result = response.json()
  303. assert result["id"] == lib_file.id
  304. assert result["filename"] == "test.3mf"
  305. @pytest.mark.asyncio
  306. @pytest.mark.integration
  307. async def test_get_file_not_found(self, async_client: AsyncClient, db_session):
  308. """Verify 404 for non-existent file."""
  309. response = await async_client.get("/api/v1/library/files/9999")
  310. assert response.status_code == 404
  311. @pytest.mark.asyncio
  312. @pytest.mark.integration
  313. async def test_delete_file(self, async_client: AsyncClient, file_factory, db_session):
  314. """Verify file can be deleted."""
  315. lib_file = await file_factory()
  316. response = await async_client.delete(f"/api/v1/library/files/{lib_file.id}")
  317. assert response.status_code == 200
  318. result = response.json()
  319. assert result.get("message") or result.get("success", True)
  320. @pytest.mark.asyncio
  321. @pytest.mark.integration
  322. async def test_rename_file(self, async_client: AsyncClient, file_factory, db_session):
  323. """Verify file can be renamed."""
  324. lib_file = await file_factory(filename="old_name.3mf")
  325. data = {"filename": "new_name.3mf"}
  326. response = await async_client.put(f"/api/v1/library/files/{lib_file.id}", json=data)
  327. assert response.status_code == 200
  328. result = response.json()
  329. assert result["filename"] == "new_name.3mf"
  330. @pytest.mark.asyncio
  331. @pytest.mark.integration
  332. async def test_rename_file_invalid_path_separator(self, async_client: AsyncClient, file_factory, db_session):
  333. """Verify file rename fails with a forward slash (FAT32-illegal, #1540)."""
  334. lib_file = await file_factory(filename="test.3mf")
  335. data = {"filename": "path/to/file.3mf"}
  336. response = await async_client.put(f"/api/v1/library/files/{lib_file.id}", json=data)
  337. assert response.status_code == 400
  338. assert "invalid character" in response.json()["detail"].lower()
  339. assert "/" in response.json()["detail"]
  340. @pytest.mark.asyncio
  341. @pytest.mark.integration
  342. async def test_rename_file_invalid_backslash(self, async_client: AsyncClient, file_factory, db_session):
  343. """Verify file rename fails with a backslash (FAT32-illegal, #1540)."""
  344. lib_file = await file_factory(filename="test.3mf")
  345. data = {"filename": "path\\to\\file.3mf"}
  346. response = await async_client.put(f"/api/v1/library/files/{lib_file.id}", json=data)
  347. assert response.status_code == 400
  348. assert "invalid character" in response.json()["detail"].lower()
  349. assert "\\" in response.json()["detail"]
  350. @pytest.mark.asyncio
  351. @pytest.mark.integration
  352. async def test_library_stats(self, async_client: AsyncClient, folder_factory, file_factory, db_session):
  353. """Verify library stats endpoint returns counts."""
  354. await folder_factory()
  355. await folder_factory()
  356. await file_factory()
  357. response = await async_client.get("/api/v1/library/stats")
  358. assert response.status_code == 200
  359. result = response.json()
  360. assert result["total_folders"] == 2
  361. assert result["total_files"] == 1
  362. @pytest.mark.asyncio
  363. @pytest.mark.integration
  364. async def test_file_list_includes_user_tracking_fields(self, async_client: AsyncClient, file_factory, db_session):
  365. """Verify file list response includes user tracking fields (Issue #206)."""
  366. lib_file = await file_factory(filename="test.3mf")
  367. response = await async_client.get("/api/v1/library/files?include_root=false")
  368. assert response.status_code == 200
  369. result = response.json()
  370. assert len(result) >= 1
  371. # Find our test file
  372. test_file = next((f for f in result if f["id"] == lib_file.id), None)
  373. assert test_file is not None
  374. # User tracking fields should be present (even if null)
  375. assert "created_by_id" in test_file
  376. assert "created_by_username" in test_file
  377. @pytest.mark.asyncio
  378. @pytest.mark.integration
  379. async def test_file_detail_includes_user_tracking_fields(self, async_client: AsyncClient, file_factory, db_session):
  380. """Verify file detail response includes user tracking fields (Issue #206)."""
  381. lib_file = await file_factory(filename="test_detail.3mf")
  382. response = await async_client.get(f"/api/v1/library/files/{lib_file.id}")
  383. assert response.status_code == 200
  384. result = response.json()
  385. # User tracking fields should be present (even if null)
  386. assert "created_by_id" in result
  387. assert "created_by_username" in result
  388. @pytest.mark.asyncio
  389. @pytest.mark.integration
  390. async def test_file_with_user_tracking(self, async_client: AsyncClient, db_session):
  391. """Verify file created with user shows username in response (Issue #206)."""
  392. from backend.app.models.library import LibraryFile
  393. from backend.app.models.user import User
  394. # Create a test user
  395. user = User(username="testuploader", password_hash="fakehash", role="user")
  396. db_session.add(user)
  397. await db_session.flush()
  398. # Create a file with created_by_id set
  399. lib_file = LibraryFile(
  400. filename="user_uploaded.3mf",
  401. file_path="/test/user_uploaded.3mf",
  402. file_size=2048,
  403. file_type="3mf",
  404. created_by_id=user.id,
  405. )
  406. db_session.add(lib_file)
  407. await db_session.commit()
  408. await db_session.refresh(lib_file)
  409. # Verify file detail shows username
  410. response = await async_client.get(f"/api/v1/library/files/{lib_file.id}")
  411. assert response.status_code == 200
  412. result = response.json()
  413. assert result["created_by_id"] == user.id
  414. assert result["created_by_username"] == "testuploader"
  415. # Verify file list also shows username
  416. response = await async_client.get("/api/v1/library/files?include_root=false")
  417. assert response.status_code == 200
  418. files = response.json()
  419. test_file = next((f for f in files if f["id"] == lib_file.id), None)
  420. assert test_file is not None
  421. assert test_file["created_by_id"] == user.id
  422. assert test_file["created_by_username"] == "testuploader"
  423. @pytest.mark.asyncio
  424. @pytest.mark.integration
  425. async def test_list_files_recursive_includes_subfolders(
  426. self, async_client: AsyncClient, folder_factory, file_factory
  427. ):
  428. """#1268: ?recursive=true with folder_id must include every descendant.
  429. Tree:
  430. toys/ ← f_toys, direct file "robot_top.3mf"
  431. cars/ ← child of toys, file "robot_car.3mf"
  432. race/ ← grandchild, file "robot_race.3mf"
  433. other/ ← unrelated, file "robot_other.3mf" (must NOT appear)
  434. """
  435. toys = await folder_factory(name="toys")
  436. cars = await folder_factory(name="cars", parent_id=toys.id)
  437. race = await folder_factory(name="race", parent_id=cars.id)
  438. other = await folder_factory(name="other")
  439. top = await file_factory(folder_id=toys.id, filename="robot_top.3mf")
  440. mid = await file_factory(folder_id=cars.id, filename="robot_car.3mf")
  441. deep = await file_factory(folder_id=race.id, filename="robot_race.3mf")
  442. await file_factory(folder_id=other.id, filename="robot_other.3mf")
  443. # Non-recursive: only the file directly under toys.
  444. r = await async_client.get(f"/api/v1/library/files?folder_id={toys.id}")
  445. assert r.status_code == 200
  446. assert {f["id"] for f in r.json()} == {top.id}
  447. # Recursive: toys + cars + race files, but NOT other/.
  448. r = await async_client.get(f"/api/v1/library/files?folder_id={toys.id}&recursive=true")
  449. assert r.status_code == 200
  450. assert {f["id"] for f in r.json()} == {top.id, mid.id, deep.id}
  451. @pytest.mark.asyncio
  452. @pytest.mark.integration
  453. async def test_list_files_recursive_without_folder_id_is_noop(
  454. self, async_client: AsyncClient, folder_factory, file_factory
  455. ):
  456. """recursive=true is meaningful only with folder_id — without it the
  457. existing include_root branch handles scoping. Just confirming the new
  458. param doesn't shadow that path."""
  459. folder = await folder_factory()
  460. f_in = await file_factory(folder_id=folder.id)
  461. f_root = await file_factory()
  462. r = await async_client.get("/api/v1/library/files?include_root=false&recursive=true")
  463. assert r.status_code == 200
  464. assert {f["id"] for f in r.json()} == {f_in.id, f_root.id}
  465. @pytest.mark.asyncio
  466. @pytest.mark.integration
  467. async def test_get_folder_readme_returns_first_markdown(
  468. self, async_client: AsyncClient, folder_factory, file_factory
  469. ):
  470. """#1268: /folders/{id}/readme reads on-disk content of the first .md."""
  471. folder = await folder_factory()
  472. with tempfile.NamedTemporaryFile(suffix=".md", delete=False, mode="w", encoding="utf-8") as f:
  473. f.write("# Robot\n\nA cute little robot.")
  474. md_path = f.name
  475. try:
  476. await file_factory(
  477. folder_id=folder.id,
  478. filename="README.md",
  479. file_path=md_path,
  480. file_type="md",
  481. file_size=Path(md_path).stat().st_size,
  482. )
  483. r = await async_client.get(f"/api/v1/library/folders/{folder.id}/readme")
  484. assert r.status_code == 200
  485. body = r.json()
  486. assert body["filename"] == "README.md"
  487. assert body["content"] == "# Robot\n\nA cute little robot."
  488. assert body["truncated"] is False
  489. finally:
  490. import os
  491. os.unlink(md_path)
  492. @pytest.mark.asyncio
  493. @pytest.mark.integration
  494. async def test_get_folder_readme_prefers_readme_over_other_md(
  495. self, async_client: AsyncClient, folder_factory, file_factory
  496. ):
  497. """When the folder has multiple .md files, README.md / description.md
  498. wins regardless of insertion order or filename case."""
  499. folder = await folder_factory()
  500. with tempfile.NamedTemporaryFile(suffix=".md", delete=False, mode="w", encoding="utf-8") as f:
  501. f.write("notes notes notes")
  502. notes_path = f.name
  503. with tempfile.NamedTemporaryFile(suffix=".md", delete=False, mode="w", encoding="utf-8") as f:
  504. f.write("the real one")
  505. readme_path = f.name
  506. try:
  507. # notes.md inserted FIRST — naive ordering would pick this one.
  508. await file_factory(
  509. folder_id=folder.id,
  510. filename="notes.md",
  511. file_path=notes_path,
  512. file_type="md",
  513. )
  514. await file_factory(
  515. folder_id=folder.id,
  516. filename="readme.md", # lowercase to confirm case-insensitive match
  517. file_path=readme_path,
  518. file_type="md",
  519. )
  520. r = await async_client.get(f"/api/v1/library/folders/{folder.id}/readme")
  521. assert r.status_code == 200
  522. assert r.json()["filename"] == "readme.md"
  523. assert r.json()["content"] == "the real one"
  524. finally:
  525. import os
  526. os.unlink(notes_path)
  527. os.unlink(readme_path)
  528. @pytest.mark.asyncio
  529. @pytest.mark.integration
  530. async def test_get_folder_readme_404_when_no_markdown(
  531. self, async_client: AsyncClient, folder_factory, file_factory
  532. ):
  533. """No .md in the folder → 404 so the FE can hide the side panel."""
  534. folder = await folder_factory()
  535. await file_factory(folder_id=folder.id, filename="model.3mf", file_type="3mf")
  536. r = await async_client.get(f"/api/v1/library/folders/{folder.id}/readme")
  537. assert r.status_code == 404
  538. @pytest.mark.asyncio
  539. @pytest.mark.integration
  540. async def test_get_folder_readme_404_when_folder_missing(self, async_client: AsyncClient):
  541. r = await async_client.get("/api/v1/library/folders/999999/readme")
  542. assert r.status_code == 404
  543. class TestLibraryAddToQueueAPI:
  544. """Integration tests for /api/v1/library/files/add-to-queue endpoint."""
  545. @pytest.fixture
  546. async def printer_factory(self, db_session):
  547. """Factory to create test printers."""
  548. _counter = [0]
  549. async def _create_printer(**kwargs):
  550. from backend.app.models.printer import Printer
  551. _counter[0] += 1
  552. counter = _counter[0]
  553. defaults = {
  554. "name": f"Test Printer {counter}",
  555. "ip_address": f"192.168.1.{100 + counter}",
  556. "serial_number": f"TESTSERIAL{counter:04d}",
  557. "access_code": "12345678",
  558. "model": "X1C",
  559. }
  560. defaults.update(kwargs)
  561. printer = Printer(**defaults)
  562. db_session.add(printer)
  563. await db_session.commit()
  564. await db_session.refresh(printer)
  565. return printer
  566. return _create_printer
  567. @pytest.fixture
  568. async def library_file_factory(self, db_session):
  569. """Factory to create test library files."""
  570. _counter = [0]
  571. async def _create_library_file(**kwargs):
  572. from backend.app.models.library import LibraryFile
  573. _counter[0] += 1
  574. counter = _counter[0]
  575. defaults = {
  576. "filename": f"test_file_{counter}.gcode.3mf",
  577. "file_path": f"/test/path/test_file_{counter}.gcode.3mf",
  578. "file_size": 1024,
  579. "file_type": "3mf",
  580. }
  581. defaults.update(kwargs)
  582. lib_file = LibraryFile(**defaults)
  583. db_session.add(lib_file)
  584. await db_session.commit()
  585. await db_session.refresh(lib_file)
  586. return lib_file
  587. return _create_library_file
  588. @pytest.fixture
  589. async def on_disk_file_factory(self, library_file_factory):
  590. """A library file whose bytes exist, so the route gets past its disk check."""
  591. written: list[Path] = []
  592. async def _create(**kwargs):
  593. counter = len(written) + 1
  594. rel_path = kwargs.pop("file_path", f"archive/library/files/queue_probe_{counter}.gcode.3mf")
  595. abs_path = Path(app_settings.base_dir) / rel_path
  596. abs_path.parent.mkdir(parents=True, exist_ok=True)
  597. abs_path.write_bytes(b"probe")
  598. written.append(abs_path)
  599. kwargs.setdefault("filename", f"queue_probe_{counter}.gcode.3mf")
  600. return await library_file_factory(file_path=rel_path, **kwargs)
  601. yield _create
  602. for path in written:
  603. path.unlink(missing_ok=True)
  604. @pytest.mark.asyncio
  605. @pytest.mark.integration
  606. async def test_add_to_queue_file_not_found(self, async_client: AsyncClient, printer_factory, db_session):
  607. """Nothing queued is not a success (#3112).
  608. This used to assert 200: the caller got an OK for a call that created
  609. nothing, with the reason in a body it had no cause to read. The reason
  610. is still reported, now where a failed call puts it.
  611. """
  612. await printer_factory()
  613. data = {"file_ids": [9999]}
  614. response = await async_client.post("/api/v1/library/files/add-to-queue", json=data)
  615. assert response.status_code == 400
  616. errors = response.json()["detail"]["errors"]
  617. assert len(errors) == 1
  618. assert errors[0]["file_id"] == 9999
  619. @pytest.mark.asyncio
  620. @pytest.mark.integration
  621. async def test_add_non_sliced_file_to_queue_fails(
  622. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  623. ):
  624. """Verify non-sliced file cannot be added to queue."""
  625. await printer_factory()
  626. lib_file = await library_file_factory(
  627. filename="model.stl",
  628. file_path="/test/path/model.stl",
  629. file_type="stl",
  630. )
  631. data = {"file_ids": [lib_file.id]}
  632. response = await async_client.post("/api/v1/library/files/add-to-queue", json=data)
  633. assert response.status_code == 400
  634. errors = response.json()["detail"]["errors"]
  635. assert len(errors) == 1
  636. assert "sliced" in errors[0]["error"].lower()
  637. @pytest.mark.asyncio
  638. @pytest.mark.integration
  639. async def test_partial_success_still_returns_200(
  640. self, async_client: AsyncClient, printer_factory, library_file_factory, on_disk_file_factory, db_session
  641. ):
  642. """Items really were created, so the call succeeded (#3112).
  643. The per-file errors ride along with them, which is the whole point of a
  644. bulk endpoint. Only a call that produced nothing is a failed call.
  645. """
  646. await printer_factory()
  647. good = await on_disk_file_factory()
  648. bad = await library_file_factory(filename="model.stl", file_path="/test/path/model.stl", file_type="stl")
  649. response = await async_client.post("/api/v1/library/files/add-to-queue", json={"file_ids": [good.id, bad.id]})
  650. assert response.status_code == 200
  651. result = response.json()
  652. assert [a["file_id"] for a in result["added"]] == [good.id]
  653. assert [e["file_id"] for e in result["errors"]] == [bad.id]
  654. @pytest.mark.asyncio
  655. @pytest.mark.integration
  656. async def test_target_model_is_inferred_so_the_item_can_be_dispatched(
  657. self, async_client: AsyncClient, printer_factory, on_disk_file_factory, db_session
  658. ):
  659. """#3112: an item with no printer and no target model is inert.
  660. The scheduler dispatches on `item.printer_id` or on
  661. `item.target_model or item.variants`; a row with neither matches no
  662. branch and waits forever. With an active X1C present, a file that says
  663. it was sliced for one is aimed at it.
  664. """
  665. await printer_factory(model="X1C")
  666. lib_file = await on_disk_file_factory(file_metadata={"sliced_for_model": "X1C"})
  667. response = await async_client.post("/api/v1/library/files/add-to-queue", json={"file_ids": [lib_file.id]})
  668. assert response.status_code == 200
  669. item = await _read_queue_item(db_session, response.json()["added"][0]["queue_item_id"])
  670. assert item.printer_id is None
  671. assert item.target_model == "X1C"
  672. @pytest.mark.asyncio
  673. @pytest.mark.integration
  674. async def test_no_printer_of_that_model_leaves_the_item_unassigned(
  675. self, async_client: AsyncClient, printer_factory, on_disk_file_factory, db_session
  676. ):
  677. """Aiming an item at hardware nobody owns would only look like progress.
  678. Having no H2D is the user's situation, not their mistake, so the file
  679. is still queued -- as the unassigned row it has always been.
  680. """
  681. await printer_factory(model="X1C")
  682. lib_file = await on_disk_file_factory(file_metadata={"sliced_for_model": "H2D"})
  683. response = await async_client.post("/api/v1/library/files/add-to-queue", json={"file_ids": [lib_file.id]})
  684. assert response.status_code == 200
  685. item = await _read_queue_item(db_session, response.json()["added"][0]["queue_item_id"])
  686. assert item.printer_id is None
  687. assert item.target_model is None
  688. @pytest.mark.asyncio
  689. @pytest.mark.integration
  690. async def test_explicit_printer_wins_over_the_files_own_model(
  691. self, async_client: AsyncClient, printer_factory, on_disk_file_factory, db_session
  692. ):
  693. printer = await printer_factory(model="X1C")
  694. # Read before the queue row is re-read: that expires the session, and
  695. # a lazy refresh of this row would then happen outside the greenlet.
  696. printer_id = printer.id
  697. lib_file = await on_disk_file_factory(file_metadata={"sliced_for_model": "X1C"})
  698. response = await async_client.post(
  699. "/api/v1/library/files/add-to-queue",
  700. json={"file_ids": [lib_file.id], "printer_id": printer_id},
  701. )
  702. assert response.status_code == 200
  703. item = await _read_queue_item(db_session, response.json()["added"][0]["queue_item_id"])
  704. assert item.printer_id == printer_id
  705. assert item.target_model is None
  706. @pytest.mark.asyncio
  707. @pytest.mark.integration
  708. async def test_incompatible_target_model_is_refused_per_file(
  709. self, async_client: AsyncClient, printer_factory, on_disk_file_factory, db_session
  710. ):
  711. """The same cross-model gate POST /queue/ applies (#2578).
  712. The scheduler hands model-based items to hardware with no human in the
  713. loop, so a file sliced for one model must not be aimed at another.
  714. """
  715. await printer_factory(model="A1")
  716. lib_file = await on_disk_file_factory(file_metadata={"sliced_for_model": "X1C"})
  717. response = await async_client.post(
  718. "/api/v1/library/files/add-to-queue",
  719. json={"file_ids": [lib_file.id], "target_model": "A1"},
  720. )
  721. assert response.status_code == 400
  722. assert "cannot be dispatched" in response.json()["detail"]["errors"][0]["error"]
  723. @pytest.mark.asyncio
  724. @pytest.mark.integration
  725. async def test_target_model_without_an_active_printer_is_refused(
  726. self, async_client: AsyncClient, printer_factory, on_disk_file_factory, db_session
  727. ):
  728. await printer_factory(model="X1C")
  729. lib_file = await on_disk_file_factory(file_metadata={"sliced_for_model": "H2D"})
  730. response = await async_client.post(
  731. "/api/v1/library/files/add-to-queue",
  732. json={"file_ids": [lib_file.id], "target_model": "H2D"},
  733. )
  734. assert response.status_code == 400
  735. assert "No active printers" in response.json()["detail"]
  736. @pytest.mark.asyncio
  737. @pytest.mark.integration
  738. async def test_printer_and_target_model_together_are_refused(
  739. self, async_client: AsyncClient, printer_factory, on_disk_file_factory, db_session
  740. ):
  741. printer = await printer_factory(model="X1C")
  742. lib_file = await on_disk_file_factory()
  743. response = await async_client.post(
  744. "/api/v1/library/files/add-to-queue",
  745. json={"file_ids": [lib_file.id], "printer_id": printer.id, "target_model": "X1C"},
  746. )
  747. assert response.status_code == 400
  748. assert "both" in response.json()["detail"].lower()
  749. @pytest.mark.asyncio
  750. @pytest.mark.integration
  751. async def test_unknown_printer_is_refused(
  752. self, async_client: AsyncClient, printer_factory, on_disk_file_factory, db_session
  753. ):
  754. await printer_factory(model="X1C")
  755. lib_file = await on_disk_file_factory()
  756. response = await async_client.post(
  757. "/api/v1/library/files/add-to-queue",
  758. json={"file_ids": [lib_file.id], "printer_id": 999999},
  759. )
  760. assert response.status_code == 400
  761. assert response.json()["detail"] == "Printer not found"
  762. @pytest.mark.asyncio
  763. @pytest.mark.integration
  764. async def test_a_filename_the_printer_cannot_store_is_refused(
  765. self, async_client: AsyncClient, printer_factory, on_disk_file_factory, db_session
  766. ):
  767. """The Bambu SD card is FAT32; an illegal character 553s at upload.
  768. POST /queue/ has rejected these at queue time since #1540. This route
  769. did not, so the mistake surfaced as a print that failed later.
  770. """
  771. await printer_factory(model="X1C")
  772. lib_file = await on_disk_file_factory(filename="bad:name?.gcode.3mf")
  773. response = await async_client.post("/api/v1/library/files/add-to-queue", json={"file_ids": [lib_file.id]})
  774. assert response.status_code == 400
  775. assert response.json()["detail"]["errors"][0]["file_id"] == lib_file.id
  776. class TestLibraryZipExtractAPI:
  777. """Integration tests for ZIP extraction endpoint."""
  778. @pytest.mark.asyncio
  779. @pytest.mark.integration
  780. async def test_extract_zip_invalid_file_type(self, async_client: AsyncClient, db_session):
  781. """Verify non-ZIP files are rejected."""
  782. # Create a fake file that's not a ZIP
  783. files = {"file": ("test.txt", b"This is not a zip file", "text/plain")}
  784. response = await async_client.post("/api/v1/library/files/extract-zip", files=files)
  785. assert response.status_code == 400
  786. assert "ZIP" in response.json()["detail"]
  787. @pytest.mark.asyncio
  788. @pytest.mark.integration
  789. async def test_extract_zip_basic(self, async_client: AsyncClient, db_session):
  790. """Verify basic ZIP extraction works."""
  791. import io
  792. # Create a simple ZIP file in memory
  793. zip_buffer = io.BytesIO()
  794. with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zf:
  795. zf.writestr("test1.txt", "Content of file 1")
  796. zf.writestr("test2.txt", "Content of file 2")
  797. zip_buffer.seek(0)
  798. files = {"file": ("test.zip", zip_buffer.read(), "application/zip")}
  799. response = await async_client.post("/api/v1/library/files/extract-zip", files=files)
  800. assert response.status_code == 200
  801. result = response.json()
  802. assert result["extracted"] == 2
  803. assert len(result["files"]) == 2
  804. assert len(result["errors"]) == 0
  805. @pytest.mark.asyncio
  806. @pytest.mark.integration
  807. async def test_extract_zip_with_folders(self, async_client: AsyncClient, db_session):
  808. """Verify ZIP extraction preserves folder structure."""
  809. import io
  810. # Create a ZIP file with folder structure
  811. zip_buffer = io.BytesIO()
  812. with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zf:
  813. zf.writestr("folder1/file1.txt", "Content 1")
  814. zf.writestr("folder1/subfolder/file2.txt", "Content 2")
  815. zf.writestr("folder2/file3.txt", "Content 3")
  816. zip_buffer.seek(0)
  817. files = {"file": ("test.zip", zip_buffer.read(), "application/zip")}
  818. params = {"preserve_structure": "true"}
  819. response = await async_client.post("/api/v1/library/files/extract-zip", files=files, params=params)
  820. assert response.status_code == 200
  821. result = response.json()
  822. assert result["extracted"] == 3
  823. assert result["folders_created"] >= 3 # folder1, folder1/subfolder, folder2
  824. @pytest.mark.asyncio
  825. @pytest.mark.integration
  826. async def test_extract_zip_flat(self, async_client: AsyncClient, db_session):
  827. """Verify ZIP extraction can extract flat (no folders)."""
  828. import io
  829. # Create a ZIP file with folder structure
  830. zip_buffer = io.BytesIO()
  831. with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zf:
  832. zf.writestr("folder/file1.txt", "Content 1")
  833. zf.writestr("folder/file2.txt", "Content 2")
  834. zip_buffer.seek(0)
  835. files = {"file": ("test.zip", zip_buffer.read(), "application/zip")}
  836. params = {"preserve_structure": "false"}
  837. response = await async_client.post("/api/v1/library/files/extract-zip", files=files, params=params)
  838. assert response.status_code == 200
  839. result = response.json()
  840. assert result["extracted"] == 2
  841. assert result["folders_created"] == 0 # No folders created when flat
  842. @pytest.mark.asyncio
  843. @pytest.mark.integration
  844. async def test_extract_zip_skips_macos_files(self, async_client: AsyncClient, db_session):
  845. """Verify ZIP extraction skips __MACOSX and hidden files."""
  846. import io
  847. # Create a ZIP file with macOS junk files
  848. zip_buffer = io.BytesIO()
  849. with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zf:
  850. zf.writestr("real_file.txt", "Real content")
  851. zf.writestr("__MACOSX/._real_file.txt", "macOS metadata")
  852. zf.writestr(".hidden_file", "Hidden content")
  853. zip_buffer.seek(0)
  854. files = {"file": ("test.zip", zip_buffer.read(), "application/zip")}
  855. response = await async_client.post("/api/v1/library/files/extract-zip", files=files)
  856. assert response.status_code == 200
  857. result = response.json()
  858. assert result["extracted"] == 1 # Only real_file.txt
  859. assert result["files"][0]["filename"] == "real_file.txt"
  860. @pytest.mark.asyncio
  861. @pytest.mark.integration
  862. async def test_extract_zip_create_folder_from_zip(self, async_client: AsyncClient, db_session):
  863. """Verify ZIP extraction creates a folder from the ZIP filename."""
  864. import io
  865. # Create a ZIP file with some files
  866. zip_buffer = io.BytesIO()
  867. with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zf:
  868. zf.writestr("file1.txt", "Content 1")
  869. zf.writestr("file2.txt", "Content 2")
  870. zip_buffer.seek(0)
  871. files = {"file": ("MyProject.zip", zip_buffer.read(), "application/zip")}
  872. params = {"create_folder_from_zip": "true", "preserve_structure": "false"}
  873. response = await async_client.post("/api/v1/library/files/extract-zip", files=files, params=params)
  874. assert response.status_code == 200
  875. result = response.json()
  876. assert result["extracted"] == 2
  877. assert result["folders_created"] == 1 # MyProject folder created
  878. # Verify the files are in a folder
  879. assert result["files"][0]["folder_id"] is not None
  880. assert result["files"][1]["folder_id"] is not None
  881. # Both files should be in the same folder
  882. assert result["files"][0]["folder_id"] == result["files"][1]["folder_id"]
  883. # Verify the folder was created with the right name
  884. folder_response = await async_client.get(f"/api/v1/library/folders/{result['files'][0]['folder_id']}")
  885. assert folder_response.status_code == 200
  886. folder = folder_response.json()
  887. assert folder["name"] == "MyProject"
  888. class TestLibraryStlThumbnailAPI:
  889. """Integration tests for STL thumbnail generation endpoints."""
  890. @pytest.fixture
  891. async def file_factory(self, db_session):
  892. """Factory to create test files."""
  893. _counter = [0]
  894. async def _create_file(**kwargs):
  895. from backend.app.models.library import LibraryFile
  896. _counter[0] += 1
  897. counter = _counter[0]
  898. defaults = {
  899. "filename": f"test_model_{counter}.stl",
  900. "file_path": f"/test/path/test_model_{counter}.stl",
  901. "file_size": 1024,
  902. "file_type": "stl",
  903. }
  904. defaults.update(kwargs)
  905. lib_file = LibraryFile(**defaults)
  906. db_session.add(lib_file)
  907. await db_session.commit()
  908. await db_session.refresh(lib_file)
  909. return lib_file
  910. return _create_file
  911. @pytest.mark.asyncio
  912. @pytest.mark.integration
  913. async def test_batch_generate_thumbnails_empty(self, async_client: AsyncClient, db_session):
  914. """Verify batch thumbnail generation with no files."""
  915. data = {"all_missing": True}
  916. response = await async_client.post("/api/v1/library/generate-stl-thumbnails", json=data)
  917. assert response.status_code == 200
  918. result = response.json()
  919. assert result["processed"] == 0
  920. assert result["succeeded"] == 0
  921. assert result["failed"] == 0
  922. assert result["results"] == []
  923. @pytest.mark.asyncio
  924. @pytest.mark.integration
  925. async def test_batch_generate_thumbnails_no_criteria(self, async_client: AsyncClient, db_session):
  926. """Verify batch thumbnail generation with no criteria returns empty."""
  927. data = {}
  928. response = await async_client.post("/api/v1/library/generate-stl-thumbnails", json=data)
  929. assert response.status_code == 200
  930. result = response.json()
  931. assert result["processed"] == 0
  932. @pytest.mark.asyncio
  933. @pytest.mark.integration
  934. async def test_batch_generate_thumbnails_file_not_on_disk(
  935. self, async_client: AsyncClient, file_factory, db_session
  936. ):
  937. """Verify batch thumbnail generation handles missing files gracefully."""
  938. # Create a file in DB but not on disk
  939. stl_file = await file_factory(
  940. filename="missing.stl",
  941. file_path="/nonexistent/path/missing.stl",
  942. thumbnail_path=None,
  943. )
  944. data = {"file_ids": [stl_file.id]}
  945. response = await async_client.post("/api/v1/library/generate-stl-thumbnails", json=data)
  946. assert response.status_code == 200
  947. result = response.json()
  948. assert result["processed"] == 1
  949. assert result["succeeded"] == 0
  950. assert result["failed"] == 1
  951. assert result["results"][0]["success"] is False
  952. assert "not found" in result["results"][0]["error"].lower()
  953. @pytest.mark.asyncio
  954. @pytest.mark.integration
  955. async def test_batch_generate_thumbnails_with_real_stl(self, async_client: AsyncClient, db_session):
  956. """Verify batch thumbnail generation with a real STL file."""
  957. from backend.app.models.library import LibraryFile
  958. # Create a simple ASCII STL cube
  959. stl_content = """solid cube
  960. facet normal 0 0 -1
  961. outer loop
  962. vertex 0 0 0
  963. vertex 1 0 0
  964. vertex 1 1 0
  965. endloop
  966. endfacet
  967. facet normal 0 0 1
  968. outer loop
  969. vertex 0 0 1
  970. vertex 1 1 1
  971. vertex 1 0 1
  972. endloop
  973. endfacet
  974. endsolid cube"""
  975. with tempfile.NamedTemporaryFile(suffix=".stl", delete=False, mode="w") as f:
  976. f.write(stl_content)
  977. stl_path = f.name
  978. try:
  979. # Create file in DB pointing to real STL
  980. lib_file = LibraryFile(
  981. filename="test_cube.stl",
  982. file_path=stl_path,
  983. file_size=len(stl_content),
  984. file_type="stl",
  985. thumbnail_path=None,
  986. )
  987. db_session.add(lib_file)
  988. await db_session.commit()
  989. await db_session.refresh(lib_file)
  990. data = {"file_ids": [lib_file.id]}
  991. response = await async_client.post("/api/v1/library/generate-stl-thumbnails", json=data)
  992. assert response.status_code == 200
  993. result = response.json()
  994. assert result["processed"] == 1
  995. # Result depends on whether trimesh/matplotlib are installed
  996. # Either succeeds or fails gracefully
  997. assert result["succeeded"] + result["failed"] == 1
  998. finally:
  999. import os
  1000. if os.path.exists(stl_path):
  1001. os.unlink(stl_path)
  1002. @pytest.mark.asyncio
  1003. @pytest.mark.integration
  1004. async def test_upload_file_with_stl_thumbnail_param(self, async_client: AsyncClient, db_session):
  1005. """Verify file upload accepts generate_stl_thumbnails parameter."""
  1006. # Create a simple STL file
  1007. stl_content = b"solid test\nendsolid test"
  1008. files = {"file": ("test.stl", stl_content, "application/octet-stream")}
  1009. params = {"generate_stl_thumbnails": "false"}
  1010. response = await async_client.post("/api/v1/library/files", files=files, params=params)
  1011. assert response.status_code == 200
  1012. result = response.json()
  1013. assert result["filename"] == "test.stl"
  1014. assert result["file_type"] == "stl"
  1015. # No thumbnail should be generated when disabled
  1016. assert result["thumbnail_path"] is None
  1017. @pytest.mark.asyncio
  1018. @pytest.mark.integration
  1019. async def test_extract_zip_with_stl_thumbnail_param(self, async_client: AsyncClient, db_session):
  1020. """Verify ZIP extraction accepts generate_stl_thumbnails parameter."""
  1021. # Create a ZIP file containing an STL
  1022. stl_content = b"solid test\nendsolid test"
  1023. zip_buffer = io.BytesIO()
  1024. with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zf:
  1025. zf.writestr("model.stl", stl_content)
  1026. zip_buffer.seek(0)
  1027. files = {"file": ("test.zip", zip_buffer.read(), "application/zip")}
  1028. params = {"generate_stl_thumbnails": "false"}
  1029. response = await async_client.post("/api/v1/library/files/extract-zip", files=files, params=params)
  1030. assert response.status_code == 200
  1031. result = response.json()
  1032. assert result["extracted"] == 1
  1033. assert result["files"][0]["filename"] == "model.stl"
  1034. @pytest.mark.asyncio
  1035. @pytest.mark.integration
  1036. async def test_batch_generate_thumbnails_by_folder(self, async_client: AsyncClient, file_factory, db_session):
  1037. """Verify batch thumbnail generation can filter by folder."""
  1038. from backend.app.models.library import LibraryFolder
  1039. # Create a folder
  1040. folder = LibraryFolder(name="STL Folder")
  1041. db_session.add(folder)
  1042. await db_session.commit()
  1043. await db_session.refresh(folder)
  1044. # Create STL file in folder (no thumbnail)
  1045. stl_in_folder = await file_factory(
  1046. filename="in_folder.stl",
  1047. folder_id=folder.id,
  1048. thumbnail_path=None,
  1049. )
  1050. # Create STL file at root (no thumbnail)
  1051. _stl_at_root = await file_factory(
  1052. filename="at_root.stl",
  1053. folder_id=None,
  1054. thumbnail_path=None,
  1055. )
  1056. # Request thumbnails only for files in folder
  1057. data = {"folder_id": folder.id, "all_missing": True}
  1058. response = await async_client.post("/api/v1/library/generate-stl-thumbnails", json=data)
  1059. assert response.status_code == 200
  1060. result = response.json()
  1061. # Should only process the file in the folder
  1062. assert result["processed"] == 1
  1063. assert result["results"][0]["file_id"] == stl_in_folder.id
  1064. @pytest.mark.asyncio
  1065. @pytest.mark.integration
  1066. async def test_batch_generate_thumbnails_all_missing(self, async_client: AsyncClient, file_factory, db_session):
  1067. """Verify batch thumbnail generation finds all STL files missing thumbnails."""
  1068. # Create files with and without thumbnails
  1069. _stl_with_thumb = await file_factory(
  1070. filename="with_thumb.stl",
  1071. thumbnail_path="/some/path/thumb.png",
  1072. )
  1073. stl_without_thumb1 = await file_factory(
  1074. filename="without_thumb1.stl",
  1075. thumbnail_path=None,
  1076. )
  1077. stl_without_thumb2 = await file_factory(
  1078. filename="without_thumb2.stl",
  1079. thumbnail_path=None,
  1080. )
  1081. data = {"all_missing": True}
  1082. response = await async_client.post("/api/v1/library/generate-stl-thumbnails", json=data)
  1083. assert response.status_code == 200
  1084. result = response.json()
  1085. # Should only process files without thumbnails
  1086. assert result["processed"] == 2
  1087. file_ids = {r["file_id"] for r in result["results"]}
  1088. assert stl_without_thumb1.id in file_ids
  1089. assert stl_without_thumb2.id in file_ids
  1090. class TestLibraryPathHelpers:
  1091. """Tests for path handling utilities used for backup portability."""
  1092. def test_to_relative_path_converts_absolute(self):
  1093. """Verify absolute paths are converted to relative paths."""
  1094. from backend.app.api.routes.library import to_relative_path
  1095. from backend.app.core.config import settings
  1096. base_dir = str(settings.base_dir)
  1097. abs_path = f"{base_dir}/archive/library/files/test.3mf"
  1098. rel_path = to_relative_path(abs_path)
  1099. assert not rel_path.startswith("/")
  1100. assert rel_path == "archive/library/files/test.3mf"
  1101. def test_to_relative_path_handles_path_object(self):
  1102. """Verify Path objects are handled correctly."""
  1103. from pathlib import Path
  1104. from backend.app.api.routes.library import to_relative_path
  1105. from backend.app.core.config import settings
  1106. abs_path = Path(settings.base_dir) / "archive" / "test.3mf"
  1107. rel_path = to_relative_path(abs_path)
  1108. assert not rel_path.startswith("/")
  1109. assert rel_path == "archive/test.3mf"
  1110. def test_to_relative_path_returns_empty_for_empty_input(self):
  1111. """Verify empty input returns empty string."""
  1112. from backend.app.api.routes.library import to_relative_path
  1113. assert to_relative_path("") == ""
  1114. assert to_relative_path(None) == ""
  1115. def test_to_absolute_path_converts_relative(self):
  1116. """Verify relative paths are converted to absolute paths."""
  1117. from backend.app.api.routes.library import to_absolute_path
  1118. from backend.app.core.config import settings
  1119. rel_path = "archive/library/files/test.3mf"
  1120. abs_path = to_absolute_path(rel_path)
  1121. assert abs_path is not None
  1122. assert abs_path.is_absolute()
  1123. assert str(abs_path) == f"{settings.base_dir}/archive/library/files/test.3mf"
  1124. def test_to_absolute_path_handles_already_absolute(self):
  1125. """Verify already absolute paths are returned as-is (for backwards compatibility)."""
  1126. from backend.app.api.routes.library import to_absolute_path
  1127. abs_path_str = "/data/archive/test.3mf"
  1128. result = to_absolute_path(abs_path_str)
  1129. assert result is not None
  1130. assert str(result) == abs_path_str
  1131. def test_to_absolute_path_returns_none_for_empty(self):
  1132. """Verify None/empty input returns None."""
  1133. from backend.app.api.routes.library import to_absolute_path
  1134. assert to_absolute_path(None) is None
  1135. assert to_absolute_path("") is None
  1136. class TestLibraryPermissions:
  1137. """Tests for library permission enforcement."""
  1138. @pytest.fixture
  1139. async def auth_setup(self, db_session):
  1140. """Set up auth with users of different permission levels."""
  1141. from backend.app.core.auth import create_access_token, get_password_hash
  1142. from backend.app.models.group import Group
  1143. from backend.app.models.settings import Settings
  1144. from backend.app.models.user import User
  1145. # Enable auth
  1146. settings = Settings(key="auth_enabled", value="true")
  1147. db_session.add(settings)
  1148. await db_session.commit()
  1149. # Groups are auto-seeded during db init, but we need to commit them
  1150. await db_session.commit()
  1151. # Get groups
  1152. from sqlalchemy import select
  1153. admin_group = (await db_session.execute(select(Group).where(Group.name == "Administrators"))).scalar_one()
  1154. operator_group = (await db_session.execute(select(Group).where(Group.name == "Operators"))).scalar_one()
  1155. viewer_group = (await db_session.execute(select(Group).where(Group.name == "Viewers"))).scalar_one()
  1156. password_hash = get_password_hash("password")
  1157. # Create users
  1158. admin_user = User(username="admin_lib", password_hash=password_hash, role="admin", is_active=True)
  1159. admin_user.groups.append(admin_group)
  1160. operator_user = User(username="operator_lib", password_hash=password_hash, is_active=True)
  1161. operator_user.groups.append(operator_group)
  1162. viewer_user = User(username="viewer_lib", password_hash=password_hash, is_active=True)
  1163. viewer_user.groups.append(viewer_group)
  1164. db_session.add_all([admin_user, operator_user, viewer_user])
  1165. await db_session.commit()
  1166. # Create tokens
  1167. admin_token = create_access_token(data={"sub": admin_user.username})
  1168. operator_token = create_access_token(data={"sub": operator_user.username})
  1169. viewer_token = create_access_token(data={"sub": viewer_user.username})
  1170. return {
  1171. "admin_user": admin_user,
  1172. "operator_user": operator_user,
  1173. "viewer_user": viewer_user,
  1174. "admin_token": admin_token,
  1175. "operator_token": operator_token,
  1176. "viewer_token": viewer_token,
  1177. }
  1178. @pytest.fixture
  1179. async def test_file(self, db_session, auth_setup):
  1180. """Create a test file owned by the operator user."""
  1181. from backend.app.models.library import LibraryFile
  1182. operator_user = auth_setup["operator_user"]
  1183. lib_file = LibraryFile(
  1184. filename="test.txt",
  1185. file_path="data/archive/library/files/test.txt",
  1186. file_type="txt",
  1187. file_size=100,
  1188. created_by_id=operator_user.id,
  1189. )
  1190. db_session.add(lib_file)
  1191. await db_session.commit()
  1192. await db_session.refresh(lib_file)
  1193. return lib_file
  1194. @pytest.mark.asyncio
  1195. @pytest.mark.integration
  1196. async def test_list_files_requires_library_read(self, async_client: AsyncClient, db_session, auth_setup):
  1197. """Verify list_files requires library:read permission."""
  1198. viewer_token = auth_setup["viewer_token"]
  1199. # Viewers have library:read, should succeed
  1200. response = await async_client.get("/api/v1/library/files", headers={"Authorization": f"Bearer {viewer_token}"})
  1201. assert response.status_code == 200
  1202. @pytest.mark.asyncio
  1203. @pytest.mark.integration
  1204. async def test_list_files_denied_without_permission(self, async_client: AsyncClient, db_session):
  1205. """Verify list_files denied without auth when auth is enabled."""
  1206. from backend.app.models.settings import Settings
  1207. # Enable auth
  1208. settings = Settings(key="auth_enabled", value="true")
  1209. db_session.add(settings)
  1210. await db_session.commit()
  1211. # Request without token should fail
  1212. response = await async_client.get("/api/v1/library/files")
  1213. assert response.status_code == 401
  1214. @pytest.mark.asyncio
  1215. @pytest.mark.integration
  1216. async def test_delete_file_own_by_owner(self, async_client: AsyncClient, db_session, auth_setup, test_file):
  1217. """Verify operator can delete their own files."""
  1218. from pathlib import Path
  1219. # Create actual file on disk so delete doesn't fail
  1220. from backend.app.core.config import settings as app_settings
  1221. file_path = Path(app_settings.base_dir) / test_file.file_path
  1222. file_path.parent.mkdir(parents=True, exist_ok=True)
  1223. file_path.write_text("test content")
  1224. operator_token = auth_setup["operator_token"]
  1225. response = await async_client.delete(
  1226. f"/api/v1/library/files/{test_file.id}", headers={"Authorization": f"Bearer {operator_token}"}
  1227. )
  1228. assert response.status_code == 200
  1229. @pytest.mark.asyncio
  1230. @pytest.mark.integration
  1231. async def test_delete_file_own_denied_for_others_file(self, async_client: AsyncClient, db_session, auth_setup):
  1232. """Verify operator cannot delete files owned by others."""
  1233. # Create another operator user with a file
  1234. from sqlalchemy import select
  1235. from backend.app.core.auth import create_access_token
  1236. from backend.app.models.group import Group
  1237. from backend.app.models.library import LibraryFile
  1238. from backend.app.models.user import User
  1239. operator_group = (await db_session.execute(select(Group).where(Group.name == "Operators"))).scalar_one()
  1240. from backend.app.core.auth import get_password_hash as get_pw_hash
  1241. other_user = User(username="other_op", password_hash=get_pw_hash("password"), is_active=True)
  1242. other_user.groups.append(operator_group)
  1243. db_session.add(other_user)
  1244. await db_session.commit()
  1245. await db_session.refresh(other_user)
  1246. # Create file owned by other user
  1247. other_file = LibraryFile(
  1248. filename="other.txt",
  1249. file_path="data/archive/library/files/other.txt",
  1250. file_type="txt",
  1251. file_size=100,
  1252. created_by_id=other_user.id,
  1253. )
  1254. db_session.add(other_file)
  1255. await db_session.commit()
  1256. await db_session.refresh(other_file)
  1257. # Original operator should not be able to delete it
  1258. operator_token = auth_setup["operator_token"]
  1259. response = await async_client.delete(
  1260. f"/api/v1/library/files/{other_file.id}", headers={"Authorization": f"Bearer {operator_token}"}
  1261. )
  1262. assert response.status_code == 403
  1263. assert "your own files" in response.json()["detail"].lower()
  1264. @pytest.mark.asyncio
  1265. @pytest.mark.integration
  1266. async def test_delete_file_admin_can_delete_any(self, async_client: AsyncClient, db_session, auth_setup):
  1267. """Verify admin can delete any file."""
  1268. from pathlib import Path
  1269. from backend.app.core.config import settings as app_settings
  1270. from backend.app.models.library import LibraryFile
  1271. # Create file owned by operator
  1272. operator_user = auth_setup["operator_user"]
  1273. lib_file = LibraryFile(
  1274. filename="admin_can_delete.txt",
  1275. file_path="data/archive/library/files/admin_can_delete.txt",
  1276. file_type="txt",
  1277. file_size=100,
  1278. created_by_id=operator_user.id,
  1279. )
  1280. db_session.add(lib_file)
  1281. await db_session.commit()
  1282. await db_session.refresh(lib_file)
  1283. # Create actual file on disk
  1284. file_path = Path(app_settings.base_dir) / lib_file.file_path
  1285. file_path.parent.mkdir(parents=True, exist_ok=True)
  1286. file_path.write_text("test content")
  1287. # Admin should be able to delete it
  1288. admin_token = auth_setup["admin_token"]
  1289. response = await async_client.delete(
  1290. f"/api/v1/library/files/{lib_file.id}", headers={"Authorization": f"Bearer {admin_token}"}
  1291. )
  1292. assert response.status_code == 200
  1293. @pytest.mark.asyncio
  1294. @pytest.mark.integration
  1295. async def test_viewer_cannot_delete_files(self, async_client: AsyncClient, db_session, auth_setup, test_file):
  1296. """Verify viewer cannot delete any files."""
  1297. viewer_token = auth_setup["viewer_token"]
  1298. response = await async_client.delete(
  1299. f"/api/v1/library/files/{test_file.id}", headers={"Authorization": f"Bearer {viewer_token}"}
  1300. )
  1301. # Viewers don't have delete_own or delete_all permissions
  1302. assert response.status_code == 403
  1303. # ---------- #1832: API-key curation under can_manage_library ----------
  1304. #
  1305. # require_ownership_permission gates API keys on `all_perm`, but the
  1306. # library deliberately split UPDATE_OWN/DELETE_OWN (allowed under
  1307. # can_manage_library) from UPDATE_ALL/DELETE_ALL (previously denied).
  1308. # That made the entire curation surface (DELETE, PUT rename, POST move)
  1309. # unreachable for API keys, including for files the key's owner uploaded.
  1310. # The fix folds UPDATE_ALL/DELETE_ALL into can_manage_library so the
  1311. # checker passes; LIBRARY_PURGE stays admin-only.
  1312. @pytest.fixture
  1313. async def manage_library_key(self, db_session, auth_setup):
  1314. """Mint an API key owned by the admin user with can_manage_library."""
  1315. from backend.app.core.auth import generate_api_key
  1316. from backend.app.models.api_key import APIKey
  1317. admin = auth_setup["admin_user"]
  1318. full_key, key_hash, key_prefix = generate_api_key()
  1319. row = APIKey(
  1320. name="lib-curation",
  1321. key_hash=key_hash,
  1322. key_prefix=key_prefix,
  1323. user_id=admin.id,
  1324. can_manage_library=True,
  1325. )
  1326. db_session.add(row)
  1327. await db_session.commit()
  1328. return full_key
  1329. @pytest.mark.asyncio
  1330. @pytest.mark.integration
  1331. async def test_apikey_with_manage_library_can_delete_file(
  1332. self, async_client: AsyncClient, db_session, auth_setup, test_file, manage_library_key
  1333. ):
  1334. """Pre-#1832 this 403'd with "administrative operations" because
  1335. LIBRARY_DELETE_ALL wasn't in _APIKEY_SCOPE_BY_PERMISSION."""
  1336. from pathlib import Path
  1337. from backend.app.core.config import settings as app_settings
  1338. # Materialise the file on disk so the delete handler doesn't 500 on
  1339. # the path it tries to unlink.
  1340. file_path = Path(app_settings.base_dir) / test_file.file_path
  1341. file_path.parent.mkdir(parents=True, exist_ok=True)
  1342. file_path.write_text("test content")
  1343. response = await async_client.delete(
  1344. f"/api/v1/library/files/{test_file.id}",
  1345. headers={"X-API-Key": manage_library_key},
  1346. )
  1347. assert response.status_code == 200, response.text
  1348. @pytest.mark.asyncio
  1349. @pytest.mark.integration
  1350. async def test_apikey_with_manage_library_can_rename_file(
  1351. self, async_client: AsyncClient, db_session, auth_setup, test_file, manage_library_key
  1352. ):
  1353. """PUT /library/files/{id} is gated on LIBRARY_UPDATE_ALL/OWN. Same
  1354. #1832 path as delete."""
  1355. response = await async_client.put(
  1356. f"/api/v1/library/files/{test_file.id}",
  1357. headers={"X-API-Key": manage_library_key},
  1358. json={"filename": "renamed.txt"},
  1359. )
  1360. assert response.status_code == 200, response.text
  1361. assert response.json()["filename"] == "renamed.txt"
  1362. @pytest.mark.asyncio
  1363. @pytest.mark.integration
  1364. async def test_apikey_with_manage_library_can_move_file(
  1365. self, async_client: AsyncClient, db_session, auth_setup, test_file, manage_library_key
  1366. ):
  1367. """POST /library/files/move (bulk) is gated on LIBRARY_UPDATE_ALL/OWN
  1368. — same checker, same #1832 path."""
  1369. # Create a target folder the move can land in.
  1370. from backend.app.models.library import LibraryFolder
  1371. folder = LibraryFolder(name="target")
  1372. db_session.add(folder)
  1373. await db_session.commit()
  1374. await db_session.refresh(folder)
  1375. response = await async_client.post(
  1376. "/api/v1/library/files/move",
  1377. headers={"X-API-Key": manage_library_key},
  1378. json={"file_ids": [test_file.id], "folder_id": folder.id},
  1379. )
  1380. assert response.status_code == 200, response.text
  1381. @pytest.mark.asyncio
  1382. @pytest.mark.integration
  1383. async def test_apikey_without_manage_library_still_blocked(
  1384. self, async_client: AsyncClient, db_session, auth_setup, test_file
  1385. ):
  1386. """Regression guard: a key WITHOUT can_manage_library must still get
  1387. 403 — the fix widens the allowed-permission set, it doesn't bypass
  1388. the per-key scope check."""
  1389. from backend.app.core.auth import generate_api_key
  1390. from backend.app.models.api_key import APIKey
  1391. admin = auth_setup["admin_user"]
  1392. full_key, key_hash, key_prefix = generate_api_key()
  1393. row = APIKey(
  1394. name="read-only",
  1395. key_hash=key_hash,
  1396. key_prefix=key_prefix,
  1397. user_id=admin.id,
  1398. can_read_status=True,
  1399. can_manage_library=False,
  1400. )
  1401. db_session.add(row)
  1402. await db_session.commit()
  1403. response = await async_client.delete(
  1404. f"/api/v1/library/files/{test_file.id}",
  1405. headers={"X-API-Key": full_key},
  1406. )
  1407. assert response.status_code == 403
  1408. @pytest.mark.asyncio
  1409. @pytest.mark.integration
  1410. async def test_apikey_with_manage_library_still_cannot_purge(
  1411. self, async_client: AsyncClient, db_session, auth_setup, manage_library_key
  1412. ):
  1413. """LIBRARY_PURGE deliberately stays in _APIKEY_DENIED_PERMISSIONS as
  1414. a genuinely destructive op that bypasses the soft-delete window.
  1415. can_manage_library does NOT grant it."""
  1416. response = await async_client.post(
  1417. "/api/v1/library/purge",
  1418. headers={"X-API-Key": manage_library_key},
  1419. json={"days_in_trash": 30},
  1420. )
  1421. assert response.status_code == 403
  1422. class TestPrintFileUploadValidation:
  1423. """#1401: pre-flight rejection of unprintable uploads at the library +
  1424. archive routes. Smoke tests the shared ``validate_print_file_upload``
  1425. helper through both surfaces a user can reach with a drag-drop."""
  1426. def _valid_3mf_bytes(self, name: str = "Metadata/plate_1.gcode") -> bytes:
  1427. """Build a minimal-but-real zip with the gcode-3mf magic in it so
  1428. the validator's ``startswith(b"PK\\x03\\x04")`` check passes."""
  1429. buf = io.BytesIO()
  1430. with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
  1431. zf.writestr(name, "; G-code\nG28\n")
  1432. return buf.getvalue()
  1433. @pytest.mark.asyncio
  1434. @pytest.mark.integration
  1435. async def test_library_rejects_raw_gcode_upload(self, async_client: AsyncClient, db_session):
  1436. """``Foo.gcode`` direct uploads are blocked at the library route —
  1437. the dispatcher would otherwise append ``.3mf`` and ship raw gcode
  1438. to the printer as a fake 3MF."""
  1439. files = {"file": ("plate_1.gcode", b"; raw gcode\nG28\n", "application/octet-stream")}
  1440. response = await async_client.post("/api/v1/library/files", files=files)
  1441. assert response.status_code == 400
  1442. # Error message must name the actual remedy, not just say "invalid".
  1443. assert "gcode.3mf" in response.json()["detail"]
  1444. @pytest.mark.asyncio
  1445. @pytest.mark.integration
  1446. async def test_library_rejects_non_zip_3mf_upload(self, async_client: AsyncClient, db_session):
  1447. """A ``.3mf`` upload whose body isn't a zip is rejected — covers
  1448. raw gcode renamed to .3mf, corrupted downloads, etc."""
  1449. files = {"file": ("model.3mf", b"; raw gcode\nG28\n", "application/octet-stream")}
  1450. response = await async_client.post("/api/v1/library/files", files=files)
  1451. assert response.status_code == 400
  1452. assert "ZIP container" in response.json()["detail"]
  1453. @pytest.mark.asyncio
  1454. @pytest.mark.integration
  1455. async def test_library_rejects_non_zip_gcode_3mf_upload(self, async_client: AsyncClient, db_session):
  1456. """The compound-extension ``.gcode.3mf`` case is gated by the same
  1457. zip-magic check — splitext returns just ``.3mf``, but the suffix
  1458. match covers both."""
  1459. files = {"file": ("plate_1.gcode.3mf", b"; raw gcode\nG28\n", "application/octet-stream")}
  1460. response = await async_client.post("/api/v1/library/files", files=files)
  1461. assert response.status_code == 400
  1462. assert "ZIP container" in response.json()["detail"]
  1463. @pytest.mark.asyncio
  1464. @pytest.mark.integration
  1465. async def test_library_accepts_valid_gcode_3mf_upload(self, async_client: AsyncClient, db_session):
  1466. """A real ``.gcode.3mf`` zip uploads successfully — the existing
  1467. happy path is not regressed by the new validation."""
  1468. files = {
  1469. "file": (
  1470. "plate_1.gcode.3mf",
  1471. self._valid_3mf_bytes(),
  1472. "application/zip",
  1473. )
  1474. }
  1475. response = await async_client.post("/api/v1/library/files", files=files)
  1476. assert response.status_code == 200
  1477. result = response.json()
  1478. assert result["filename"] == "plate_1.gcode.3mf"
  1479. @pytest.mark.asyncio
  1480. @pytest.mark.integration
  1481. async def test_library_upload_classifies_gcode_3mf_as_compound(self, async_client: AsyncClient, db_session):
  1482. """#1600 follow-up: upload path used to strip to the trailing
  1483. extension and store ``file_type='3mf'`` for sliced outputs, while
  1484. the external-folder scan stored ``file_type='gcode.3mf'``. Now
  1485. every ingest path goes through ``classify_file_type`` and
  1486. produces the canonical compound name."""
  1487. files = {
  1488. "file": (
  1489. "sliced.gcode.3mf",
  1490. self._valid_3mf_bytes(),
  1491. "application/zip",
  1492. )
  1493. }
  1494. response = await async_client.post("/api/v1/library/files", files=files)
  1495. assert response.status_code == 200
  1496. assert response.json()["file_type"] == "gcode.3mf"
  1497. @pytest.mark.asyncio
  1498. @pytest.mark.integration
  1499. async def test_library_get_gcode_endpoint_accepts_compound_file_type(self, async_client: AsyncClient, db_session):
  1500. """#1600 follow-up: pre-fix, ``GET /files/{id}/gcode`` only handled
  1501. ``file_type`` of ``gcode`` or ``3mf`` and 400'd on a row whose
  1502. ``file_type`` was ``gcode.3mf`` — exactly the rows the external-
  1503. folder scan was creating. The gate now treats both as 3MF and
  1504. unzips the embedded gcode the same way."""
  1505. from backend.app.models.library import LibraryFile
  1506. # Persist a real `.gcode.3mf` zip under file_type='gcode.3mf' so
  1507. # the endpoint hits the new branch.
  1508. with tempfile.NamedTemporaryFile(suffix=".gcode.3mf", delete=False) as tmp:
  1509. tmp.write(self._valid_3mf_bytes(name="Metadata/plate_1.gcode"))
  1510. tmp_path = tmp.name
  1511. lib_file = LibraryFile(
  1512. filename="sliced.gcode.3mf",
  1513. file_path=tmp_path,
  1514. file_type="gcode.3mf",
  1515. file_size=Path(tmp_path).stat().st_size,
  1516. )
  1517. db_session.add(lib_file)
  1518. await db_session.commit()
  1519. await db_session.refresh(lib_file)
  1520. response = await async_client.get(f"/api/v1/library/files/{lib_file.id}/gcode")
  1521. assert response.status_code == 200
  1522. assert b"G28" in response.content
  1523. @pytest.mark.asyncio
  1524. @pytest.mark.integration
  1525. async def test_library_get_gcode_recovers_legacy_gcode_type_for_3mf(self, async_client: AsyncClient, db_session):
  1526. """#1709 regression guard. Before the fix, ``slice_and_persist``
  1527. wrote a `.gcode.3mf` ZIP container to disk but stored the row with
  1528. ``file_type='gcode'`` — the preview endpoint then streamed the
  1529. ZIP body as ``text/plain`` and the embedded G-code viewer saw
  1530. ``PK\\x03\\x04...`` instead of the toolpath. New sliced rows now
  1531. store ``file_type='gcode.3mf'``; rows already written under the
  1532. bug self-heal because the endpoint also detects the ZIP via the
  1533. ``.gcode.3mf`` filename suffix when the column is still legacy."""
  1534. from backend.app.models.library import LibraryFile
  1535. with tempfile.NamedTemporaryFile(suffix=".gcode.3mf", delete=False) as tmp:
  1536. tmp.write(self._valid_3mf_bytes(name="Metadata/plate_1.gcode"))
  1537. tmp_path = tmp.name
  1538. lib_file = LibraryFile(
  1539. filename="legacy-sliced.gcode.3mf",
  1540. file_path=tmp_path,
  1541. file_type="gcode",
  1542. file_size=Path(tmp_path).stat().st_size,
  1543. )
  1544. db_session.add(lib_file)
  1545. await db_session.commit()
  1546. await db_session.refresh(lib_file)
  1547. response = await async_client.get(f"/api/v1/library/files/{lib_file.id}/gcode")
  1548. assert response.status_code == 200
  1549. assert response.headers["content-type"].startswith("text/plain")
  1550. assert b"G28" in response.content
  1551. # The whole point of #1709: must NOT be ZIP bytes shoved at the viewer.
  1552. assert not response.content.startswith(b"PK")
  1553. async def _multi_plate_file(self, db_session):
  1554. """A two-plate `.gcode.3mf` written plate 2 first, as Bambu Studio does.
  1555. The member order is copied from the file this was reported on — taking
  1556. the first `.gcode` in the zip opened plate 2.
  1557. """
  1558. from backend.app.models.library import LibraryFile
  1559. buf = io.BytesIO()
  1560. with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
  1561. zf.writestr("Metadata/plate_2.gcode", "; plate two\nG28\n")
  1562. zf.writestr("Metadata/plate_1.gcode", "; plate one\nG28\n")
  1563. with tempfile.NamedTemporaryFile(suffix=".gcode.3mf", delete=False) as tmp:
  1564. tmp.write(buf.getvalue())
  1565. tmp_path = tmp.name
  1566. lib_file = LibraryFile(
  1567. filename="two-plates.gcode.3mf",
  1568. file_path=tmp_path,
  1569. file_type="gcode.3mf",
  1570. file_size=Path(tmp_path).stat().st_size,
  1571. )
  1572. db_session.add(lib_file)
  1573. await db_session.commit()
  1574. await db_session.refresh(lib_file)
  1575. return lib_file
  1576. @pytest.mark.asyncio
  1577. @pytest.mark.integration
  1578. async def test_library_gcode_serves_the_requested_plate(self, async_client: AsyncClient, db_session):
  1579. """The viewer has always sent ``?plate=``; this route took no such
  1580. parameter, and FastAPI drops unknown query parameters without a word —
  1581. so picking a plate did nothing at all."""
  1582. lib_file = await self._multi_plate_file(db_session)
  1583. first = await async_client.get(f"/api/v1/library/files/{lib_file.id}/gcode?plate=1")
  1584. second = await async_client.get(f"/api/v1/library/files/{lib_file.id}/gcode?plate=2")
  1585. assert first.status_code == 200
  1586. assert b"plate one" in first.content
  1587. assert second.status_code == 200
  1588. assert b"plate two" in second.content
  1589. @pytest.mark.asyncio
  1590. @pytest.mark.integration
  1591. async def test_library_gcode_without_a_plate_serves_the_first_plate(self, async_client: AsyncClient, db_session):
  1592. """Not the first member in the zip — that is plate 2 in this file, and
  1593. opening a multi-plate file from the File Manager passes no plate."""
  1594. lib_file = await self._multi_plate_file(db_session)
  1595. response = await async_client.get(f"/api/v1/library/files/{lib_file.id}/gcode")
  1596. assert response.status_code == 200
  1597. assert b"plate one" in response.content
  1598. @pytest.mark.asyncio
  1599. @pytest.mark.integration
  1600. async def test_library_gcode_rejects_a_plate_the_file_does_not_hold(self, async_client: AsyncClient, db_session):
  1601. """404 rather than quietly rendering some other plate."""
  1602. lib_file = await self._multi_plate_file(db_session)
  1603. missing = await async_client.get(f"/api/v1/library/files/{lib_file.id}/gcode?plate=3")
  1604. zeroth = await async_client.get(f"/api/v1/library/files/{lib_file.id}/gcode?plate=0")
  1605. assert missing.status_code == 404
  1606. assert zeroth.status_code == 400
  1607. @pytest.mark.asyncio
  1608. @pytest.mark.integration
  1609. async def test_library_still_accepts_non_print_extensions(self, async_client: AsyncClient, db_session):
  1610. """STL / image / other non-print uploads bypass the validator
  1611. entirely — Bambuddy is also a library, not just a print dispatcher."""
  1612. files = {"file": ("model.stl", b"solid test\nendsolid test", "application/octet-stream")}
  1613. response = await async_client.post(
  1614. "/api/v1/library/files", files=files, params={"generate_stl_thumbnails": "false"}
  1615. )
  1616. assert response.status_code == 200
  1617. @pytest.mark.asyncio
  1618. @pytest.mark.integration
  1619. async def test_archive_upload_rejects_non_zip(self, async_client: AsyncClient, db_session):
  1620. """``POST /archives/upload`` shares the same validator — covers the
  1621. manual archive-upload entry point too."""
  1622. files = {"file": ("model.3mf", b"; raw gcode\nG28\n", "application/octet-stream")}
  1623. response = await async_client.post("/api/v1/archives/upload", files=files)
  1624. assert response.status_code == 400
  1625. assert "ZIP container" in response.json()["detail"]
  1626. @pytest.mark.asyncio
  1627. @pytest.mark.integration
  1628. async def test_archive_bulk_upload_collects_per_file_errors(self, async_client: AsyncClient, db_session):
  1629. """The bulk-archive route reports validation failures per file and
  1630. continues processing the remaining items — one bad upload in a
  1631. 10-file drag-drop must not abort the whole batch."""
  1632. good = self._valid_3mf_bytes()
  1633. bad = b"; raw gcode\nG28\n"
  1634. # httpx multipart with a list-of-tuples preserves order + same field name.
  1635. files = [
  1636. ("files", ("good.3mf", good, "application/zip")),
  1637. ("files", ("bad.3mf", bad, "application/octet-stream")),
  1638. ]
  1639. response = await async_client.post("/api/v1/archives/upload-bulk", files=files)
  1640. assert response.status_code == 200
  1641. body = response.json()
  1642. # The bulk route's archive_print may still reject the "good" file
  1643. # downstream (no printer match, etc.) — we don't care about that
  1644. # here; what matters is the bad file lands in `errors` with the
  1645. # validator's message and the route didn't 500.
  1646. assert body["failed"] >= 1
  1647. bad_errors = [e for e in body["errors"] if e["filename"] == "bad.3mf"]
  1648. assert bad_errors, body
  1649. assert "ZIP container" in bad_errors[0]["error"]