test_archives_api.py 71 KB

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