test_archives_api.py 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574
  1. """Integration tests for Archives API endpoints.
  2. Tests the full request/response cycle for /api/v1/archives/ endpoints.
  3. """
  4. from pathlib import Path
  5. import pytest
  6. from httpx import AsyncClient
  7. class TestArchivesAPI:
  8. """Integration tests for /api/v1/archives/ endpoints."""
  9. # ========================================================================
  10. # List endpoints
  11. # ========================================================================
  12. @pytest.mark.asyncio
  13. @pytest.mark.integration
  14. async def test_list_archives_empty(self, async_client: AsyncClient):
  15. """Verify empty list is returned when no archives exist."""
  16. response = await async_client.get("/api/v1/archives/")
  17. assert response.status_code == 200
  18. data = response.json()
  19. assert isinstance(data, list)
  20. assert len(data) == 0
  21. @pytest.mark.asyncio
  22. @pytest.mark.integration
  23. async def test_list_archives_with_data(
  24. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  25. ):
  26. """Verify list returns existing archives."""
  27. printer = await printer_factory()
  28. await archive_factory(printer.id, print_name="Test Archive")
  29. response = await async_client.get("/api/v1/archives/")
  30. assert response.status_code == 200
  31. data = response.json()
  32. assert isinstance(data, list)
  33. assert len(data) >= 1
  34. assert any(a["print_name"] == "Test Archive" for a in data)
  35. @pytest.mark.asyncio
  36. @pytest.mark.integration
  37. async def test_list_archives_pagination(
  38. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  39. ):
  40. """Verify pagination works correctly."""
  41. printer = await printer_factory()
  42. # Create 5 archives
  43. for i in range(5):
  44. await archive_factory(printer.id, print_name=f"Archive {i}")
  45. # Get first page with limit 2
  46. response = await async_client.get("/api/v1/archives/?limit=2&offset=0")
  47. assert response.status_code == 200
  48. data = response.json()
  49. assert isinstance(data, list)
  50. assert len(data) == 2
  51. @pytest.mark.asyncio
  52. @pytest.mark.integration
  53. async def test_list_archives_filter_by_printer(
  54. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  55. ):
  56. """Verify filtering by printer_id works."""
  57. printer1 = await printer_factory(name="Printer 1", serial_number="00M09A000000001")
  58. printer2 = await printer_factory(name="Printer 2", serial_number="00M09A000000002")
  59. await archive_factory(printer1.id, print_name="Printer 1 Archive")
  60. await archive_factory(printer2.id, print_name="Printer 2 Archive")
  61. response = await async_client.get(f"/api/v1/archives/?printer_id={printer1.id}")
  62. assert response.status_code == 200
  63. data = response.json()
  64. assert all(a["printer_id"] == printer1.id for a in data)
  65. # ========================================================================
  66. # Get single endpoint
  67. # ========================================================================
  68. @pytest.mark.asyncio
  69. @pytest.mark.integration
  70. async def test_get_archive(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  71. """Verify single archive can be retrieved."""
  72. printer = await printer_factory()
  73. archive = await archive_factory(printer.id, print_name="Get Test Archive")
  74. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  75. assert response.status_code == 200
  76. result = response.json()
  77. assert result["id"] == archive.id
  78. assert result["print_name"] == "Get Test Archive"
  79. @pytest.mark.asyncio
  80. @pytest.mark.integration
  81. async def test_get_archive_not_found(self, async_client: AsyncClient):
  82. """Verify 404 for non-existent archive."""
  83. response = await async_client.get("/api/v1/archives/9999")
  84. assert response.status_code == 404
  85. # ========================================================================
  86. # Update endpoints
  87. # ========================================================================
  88. @pytest.mark.asyncio
  89. @pytest.mark.integration
  90. async def test_update_archive_name(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  91. """Verify archive name can be updated."""
  92. printer = await printer_factory()
  93. archive = await archive_factory(printer.id, print_name="Original Name")
  94. response = await async_client.patch(f"/api/v1/archives/{archive.id}", json={"print_name": "Updated Name"})
  95. assert response.status_code == 200
  96. assert response.json()["print_name"] == "Updated Name"
  97. @pytest.mark.asyncio
  98. @pytest.mark.integration
  99. async def test_update_archive_notes(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  100. """Verify archive notes can be updated."""
  101. printer = await printer_factory()
  102. archive = await archive_factory(printer.id)
  103. response = await async_client.patch(f"/api/v1/archives/{archive.id}", json={"notes": "Great print!"})
  104. assert response.status_code == 200
  105. assert response.json()["notes"] == "Great print!"
  106. @pytest.mark.asyncio
  107. @pytest.mark.integration
  108. async def test_update_archive_favorite(
  109. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  110. ):
  111. """Verify archive favorite status can be updated."""
  112. printer = await printer_factory()
  113. archive = await archive_factory(printer.id)
  114. response = await async_client.patch(f"/api/v1/archives/{archive.id}", json={"is_favorite": True})
  115. assert response.status_code == 200
  116. assert response.json()["is_favorite"] is True
  117. @pytest.mark.asyncio
  118. @pytest.mark.integration
  119. async def test_update_archive_external_url(
  120. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  121. ):
  122. """Verify archive external_url can be updated."""
  123. printer = await printer_factory()
  124. archive = await archive_factory(printer.id)
  125. response = await async_client.patch(
  126. f"/api/v1/archives/{archive.id}", json={"external_url": "https://printables.com/model/12345"}
  127. )
  128. assert response.status_code == 200
  129. assert response.json()["external_url"] == "https://printables.com/model/12345"
  130. # Verify it can be cleared
  131. response = await async_client.patch(f"/api/v1/archives/{archive.id}", json={"external_url": None})
  132. assert response.status_code == 200
  133. assert response.json()["external_url"] is None
  134. @pytest.mark.asyncio
  135. @pytest.mark.integration
  136. async def test_update_archive_failure_reason_mirrors_to_print_log_entry(
  137. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  138. ):
  139. """#1444: PATCH /archives/{id} with failure_reason must mirror to the
  140. latest PrintLogEntry so the Stats page Failure Analysis widget
  141. (which reads PrintLogEntry.failure_reason) reflects the user's
  142. reclassification instead of showing "Unknown" forever.
  143. """
  144. from sqlalchemy import select
  145. from backend.app.models.print_log import PrintLogEntry
  146. printer = await printer_factory()
  147. # archive_factory auto-creates a matching PrintLogEntry (failure_reason
  148. # carried from the archive, which is NULL here — same shape as the bug
  149. # repro: print completed → log entry written with NULL → user goes to
  150. # classify the failure afterwards).
  151. archive = await archive_factory(printer.id, print_name="Failed Print", status="failed", run_status="failed")
  152. response = await async_client.patch(
  153. f"/api/v1/archives/{archive.id}",
  154. json={"failure_reason": "Adhesion failure"},
  155. )
  156. assert response.status_code == 200
  157. result = await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  158. mirrored = result.scalar_one()
  159. assert mirrored.failure_reason == "Adhesion failure"
  160. @pytest.mark.asyncio
  161. @pytest.mark.integration
  162. async def test_update_archive_status_mirrors_to_print_log_entry(
  163. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  164. ):
  165. """#1444: PATCH /archives/{id} with status must mirror to the latest
  166. PrintLogEntry so stats that filter on PrintLogEntry.status see the
  167. user's reclassification.
  168. """
  169. from sqlalchemy import select
  170. from backend.app.models.print_log import PrintLogEntry
  171. printer = await printer_factory()
  172. archive = await archive_factory(printer.id, run_status="completed")
  173. response = await async_client.patch(
  174. f"/api/v1/archives/{archive.id}",
  175. json={"status": "failed"},
  176. )
  177. assert response.status_code == 200
  178. result = await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  179. mirrored = result.scalar_one()
  180. assert mirrored.status == "failed"
  181. @pytest.mark.asyncio
  182. @pytest.mark.integration
  183. async def test_update_archive_failure_reason_only_touches_latest_entry(
  184. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  185. ):
  186. """#1444: For an archive with multiple runs (reprints), only the
  187. latest PrintLogEntry should receive the reclassification. Earlier
  188. runs were classified at their own time and must not be retroactively
  189. overwritten.
  190. """
  191. from backend.app.models.print_log import PrintLogEntry
  192. printer = await printer_factory()
  193. # First run — created by the factory's auto-run with its own reason.
  194. archive = await archive_factory(printer.id, status="failed", run_status="failed")
  195. from sqlalchemy import select
  196. first_run = (
  197. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  198. ).scalar_one()
  199. first_run.failure_reason = "Filament tangle"
  200. await db_session.commit()
  201. # Second run — the reprint that just finished with NULL classification.
  202. latest_run = PrintLogEntry(archive_id=archive.id, status="failed", failure_reason=None)
  203. db_session.add(latest_run)
  204. await db_session.commit()
  205. response = await async_client.patch(
  206. f"/api/v1/archives/{archive.id}",
  207. json={"failure_reason": "Adhesion failure"},
  208. )
  209. assert response.status_code == 200
  210. await db_session.refresh(first_run)
  211. await db_session.refresh(latest_run)
  212. assert first_run.failure_reason == "Filament tangle"
  213. assert latest_run.failure_reason == "Adhesion failure"
  214. # ========================================================================
  215. # Delete endpoints
  216. # ========================================================================
  217. @pytest.mark.asyncio
  218. @pytest.mark.integration
  219. async def test_delete_archive(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  220. """Verify archive can be deleted."""
  221. printer = await printer_factory()
  222. archive = await archive_factory(printer.id)
  223. archive_id = archive.id
  224. response = await async_client.delete(f"/api/v1/archives/{archive_id}")
  225. assert response.status_code == 200
  226. # Verify deleted
  227. response = await async_client.get(f"/api/v1/archives/{archive_id}")
  228. assert response.status_code == 404
  229. @pytest.mark.asyncio
  230. @pytest.mark.integration
  231. async def test_delete_nonexistent_archive(self, async_client: AsyncClient):
  232. """Verify deleting non-existent archive returns 404."""
  233. response = await async_client.delete("/api/v1/archives/9999")
  234. assert response.status_code == 404
  235. @pytest.mark.asyncio
  236. @pytest.mark.integration
  237. async def test_soft_delete_preserves_stats_contribution(
  238. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  239. ):
  240. """#1343: deleting an archive without ``purge_stats`` keeps its
  241. contribution in Quick Stats. The row vanishes from listings but the
  242. filament / time / cost totals stay intact.
  243. """
  244. printer = await printer_factory()
  245. await archive_factory(
  246. printer.id,
  247. status="completed",
  248. print_time_seconds=3600,
  249. filament_used_grams=50.0,
  250. cost=1.50,
  251. )
  252. archive_to_delete = await archive_factory(
  253. printer.id,
  254. status="completed",
  255. print_time_seconds=7200,
  256. filament_used_grams=100.0,
  257. cost=3.00,
  258. )
  259. # Pre-delete: stats include both archives.
  260. pre = (await async_client.get("/api/v1/archives/stats")).json()
  261. assert pre["total_prints"] == 2
  262. assert pre["total_filament_grams"] == 150.0
  263. assert pre["total_cost"] == 4.50
  264. # Soft delete (default — no purge_stats param).
  265. resp = await async_client.delete(f"/api/v1/archives/{archive_to_delete.id}")
  266. assert resp.status_code == 200
  267. body = resp.json()
  268. assert body["purged_from_stats"] is False
  269. # Listing hides the deleted archive…
  270. listing = (await async_client.get("/api/v1/archives/")).json()
  271. assert all(a["id"] != archive_to_delete.id for a in listing)
  272. # …but stats still reflect both prints (the whole point of #1343).
  273. post = (await async_client.get("/api/v1/archives/stats")).json()
  274. assert post["total_prints"] == 2
  275. assert post["total_filament_grams"] == 150.0
  276. assert post["total_cost"] == 4.50
  277. @pytest.mark.asyncio
  278. @pytest.mark.integration
  279. async def test_soft_delete_clears_thumbnail_path_on_linked_log_entries(
  280. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  281. ):
  282. """#1348 follow-up: soft-deleting an archive removes its files from disk;
  283. the cached thumbnail_path on linked PrintLogEntry rows must be NULLed
  284. in the same transaction so the print-log view doesn't 404-storm on the
  285. now-deleted thumbnail file."""
  286. from sqlalchemy import select
  287. from backend.app.models.print_log import PrintLogEntry
  288. printer = await printer_factory()
  289. archive = await archive_factory(
  290. printer.id,
  291. status="completed",
  292. thumbnail_path="archives/test/test_print/thumbnail.png",
  293. )
  294. # The factory's auto-PrintLogEntry doesn't copy thumbnail_path; set it
  295. # manually to mirror what the production write_log_entry path stores.
  296. run_query = await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  297. run = run_query.scalar_one()
  298. run.thumbnail_path = "archives/test/test_print/thumbnail.png"
  299. await db_session.commit()
  300. assert run.thumbnail_path is not None
  301. resp = await async_client.delete(f"/api/v1/archives/{archive.id}")
  302. assert resp.status_code == 200
  303. assert resp.json()["purged_from_stats"] is False
  304. await db_session.refresh(run)
  305. assert run.thumbnail_path is None, "soft-delete must NULL thumbnail_path on linked log entry"
  306. # The log entry itself survives the soft delete (its filament/cost
  307. # contribution still needs to flow into stats per #1343).
  308. assert run.id is not None
  309. assert run.archive_id == archive.id
  310. @pytest.mark.asyncio
  311. @pytest.mark.integration
  312. async def test_hard_delete_clears_thumbnail_path_before_fk_cascade(
  313. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  314. ):
  315. """#1348 follow-up: the auto-purge sweeper (and any caller of
  316. ArchiveService.delete_archive) hard-deletes the archive row but leaves
  317. PrintLogEntry rows alive via ON DELETE SET NULL. The eager
  318. thumbnail_path clear must run inside delete_archive so even orphaned
  319. log entries don't surface stale paths."""
  320. from sqlalchemy import select
  321. from backend.app.models.print_log import PrintLogEntry
  322. from backend.app.services.archive import ArchiveService
  323. printer = await printer_factory()
  324. archive = await archive_factory(
  325. printer.id,
  326. status="completed",
  327. thumbnail_path="archives/test/test_print/thumbnail.png",
  328. )
  329. run_query = await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  330. run = run_query.scalar_one()
  331. run.thumbnail_path = "archives/test/test_print/thumbnail.png"
  332. await db_session.commit()
  333. run_id = run.id
  334. service = ArchiveService(db_session)
  335. assert await service.delete_archive(archive.id) is True
  336. # Log entry survives the hard-delete (the FK is ON DELETE SET NULL
  337. # in production; SQLite test config doesn't enable foreign_keys=ON
  338. # by default so archive_id may still be set, but the row itself
  339. # remains for audit). The thumbnail_path was cleared eagerly by
  340. # _null_print_log_thumbnail_paths before db.delete(archive).
  341. refetch = await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.id == run_id))
  342. survivor = refetch.scalar_one()
  343. assert survivor.thumbnail_path is None, (
  344. "delete_archive must NULL thumbnail_path before removing the archive row"
  345. )
  346. @pytest.mark.asyncio
  347. @pytest.mark.integration
  348. async def test_print_log_thumbnail_route_lazy_nulls_missing_file(
  349. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  350. ):
  351. """#1348 follow-up: GET /print-log/{id}/thumbnail self-heals when the
  352. thumbnail_path on a log entry points at a missing file (failed print
  353. whose thumbnail was never written, or a stale path that escaped the
  354. delete-time cleanup)."""
  355. from sqlalchemy import select
  356. from backend.app.models.print_log import PrintLogEntry
  357. printer = await printer_factory()
  358. archive = await archive_factory(printer.id, status="failed")
  359. run_query = await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  360. run = run_query.scalar_one()
  361. # Path points at a file that never existed (failed-print case where
  362. # archive.thumbnail_path was set but the extractor never produced one).
  363. run.thumbnail_path = "archives/missing/never_written/thumbnail.png"
  364. await db_session.commit()
  365. # Auth is disabled in the integration test config, so the stream-token
  366. # guard is bypassed — the route runs the lazy-NULL branch directly.
  367. resp = await async_client.get(f"/api/v1/print-log/{run.id}/thumbnail")
  368. assert resp.status_code == 404
  369. await db_session.refresh(run)
  370. assert run.thumbnail_path is None, "missing file must self-heal to NULL"
  371. @pytest.mark.asyncio
  372. @pytest.mark.integration
  373. async def test_purge_stats_drops_archive_from_quick_stats(
  374. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  375. ):
  376. """#1343: deleting with ``?purge_stats=true`` hard-deletes the row,
  377. dropping its contribution from Quick Stats (the original behaviour,
  378. now opt-in)."""
  379. printer = await printer_factory()
  380. keep = await archive_factory(printer.id, status="completed", filament_used_grams=50.0)
  381. purge = await archive_factory(printer.id, status="completed", filament_used_grams=100.0)
  382. resp = await async_client.delete(f"/api/v1/archives/{purge.id}?purge_stats=true")
  383. assert resp.status_code == 200
  384. assert resp.json()["purged_from_stats"] is True
  385. stats = (await async_client.get("/api/v1/archives/stats")).json()
  386. assert stats["total_prints"] == 1
  387. assert stats["total_filament_grams"] == 50.0
  388. # The kept archive is still listed.
  389. listing = (await async_client.get("/api/v1/archives/")).json()
  390. assert [a["id"] for a in listing] == [keep.id]
  391. @pytest.mark.asyncio
  392. @pytest.mark.integration
  393. async def test_soft_deleted_archive_404_on_detail(
  394. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  395. ):
  396. """A soft-deleted archive must 404 on GET — a stale bookmark or
  397. direct URL should not expose a row the user has already removed."""
  398. printer = await printer_factory()
  399. archive = await archive_factory(printer.id)
  400. await async_client.delete(f"/api/v1/archives/{archive.id}")
  401. resp = await async_client.get(f"/api/v1/archives/{archive.id}")
  402. assert resp.status_code == 404
  403. @pytest.mark.asyncio
  404. @pytest.mark.integration
  405. async def test_soft_deleted_archive_hidden_from_search(
  406. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  407. ):
  408. """Search must skip soft-deleted archives. Uses the LIKE fallback by
  409. querying a single-character pattern that the SQLite FTS5 rejects, so
  410. the test covers the fallback path that the production FTS path also
  411. respects."""
  412. printer = await printer_factory()
  413. archive = await archive_factory(printer.id, print_name="UniqueSoftDeleteCandidate")
  414. await async_client.delete(f"/api/v1/archives/{archive.id}")
  415. resp = await async_client.get("/api/v1/archives/search?q=UniqueSoftDeleteCandidate")
  416. assert resp.status_code == 200
  417. assert resp.json() == []
  418. # ========================================================================
  419. # Statistics endpoints
  420. # ========================================================================
  421. @pytest.mark.asyncio
  422. @pytest.mark.integration
  423. async def test_get_archive_stats(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  424. """Verify archive statistics can be retrieved."""
  425. printer = await printer_factory()
  426. await archive_factory(
  427. printer.id,
  428. status="completed",
  429. print_time_seconds=3600,
  430. filament_used_grams=50.0,
  431. )
  432. await archive_factory(
  433. printer.id,
  434. status="completed",
  435. print_time_seconds=7200,
  436. filament_used_grams=100.0,
  437. )
  438. response = await async_client.get("/api/v1/archives/stats")
  439. assert response.status_code == 200
  440. result = response.json()
  441. # Check for actual stats fields
  442. assert "total_prints" in result
  443. assert "successful_prints" in result
  444. class TestPrintLogEntryDelete:
  445. """#1687: per-row delete on the Print Log page.
  446. Pin the route's three contracts: (1) deleting a row drops its filament
  447. / cost / count contribution from /archives/stats in the same response
  448. cycle; (2) the matching archive (if any) is untouched; (3) missing IDs
  449. return 404 rather than 200-silently.
  450. """
  451. @pytest.mark.asyncio
  452. @pytest.mark.integration
  453. async def test_delete_print_log_entry_drops_from_stats(
  454. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  455. ):
  456. from sqlalchemy import select
  457. from backend.app.models.print_log import PrintLogEntry
  458. printer = await printer_factory()
  459. keep = await archive_factory(printer.id, status="completed", filament_used_grams=50.0)
  460. drop = await archive_factory(printer.id, status="completed", filament_used_grams=125.0)
  461. drop_run = (
  462. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == drop.id))
  463. ).scalar_one()
  464. resp = await async_client.delete(f"/api/v1/print-log/{drop_run.id}")
  465. assert resp.status_code == 200
  466. assert resp.json()["status"] == "deleted"
  467. assert resp.json()["id"] == drop_run.id
  468. # The linked archive survives — the row was a stats row, not the archive.
  469. listing = (await async_client.get("/api/v1/archives/")).json()
  470. assert {a["id"] for a in listing} == {keep.id, drop.id}
  471. # /stats no longer counts the dropped run's filament contribution.
  472. stats = (await async_client.get("/api/v1/archives/stats")).json()
  473. assert stats["total_prints"] == 1
  474. assert stats["total_filament_grams"] == 50.0
  475. @pytest.mark.asyncio
  476. @pytest.mark.integration
  477. async def test_delete_print_log_entry_404_when_missing(self, async_client: AsyncClient):
  478. resp = await async_client.delete("/api/v1/print-log/999999")
  479. assert resp.status_code == 404
  480. @pytest.mark.asyncio
  481. @pytest.mark.integration
  482. async def test_delete_print_log_entry_does_not_clear_others(
  483. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  484. ):
  485. """Deleting one row must not touch siblings — guard against an accidental
  486. ``delete(PrintLogEntry)`` without a ``where`` clause (cf. clear_print_log
  487. which intentionally drops everything)."""
  488. from sqlalchemy import select
  489. from backend.app.models.print_log import PrintLogEntry
  490. printer = await printer_factory()
  491. a = await archive_factory(printer.id, status="completed", filament_used_grams=10.0)
  492. b = await archive_factory(printer.id, status="completed", filament_used_grams=20.0)
  493. c = await archive_factory(printer.id, status="completed", filament_used_grams=30.0)
  494. runs = {r.archive_id: r for r in (await db_session.execute(select(PrintLogEntry))).scalars().all()}
  495. resp = await async_client.delete(f"/api/v1/print-log/{runs[b.id].id}")
  496. assert resp.status_code == 200
  497. survivors = (await db_session.execute(select(PrintLogEntry.archive_id))).scalars().all()
  498. assert set(survivors) == {a.id, c.id}
  499. class TestPrintLogEntryUpdate:
  500. """Tests for ``PATCH /print-log/{entry_id}`` (#1687 part 4).
  501. Pin the route's contracts: (1) GET serialiser actually surfaces
  502. ``failure_reason`` (previously it was silently dropped from the response
  503. even when set in the DB); (2) PATCH persists ``failure_reason`` and
  504. ``status``; (3) unknown vocabulary returns 400 rather than getting stored
  505. as raw garbage; (4) missing IDs return 404.
  506. """
  507. @pytest.mark.asyncio
  508. @pytest.mark.integration
  509. async def test_get_surfaces_failure_reason(
  510. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  511. ):
  512. """Pre-fix the GET endpoint built PrintLogEntrySchema without
  513. ``failure_reason`` even though the column was populated, so the Print
  514. Log table couldn't render what the Failure Analysis widget already
  515. groups by. Regression guard for the silent-drop bug.
  516. """
  517. from sqlalchemy import select
  518. from backend.app.models.print_log import PrintLogEntry
  519. printer = await printer_factory()
  520. archive = await archive_factory(printer.id, status="failed")
  521. entry = (
  522. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  523. ).scalar_one()
  524. entry.failure_reason = "spaghettiDetached"
  525. await db_session.commit()
  526. body = (await async_client.get("/api/v1/print-log/")).json()
  527. match = next(item for item in body["items"] if item["id"] == entry.id)
  528. assert match["failure_reason"] == "spaghettiDetached"
  529. # archive_id should also flow through so the frontend can tell orphan
  530. # entries apart from archive-linked ones.
  531. assert match["archive_id"] == archive.id
  532. @pytest.mark.asyncio
  533. @pytest.mark.integration
  534. async def test_patch_sets_failure_reason(
  535. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  536. ):
  537. from sqlalchemy import select
  538. from backend.app.models.print_log import PrintLogEntry
  539. printer = await printer_factory()
  540. archive = await archive_factory(printer.id, status="failed")
  541. entry = (
  542. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  543. ).scalar_one()
  544. assert entry.failure_reason is None
  545. resp = await async_client.patch(
  546. f"/api/v1/print-log/{entry.id}",
  547. json={"failure_reason": "cloggedNozzle"},
  548. )
  549. assert resp.status_code == 200
  550. assert resp.json()["failure_reason"] == "cloggedNozzle"
  551. await db_session.refresh(entry)
  552. assert entry.failure_reason == "cloggedNozzle"
  553. @pytest.mark.asyncio
  554. @pytest.mark.integration
  555. async def test_patch_can_clear_failure_reason(
  556. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  557. ):
  558. """Empty-string failure_reason stores back as NULL (the column's
  559. nullable=True intent is preserved end-to-end)."""
  560. from sqlalchemy import select
  561. from backend.app.models.print_log import PrintLogEntry
  562. printer = await printer_factory()
  563. archive = await archive_factory(printer.id, status="failed")
  564. entry = (
  565. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  566. ).scalar_one()
  567. entry.failure_reason = "warping"
  568. await db_session.commit()
  569. resp = await async_client.patch(
  570. f"/api/v1/print-log/{entry.id}",
  571. json={"failure_reason": ""},
  572. )
  573. assert resp.status_code == 200
  574. assert resp.json()["failure_reason"] is None
  575. await db_session.refresh(entry)
  576. assert entry.failure_reason is None
  577. @pytest.mark.asyncio
  578. @pytest.mark.integration
  579. async def test_patch_rejects_unknown_failure_reason(
  580. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  581. ):
  582. """Unknown values must 400 — otherwise the UI would render raw garbage
  583. because the i18n layer maps the value back through the canonical
  584. vocabulary."""
  585. from sqlalchemy import select
  586. from backend.app.models.print_log import PrintLogEntry
  587. printer = await printer_factory()
  588. archive = await archive_factory(printer.id, status="failed")
  589. entry = (
  590. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  591. ).scalar_one()
  592. resp = await async_client.patch(
  593. f"/api/v1/print-log/{entry.id}",
  594. json={"failure_reason": "completely-made-up"},
  595. )
  596. assert resp.status_code == 400
  597. @pytest.mark.asyncio
  598. @pytest.mark.integration
  599. async def test_patch_updates_status(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  600. from sqlalchemy import select
  601. from backend.app.models.print_log import PrintLogEntry
  602. printer = await printer_factory()
  603. archive = await archive_factory(printer.id, status="completed")
  604. entry = (
  605. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  606. ).scalar_one()
  607. entry.status = "completed"
  608. await db_session.commit()
  609. resp = await async_client.patch(
  610. f"/api/v1/print-log/{entry.id}",
  611. json={"status": "failed", "failure_reason": "layerShift"},
  612. )
  613. assert resp.status_code == 200
  614. assert resp.json()["status"] == "failed"
  615. assert resp.json()["failure_reason"] == "layerShift"
  616. @pytest.mark.asyncio
  617. @pytest.mark.integration
  618. async def test_patch_rejects_unknown_status(
  619. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  620. ):
  621. from sqlalchemy import select
  622. from backend.app.models.print_log import PrintLogEntry
  623. printer = await printer_factory()
  624. archive = await archive_factory(printer.id, status="failed")
  625. entry = (
  626. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  627. ).scalar_one()
  628. resp = await async_client.patch(
  629. f"/api/v1/print-log/{entry.id}",
  630. json={"status": "bogus-status"},
  631. )
  632. assert resp.status_code == 400
  633. @pytest.mark.asyncio
  634. @pytest.mark.integration
  635. async def test_patch_404_when_missing(self, async_client: AsyncClient):
  636. resp = await async_client.patch(
  637. "/api/v1/print-log/999999",
  638. json={"failure_reason": "cloggedNozzle"},
  639. )
  640. assert resp.status_code == 404
  641. @pytest.mark.asyncio
  642. @pytest.mark.integration
  643. async def test_patch_works_on_orphan_entry(self, async_client: AsyncClient, printer_factory, db_session):
  644. """Orphan log entries (no archive_id) are the actual reason this
  645. endpoint exists — the Archive Edit modal can't reach them. Make sure
  646. the PATCH works for those rows specifically."""
  647. from backend.app.models.print_log import PrintLogEntry
  648. printer = await printer_factory()
  649. orphan = PrintLogEntry(
  650. archive_id=None,
  651. print_name="failed-before-archive-created",
  652. printer_id=printer.id,
  653. status="failed",
  654. failure_reason=None,
  655. )
  656. db_session.add(orphan)
  657. await db_session.commit()
  658. await db_session.refresh(orphan)
  659. assert orphan.archive_id is None
  660. resp = await async_client.patch(
  661. f"/api/v1/print-log/{orphan.id}",
  662. json={"failure_reason": "powerFailure"},
  663. )
  664. assert resp.status_code == 200
  665. assert resp.json()["failure_reason"] == "powerFailure"
  666. assert resp.json()["archive_id"] is None
  667. class TestArchivesSlimAPI:
  668. """Integration tests for /api/v1/archives/slim endpoint."""
  669. @pytest.mark.asyncio
  670. @pytest.mark.integration
  671. async def test_slim_empty(self, async_client: AsyncClient):
  672. """Verify empty list when no archives exist."""
  673. response = await async_client.get("/api/v1/archives/slim")
  674. assert response.status_code == 200
  675. assert response.json() == []
  676. @pytest.mark.asyncio
  677. @pytest.mark.integration
  678. async def test_slim_returns_only_expected_fields(
  679. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  680. ):
  681. """Verify response contains only slim fields, not full archive data."""
  682. printer = await printer_factory()
  683. await archive_factory(
  684. printer.id,
  685. print_name="Slim Test",
  686. status="completed",
  687. filament_type="PLA",
  688. filament_color="#FF0000",
  689. filament_used_grams=50.0,
  690. print_time_seconds=3600,
  691. cost=1.50,
  692. quantity=2,
  693. )
  694. response = await async_client.get("/api/v1/archives/slim")
  695. assert response.status_code == 200
  696. data = response.json()
  697. assert len(data) == 1
  698. item = data[0]
  699. # Expected fields present
  700. assert item["printer_id"] == printer.id
  701. assert item["print_name"] == "Slim Test"
  702. assert item["status"] == "completed"
  703. assert item["filament_type"] == "PLA"
  704. assert item["filament_color"] == "#FF0000"
  705. assert item["filament_used_grams"] == 50.0
  706. assert item["print_time_seconds"] == 3600
  707. assert item["cost"] == 1.50
  708. # quantity is per-event semantics now (each PrintLogEntry = one run);
  709. # the archive's quantity field is no longer surfaced through this
  710. # endpoint after the #1390 per-event migration.
  711. assert item["quantity"] == 1
  712. assert "created_at" in item
  713. # Full archive fields must NOT be present
  714. assert "id" not in item
  715. assert "filename" not in item
  716. assert "file_path" not in item
  717. assert "file_size" not in item
  718. assert "extra_data" not in item
  719. assert "notes" not in item
  720. assert "tags" not in item
  721. assert "photos" not in item
  722. assert "thumbnail_path" not in item
  723. assert "content_hash" not in item
  724. assert "duplicates" not in item
  725. assert "duplicate_count" not in item
  726. @pytest.mark.asyncio
  727. @pytest.mark.integration
  728. async def test_slim_computes_actual_time(
  729. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  730. ):
  731. """Verify actual_time_seconds is computed from started_at/completed_at."""
  732. from datetime import datetime, timezone
  733. printer = await printer_factory()
  734. started = datetime(2024, 1, 1, 10, 0, 0, tzinfo=timezone.utc)
  735. completed = datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc) # 2 hours = 7200s
  736. await archive_factory(
  737. printer.id,
  738. status="completed",
  739. started_at=started,
  740. completed_at=completed,
  741. )
  742. response = await async_client.get("/api/v1/archives/slim")
  743. assert response.status_code == 200
  744. item = response.json()[0]
  745. assert item["actual_time_seconds"] == 7200
  746. @pytest.mark.asyncio
  747. @pytest.mark.integration
  748. async def test_slim_actual_time_for_failed_includes_elapsed(
  749. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  750. ):
  751. """Failed prints report measured elapsed time so Printer Stats By Time
  752. matches Quick Stats Print Time (#1390). Previously this returned null
  753. and the frontend fell back to the slicer estimate, double-counting the
  754. unfinished portion of the print."""
  755. from datetime import datetime, timezone
  756. printer = await printer_factory()
  757. await archive_factory(
  758. printer.id,
  759. status="failed",
  760. started_at=datetime(2024, 1, 1, 10, 0, 0, tzinfo=timezone.utc),
  761. completed_at=datetime(2024, 1, 1, 11, 0, 0, tzinfo=timezone.utc),
  762. )
  763. response = await async_client.get("/api/v1/archives/slim")
  764. assert response.status_code == 200
  765. item = response.json()[0]
  766. assert item["actual_time_seconds"] == 3600
  767. @pytest.mark.asyncio
  768. @pytest.mark.integration
  769. async def test_slim_date_filtering(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  770. """Verify date_from and date_to filters work."""
  771. from datetime import datetime, timezone
  772. printer = await printer_factory()
  773. await archive_factory(
  774. printer.id,
  775. print_name="Old Print",
  776. created_at=datetime(2024, 1, 1, tzinfo=timezone.utc),
  777. )
  778. await archive_factory(
  779. printer.id,
  780. print_name="New Print",
  781. created_at=datetime(2024, 6, 15, tzinfo=timezone.utc),
  782. )
  783. # Filter to only June 2024
  784. response = await async_client.get("/api/v1/archives/slim?date_from=2024-06-01&date_to=2024-06-30")
  785. assert response.status_code == 200
  786. data = response.json()
  787. assert len(data) == 1
  788. assert data[0]["print_name"] == "New Print"
  789. @pytest.mark.asyncio
  790. @pytest.mark.integration
  791. async def test_slim_pagination(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  792. """Verify limit and offset work."""
  793. printer = await printer_factory()
  794. for i in range(5):
  795. await archive_factory(printer.id, print_name=f"Print {i}")
  796. response = await async_client.get("/api/v1/archives/slim?limit=2&offset=0")
  797. assert response.status_code == 200
  798. assert len(response.json()) == 2
  799. @pytest.mark.asyncio
  800. @pytest.mark.integration
  801. async def test_slim_counts_reprints_as_separate_rows(
  802. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  803. ):
  804. """Reprints add events even though the archive row is overwritten (#1390).
  805. Before the per-event migration, /archives/slim returned one row per
  806. archive — so an archive that had been reprinted three times appeared
  807. once and undercounted Filament Used / Cost / Time. The endpoint must
  808. now return one row per logged event.
  809. """
  810. from backend.app.models.print_log import PrintLogEntry
  811. printer = await printer_factory()
  812. archive = await archive_factory(
  813. printer.id,
  814. print_name="Reprinted Model",
  815. filament_used_grams=50.0,
  816. cost=1.50,
  817. )
  818. # archive_factory synthesizes one event; add two more to simulate
  819. # the same archive being reprinted twice more.
  820. for _ in range(2):
  821. db_session.add(
  822. PrintLogEntry(
  823. archive_id=archive.id,
  824. printer_id=archive.printer_id,
  825. status="completed",
  826. filament_type=archive.filament_type,
  827. filament_used_grams=archive.filament_used_grams,
  828. cost=archive.cost,
  829. print_name=archive.print_name,
  830. )
  831. )
  832. await db_session.commit()
  833. response = await async_client.get("/api/v1/archives/slim")
  834. assert response.status_code == 200
  835. data = response.json()
  836. assert len(data) == 3, "Each reprint must contribute one row"
  837. total_filament = sum(item["filament_used_grams"] or 0 for item in data)
  838. assert total_filament == 150.0, "Sum across events must reflect all three runs"
  839. @pytest.mark.asyncio
  840. @pytest.mark.integration
  841. async def test_slim_includes_orphan_events(self, async_client: AsyncClient, printer_factory, db_session):
  842. """Events whose archive was hard-deleted still appear (#1390).
  843. After ON DELETE SET NULL the event row survives with archive_id=NULL.
  844. The slim endpoint must keep counting it so Quick Stats and the
  845. archive-iterating widgets stay aligned.
  846. """
  847. from backend.app.models.print_log import PrintLogEntry
  848. printer = await printer_factory()
  849. db_session.add(
  850. PrintLogEntry(
  851. archive_id=None,
  852. printer_id=printer.id,
  853. status="completed",
  854. filament_type="PETG",
  855. filament_used_grams=25.0,
  856. cost=0.75,
  857. print_name="Orphaned Print",
  858. )
  859. )
  860. await db_session.commit()
  861. response = await async_client.get("/api/v1/archives/slim")
  862. assert response.status_code == 200
  863. data = response.json()
  864. assert len(data) == 1
  865. assert data[0]["print_name"] == "Orphaned Print"
  866. assert data[0]["filament_used_grams"] == 25.0
  867. # print_time_seconds (sliced estimate) comes from the archive table,
  868. # which orphans no longer have — must surface as null gracefully.
  869. assert data[0]["print_time_seconds"] is None
  870. class TestFailureAnalysisAPI:
  871. """Per-event failure analysis (#1390)."""
  872. @pytest.mark.asyncio
  873. @pytest.mark.integration
  874. async def test_failure_analysis_counts_reprints_and_orphans(
  875. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  876. ):
  877. """Failure analysis aggregates per event, not per archive.
  878. Verifies the dual fix for #1390: a reprint that adds a second failed
  879. event must count twice, and an orphan failed event (archive deleted)
  880. must still appear in the totals.
  881. """
  882. from backend.app.models.print_log import PrintLogEntry
  883. printer = await printer_factory()
  884. archive = await archive_factory(
  885. printer.id,
  886. print_name="Failing Model",
  887. status="failed",
  888. failure_reason="filament_runout",
  889. )
  890. # Add a second failed event for the same archive (a reprint that also
  891. # failed) and one orphan failed event (archive was deleted).
  892. db_session.add(
  893. PrintLogEntry(
  894. archive_id=archive.id,
  895. printer_id=printer.id,
  896. status="failed",
  897. failure_reason="filament_runout",
  898. filament_type=archive.filament_type,
  899. print_name=archive.print_name,
  900. )
  901. )
  902. db_session.add(
  903. PrintLogEntry(
  904. archive_id=None,
  905. printer_id=printer.id,
  906. status="failed",
  907. failure_reason="bed_adhesion",
  908. filament_type="PETG",
  909. print_name="Orphaned Failed Print",
  910. )
  911. )
  912. await db_session.commit()
  913. response = await async_client.get("/api/v1/archives/analysis/failures")
  914. assert response.status_code == 200
  915. result = response.json()
  916. assert result["total_prints"] == 3
  917. assert result["failed_prints"] == 3
  918. assert result["failures_by_reason"]["filament_runout"] == 2
  919. assert result["failures_by_reason"]["bed_adhesion"] == 1
  920. class TestArchiveDataIntegrity:
  921. """Tests for archive data integrity."""
  922. @pytest.mark.asyncio
  923. @pytest.mark.integration
  924. async def test_archive_linked_to_printer(
  925. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  926. ):
  927. """Verify archive is properly linked to printer."""
  928. printer = await printer_factory(name="My Printer")
  929. archive = await archive_factory(printer.id)
  930. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  931. assert response.status_code == 200
  932. result = response.json()
  933. assert result["printer_id"] == printer.id
  934. @pytest.mark.asyncio
  935. @pytest.mark.integration
  936. async def test_archive_stores_print_data(
  937. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  938. ):
  939. """Verify archive stores all print data correctly."""
  940. printer = await printer_factory()
  941. archive = await archive_factory(
  942. printer.id,
  943. print_name="Test Print",
  944. filename="test.3mf",
  945. status="completed",
  946. filament_type="PLA",
  947. filament_used_grams=75.5,
  948. print_time_seconds=5400,
  949. )
  950. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  951. assert response.status_code == 200
  952. result = response.json()
  953. assert result["print_name"] == "Test Print"
  954. assert result["filename"] == "test.3mf"
  955. assert result["status"] == "completed"
  956. assert result["filament_type"] == "PLA"
  957. assert result["filament_used_grams"] == 75.5
  958. assert result["print_time_seconds"] == 5400
  959. @pytest.mark.asyncio
  960. @pytest.mark.integration
  961. async def test_archive_update_persists(
  962. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  963. ):
  964. """CRITICAL: Verify archive updates persist."""
  965. printer = await printer_factory()
  966. archive = await archive_factory(printer.id, notes="Original notes")
  967. # Update
  968. await async_client.patch(f"/api/v1/archives/{archive.id}", json={"notes": "Updated notes", "is_favorite": True})
  969. # Verify persistence
  970. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  971. result = response.json()
  972. assert result["notes"] == "Updated notes"
  973. assert result["is_favorite"] is True
  974. class TestArchiveF3DEndpoints:
  975. """Tests for F3D (Fusion 360 design file) attachment endpoints."""
  976. @pytest.mark.asyncio
  977. @pytest.mark.integration
  978. async def test_archive_response_includes_f3d_path(
  979. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  980. ):
  981. """Verify f3d_path is included in archive response."""
  982. printer = await printer_factory()
  983. archive = await archive_factory(printer.id, f3d_path="archives/test/design.f3d")
  984. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  985. assert response.status_code == 200
  986. result = response.json()
  987. assert "f3d_path" in result
  988. assert result["f3d_path"] == "archives/test/design.f3d"
  989. @pytest.mark.asyncio
  990. @pytest.mark.integration
  991. async def test_archive_response_f3d_path_null_when_not_set(
  992. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  993. ):
  994. """Verify f3d_path is null when no F3D file attached."""
  995. printer = await printer_factory()
  996. archive = await archive_factory(printer.id)
  997. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  998. assert response.status_code == 200
  999. result = response.json()
  1000. assert "f3d_path" in result
  1001. assert result["f3d_path"] is None
  1002. @pytest.mark.asyncio
  1003. @pytest.mark.integration
  1004. async def test_upload_f3d_to_nonexistent_archive(self, async_client: AsyncClient):
  1005. """Verify 404 when uploading F3D to non-existent archive."""
  1006. # Create a minimal file-like upload
  1007. files = {"file": ("design.f3d", b"fake f3d content", "application/octet-stream")}
  1008. response = await async_client.post("/api/v1/archives/9999/f3d", files=files)
  1009. assert response.status_code == 404
  1010. @pytest.mark.asyncio
  1011. @pytest.mark.integration
  1012. async def test_download_f3d_not_found_when_no_file(
  1013. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1014. ):
  1015. """Verify 404 when downloading F3D from archive without F3D file."""
  1016. printer = await printer_factory()
  1017. archive = await archive_factory(printer.id)
  1018. response = await async_client.get(f"/api/v1/archives/{archive.id}/f3d")
  1019. assert response.status_code == 404
  1020. @pytest.mark.asyncio
  1021. @pytest.mark.integration
  1022. async def test_download_f3d_nonexistent_archive(self, async_client: AsyncClient):
  1023. """Verify 404 when downloading F3D from non-existent archive."""
  1024. response = await async_client.get("/api/v1/archives/9999/f3d")
  1025. assert response.status_code == 404
  1026. @pytest.mark.asyncio
  1027. @pytest.mark.integration
  1028. async def test_delete_f3d_nonexistent_archive(self, async_client: AsyncClient):
  1029. """Verify 404 when deleting F3D from non-existent archive."""
  1030. response = await async_client.delete("/api/v1/archives/9999/f3d")
  1031. assert response.status_code == 404
  1032. @pytest.mark.asyncio
  1033. @pytest.mark.integration
  1034. async def test_delete_f3d_when_no_file(
  1035. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1036. ):
  1037. """Verify 404 when deleting F3D from archive without F3D file."""
  1038. printer = await printer_factory()
  1039. archive = await archive_factory(printer.id)
  1040. response = await async_client.delete(f"/api/v1/archives/{archive.id}/f3d")
  1041. assert response.status_code == 404
  1042. @pytest.mark.asyncio
  1043. @pytest.mark.integration
  1044. async def test_list_archives_includes_f3d_path(
  1045. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1046. ):
  1047. """Verify f3d_path is included in archive list responses."""
  1048. printer = await printer_factory()
  1049. await archive_factory(printer.id, print_name="With F3D", f3d_path="archives/test/design.f3d")
  1050. await archive_factory(printer.id, print_name="Without F3D")
  1051. response = await async_client.get("/api/v1/archives/")
  1052. assert response.status_code == 200
  1053. data = response.json()
  1054. assert len(data) >= 2
  1055. with_f3d = next((a for a in data if a["print_name"] == "With F3D"), None)
  1056. without_f3d = next((a for a in data if a["print_name"] == "Without F3D"), None)
  1057. assert with_f3d is not None
  1058. assert with_f3d["f3d_path"] == "archives/test/design.f3d"
  1059. assert without_f3d is not None
  1060. assert without_f3d["f3d_path"] is None
  1061. # ========================================================================
  1062. # Multi-Plate 3MF endpoints (Issue #93)
  1063. # ========================================================================
  1064. @pytest.mark.asyncio
  1065. @pytest.mark.integration
  1066. async def test_get_archive_plates_not_found(self, async_client: AsyncClient):
  1067. """Verify 404 when fetching plates for non-existent archive."""
  1068. response = await async_client.get("/api/v1/archives/999999/plates")
  1069. assert response.status_code == 404
  1070. @pytest.mark.asyncio
  1071. @pytest.mark.integration
  1072. async def test_get_plate_thumbnail_not_found(self, async_client: AsyncClient):
  1073. """Verify 404 when fetching plate thumbnail for non-existent archive."""
  1074. response = await async_client.get("/api/v1/archives/999999/plate-thumbnail/1")
  1075. assert response.status_code == 404
  1076. @pytest.mark.asyncio
  1077. @pytest.mark.integration
  1078. async def test_filament_requirements_not_found(self, async_client: AsyncClient):
  1079. """Verify filament-requirements returns 404 for non-existent archive."""
  1080. response = await async_client.get("/api/v1/archives/999999/filament-requirements")
  1081. assert response.status_code == 404
  1082. @pytest.mark.asyncio
  1083. @pytest.mark.integration
  1084. async def test_filament_requirements_with_plate_id_not_found(self, async_client: AsyncClient):
  1085. """Verify filament-requirements with plate_id returns 404 for non-existent archive."""
  1086. response = await async_client.get("/api/v1/archives/999999/filament-requirements?plate_id=1")
  1087. assert response.status_code == 404
  1088. # ========================================================================
  1089. # Tag Management endpoints (Issue #183)
  1090. # ========================================================================
  1091. @pytest.mark.asyncio
  1092. @pytest.mark.integration
  1093. async def test_get_tags_empty(self, async_client: AsyncClient):
  1094. """Verify empty list when no tags exist."""
  1095. response = await async_client.get("/api/v1/archives/tags")
  1096. assert response.status_code == 200
  1097. data = response.json()
  1098. assert isinstance(data, list)
  1099. assert len(data) == 0
  1100. @pytest.mark.asyncio
  1101. @pytest.mark.integration
  1102. async def test_get_tags_with_data(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  1103. """Verify tags are returned with counts."""
  1104. printer = await printer_factory()
  1105. await archive_factory(printer.id, print_name="Archive 1", tags="functional, test")
  1106. await archive_factory(printer.id, print_name="Archive 2", tags="functional, calibration")
  1107. await archive_factory(printer.id, print_name="Archive 3", tags="test")
  1108. response = await async_client.get("/api/v1/archives/tags")
  1109. assert response.status_code == 200
  1110. data = response.json()
  1111. assert isinstance(data, list)
  1112. # Convert to dict for easier lookup
  1113. tags_dict = {t["name"]: t["count"] for t in data}
  1114. assert tags_dict.get("functional") == 2
  1115. assert tags_dict.get("test") == 2
  1116. assert tags_dict.get("calibration") == 1
  1117. @pytest.mark.asyncio
  1118. @pytest.mark.integration
  1119. async def test_get_tags_sorted_by_count(
  1120. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1121. ):
  1122. """Verify tags are sorted by count descending, then by name."""
  1123. printer = await printer_factory()
  1124. await archive_factory(printer.id, tags="alpha")
  1125. await archive_factory(printer.id, tags="beta, alpha")
  1126. await archive_factory(printer.id, tags="gamma, beta, alpha")
  1127. response = await async_client.get("/api/v1/archives/tags")
  1128. assert response.status_code == 200
  1129. data = response.json()
  1130. # alpha=3, beta=2, gamma=1
  1131. assert data[0]["name"] == "alpha"
  1132. assert data[0]["count"] == 3
  1133. assert data[1]["name"] == "beta"
  1134. assert data[1]["count"] == 2
  1135. assert data[2]["name"] == "gamma"
  1136. assert data[2]["count"] == 1
  1137. @pytest.mark.asyncio
  1138. @pytest.mark.integration
  1139. async def test_rename_tag(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  1140. """Verify renaming a tag updates all archives."""
  1141. printer = await printer_factory()
  1142. a1 = await archive_factory(printer.id, print_name="Archive 1", tags="old-tag, other")
  1143. a2 = await archive_factory(printer.id, print_name="Archive 2", tags="old-tag")
  1144. await archive_factory(printer.id, print_name="Archive 3", tags="different")
  1145. response = await async_client.put("/api/v1/archives/tags/old-tag", json={"new_name": "new-tag"})
  1146. assert response.status_code == 200
  1147. data = response.json()
  1148. assert data["affected"] == 2
  1149. # Verify the archives were updated
  1150. response = await async_client.get(f"/api/v1/archives/{a1.id}")
  1151. assert "new-tag" in response.json()["tags"]
  1152. assert "old-tag" not in response.json()["tags"]
  1153. response = await async_client.get(f"/api/v1/archives/{a2.id}")
  1154. assert response.json()["tags"] == "new-tag"
  1155. @pytest.mark.asyncio
  1156. @pytest.mark.integration
  1157. async def test_rename_tag_no_change(self, async_client: AsyncClient):
  1158. """Verify renaming to same name returns 0 affected."""
  1159. response = await async_client.put("/api/v1/archives/tags/some-tag", json={"new_name": "some-tag"})
  1160. assert response.status_code == 200
  1161. assert response.json()["affected"] == 0
  1162. @pytest.mark.asyncio
  1163. @pytest.mark.integration
  1164. async def test_rename_tag_empty_name_error(self, async_client: AsyncClient):
  1165. """Verify renaming to empty name returns error."""
  1166. response = await async_client.put("/api/v1/archives/tags/some-tag", json={"new_name": ""})
  1167. assert response.status_code == 400
  1168. @pytest.mark.asyncio
  1169. @pytest.mark.integration
  1170. async def test_delete_tag(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  1171. """Verify deleting a tag removes it from all archives."""
  1172. printer = await printer_factory()
  1173. a1 = await archive_factory(printer.id, print_name="Archive 1", tags="delete-me, keep")
  1174. a2 = await archive_factory(printer.id, print_name="Archive 2", tags="delete-me")
  1175. await archive_factory(printer.id, print_name="Archive 3", tags="different")
  1176. response = await async_client.delete("/api/v1/archives/tags/delete-me")
  1177. assert response.status_code == 200
  1178. data = response.json()
  1179. assert data["affected"] == 2
  1180. # Verify the archives were updated
  1181. response = await async_client.get(f"/api/v1/archives/{a1.id}")
  1182. assert response.json()["tags"] == "keep"
  1183. response = await async_client.get(f"/api/v1/archives/{a2.id}")
  1184. # Should be None or empty when last tag is removed
  1185. assert response.json()["tags"] is None or response.json()["tags"] == ""
  1186. @pytest.mark.asyncio
  1187. @pytest.mark.integration
  1188. async def test_delete_tag_not_found(self, async_client: AsyncClient):
  1189. """Verify deleting non-existent tag returns 0 affected."""
  1190. response = await async_client.delete("/api/v1/archives/tags/nonexistent-tag")
  1191. assert response.status_code == 200
  1192. assert response.json()["affected"] == 0
  1193. class TestUploadSourceThreeMF:
  1194. """Regression for #1531: source-3MF upload on fallback archives."""
  1195. @staticmethod
  1196. def _minimal_3mf_bytes() -> bytes:
  1197. """Smallest valid .3mf — the upload path enforces a zip header check."""
  1198. import io
  1199. import zipfile
  1200. buf = io.BytesIO()
  1201. with zipfile.ZipFile(buf, "w") as zf:
  1202. zf.writestr("[Content_Types].xml", "<types/>")
  1203. return buf.getvalue()
  1204. @pytest.mark.asyncio
  1205. @pytest.mark.integration
  1206. async def test_fallback_archive_source_upload_lands_under_base_dir(
  1207. self, async_client: AsyncClient, archive_factory, printer_factory, monkeypatch, tmp_path
  1208. ):
  1209. """Fallback archive (file_path='') must accept a source upload and store it inside base_dir.
  1210. Pre-fix, ``Path(base_dir) / ''`` collapsed to ``base_dir`` and the
  1211. ``.parent`` walked out of the data volume, sending the file to
  1212. ``/app/source/...`` and crashing on ``relative_to``.
  1213. """
  1214. from backend.app.core.config import settings as app_settings
  1215. monkeypatch.setattr(app_settings, "base_dir", tmp_path)
  1216. printer = await printer_factory()
  1217. archive = await archive_factory(
  1218. printer.id,
  1219. print_name="Cloud Print",
  1220. file_path="", # fallback archive — no source 3MF was archived
  1221. filename="Cloud Print.3mf",
  1222. )
  1223. files = {"file": ("cloud_print.3mf", self._minimal_3mf_bytes(), "application/octet-stream")}
  1224. response = await async_client.post(f"/api/v1/archives/{archive.id}/source", files=files)
  1225. assert response.status_code == 200, response.text
  1226. payload = response.json()
  1227. rel = payload["source_3mf_path"]
  1228. # Stored as a relative path inside base_dir.
  1229. assert not rel.startswith("/"), f"source_3mf_path should be relative, got {rel!r}"
  1230. # File physically landed under base_dir (NOT escaped to /app/source/).
  1231. assert (tmp_path / rel).is_file()
  1232. # Deterministic fallback location keyed off archive id.
  1233. assert rel == f"archive/no_source/{archive.id}/cloud_print.3mf"
  1234. @pytest.mark.asyncio
  1235. @pytest.mark.integration
  1236. async def test_normal_archive_source_upload_unchanged(
  1237. self, async_client: AsyncClient, archive_factory, printer_factory, monkeypatch, tmp_path
  1238. ):
  1239. """Normal archive (file_path set) still nests the source under <archive>/source/."""
  1240. from backend.app.core.config import settings as app_settings
  1241. monkeypatch.setattr(app_settings, "base_dir", tmp_path)
  1242. printer = await printer_factory()
  1243. # archive_factory's default file_path is "archives/test/test_print.gcode.3mf".
  1244. archive = await archive_factory(printer.id, print_name="Real Print")
  1245. files = {"file": ("real_print.3mf", self._minimal_3mf_bytes(), "application/octet-stream")}
  1246. response = await async_client.post(f"/api/v1/archives/{archive.id}/source", files=files)
  1247. assert response.status_code == 200, response.text
  1248. rel = response.json()["source_3mf_path"]
  1249. assert rel == "archives/test/source/real_print.3mf"
  1250. assert (tmp_path / rel).is_file()
  1251. @pytest.mark.asyncio
  1252. @pytest.mark.integration
  1253. async def test_symlinked_data_dir_upload_succeeds(
  1254. self, async_client: AsyncClient, archive_factory, printer_factory, monkeypatch, tmp_path
  1255. ):
  1256. """Regression: DATA_DIR that's a symlink to the real storage must not break the upload.
  1257. Common on TrueNAS / Synology / QNAP storage pools, and any
  1258. ``-v /symlinked/host/path:/app/data`` mount. The helper resolves
  1259. only for the containment check and returns literal paths so the
  1260. caller's ``relative_to(settings.base_dir)`` doesn't trip over a
  1261. canonical-vs-symlink mismatch.
  1262. """
  1263. from backend.app.core.config import settings as app_settings
  1264. real_dir = tmp_path / "real_storage"
  1265. real_dir.mkdir()
  1266. symlink_dir = tmp_path / "data_via_symlink"
  1267. symlink_dir.symlink_to(real_dir)
  1268. monkeypatch.setattr(app_settings, "base_dir", symlink_dir)
  1269. printer = await printer_factory()
  1270. archive = await archive_factory(
  1271. printer.id,
  1272. print_name="Symlinked Print",
  1273. file_path="archives/X1C/print.gcode.3mf",
  1274. filename="print.gcode.3mf",
  1275. )
  1276. files = {"file": ("print.3mf", self._minimal_3mf_bytes(), "application/octet-stream")}
  1277. response = await async_client.post(f"/api/v1/archives/{archive.id}/source", files=files)
  1278. assert response.status_code == 200, response.text
  1279. rel = response.json()["source_3mf_path"]
  1280. assert rel == "archives/X1C/source/print.3mf"
  1281. # Reachable via both the symlink and the canonical path.
  1282. assert (symlink_dir / rel).is_file()
  1283. assert (real_dir / rel).is_file()
  1284. @pytest.mark.asyncio
  1285. @pytest.mark.integration
  1286. async def test_absolute_file_path_rejected_with_clear_500(
  1287. self, async_client: AsyncClient, archive_factory, printer_factory, monkeypatch, tmp_path
  1288. ):
  1289. """A row whose file_path is absolute (corrupted by old import / manual edit)
  1290. must fail with the explicit "outside the data directory" message, not silently
  1291. write outside base_dir."""
  1292. from backend.app.core.config import settings as app_settings
  1293. monkeypatch.setattr(app_settings, "base_dir", tmp_path)
  1294. printer = await printer_factory()
  1295. archive = await archive_factory(
  1296. printer.id,
  1297. print_name="Corrupt Path",
  1298. file_path="/tmp/totally_outside.gcode.3mf",
  1299. filename="totally_outside.gcode.3mf",
  1300. )
  1301. files = {"file": ("totally_outside.3mf", self._minimal_3mf_bytes(), "application/octet-stream")}
  1302. response = await async_client.post(f"/api/v1/archives/{archive.id}/source", files=files)
  1303. assert response.status_code == 500
  1304. assert "outside the data directory" in response.json()["detail"]
  1305. # Did not write anything under the bogus /tmp/source/ either.
  1306. assert not (Path("/tmp") / "source").exists() or not (Path("/tmp") / "source" / "totally_outside.3mf").exists()