test_archives_api.py 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664
  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 TestNo3MFWarning:
  445. """`GET /archives/no-3mf-warning` — install step 4 reactive nudge.
  446. The connection diagnostic's external_storage check only catches the
  447. printer-side variant of the setting (newer firmware). For older slicers
  448. where the toggle lives only in BambuStudio, the printer never reports
  449. it. The fallback path in main.py creates the archive with
  450. extra_data.no_3mf_available=True; this endpoint exposes that as a
  451. boolean so the frontend can surface a one-time banner.
  452. """
  453. @pytest.mark.asyncio
  454. @pytest.mark.integration
  455. async def test_returns_true_when_recent_fallback_exists(
  456. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  457. ):
  458. printer = await printer_factory()
  459. await archive_factory(printer.id, extra_data={"no_3mf_available": True})
  460. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  461. assert response.status_code == 200
  462. assert response.json() == {"has_fallback": True}
  463. @pytest.mark.asyncio
  464. @pytest.mark.integration
  465. async def test_returns_false_when_no_archives(self, async_client: AsyncClient):
  466. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  467. assert response.status_code == 200
  468. assert response.json() == {"has_fallback": False}
  469. @pytest.mark.asyncio
  470. @pytest.mark.integration
  471. async def test_returns_false_when_only_normal_archives(
  472. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  473. ):
  474. printer = await printer_factory()
  475. # extra_data has other keys but no_3mf_available is absent — normal
  476. # archives must not trigger the nudge.
  477. await archive_factory(printer.id, extra_data={"makerworld_url": "https://example"})
  478. await archive_factory(printer.id, extra_data=None)
  479. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  480. assert response.status_code == 200
  481. assert response.json() == {"has_fallback": False}
  482. @pytest.mark.asyncio
  483. @pytest.mark.integration
  484. async def test_ignores_archives_older_than_30_days(
  485. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  486. ):
  487. from datetime import datetime, timedelta, timezone
  488. from backend.app.models.archive import PrintArchive
  489. printer = await printer_factory()
  490. archive = await archive_factory(printer.id, extra_data={"no_3mf_available": True})
  491. # Backdate past the 30-day window — old fallbacks are forgiven.
  492. archive.created_at = datetime.now(timezone.utc) - timedelta(days=45)
  493. await db_session.commit()
  494. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  495. assert response.status_code == 200
  496. assert response.json() == {"has_fallback": False}
  497. # Sanity: row really is in the DB, we just don't surface it.
  498. assert (await db_session.get(PrintArchive, archive.id)) is not None
  499. @pytest.mark.asyncio
  500. @pytest.mark.integration
  501. async def test_ignores_soft_deleted_fallbacks(
  502. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  503. ):
  504. from datetime import datetime, timezone
  505. printer = await printer_factory()
  506. archive = await archive_factory(printer.id, extra_data={"no_3mf_available": True})
  507. archive.deleted_at = datetime.now(timezone.utc)
  508. await db_session.commit()
  509. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  510. assert response.status_code == 200
  511. # Soft-deleted fallbacks have been actioned (user clearing the
  512. # evidence). Stop nudging.
  513. assert response.json() == {"has_fallback": False}
  514. class TestPrintLogEntryDelete:
  515. """#1687: per-row delete on the Print Log page.
  516. Pin the route's three contracts: (1) deleting a row drops its filament
  517. / cost / count contribution from /archives/stats in the same response
  518. cycle; (2) the matching archive (if any) is untouched; (3) missing IDs
  519. return 404 rather than 200-silently.
  520. """
  521. @pytest.mark.asyncio
  522. @pytest.mark.integration
  523. async def test_delete_print_log_entry_drops_from_stats(
  524. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  525. ):
  526. from sqlalchemy import select
  527. from backend.app.models.print_log import PrintLogEntry
  528. printer = await printer_factory()
  529. keep = await archive_factory(printer.id, status="completed", filament_used_grams=50.0)
  530. drop = await archive_factory(printer.id, status="completed", filament_used_grams=125.0)
  531. drop_run = (
  532. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == drop.id))
  533. ).scalar_one()
  534. resp = await async_client.delete(f"/api/v1/print-log/{drop_run.id}")
  535. assert resp.status_code == 200
  536. assert resp.json()["status"] == "deleted"
  537. assert resp.json()["id"] == drop_run.id
  538. # The linked archive survives — the row was a stats row, not the archive.
  539. listing = (await async_client.get("/api/v1/archives/")).json()
  540. assert {a["id"] for a in listing} == {keep.id, drop.id}
  541. # /stats no longer counts the dropped run's filament contribution.
  542. stats = (await async_client.get("/api/v1/archives/stats")).json()
  543. assert stats["total_prints"] == 1
  544. assert stats["total_filament_grams"] == 50.0
  545. @pytest.mark.asyncio
  546. @pytest.mark.integration
  547. async def test_delete_print_log_entry_404_when_missing(self, async_client: AsyncClient):
  548. resp = await async_client.delete("/api/v1/print-log/999999")
  549. assert resp.status_code == 404
  550. @pytest.mark.asyncio
  551. @pytest.mark.integration
  552. async def test_delete_print_log_entry_does_not_clear_others(
  553. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  554. ):
  555. """Deleting one row must not touch siblings — guard against an accidental
  556. ``delete(PrintLogEntry)`` without a ``where`` clause (cf. clear_print_log
  557. which intentionally drops everything)."""
  558. from sqlalchemy import select
  559. from backend.app.models.print_log import PrintLogEntry
  560. printer = await printer_factory()
  561. a = await archive_factory(printer.id, status="completed", filament_used_grams=10.0)
  562. b = await archive_factory(printer.id, status="completed", filament_used_grams=20.0)
  563. c = await archive_factory(printer.id, status="completed", filament_used_grams=30.0)
  564. runs = {r.archive_id: r for r in (await db_session.execute(select(PrintLogEntry))).scalars().all()}
  565. resp = await async_client.delete(f"/api/v1/print-log/{runs[b.id].id}")
  566. assert resp.status_code == 200
  567. survivors = (await db_session.execute(select(PrintLogEntry.archive_id))).scalars().all()
  568. assert set(survivors) == {a.id, c.id}
  569. class TestPrintLogEntryUpdate:
  570. """Tests for ``PATCH /print-log/{entry_id}`` (#1687 part 4).
  571. Pin the route's contracts: (1) GET serialiser actually surfaces
  572. ``failure_reason`` (previously it was silently dropped from the response
  573. even when set in the DB); (2) PATCH persists ``failure_reason`` and
  574. ``status``; (3) unknown vocabulary returns 400 rather than getting stored
  575. as raw garbage; (4) missing IDs return 404.
  576. """
  577. @pytest.mark.asyncio
  578. @pytest.mark.integration
  579. async def test_get_surfaces_failure_reason(
  580. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  581. ):
  582. """Pre-fix the GET endpoint built PrintLogEntrySchema without
  583. ``failure_reason`` even though the column was populated, so the Print
  584. Log table couldn't render what the Failure Analysis widget already
  585. groups by. Regression guard for the silent-drop bug.
  586. """
  587. from sqlalchemy import select
  588. from backend.app.models.print_log import PrintLogEntry
  589. printer = await printer_factory()
  590. archive = await archive_factory(printer.id, status="failed")
  591. entry = (
  592. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  593. ).scalar_one()
  594. entry.failure_reason = "spaghettiDetached"
  595. await db_session.commit()
  596. body = (await async_client.get("/api/v1/print-log/")).json()
  597. match = next(item for item in body["items"] if item["id"] == entry.id)
  598. assert match["failure_reason"] == "spaghettiDetached"
  599. # archive_id should also flow through so the frontend can tell orphan
  600. # entries apart from archive-linked ones.
  601. assert match["archive_id"] == archive.id
  602. @pytest.mark.asyncio
  603. @pytest.mark.integration
  604. async def test_patch_sets_failure_reason(
  605. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  606. ):
  607. from sqlalchemy import select
  608. from backend.app.models.print_log import PrintLogEntry
  609. printer = await printer_factory()
  610. archive = await archive_factory(printer.id, status="failed")
  611. entry = (
  612. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  613. ).scalar_one()
  614. assert entry.failure_reason is None
  615. resp = await async_client.patch(
  616. f"/api/v1/print-log/{entry.id}",
  617. json={"failure_reason": "cloggedNozzle"},
  618. )
  619. assert resp.status_code == 200
  620. assert resp.json()["failure_reason"] == "cloggedNozzle"
  621. await db_session.refresh(entry)
  622. assert entry.failure_reason == "cloggedNozzle"
  623. @pytest.mark.asyncio
  624. @pytest.mark.integration
  625. async def test_patch_can_clear_failure_reason(
  626. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  627. ):
  628. """Empty-string failure_reason stores back as NULL (the column's
  629. nullable=True intent is preserved end-to-end)."""
  630. from sqlalchemy import select
  631. from backend.app.models.print_log import PrintLogEntry
  632. printer = await printer_factory()
  633. archive = await archive_factory(printer.id, status="failed")
  634. entry = (
  635. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  636. ).scalar_one()
  637. entry.failure_reason = "warping"
  638. await db_session.commit()
  639. resp = await async_client.patch(
  640. f"/api/v1/print-log/{entry.id}",
  641. json={"failure_reason": ""},
  642. )
  643. assert resp.status_code == 200
  644. assert resp.json()["failure_reason"] is None
  645. await db_session.refresh(entry)
  646. assert entry.failure_reason is None
  647. @pytest.mark.asyncio
  648. @pytest.mark.integration
  649. async def test_patch_rejects_unknown_failure_reason(
  650. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  651. ):
  652. """Unknown values must 400 — otherwise the UI would render raw garbage
  653. because the i18n layer maps the value back through the canonical
  654. vocabulary."""
  655. from sqlalchemy import select
  656. from backend.app.models.print_log import PrintLogEntry
  657. printer = await printer_factory()
  658. archive = await archive_factory(printer.id, status="failed")
  659. entry = (
  660. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  661. ).scalar_one()
  662. resp = await async_client.patch(
  663. f"/api/v1/print-log/{entry.id}",
  664. json={"failure_reason": "completely-made-up"},
  665. )
  666. assert resp.status_code == 400
  667. @pytest.mark.asyncio
  668. @pytest.mark.integration
  669. async def test_patch_updates_status(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  670. from sqlalchemy import select
  671. from backend.app.models.print_log import PrintLogEntry
  672. printer = await printer_factory()
  673. archive = await archive_factory(printer.id, status="completed")
  674. entry = (
  675. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  676. ).scalar_one()
  677. entry.status = "completed"
  678. await db_session.commit()
  679. resp = await async_client.patch(
  680. f"/api/v1/print-log/{entry.id}",
  681. json={"status": "failed", "failure_reason": "layerShift"},
  682. )
  683. assert resp.status_code == 200
  684. assert resp.json()["status"] == "failed"
  685. assert resp.json()["failure_reason"] == "layerShift"
  686. @pytest.mark.asyncio
  687. @pytest.mark.integration
  688. async def test_patch_rejects_unknown_status(
  689. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  690. ):
  691. from sqlalchemy import select
  692. from backend.app.models.print_log import PrintLogEntry
  693. printer = await printer_factory()
  694. archive = await archive_factory(printer.id, status="failed")
  695. entry = (
  696. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  697. ).scalar_one()
  698. resp = await async_client.patch(
  699. f"/api/v1/print-log/{entry.id}",
  700. json={"status": "bogus-status"},
  701. )
  702. assert resp.status_code == 400
  703. @pytest.mark.asyncio
  704. @pytest.mark.integration
  705. async def test_patch_404_when_missing(self, async_client: AsyncClient):
  706. resp = await async_client.patch(
  707. "/api/v1/print-log/999999",
  708. json={"failure_reason": "cloggedNozzle"},
  709. )
  710. assert resp.status_code == 404
  711. @pytest.mark.asyncio
  712. @pytest.mark.integration
  713. async def test_patch_works_on_orphan_entry(self, async_client: AsyncClient, printer_factory, db_session):
  714. """Orphan log entries (no archive_id) are the actual reason this
  715. endpoint exists — the Archive Edit modal can't reach them. Make sure
  716. the PATCH works for those rows specifically."""
  717. from backend.app.models.print_log import PrintLogEntry
  718. printer = await printer_factory()
  719. orphan = PrintLogEntry(
  720. archive_id=None,
  721. print_name="failed-before-archive-created",
  722. printer_id=printer.id,
  723. status="failed",
  724. failure_reason=None,
  725. )
  726. db_session.add(orphan)
  727. await db_session.commit()
  728. await db_session.refresh(orphan)
  729. assert orphan.archive_id is None
  730. resp = await async_client.patch(
  731. f"/api/v1/print-log/{orphan.id}",
  732. json={"failure_reason": "powerFailure"},
  733. )
  734. assert resp.status_code == 200
  735. assert resp.json()["failure_reason"] == "powerFailure"
  736. assert resp.json()["archive_id"] is None
  737. class TestArchivesSlimAPI:
  738. """Integration tests for /api/v1/archives/slim endpoint."""
  739. @pytest.mark.asyncio
  740. @pytest.mark.integration
  741. async def test_slim_empty(self, async_client: AsyncClient):
  742. """Verify empty list when no archives exist."""
  743. response = await async_client.get("/api/v1/archives/slim")
  744. assert response.status_code == 200
  745. assert response.json() == []
  746. @pytest.mark.asyncio
  747. @pytest.mark.integration
  748. async def test_slim_returns_only_expected_fields(
  749. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  750. ):
  751. """Verify response contains only slim fields, not full archive data."""
  752. printer = await printer_factory()
  753. await archive_factory(
  754. printer.id,
  755. print_name="Slim Test",
  756. status="completed",
  757. filament_type="PLA",
  758. filament_color="#FF0000",
  759. filament_used_grams=50.0,
  760. print_time_seconds=3600,
  761. cost=1.50,
  762. quantity=2,
  763. )
  764. response = await async_client.get("/api/v1/archives/slim")
  765. assert response.status_code == 200
  766. data = response.json()
  767. assert len(data) == 1
  768. item = data[0]
  769. # Expected fields present
  770. assert item["printer_id"] == printer.id
  771. assert item["print_name"] == "Slim Test"
  772. assert item["status"] == "completed"
  773. assert item["filament_type"] == "PLA"
  774. assert item["filament_color"] == "#FF0000"
  775. assert item["filament_used_grams"] == 50.0
  776. assert item["print_time_seconds"] == 3600
  777. assert item["cost"] == 1.50
  778. # quantity is per-event semantics now (each PrintLogEntry = one run);
  779. # the archive's quantity field is no longer surfaced through this
  780. # endpoint after the #1390 per-event migration.
  781. assert item["quantity"] == 1
  782. assert "created_at" in item
  783. # Full archive fields must NOT be present
  784. assert "id" not in item
  785. assert "filename" not in item
  786. assert "file_path" not in item
  787. assert "file_size" not in item
  788. assert "extra_data" not in item
  789. assert "notes" not in item
  790. assert "tags" not in item
  791. assert "photos" not in item
  792. assert "thumbnail_path" not in item
  793. assert "content_hash" not in item
  794. assert "duplicates" not in item
  795. assert "duplicate_count" not in item
  796. @pytest.mark.asyncio
  797. @pytest.mark.integration
  798. async def test_slim_computes_actual_time(
  799. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  800. ):
  801. """Verify actual_time_seconds is computed from started_at/completed_at."""
  802. from datetime import datetime, timezone
  803. printer = await printer_factory()
  804. started = datetime(2024, 1, 1, 10, 0, 0, tzinfo=timezone.utc)
  805. completed = datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc) # 2 hours = 7200s
  806. await archive_factory(
  807. printer.id,
  808. status="completed",
  809. started_at=started,
  810. completed_at=completed,
  811. )
  812. response = await async_client.get("/api/v1/archives/slim")
  813. assert response.status_code == 200
  814. item = response.json()[0]
  815. assert item["actual_time_seconds"] == 7200
  816. @pytest.mark.asyncio
  817. @pytest.mark.integration
  818. async def test_slim_actual_time_for_failed_includes_elapsed(
  819. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  820. ):
  821. """Failed prints report measured elapsed time so Printer Stats By Time
  822. matches Quick Stats Print Time (#1390). Previously this returned null
  823. and the frontend fell back to the slicer estimate, double-counting the
  824. unfinished portion of the print."""
  825. from datetime import datetime, timezone
  826. printer = await printer_factory()
  827. await archive_factory(
  828. printer.id,
  829. status="failed",
  830. started_at=datetime(2024, 1, 1, 10, 0, 0, tzinfo=timezone.utc),
  831. completed_at=datetime(2024, 1, 1, 11, 0, 0, tzinfo=timezone.utc),
  832. )
  833. response = await async_client.get("/api/v1/archives/slim")
  834. assert response.status_code == 200
  835. item = response.json()[0]
  836. assert item["actual_time_seconds"] == 3600
  837. @pytest.mark.asyncio
  838. @pytest.mark.integration
  839. async def test_slim_date_filtering(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  840. """Verify date_from and date_to filters work."""
  841. from datetime import datetime, timezone
  842. printer = await printer_factory()
  843. await archive_factory(
  844. printer.id,
  845. print_name="Old Print",
  846. created_at=datetime(2024, 1, 1, tzinfo=timezone.utc),
  847. )
  848. await archive_factory(
  849. printer.id,
  850. print_name="New Print",
  851. created_at=datetime(2024, 6, 15, tzinfo=timezone.utc),
  852. )
  853. # Filter to only June 2024
  854. response = await async_client.get("/api/v1/archives/slim?date_from=2024-06-01&date_to=2024-06-30")
  855. assert response.status_code == 200
  856. data = response.json()
  857. assert len(data) == 1
  858. assert data[0]["print_name"] == "New Print"
  859. @pytest.mark.asyncio
  860. @pytest.mark.integration
  861. async def test_slim_pagination(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  862. """Verify limit and offset work."""
  863. printer = await printer_factory()
  864. for i in range(5):
  865. await archive_factory(printer.id, print_name=f"Print {i}")
  866. response = await async_client.get("/api/v1/archives/slim?limit=2&offset=0")
  867. assert response.status_code == 200
  868. assert len(response.json()) == 2
  869. @pytest.mark.asyncio
  870. @pytest.mark.integration
  871. async def test_slim_counts_reprints_as_separate_rows(
  872. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  873. ):
  874. """Reprints add events even though the archive row is overwritten (#1390).
  875. Before the per-event migration, /archives/slim returned one row per
  876. archive — so an archive that had been reprinted three times appeared
  877. once and undercounted Filament Used / Cost / Time. The endpoint must
  878. now return one row per logged event.
  879. """
  880. from backend.app.models.print_log import PrintLogEntry
  881. printer = await printer_factory()
  882. archive = await archive_factory(
  883. printer.id,
  884. print_name="Reprinted Model",
  885. filament_used_grams=50.0,
  886. cost=1.50,
  887. )
  888. # archive_factory synthesizes one event; add two more to simulate
  889. # the same archive being reprinted twice more.
  890. for _ in range(2):
  891. db_session.add(
  892. PrintLogEntry(
  893. archive_id=archive.id,
  894. printer_id=archive.printer_id,
  895. status="completed",
  896. filament_type=archive.filament_type,
  897. filament_used_grams=archive.filament_used_grams,
  898. cost=archive.cost,
  899. print_name=archive.print_name,
  900. )
  901. )
  902. await db_session.commit()
  903. response = await async_client.get("/api/v1/archives/slim")
  904. assert response.status_code == 200
  905. data = response.json()
  906. assert len(data) == 3, "Each reprint must contribute one row"
  907. total_filament = sum(item["filament_used_grams"] or 0 for item in data)
  908. assert total_filament == 150.0, "Sum across events must reflect all three runs"
  909. @pytest.mark.asyncio
  910. @pytest.mark.integration
  911. async def test_slim_includes_orphan_events(self, async_client: AsyncClient, printer_factory, db_session):
  912. """Events whose archive was hard-deleted still appear (#1390).
  913. After ON DELETE SET NULL the event row survives with archive_id=NULL.
  914. The slim endpoint must keep counting it so Quick Stats and the
  915. archive-iterating widgets stay aligned.
  916. """
  917. from backend.app.models.print_log import PrintLogEntry
  918. printer = await printer_factory()
  919. db_session.add(
  920. PrintLogEntry(
  921. archive_id=None,
  922. printer_id=printer.id,
  923. status="completed",
  924. filament_type="PETG",
  925. filament_used_grams=25.0,
  926. cost=0.75,
  927. print_name="Orphaned Print",
  928. )
  929. )
  930. await db_session.commit()
  931. response = await async_client.get("/api/v1/archives/slim")
  932. assert response.status_code == 200
  933. data = response.json()
  934. assert len(data) == 1
  935. assert data[0]["print_name"] == "Orphaned Print"
  936. assert data[0]["filament_used_grams"] == 25.0
  937. # print_time_seconds (sliced estimate) comes from the archive table,
  938. # which orphans no longer have — must surface as null gracefully.
  939. assert data[0]["print_time_seconds"] is None
  940. class TestFailureAnalysisAPI:
  941. """Per-event failure analysis (#1390)."""
  942. @pytest.mark.asyncio
  943. @pytest.mark.integration
  944. async def test_failure_analysis_counts_reprints_and_orphans(
  945. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  946. ):
  947. """Failure analysis aggregates per event, not per archive.
  948. Verifies the dual fix for #1390: a reprint that adds a second failed
  949. event must count twice, and an orphan failed event (archive deleted)
  950. must still appear in the totals.
  951. """
  952. from backend.app.models.print_log import PrintLogEntry
  953. printer = await printer_factory()
  954. archive = await archive_factory(
  955. printer.id,
  956. print_name="Failing Model",
  957. status="failed",
  958. failure_reason="filament_runout",
  959. )
  960. # Add a second failed event for the same archive (a reprint that also
  961. # failed) and one orphan failed event (archive was deleted).
  962. db_session.add(
  963. PrintLogEntry(
  964. archive_id=archive.id,
  965. printer_id=printer.id,
  966. status="failed",
  967. failure_reason="filament_runout",
  968. filament_type=archive.filament_type,
  969. print_name=archive.print_name,
  970. )
  971. )
  972. db_session.add(
  973. PrintLogEntry(
  974. archive_id=None,
  975. printer_id=printer.id,
  976. status="failed",
  977. failure_reason="bed_adhesion",
  978. filament_type="PETG",
  979. print_name="Orphaned Failed Print",
  980. )
  981. )
  982. await db_session.commit()
  983. response = await async_client.get("/api/v1/archives/analysis/failures")
  984. assert response.status_code == 200
  985. result = response.json()
  986. assert result["total_prints"] == 3
  987. assert result["failed_prints"] == 3
  988. assert result["failures_by_reason"]["filament_runout"] == 2
  989. assert result["failures_by_reason"]["bed_adhesion"] == 1
  990. class TestArchiveDataIntegrity:
  991. """Tests for archive data integrity."""
  992. @pytest.mark.asyncio
  993. @pytest.mark.integration
  994. async def test_archive_linked_to_printer(
  995. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  996. ):
  997. """Verify archive is properly linked to printer."""
  998. printer = await printer_factory(name="My Printer")
  999. archive = await archive_factory(printer.id)
  1000. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  1001. assert response.status_code == 200
  1002. result = response.json()
  1003. assert result["printer_id"] == printer.id
  1004. @pytest.mark.asyncio
  1005. @pytest.mark.integration
  1006. async def test_archive_stores_print_data(
  1007. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1008. ):
  1009. """Verify archive stores all print data correctly."""
  1010. printer = await printer_factory()
  1011. archive = await archive_factory(
  1012. printer.id,
  1013. print_name="Test Print",
  1014. filename="test.3mf",
  1015. status="completed",
  1016. filament_type="PLA",
  1017. filament_used_grams=75.5,
  1018. print_time_seconds=5400,
  1019. )
  1020. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  1021. assert response.status_code == 200
  1022. result = response.json()
  1023. assert result["print_name"] == "Test Print"
  1024. assert result["filename"] == "test.3mf"
  1025. assert result["status"] == "completed"
  1026. assert result["filament_type"] == "PLA"
  1027. assert result["filament_used_grams"] == 75.5
  1028. assert result["print_time_seconds"] == 5400
  1029. @pytest.mark.asyncio
  1030. @pytest.mark.integration
  1031. async def test_archive_update_persists(
  1032. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1033. ):
  1034. """CRITICAL: Verify archive updates persist."""
  1035. printer = await printer_factory()
  1036. archive = await archive_factory(printer.id, notes="Original notes")
  1037. # Update
  1038. await async_client.patch(f"/api/v1/archives/{archive.id}", json={"notes": "Updated notes", "is_favorite": True})
  1039. # Verify persistence
  1040. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  1041. result = response.json()
  1042. assert result["notes"] == "Updated notes"
  1043. assert result["is_favorite"] is True
  1044. class TestArchiveF3DEndpoints:
  1045. """Tests for F3D (Fusion 360 design file) attachment endpoints."""
  1046. @pytest.mark.asyncio
  1047. @pytest.mark.integration
  1048. async def test_archive_response_includes_f3d_path(
  1049. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1050. ):
  1051. """Verify f3d_path is included in archive response."""
  1052. printer = await printer_factory()
  1053. archive = await archive_factory(printer.id, f3d_path="archives/test/design.f3d")
  1054. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  1055. assert response.status_code == 200
  1056. result = response.json()
  1057. assert "f3d_path" in result
  1058. assert result["f3d_path"] == "archives/test/design.f3d"
  1059. @pytest.mark.asyncio
  1060. @pytest.mark.integration
  1061. async def test_archive_response_f3d_path_null_when_not_set(
  1062. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1063. ):
  1064. """Verify f3d_path is null when no F3D file attached."""
  1065. printer = await printer_factory()
  1066. archive = await archive_factory(printer.id)
  1067. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  1068. assert response.status_code == 200
  1069. result = response.json()
  1070. assert "f3d_path" in result
  1071. assert result["f3d_path"] is None
  1072. @pytest.mark.asyncio
  1073. @pytest.mark.integration
  1074. async def test_upload_f3d_to_nonexistent_archive(self, async_client: AsyncClient):
  1075. """Verify 404 when uploading F3D to non-existent archive."""
  1076. # Create a minimal file-like upload
  1077. files = {"file": ("design.f3d", b"fake f3d content", "application/octet-stream")}
  1078. response = await async_client.post("/api/v1/archives/9999/f3d", files=files)
  1079. assert response.status_code == 404
  1080. @pytest.mark.asyncio
  1081. @pytest.mark.integration
  1082. async def test_download_f3d_not_found_when_no_file(
  1083. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1084. ):
  1085. """Verify 404 when downloading F3D from archive without F3D file."""
  1086. printer = await printer_factory()
  1087. archive = await archive_factory(printer.id)
  1088. response = await async_client.get(f"/api/v1/archives/{archive.id}/f3d")
  1089. assert response.status_code == 404
  1090. @pytest.mark.asyncio
  1091. @pytest.mark.integration
  1092. async def test_download_f3d_nonexistent_archive(self, async_client: AsyncClient):
  1093. """Verify 404 when downloading F3D from non-existent archive."""
  1094. response = await async_client.get("/api/v1/archives/9999/f3d")
  1095. assert response.status_code == 404
  1096. @pytest.mark.asyncio
  1097. @pytest.mark.integration
  1098. async def test_delete_f3d_nonexistent_archive(self, async_client: AsyncClient):
  1099. """Verify 404 when deleting F3D from non-existent archive."""
  1100. response = await async_client.delete("/api/v1/archives/9999/f3d")
  1101. assert response.status_code == 404
  1102. @pytest.mark.asyncio
  1103. @pytest.mark.integration
  1104. async def test_delete_f3d_when_no_file(
  1105. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1106. ):
  1107. """Verify 404 when deleting F3D from archive without F3D file."""
  1108. printer = await printer_factory()
  1109. archive = await archive_factory(printer.id)
  1110. response = await async_client.delete(f"/api/v1/archives/{archive.id}/f3d")
  1111. assert response.status_code == 404
  1112. @pytest.mark.asyncio
  1113. @pytest.mark.integration
  1114. async def test_list_archives_includes_f3d_path(
  1115. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1116. ):
  1117. """Verify f3d_path is included in archive list responses."""
  1118. printer = await printer_factory()
  1119. await archive_factory(printer.id, print_name="With F3D", f3d_path="archives/test/design.f3d")
  1120. await archive_factory(printer.id, print_name="Without F3D")
  1121. response = await async_client.get("/api/v1/archives/")
  1122. assert response.status_code == 200
  1123. data = response.json()
  1124. assert len(data) >= 2
  1125. with_f3d = next((a for a in data if a["print_name"] == "With F3D"), None)
  1126. without_f3d = next((a for a in data if a["print_name"] == "Without F3D"), None)
  1127. assert with_f3d is not None
  1128. assert with_f3d["f3d_path"] == "archives/test/design.f3d"
  1129. assert without_f3d is not None
  1130. assert without_f3d["f3d_path"] is None
  1131. # ========================================================================
  1132. # Multi-Plate 3MF endpoints (Issue #93)
  1133. # ========================================================================
  1134. @pytest.mark.asyncio
  1135. @pytest.mark.integration
  1136. async def test_get_archive_plates_not_found(self, async_client: AsyncClient):
  1137. """Verify 404 when fetching plates for non-existent archive."""
  1138. response = await async_client.get("/api/v1/archives/999999/plates")
  1139. assert response.status_code == 404
  1140. @pytest.mark.asyncio
  1141. @pytest.mark.integration
  1142. async def test_get_plate_thumbnail_not_found(self, async_client: AsyncClient):
  1143. """Verify 404 when fetching plate thumbnail for non-existent archive."""
  1144. response = await async_client.get("/api/v1/archives/999999/plate-thumbnail/1")
  1145. assert response.status_code == 404
  1146. @pytest.mark.asyncio
  1147. @pytest.mark.integration
  1148. async def test_filament_requirements_not_found(self, async_client: AsyncClient):
  1149. """Verify filament-requirements returns 404 for non-existent archive."""
  1150. response = await async_client.get("/api/v1/archives/999999/filament-requirements")
  1151. assert response.status_code == 404
  1152. @pytest.mark.asyncio
  1153. @pytest.mark.integration
  1154. async def test_filament_requirements_with_plate_id_not_found(self, async_client: AsyncClient):
  1155. """Verify filament-requirements with plate_id returns 404 for non-existent archive."""
  1156. response = await async_client.get("/api/v1/archives/999999/filament-requirements?plate_id=1")
  1157. assert response.status_code == 404
  1158. # ========================================================================
  1159. # Tag Management endpoints (Issue #183)
  1160. # ========================================================================
  1161. @pytest.mark.asyncio
  1162. @pytest.mark.integration
  1163. async def test_get_tags_empty(self, async_client: AsyncClient):
  1164. """Verify empty list when no tags exist."""
  1165. response = await async_client.get("/api/v1/archives/tags")
  1166. assert response.status_code == 200
  1167. data = response.json()
  1168. assert isinstance(data, list)
  1169. assert len(data) == 0
  1170. @pytest.mark.asyncio
  1171. @pytest.mark.integration
  1172. async def test_get_tags_with_data(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  1173. """Verify tags are returned with counts."""
  1174. printer = await printer_factory()
  1175. await archive_factory(printer.id, print_name="Archive 1", tags="functional, test")
  1176. await archive_factory(printer.id, print_name="Archive 2", tags="functional, calibration")
  1177. await archive_factory(printer.id, print_name="Archive 3", tags="test")
  1178. response = await async_client.get("/api/v1/archives/tags")
  1179. assert response.status_code == 200
  1180. data = response.json()
  1181. assert isinstance(data, list)
  1182. # Convert to dict for easier lookup
  1183. tags_dict = {t["name"]: t["count"] for t in data}
  1184. assert tags_dict.get("functional") == 2
  1185. assert tags_dict.get("test") == 2
  1186. assert tags_dict.get("calibration") == 1
  1187. @pytest.mark.asyncio
  1188. @pytest.mark.integration
  1189. async def test_get_tags_sorted_by_count(
  1190. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1191. ):
  1192. """Verify tags are sorted by count descending, then by name."""
  1193. printer = await printer_factory()
  1194. await archive_factory(printer.id, tags="alpha")
  1195. await archive_factory(printer.id, tags="beta, alpha")
  1196. await archive_factory(printer.id, tags="gamma, beta, alpha")
  1197. response = await async_client.get("/api/v1/archives/tags")
  1198. assert response.status_code == 200
  1199. data = response.json()
  1200. # alpha=3, beta=2, gamma=1
  1201. assert data[0]["name"] == "alpha"
  1202. assert data[0]["count"] == 3
  1203. assert data[1]["name"] == "beta"
  1204. assert data[1]["count"] == 2
  1205. assert data[2]["name"] == "gamma"
  1206. assert data[2]["count"] == 1
  1207. @pytest.mark.asyncio
  1208. @pytest.mark.integration
  1209. async def test_rename_tag(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  1210. """Verify renaming a tag updates all archives."""
  1211. printer = await printer_factory()
  1212. a1 = await archive_factory(printer.id, print_name="Archive 1", tags="old-tag, other")
  1213. a2 = await archive_factory(printer.id, print_name="Archive 2", tags="old-tag")
  1214. await archive_factory(printer.id, print_name="Archive 3", tags="different")
  1215. response = await async_client.put("/api/v1/archives/tags/old-tag", json={"new_name": "new-tag"})
  1216. assert response.status_code == 200
  1217. data = response.json()
  1218. assert data["affected"] == 2
  1219. # Verify the archives were updated
  1220. response = await async_client.get(f"/api/v1/archives/{a1.id}")
  1221. assert "new-tag" in response.json()["tags"]
  1222. assert "old-tag" not in response.json()["tags"]
  1223. response = await async_client.get(f"/api/v1/archives/{a2.id}")
  1224. assert response.json()["tags"] == "new-tag"
  1225. @pytest.mark.asyncio
  1226. @pytest.mark.integration
  1227. async def test_rename_tag_no_change(self, async_client: AsyncClient):
  1228. """Verify renaming to same name returns 0 affected."""
  1229. response = await async_client.put("/api/v1/archives/tags/some-tag", json={"new_name": "some-tag"})
  1230. assert response.status_code == 200
  1231. assert response.json()["affected"] == 0
  1232. @pytest.mark.asyncio
  1233. @pytest.mark.integration
  1234. async def test_rename_tag_empty_name_error(self, async_client: AsyncClient):
  1235. """Verify renaming to empty name returns error."""
  1236. response = await async_client.put("/api/v1/archives/tags/some-tag", json={"new_name": ""})
  1237. assert response.status_code == 400
  1238. @pytest.mark.asyncio
  1239. @pytest.mark.integration
  1240. async def test_delete_tag(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  1241. """Verify deleting a tag removes it from all archives."""
  1242. printer = await printer_factory()
  1243. a1 = await archive_factory(printer.id, print_name="Archive 1", tags="delete-me, keep")
  1244. a2 = await archive_factory(printer.id, print_name="Archive 2", tags="delete-me")
  1245. await archive_factory(printer.id, print_name="Archive 3", tags="different")
  1246. response = await async_client.delete("/api/v1/archives/tags/delete-me")
  1247. assert response.status_code == 200
  1248. data = response.json()
  1249. assert data["affected"] == 2
  1250. # Verify the archives were updated
  1251. response = await async_client.get(f"/api/v1/archives/{a1.id}")
  1252. assert response.json()["tags"] == "keep"
  1253. response = await async_client.get(f"/api/v1/archives/{a2.id}")
  1254. # Should be None or empty when last tag is removed
  1255. assert response.json()["tags"] is None or response.json()["tags"] == ""
  1256. @pytest.mark.asyncio
  1257. @pytest.mark.integration
  1258. async def test_delete_tag_not_found(self, async_client: AsyncClient):
  1259. """Verify deleting non-existent tag returns 0 affected."""
  1260. response = await async_client.delete("/api/v1/archives/tags/nonexistent-tag")
  1261. assert response.status_code == 200
  1262. assert response.json()["affected"] == 0
  1263. class TestUploadSourceThreeMF:
  1264. """Regression for #1531: source-3MF upload on fallback archives."""
  1265. @staticmethod
  1266. def _minimal_3mf_bytes() -> bytes:
  1267. """Smallest valid .3mf — the upload path enforces a zip header check."""
  1268. import io
  1269. import zipfile
  1270. buf = io.BytesIO()
  1271. with zipfile.ZipFile(buf, "w") as zf:
  1272. zf.writestr("[Content_Types].xml", "<types/>")
  1273. return buf.getvalue()
  1274. @pytest.mark.asyncio
  1275. @pytest.mark.integration
  1276. async def test_fallback_archive_source_upload_lands_under_base_dir(
  1277. self, async_client: AsyncClient, archive_factory, printer_factory, monkeypatch, tmp_path
  1278. ):
  1279. """Fallback archive (file_path='') must accept a source upload and store it inside base_dir.
  1280. Pre-fix, ``Path(base_dir) / ''`` collapsed to ``base_dir`` and the
  1281. ``.parent`` walked out of the data volume, sending the file to
  1282. ``/app/source/...`` and crashing on ``relative_to``.
  1283. """
  1284. from backend.app.core.config import settings as app_settings
  1285. monkeypatch.setattr(app_settings, "base_dir", tmp_path)
  1286. printer = await printer_factory()
  1287. archive = await archive_factory(
  1288. printer.id,
  1289. print_name="Cloud Print",
  1290. file_path="", # fallback archive — no source 3MF was archived
  1291. filename="Cloud Print.3mf",
  1292. )
  1293. files = {"file": ("cloud_print.3mf", self._minimal_3mf_bytes(), "application/octet-stream")}
  1294. response = await async_client.post(f"/api/v1/archives/{archive.id}/source", files=files)
  1295. assert response.status_code == 200, response.text
  1296. payload = response.json()
  1297. rel = payload["source_3mf_path"]
  1298. # Stored as a relative path inside base_dir.
  1299. assert not rel.startswith("/"), f"source_3mf_path should be relative, got {rel!r}"
  1300. # File physically landed under base_dir (NOT escaped to /app/source/).
  1301. assert (tmp_path / rel).is_file()
  1302. # Deterministic fallback location keyed off archive id.
  1303. assert rel == f"archive/no_source/{archive.id}/cloud_print.3mf"
  1304. @pytest.mark.asyncio
  1305. @pytest.mark.integration
  1306. async def test_normal_archive_source_upload_unchanged(
  1307. self, async_client: AsyncClient, archive_factory, printer_factory, monkeypatch, tmp_path
  1308. ):
  1309. """Normal archive (file_path set) still nests the source under <archive>/source/."""
  1310. from backend.app.core.config import settings as app_settings
  1311. monkeypatch.setattr(app_settings, "base_dir", tmp_path)
  1312. printer = await printer_factory()
  1313. # archive_factory's default file_path is "archives/test/test_print.gcode.3mf".
  1314. archive = await archive_factory(printer.id, print_name="Real Print")
  1315. files = {"file": ("real_print.3mf", self._minimal_3mf_bytes(), "application/octet-stream")}
  1316. response = await async_client.post(f"/api/v1/archives/{archive.id}/source", files=files)
  1317. assert response.status_code == 200, response.text
  1318. rel = response.json()["source_3mf_path"]
  1319. assert rel == "archives/test/source/real_print.3mf"
  1320. assert (tmp_path / rel).is_file()
  1321. @pytest.mark.asyncio
  1322. @pytest.mark.integration
  1323. async def test_symlinked_data_dir_upload_succeeds(
  1324. self, async_client: AsyncClient, archive_factory, printer_factory, monkeypatch, tmp_path
  1325. ):
  1326. """Regression: DATA_DIR that's a symlink to the real storage must not break the upload.
  1327. Common on TrueNAS / Synology / QNAP storage pools, and any
  1328. ``-v /symlinked/host/path:/app/data`` mount. The helper resolves
  1329. only for the containment check and returns literal paths so the
  1330. caller's ``relative_to(settings.base_dir)`` doesn't trip over a
  1331. canonical-vs-symlink mismatch.
  1332. """
  1333. from backend.app.core.config import settings as app_settings
  1334. real_dir = tmp_path / "real_storage"
  1335. real_dir.mkdir()
  1336. symlink_dir = tmp_path / "data_via_symlink"
  1337. symlink_dir.symlink_to(real_dir)
  1338. monkeypatch.setattr(app_settings, "base_dir", symlink_dir)
  1339. printer = await printer_factory()
  1340. archive = await archive_factory(
  1341. printer.id,
  1342. print_name="Symlinked Print",
  1343. file_path="archives/X1C/print.gcode.3mf",
  1344. filename="print.gcode.3mf",
  1345. )
  1346. files = {"file": ("print.3mf", self._minimal_3mf_bytes(), "application/octet-stream")}
  1347. response = await async_client.post(f"/api/v1/archives/{archive.id}/source", files=files)
  1348. assert response.status_code == 200, response.text
  1349. rel = response.json()["source_3mf_path"]
  1350. assert rel == "archives/X1C/source/print.3mf"
  1351. # Reachable via both the symlink and the canonical path.
  1352. assert (symlink_dir / rel).is_file()
  1353. assert (real_dir / rel).is_file()
  1354. @pytest.mark.asyncio
  1355. @pytest.mark.integration
  1356. async def test_absolute_file_path_rejected_with_clear_500(
  1357. self, async_client: AsyncClient, archive_factory, printer_factory, monkeypatch, tmp_path
  1358. ):
  1359. """A row whose file_path is absolute (corrupted by old import / manual edit)
  1360. must fail with the explicit "outside the data directory" message, not silently
  1361. write outside base_dir."""
  1362. from backend.app.core.config import settings as app_settings
  1363. monkeypatch.setattr(app_settings, "base_dir", tmp_path)
  1364. printer = await printer_factory()
  1365. archive = await archive_factory(
  1366. printer.id,
  1367. print_name="Corrupt Path",
  1368. file_path="/tmp/totally_outside.gcode.3mf", # nosec B108
  1369. filename="totally_outside.gcode.3mf",
  1370. )
  1371. files = {"file": ("totally_outside.3mf", self._minimal_3mf_bytes(), "application/octet-stream")}
  1372. response = await async_client.post(f"/api/v1/archives/{archive.id}/source", files=files)
  1373. assert response.status_code == 500
  1374. assert "outside the data directory" in response.json()["detail"]
  1375. # Did not write anything under the bogus /tmp/source/ either.
  1376. assert not (Path("/tmp") / "source").exists() or not (Path("/tmp") / "source" / "totally_outside.3mf").exists() # nosec B108