test_archives_api.py 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132
  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. from unittest.mock import AsyncMock, patch
  6. import pytest
  7. from httpx import AsyncClient
  8. class TestArchivesAPI:
  9. """Integration tests for /api/v1/archives/ endpoints."""
  10. # ========================================================================
  11. # Upload endpoint
  12. # ========================================================================
  13. @pytest.mark.asyncio
  14. @pytest.mark.integration
  15. @pytest.mark.parametrize("prefer_filename_for_name", [True, False])
  16. async def test_upload_archive_forwards_prefer_filename_for_name(
  17. self, async_client: AsyncClient, archive_factory, printer_factory, prefer_filename_for_name
  18. ):
  19. """POST /archives/upload must forward prefer_filename_for_name to
  20. ArchiveService.archive_print unchanged — this flag lets a caller (e.g.
  21. the manual upload UI or an external integration) ask for the uploaded
  22. filename to win over the 3MF's embedded print_name (#1152 follow-up:
  23. the flag existed on the service but wasn't exposed on this route).
  24. archive_print is mocked (real 3MF metadata extraction isn't under test
  25. here) but its return value is a real PrintArchive row from the
  26. factory, so ArchiveResponse.model_validate in the route still exercises
  27. real serialization instead of masking a broken response behind a bare
  28. MagicMock.
  29. """
  30. printer = await printer_factory()
  31. archive = await archive_factory(printer.id, print_name="Mocked Return Archive")
  32. archive_print_mock = AsyncMock(return_value=archive)
  33. files = {"file": ("My Print (final).gcode.3mf", b"PK\x03\x04fake3mf", "application/octet-stream")}
  34. params = {"prefer_filename_for_name": prefer_filename_for_name}
  35. with patch(
  36. "backend.app.api.routes.archives.ArchiveService.archive_print",
  37. archive_print_mock,
  38. ):
  39. response = await async_client.post("/api/v1/archives/upload", files=files, params=params)
  40. assert response.status_code == 200
  41. assert archive_print_mock.await_count == 1
  42. kwargs = archive_print_mock.await_args.kwargs
  43. assert kwargs.get("prefer_filename_for_name") is prefer_filename_for_name
  44. @pytest.mark.asyncio
  45. @pytest.mark.integration
  46. async def test_upload_archive_defaults_prefer_filename_for_name_false(
  47. self, async_client: AsyncClient, archive_factory, printer_factory
  48. ):
  49. """Omitting the query param must not change existing behavior for
  50. callers that predate this flag."""
  51. printer = await printer_factory()
  52. archive = await archive_factory(printer.id, print_name="Mocked Return Archive")
  53. archive_print_mock = AsyncMock(return_value=archive)
  54. files = {"file": ("existing-caller.gcode.3mf", b"PK\x03\x04fake3mf", "application/octet-stream")}
  55. with patch(
  56. "backend.app.api.routes.archives.ArchiveService.archive_print",
  57. archive_print_mock,
  58. ):
  59. response = await async_client.post("/api/v1/archives/upload", files=files)
  60. assert response.status_code == 200
  61. kwargs = archive_print_mock.await_args.kwargs
  62. assert kwargs.get("prefer_filename_for_name") is False
  63. @pytest.mark.asyncio
  64. @pytest.mark.integration
  65. @pytest.mark.parametrize("prefer_filename_for_name", [True, False])
  66. async def test_upload_archives_bulk_forwards_prefer_filename_for_name(
  67. self, async_client: AsyncClient, archive_factory, printer_factory, prefer_filename_for_name
  68. ):
  69. """POST /archives/upload-bulk must forward prefer_filename_for_name to
  70. ArchiveService.archive_print for every file in the batch, keeping this
  71. route consistent with the single-file /archives/upload endpoint."""
  72. printer = await printer_factory()
  73. archive = await archive_factory(printer.id, print_name="Mocked Return Archive")
  74. archive_print_mock = AsyncMock(return_value=archive)
  75. files = [
  76. ("files", ("first.gcode.3mf", b"PK\x03\x04fake3mf", "application/octet-stream")),
  77. ("files", ("second.gcode.3mf", b"PK\x03\x04fake3mf", "application/octet-stream")),
  78. ]
  79. params = {"prefer_filename_for_name": prefer_filename_for_name}
  80. with patch(
  81. "backend.app.api.routes.archives.ArchiveService.archive_print",
  82. archive_print_mock,
  83. ):
  84. response = await async_client.post("/api/v1/archives/upload-bulk", files=files, params=params)
  85. assert response.status_code == 200
  86. assert archive_print_mock.await_count == 2
  87. for call in archive_print_mock.await_args_list:
  88. assert call.kwargs.get("prefer_filename_for_name") is prefer_filename_for_name
  89. @pytest.mark.asyncio
  90. @pytest.mark.integration
  91. async def test_upload_archives_bulk_defaults_prefer_filename_for_name_false(
  92. self, async_client: AsyncClient, archive_factory, printer_factory
  93. ):
  94. """Omitting the query param on the bulk route must not change existing
  95. behavior for callers that predate this flag."""
  96. printer = await printer_factory()
  97. archive = await archive_factory(printer.id, print_name="Mocked Return Archive")
  98. archive_print_mock = AsyncMock(return_value=archive)
  99. files = [("files", ("existing-caller.gcode.3mf", b"PK\x03\x04fake3mf", "application/octet-stream"))]
  100. with patch(
  101. "backend.app.api.routes.archives.ArchiveService.archive_print",
  102. archive_print_mock,
  103. ):
  104. response = await async_client.post("/api/v1/archives/upload-bulk", files=files)
  105. assert response.status_code == 200
  106. kwargs = archive_print_mock.await_args.kwargs
  107. assert kwargs.get("prefer_filename_for_name") is False
  108. # ========================================================================
  109. # List endpoints
  110. # ========================================================================
  111. @pytest.mark.asyncio
  112. @pytest.mark.integration
  113. async def test_list_archives_empty(self, async_client: AsyncClient):
  114. """Verify empty list is returned when no archives exist."""
  115. response = await async_client.get("/api/v1/archives/")
  116. assert response.status_code == 200
  117. data = response.json()
  118. assert isinstance(data, list)
  119. assert len(data) == 0
  120. @pytest.mark.asyncio
  121. @pytest.mark.integration
  122. async def test_list_archives_with_data(
  123. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  124. ):
  125. """Verify list returns existing archives."""
  126. printer = await printer_factory()
  127. await archive_factory(printer.id, print_name="Test Archive")
  128. response = await async_client.get("/api/v1/archives/")
  129. assert response.status_code == 200
  130. data = response.json()
  131. assert isinstance(data, list)
  132. assert len(data) >= 1
  133. assert any(a["print_name"] == "Test Archive" for a in data)
  134. @pytest.mark.asyncio
  135. @pytest.mark.integration
  136. async def test_list_archives_pagination(
  137. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  138. ):
  139. """Verify pagination works correctly."""
  140. printer = await printer_factory()
  141. # Create 5 archives
  142. for i in range(5):
  143. await archive_factory(printer.id, print_name=f"Archive {i}")
  144. # Get first page with limit 2
  145. response = await async_client.get("/api/v1/archives/?limit=2&offset=0")
  146. assert response.status_code == 200
  147. data = response.json()
  148. assert isinstance(data, list)
  149. assert len(data) == 2
  150. @pytest.mark.asyncio
  151. @pytest.mark.integration
  152. async def test_list_archives_filter_by_printer(
  153. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  154. ):
  155. """Verify filtering by printer_id works."""
  156. printer1 = await printer_factory(name="Printer 1", serial_number="00M09A000000001")
  157. printer2 = await printer_factory(name="Printer 2", serial_number="00M09A000000002")
  158. await archive_factory(printer1.id, print_name="Printer 1 Archive")
  159. await archive_factory(printer2.id, print_name="Printer 2 Archive")
  160. response = await async_client.get(f"/api/v1/archives/?printer_id={printer1.id}")
  161. assert response.status_code == 200
  162. data = response.json()
  163. assert all(a["printer_id"] == printer1.id for a in data)
  164. # ========================================================================
  165. # Get single endpoint
  166. # ========================================================================
  167. @pytest.mark.asyncio
  168. @pytest.mark.integration
  169. async def test_get_archive(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  170. """Verify single archive can be retrieved."""
  171. printer = await printer_factory()
  172. archive = await archive_factory(printer.id, print_name="Get Test Archive")
  173. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  174. assert response.status_code == 200
  175. result = response.json()
  176. assert result["id"] == archive.id
  177. assert result["print_name"] == "Get Test Archive"
  178. @pytest.mark.asyncio
  179. @pytest.mark.integration
  180. async def test_get_archive_not_found(self, async_client: AsyncClient):
  181. """Verify 404 for non-existent archive."""
  182. response = await async_client.get("/api/v1/archives/9999")
  183. assert response.status_code == 404
  184. # ========================================================================
  185. # Update endpoints
  186. # ========================================================================
  187. @pytest.mark.asyncio
  188. @pytest.mark.integration
  189. async def test_update_archive_name(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  190. """Verify archive name can be updated."""
  191. printer = await printer_factory()
  192. archive = await archive_factory(printer.id, print_name="Original Name")
  193. response = await async_client.patch(f"/api/v1/archives/{archive.id}", json={"print_name": "Updated Name"})
  194. assert response.status_code == 200
  195. assert response.json()["print_name"] == "Updated Name"
  196. @pytest.mark.asyncio
  197. @pytest.mark.integration
  198. async def test_update_archive_notes(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  199. """Verify archive notes can be updated."""
  200. printer = await printer_factory()
  201. archive = await archive_factory(printer.id)
  202. response = await async_client.patch(f"/api/v1/archives/{archive.id}", json={"notes": "Great print!"})
  203. assert response.status_code == 200
  204. assert response.json()["notes"] == "Great print!"
  205. @pytest.mark.asyncio
  206. @pytest.mark.integration
  207. async def test_update_archive_favorite(
  208. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  209. ):
  210. """Verify archive favorite status can be updated."""
  211. printer = await printer_factory()
  212. archive = await archive_factory(printer.id)
  213. response = await async_client.patch(f"/api/v1/archives/{archive.id}", json={"is_favorite": True})
  214. assert response.status_code == 200
  215. assert response.json()["is_favorite"] is True
  216. @pytest.mark.asyncio
  217. @pytest.mark.integration
  218. async def test_update_archive_external_url(
  219. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  220. ):
  221. """Verify archive external_url can be updated."""
  222. printer = await printer_factory()
  223. archive = await archive_factory(printer.id)
  224. response = await async_client.patch(
  225. f"/api/v1/archives/{archive.id}", json={"external_url": "https://printables.com/model/12345"}
  226. )
  227. assert response.status_code == 200
  228. assert response.json()["external_url"] == "https://printables.com/model/12345"
  229. # Verify it can be cleared
  230. response = await async_client.patch(f"/api/v1/archives/{archive.id}", json={"external_url": None})
  231. assert response.status_code == 200
  232. assert response.json()["external_url"] is None
  233. @pytest.mark.asyncio
  234. @pytest.mark.integration
  235. async def test_update_archive_failure_reason_mirrors_to_print_log_entry(
  236. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  237. ):
  238. """#1444: PATCH /archives/{id} with failure_reason must mirror to the
  239. latest PrintLogEntry so the Stats page Failure Analysis widget
  240. (which reads PrintLogEntry.failure_reason) reflects the user's
  241. reclassification instead of showing "Unknown" forever.
  242. """
  243. from sqlalchemy import select
  244. from backend.app.models.print_log import PrintLogEntry
  245. printer = await printer_factory()
  246. # archive_factory auto-creates a matching PrintLogEntry (failure_reason
  247. # carried from the archive, which is NULL here — same shape as the bug
  248. # repro: print completed → log entry written with NULL → user goes to
  249. # classify the failure afterwards).
  250. archive = await archive_factory(printer.id, print_name="Failed Print", status="failed", run_status="failed")
  251. response = await async_client.patch(
  252. f"/api/v1/archives/{archive.id}",
  253. json={"failure_reason": "Adhesion failure"},
  254. )
  255. assert response.status_code == 200
  256. result = await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  257. mirrored = result.scalar_one()
  258. assert mirrored.failure_reason == "Adhesion failure"
  259. @pytest.mark.asyncio
  260. @pytest.mark.integration
  261. async def test_update_archive_status_mirrors_to_print_log_entry(
  262. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  263. ):
  264. """#1444: PATCH /archives/{id} with status must mirror to the latest
  265. PrintLogEntry so stats that filter on PrintLogEntry.status see the
  266. user's reclassification.
  267. """
  268. from sqlalchemy import select
  269. from backend.app.models.print_log import PrintLogEntry
  270. printer = await printer_factory()
  271. archive = await archive_factory(printer.id, run_status="completed")
  272. response = await async_client.patch(
  273. f"/api/v1/archives/{archive.id}",
  274. json={"status": "failed"},
  275. )
  276. assert response.status_code == 200
  277. result = await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  278. mirrored = result.scalar_one()
  279. assert mirrored.status == "failed"
  280. @pytest.mark.asyncio
  281. @pytest.mark.integration
  282. async def test_update_archive_failure_reason_only_touches_latest_entry(
  283. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  284. ):
  285. """#1444: For an archive with multiple runs (reprints), only the
  286. latest PrintLogEntry should receive the reclassification. Earlier
  287. runs were classified at their own time and must not be retroactively
  288. overwritten.
  289. """
  290. from backend.app.models.print_log import PrintLogEntry
  291. printer = await printer_factory()
  292. # First run — created by the factory's auto-run with its own reason.
  293. archive = await archive_factory(printer.id, status="failed", run_status="failed")
  294. from sqlalchemy import select
  295. first_run = (
  296. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  297. ).scalar_one()
  298. first_run.failure_reason = "Filament tangle"
  299. await db_session.commit()
  300. # Second run — the reprint that just finished with NULL classification.
  301. latest_run = PrintLogEntry(archive_id=archive.id, status="failed", failure_reason=None)
  302. db_session.add(latest_run)
  303. await db_session.commit()
  304. response = await async_client.patch(
  305. f"/api/v1/archives/{archive.id}",
  306. json={"failure_reason": "Adhesion failure"},
  307. )
  308. assert response.status_code == 200
  309. await db_session.refresh(first_run)
  310. await db_session.refresh(latest_run)
  311. assert first_run.failure_reason == "Filament tangle"
  312. assert latest_run.failure_reason == "Adhesion failure"
  313. # ========================================================================
  314. # Delete endpoints
  315. # ========================================================================
  316. @pytest.mark.asyncio
  317. @pytest.mark.integration
  318. async def test_delete_archive(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  319. """Verify archive can be deleted."""
  320. printer = await printer_factory()
  321. archive = await archive_factory(printer.id)
  322. archive_id = archive.id
  323. response = await async_client.delete(f"/api/v1/archives/{archive_id}")
  324. assert response.status_code == 200
  325. # Verify deleted
  326. response = await async_client.get(f"/api/v1/archives/{archive_id}")
  327. assert response.status_code == 404
  328. @pytest.mark.asyncio
  329. @pytest.mark.integration
  330. async def test_delete_nonexistent_archive(self, async_client: AsyncClient):
  331. """Verify deleting non-existent archive returns 404."""
  332. response = await async_client.delete("/api/v1/archives/9999")
  333. assert response.status_code == 404
  334. @pytest.mark.asyncio
  335. @pytest.mark.integration
  336. async def test_delete_archive_blocked_when_related_queue_item_printing(
  337. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  338. ):
  339. """#1734: archive delete must 409 when a related queue item is currently
  340. mid-print — deleting the archive would strip the dispatcher's metadata
  341. trail (filament / plate / ams_mapping) out from under the running print.
  342. Both soft and hard delete are gated by the same precondition.
  343. """
  344. from backend.app.models.print_queue import PrintQueueItem
  345. printer = await printer_factory()
  346. archive = await archive_factory(printer.id)
  347. db_session.add(PrintQueueItem(printer_id=printer.id, archive_id=archive.id, status="printing", position=1))
  348. await db_session.commit()
  349. soft = await async_client.delete(f"/api/v1/archives/{archive.id}")
  350. assert soft.status_code == 409
  351. assert "printing" in soft.json()["detail"].lower()
  352. hard = await async_client.delete(f"/api/v1/archives/{archive.id}?purge_stats=true")
  353. assert hard.status_code == 409
  354. @pytest.mark.asyncio
  355. @pytest.mark.integration
  356. async def test_archive_delete_impact_reports_counts(
  357. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  358. ):
  359. """#1734: the delete-impact pre-flight endpoint reports the total
  360. number of related queue items AND how many are currently printing,
  361. so the frontend can both warn the user before they confirm AND
  362. disable the confirm button when the printing count is non-zero.
  363. """
  364. from backend.app.models.print_queue import PrintQueueItem
  365. printer = await printer_factory()
  366. archive = await archive_factory(printer.id)
  367. # Build a mixed-status set the way a Send All upload + later in-flight
  368. # dispatch looks at the wire (#1733).
  369. db_session.add_all(
  370. [
  371. PrintQueueItem(printer_id=printer.id, archive_id=archive.id, status="pending", position=1),
  372. PrintQueueItem(printer_id=printer.id, archive_id=archive.id, status="pending", position=2),
  373. PrintQueueItem(printer_id=printer.id, archive_id=archive.id, status="printing", position=3),
  374. ]
  375. )
  376. # An unrelated archive's queue rows must not bleed into the count.
  377. other = await archive_factory(printer.id)
  378. db_session.add(PrintQueueItem(printer_id=printer.id, archive_id=other.id, status="pending", position=4))
  379. await db_session.commit()
  380. resp = await async_client.get(f"/api/v1/archives/{archive.id}/delete-impact")
  381. assert resp.status_code == 200
  382. body = resp.json()
  383. assert body["related_queue_items"] == 3
  384. assert body["currently_printing"] == 1
  385. @pytest.mark.asyncio
  386. @pytest.mark.integration
  387. async def test_soft_delete_preserves_stats_contribution(
  388. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  389. ):
  390. """#1343: deleting an archive without ``purge_stats`` keeps its
  391. contribution in Quick Stats. The row vanishes from listings but the
  392. filament / time / cost totals stay intact.
  393. """
  394. printer = await printer_factory()
  395. await archive_factory(
  396. printer.id,
  397. status="completed",
  398. print_time_seconds=3600,
  399. filament_used_grams=50.0,
  400. cost=1.50,
  401. )
  402. archive_to_delete = await archive_factory(
  403. printer.id,
  404. status="completed",
  405. print_time_seconds=7200,
  406. filament_used_grams=100.0,
  407. cost=3.00,
  408. )
  409. # Pre-delete: stats include both archives.
  410. pre = (await async_client.get("/api/v1/archives/stats")).json()
  411. assert pre["total_prints"] == 2
  412. assert pre["total_filament_grams"] == 150.0
  413. assert pre["total_cost"] == 4.50
  414. # Soft delete (default — no purge_stats param).
  415. resp = await async_client.delete(f"/api/v1/archives/{archive_to_delete.id}")
  416. assert resp.status_code == 200
  417. body = resp.json()
  418. assert body["purged_from_stats"] is False
  419. # Listing hides the deleted archive…
  420. listing = (await async_client.get("/api/v1/archives/")).json()
  421. assert all(a["id"] != archive_to_delete.id for a in listing)
  422. # …but stats still reflect both prints (the whole point of #1343).
  423. post = (await async_client.get("/api/v1/archives/stats")).json()
  424. assert post["total_prints"] == 2
  425. assert post["total_filament_grams"] == 150.0
  426. assert post["total_cost"] == 4.50
  427. @pytest.mark.asyncio
  428. @pytest.mark.integration
  429. async def test_soft_delete_clears_thumbnail_path_on_linked_log_entries(
  430. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  431. ):
  432. """#1348 follow-up: soft-deleting an archive removes its files from disk;
  433. the cached thumbnail_path on linked PrintLogEntry rows must be NULLed
  434. in the same transaction so the print-log view doesn't 404-storm on the
  435. now-deleted thumbnail file."""
  436. from sqlalchemy import select
  437. from backend.app.models.print_log import PrintLogEntry
  438. printer = await printer_factory()
  439. archive = await archive_factory(
  440. printer.id,
  441. status="completed",
  442. thumbnail_path="archives/test/test_print/thumbnail.png",
  443. )
  444. # The factory's auto-PrintLogEntry doesn't copy thumbnail_path; set it
  445. # manually to mirror what the production write_log_entry path stores.
  446. run_query = await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  447. run = run_query.scalar_one()
  448. run.thumbnail_path = "archives/test/test_print/thumbnail.png"
  449. await db_session.commit()
  450. assert run.thumbnail_path is not None
  451. resp = await async_client.delete(f"/api/v1/archives/{archive.id}")
  452. assert resp.status_code == 200
  453. assert resp.json()["purged_from_stats"] is False
  454. await db_session.refresh(run)
  455. assert run.thumbnail_path is None, "soft-delete must NULL thumbnail_path on linked log entry"
  456. # The log entry itself survives the soft delete (its filament/cost
  457. # contribution still needs to flow into stats per #1343).
  458. assert run.id is not None
  459. assert run.archive_id == archive.id
  460. @pytest.mark.asyncio
  461. @pytest.mark.integration
  462. async def test_hard_delete_clears_thumbnail_path_before_fk_cascade(
  463. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  464. ):
  465. """#1348 follow-up: the auto-purge sweeper (and any caller of
  466. ArchiveService.delete_archive) hard-deletes the archive row but leaves
  467. PrintLogEntry rows alive via ON DELETE SET NULL. The eager
  468. thumbnail_path clear must run inside delete_archive so even orphaned
  469. log entries don't surface stale paths."""
  470. from sqlalchemy import select
  471. from backend.app.models.print_log import PrintLogEntry
  472. from backend.app.services.archive import ArchiveService
  473. printer = await printer_factory()
  474. archive = await archive_factory(
  475. printer.id,
  476. status="completed",
  477. thumbnail_path="archives/test/test_print/thumbnail.png",
  478. )
  479. run_query = await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  480. run = run_query.scalar_one()
  481. run.thumbnail_path = "archives/test/test_print/thumbnail.png"
  482. await db_session.commit()
  483. run_id = run.id
  484. service = ArchiveService(db_session)
  485. assert await service.delete_archive(archive.id) is True
  486. # Log entry survives the hard-delete (the FK is ON DELETE SET NULL
  487. # in production; SQLite test config doesn't enable foreign_keys=ON
  488. # by default so archive_id may still be set, but the row itself
  489. # remains for audit). The thumbnail_path was cleared eagerly by
  490. # _null_print_log_thumbnail_paths before db.delete(archive).
  491. refetch = await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.id == run_id))
  492. survivor = refetch.scalar_one()
  493. assert survivor.thumbnail_path is None, (
  494. "delete_archive must NULL thumbnail_path before removing the archive row"
  495. )
  496. @pytest.mark.asyncio
  497. @pytest.mark.integration
  498. async def test_print_log_thumbnail_route_lazy_nulls_missing_file(
  499. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  500. ):
  501. """#1348 follow-up: GET /print-log/{id}/thumbnail self-heals when the
  502. thumbnail_path on a log entry points at a missing file (failed print
  503. whose thumbnail was never written, or a stale path that escaped the
  504. delete-time cleanup)."""
  505. from sqlalchemy import select
  506. from backend.app.models.print_log import PrintLogEntry
  507. printer = await printer_factory()
  508. archive = await archive_factory(printer.id, status="failed")
  509. run_query = await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  510. run = run_query.scalar_one()
  511. # Path points at a file that never existed (failed-print case where
  512. # archive.thumbnail_path was set but the extractor never produced one).
  513. run.thumbnail_path = "archives/missing/never_written/thumbnail.png"
  514. await db_session.commit()
  515. # Auth is disabled in the integration test config, so the stream-token
  516. # guard is bypassed — the route runs the lazy-NULL branch directly.
  517. resp = await async_client.get(f"/api/v1/print-log/{run.id}/thumbnail")
  518. assert resp.status_code == 404
  519. await db_session.refresh(run)
  520. assert run.thumbnail_path is None, "missing file must self-heal to NULL"
  521. @pytest.mark.asyncio
  522. @pytest.mark.integration
  523. async def test_purge_stats_drops_archive_from_quick_stats(
  524. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  525. ):
  526. """#1343: deleting with ``?purge_stats=true`` hard-deletes the row,
  527. dropping its contribution from Quick Stats (the original behaviour,
  528. now opt-in)."""
  529. printer = await printer_factory()
  530. keep = await archive_factory(printer.id, status="completed", filament_used_grams=50.0)
  531. purge = await archive_factory(printer.id, status="completed", filament_used_grams=100.0)
  532. resp = await async_client.delete(f"/api/v1/archives/{purge.id}?purge_stats=true")
  533. assert resp.status_code == 200
  534. assert resp.json()["purged_from_stats"] is True
  535. stats = (await async_client.get("/api/v1/archives/stats")).json()
  536. assert stats["total_prints"] == 1
  537. assert stats["total_filament_grams"] == 50.0
  538. # The kept archive is still listed.
  539. listing = (await async_client.get("/api/v1/archives/")).json()
  540. assert [a["id"] for a in listing] == [keep.id]
  541. @pytest.mark.asyncio
  542. @pytest.mark.integration
  543. async def test_soft_deleted_archive_404_on_detail(
  544. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  545. ):
  546. """A soft-deleted archive must 404 on GET — a stale bookmark or
  547. direct URL should not expose a row the user has already removed."""
  548. printer = await printer_factory()
  549. archive = await archive_factory(printer.id)
  550. await async_client.delete(f"/api/v1/archives/{archive.id}")
  551. resp = await async_client.get(f"/api/v1/archives/{archive.id}")
  552. assert resp.status_code == 404
  553. @pytest.mark.asyncio
  554. @pytest.mark.integration
  555. async def test_soft_deleted_archive_hidden_from_search(
  556. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  557. ):
  558. """Search must skip soft-deleted archives. Uses the LIKE fallback by
  559. querying a single-character pattern that the SQLite FTS5 rejects, so
  560. the test covers the fallback path that the production FTS path also
  561. respects."""
  562. printer = await printer_factory()
  563. archive = await archive_factory(printer.id, print_name="UniqueSoftDeleteCandidate")
  564. await async_client.delete(f"/api/v1/archives/{archive.id}")
  565. resp = await async_client.get("/api/v1/archives/search?q=UniqueSoftDeleteCandidate")
  566. assert resp.status_code == 200
  567. assert resp.json() == []
  568. # ========================================================================
  569. # Statistics endpoints
  570. # ========================================================================
  571. @pytest.mark.asyncio
  572. @pytest.mark.integration
  573. async def test_get_archive_stats(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  574. """Verify archive statistics can be retrieved."""
  575. printer = await printer_factory()
  576. await archive_factory(
  577. printer.id,
  578. status="completed",
  579. print_time_seconds=3600,
  580. filament_used_grams=50.0,
  581. )
  582. await archive_factory(
  583. printer.id,
  584. status="completed",
  585. print_time_seconds=7200,
  586. filament_used_grams=100.0,
  587. )
  588. response = await async_client.get("/api/v1/archives/stats")
  589. assert response.status_code == 200
  590. result = response.json()
  591. # Check for actual stats fields
  592. assert "total_prints" in result
  593. assert "successful_prints" in result
  594. class TestNo3MFWarning:
  595. """`GET /archives/no-3mf-warning` — install step 4 reactive nudge.
  596. The connection diagnostic's external_storage check only catches the
  597. printer-side variant of the setting (newer firmware). For older slicers
  598. where the toggle lives only in BambuStudio, the printer never reports
  599. it. The fallback path in main.py creates the archive with
  600. extra_data.no_3mf_available=True; this endpoint exposes that as a
  601. boolean so the frontend can surface a one-time banner.
  602. """
  603. @pytest.mark.asyncio
  604. @pytest.mark.integration
  605. async def test_returns_true_when_recent_fallback_exists(
  606. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  607. ):
  608. printer = await printer_factory()
  609. await archive_factory(printer.id, extra_data={"no_3mf_available": True})
  610. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  611. assert response.status_code == 200
  612. assert response.json() == {"has_fallback": True}
  613. @pytest.mark.asyncio
  614. @pytest.mark.integration
  615. async def test_returns_false_when_no_archives(self, async_client: AsyncClient):
  616. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  617. assert response.status_code == 200
  618. assert response.json() == {"has_fallback": False}
  619. @pytest.mark.asyncio
  620. @pytest.mark.integration
  621. async def test_returns_false_when_only_normal_archives(
  622. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  623. ):
  624. printer = await printer_factory()
  625. # extra_data has other keys but no_3mf_available is absent — normal
  626. # archives must not trigger the nudge.
  627. await archive_factory(printer.id, extra_data={"makerworld_url": "https://example"})
  628. await archive_factory(printer.id, extra_data=None)
  629. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  630. assert response.status_code == 200
  631. assert response.json() == {"has_fallback": False}
  632. @pytest.mark.asyncio
  633. @pytest.mark.integration
  634. async def test_ignores_archives_older_than_30_days(
  635. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  636. ):
  637. from datetime import datetime, timedelta, timezone
  638. from backend.app.models.archive import PrintArchive
  639. printer = await printer_factory()
  640. archive = await archive_factory(printer.id, extra_data={"no_3mf_available": True})
  641. # Backdate past the 30-day window — old fallbacks are forgiven.
  642. archive.created_at = datetime.now(timezone.utc) - timedelta(days=45)
  643. await db_session.commit()
  644. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  645. assert response.status_code == 200
  646. assert response.json() == {"has_fallback": False}
  647. # Sanity: row really is in the DB, we just don't surface it.
  648. assert (await db_session.get(PrintArchive, archive.id)) is not None
  649. @pytest.mark.asyncio
  650. @pytest.mark.integration
  651. async def test_ignores_soft_deleted_fallbacks(
  652. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  653. ):
  654. from datetime import datetime, timezone
  655. printer = await printer_factory()
  656. archive = await archive_factory(printer.id, extra_data={"no_3mf_available": True})
  657. archive.deleted_at = datetime.now(timezone.utc)
  658. await db_session.commit()
  659. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  660. assert response.status_code == 200
  661. # Soft-deleted fallbacks have been actioned (user clearing the
  662. # evidence). Stop nudging.
  663. assert response.json() == {"has_fallback": False}
  664. class TestPrintLogEntryDelete:
  665. """#1687: per-row delete on the Print Log page.
  666. Pin the route's three contracts: (1) deleting a row drops its filament
  667. / cost / count contribution from /archives/stats in the same response
  668. cycle; (2) the matching archive (if any) is untouched; (3) missing IDs
  669. return 404 rather than 200-silently.
  670. """
  671. @pytest.mark.asyncio
  672. @pytest.mark.integration
  673. async def test_delete_print_log_entry_drops_from_stats(
  674. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  675. ):
  676. from sqlalchemy import select
  677. from backend.app.models.print_log import PrintLogEntry
  678. printer = await printer_factory()
  679. keep = await archive_factory(printer.id, status="completed", filament_used_grams=50.0)
  680. drop = await archive_factory(printer.id, status="completed", filament_used_grams=125.0)
  681. drop_run = (
  682. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == drop.id))
  683. ).scalar_one()
  684. resp = await async_client.delete(f"/api/v1/print-log/{drop_run.id}")
  685. assert resp.status_code == 200
  686. assert resp.json()["status"] == "deleted"
  687. assert resp.json()["id"] == drop_run.id
  688. # The linked archive survives — the row was a stats row, not the archive.
  689. listing = (await async_client.get("/api/v1/archives/")).json()
  690. assert {a["id"] for a in listing} == {keep.id, drop.id}
  691. # /stats no longer counts the dropped run's filament contribution.
  692. stats = (await async_client.get("/api/v1/archives/stats")).json()
  693. assert stats["total_prints"] == 1
  694. assert stats["total_filament_grams"] == 50.0
  695. @pytest.mark.asyncio
  696. @pytest.mark.integration
  697. async def test_delete_print_log_entry_404_when_missing(self, async_client: AsyncClient):
  698. resp = await async_client.delete("/api/v1/print-log/999999")
  699. assert resp.status_code == 404
  700. @pytest.mark.asyncio
  701. @pytest.mark.integration
  702. async def test_delete_print_log_entry_does_not_clear_others(
  703. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  704. ):
  705. """Deleting one row must not touch siblings — guard against an accidental
  706. ``delete(PrintLogEntry)`` without a ``where`` clause (cf. clear_print_log
  707. which intentionally drops everything)."""
  708. from sqlalchemy import select
  709. from backend.app.models.print_log import PrintLogEntry
  710. printer = await printer_factory()
  711. a = await archive_factory(printer.id, status="completed", filament_used_grams=10.0)
  712. b = await archive_factory(printer.id, status="completed", filament_used_grams=20.0)
  713. c = await archive_factory(printer.id, status="completed", filament_used_grams=30.0)
  714. runs = {r.archive_id: r for r in (await db_session.execute(select(PrintLogEntry))).scalars().all()}
  715. resp = await async_client.delete(f"/api/v1/print-log/{runs[b.id].id}")
  716. assert resp.status_code == 200
  717. survivors = (await db_session.execute(select(PrintLogEntry.archive_id))).scalars().all()
  718. assert set(survivors) == {a.id, c.id}
  719. class TestPrintLogEntryUpdate:
  720. """Tests for ``PATCH /print-log/{entry_id}`` (#1687 part 4).
  721. Pin the route's contracts: (1) GET serialiser actually surfaces
  722. ``failure_reason`` (previously it was silently dropped from the response
  723. even when set in the DB); (2) PATCH persists ``failure_reason`` and
  724. ``status``; (3) unknown vocabulary returns 400 rather than getting stored
  725. as raw garbage; (4) missing IDs return 404.
  726. """
  727. @pytest.mark.asyncio
  728. @pytest.mark.integration
  729. async def test_get_surfaces_failure_reason(
  730. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  731. ):
  732. """Pre-fix the GET endpoint built PrintLogEntrySchema without
  733. ``failure_reason`` even though the column was populated, so the Print
  734. Log table couldn't render what the Failure Analysis widget already
  735. groups by. Regression guard for the silent-drop bug.
  736. """
  737. from sqlalchemy import select
  738. from backend.app.models.print_log import PrintLogEntry
  739. printer = await printer_factory()
  740. archive = await archive_factory(printer.id, status="failed")
  741. entry = (
  742. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  743. ).scalar_one()
  744. entry.failure_reason = "spaghettiDetached"
  745. await db_session.commit()
  746. body = (await async_client.get("/api/v1/print-log/")).json()
  747. match = next(item for item in body["items"] if item["id"] == entry.id)
  748. assert match["failure_reason"] == "spaghettiDetached"
  749. # archive_id should also flow through so the frontend can tell orphan
  750. # entries apart from archive-linked ones.
  751. assert match["archive_id"] == archive.id
  752. @pytest.mark.asyncio
  753. @pytest.mark.integration
  754. async def test_patch_sets_failure_reason(
  755. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  756. ):
  757. from sqlalchemy import select
  758. from backend.app.models.print_log import PrintLogEntry
  759. printer = await printer_factory()
  760. archive = await archive_factory(printer.id, status="failed")
  761. entry = (
  762. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  763. ).scalar_one()
  764. assert entry.failure_reason is None
  765. resp = await async_client.patch(
  766. f"/api/v1/print-log/{entry.id}",
  767. json={"failure_reason": "cloggedNozzle"},
  768. )
  769. assert resp.status_code == 200
  770. assert resp.json()["failure_reason"] == "cloggedNozzle"
  771. await db_session.refresh(entry)
  772. assert entry.failure_reason == "cloggedNozzle"
  773. @pytest.mark.asyncio
  774. @pytest.mark.integration
  775. async def test_patch_can_clear_failure_reason(
  776. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  777. ):
  778. """Empty-string failure_reason stores back as NULL (the column's
  779. nullable=True intent is preserved end-to-end)."""
  780. from sqlalchemy import select
  781. from backend.app.models.print_log import PrintLogEntry
  782. printer = await printer_factory()
  783. archive = await archive_factory(printer.id, status="failed")
  784. entry = (
  785. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  786. ).scalar_one()
  787. entry.failure_reason = "warping"
  788. await db_session.commit()
  789. resp = await async_client.patch(
  790. f"/api/v1/print-log/{entry.id}",
  791. json={"failure_reason": ""},
  792. )
  793. assert resp.status_code == 200
  794. assert resp.json()["failure_reason"] is None
  795. await db_session.refresh(entry)
  796. assert entry.failure_reason is None
  797. @pytest.mark.asyncio
  798. @pytest.mark.integration
  799. async def test_patch_rejects_unknown_failure_reason(
  800. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  801. ):
  802. """Unknown values must 400 — otherwise the UI would render raw garbage
  803. because the i18n layer maps the value back through the canonical
  804. vocabulary."""
  805. from sqlalchemy import select
  806. from backend.app.models.print_log import PrintLogEntry
  807. printer = await printer_factory()
  808. archive = await archive_factory(printer.id, status="failed")
  809. entry = (
  810. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  811. ).scalar_one()
  812. resp = await async_client.patch(
  813. f"/api/v1/print-log/{entry.id}",
  814. json={"failure_reason": "completely-made-up"},
  815. )
  816. assert resp.status_code == 400
  817. @pytest.mark.asyncio
  818. @pytest.mark.integration
  819. async def test_patch_updates_status(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  820. from sqlalchemy import select
  821. from backend.app.models.print_log import PrintLogEntry
  822. printer = await printer_factory()
  823. archive = await archive_factory(printer.id, status="completed")
  824. entry = (
  825. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  826. ).scalar_one()
  827. entry.status = "completed"
  828. await db_session.commit()
  829. resp = await async_client.patch(
  830. f"/api/v1/print-log/{entry.id}",
  831. json={"status": "failed", "failure_reason": "layerShift"},
  832. )
  833. assert resp.status_code == 200
  834. assert resp.json()["status"] == "failed"
  835. assert resp.json()["failure_reason"] == "layerShift"
  836. @pytest.mark.asyncio
  837. @pytest.mark.integration
  838. async def test_patch_rejects_unknown_status(
  839. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  840. ):
  841. from sqlalchemy import select
  842. from backend.app.models.print_log import PrintLogEntry
  843. printer = await printer_factory()
  844. archive = await archive_factory(printer.id, status="failed")
  845. entry = (
  846. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  847. ).scalar_one()
  848. resp = await async_client.patch(
  849. f"/api/v1/print-log/{entry.id}",
  850. json={"status": "bogus-status"},
  851. )
  852. assert resp.status_code == 400
  853. @pytest.mark.asyncio
  854. @pytest.mark.integration
  855. async def test_patch_404_when_missing(self, async_client: AsyncClient):
  856. resp = await async_client.patch(
  857. "/api/v1/print-log/999999",
  858. json={"failure_reason": "cloggedNozzle"},
  859. )
  860. assert resp.status_code == 404
  861. @pytest.mark.asyncio
  862. @pytest.mark.integration
  863. async def test_patch_works_on_orphan_entry(self, async_client: AsyncClient, printer_factory, db_session):
  864. """Orphan log entries (no archive_id) are the actual reason this
  865. endpoint exists — the Archive Edit modal can't reach them. Make sure
  866. the PATCH works for those rows specifically."""
  867. from backend.app.models.print_log import PrintLogEntry
  868. printer = await printer_factory()
  869. orphan = PrintLogEntry(
  870. archive_id=None,
  871. print_name="failed-before-archive-created",
  872. printer_id=printer.id,
  873. status="failed",
  874. failure_reason=None,
  875. )
  876. db_session.add(orphan)
  877. await db_session.commit()
  878. await db_session.refresh(orphan)
  879. assert orphan.archive_id is None
  880. resp = await async_client.patch(
  881. f"/api/v1/print-log/{orphan.id}",
  882. json={"failure_reason": "powerFailure"},
  883. )
  884. assert resp.status_code == 200
  885. assert resp.json()["failure_reason"] == "powerFailure"
  886. assert resp.json()["archive_id"] is None
  887. class TestArchivesSlimAPI:
  888. """Integration tests for /api/v1/archives/slim endpoint."""
  889. @pytest.mark.asyncio
  890. @pytest.mark.integration
  891. async def test_slim_empty(self, async_client: AsyncClient):
  892. """Verify empty list when no archives exist."""
  893. response = await async_client.get("/api/v1/archives/slim")
  894. assert response.status_code == 200
  895. assert response.json() == []
  896. @pytest.mark.asyncio
  897. @pytest.mark.integration
  898. async def test_slim_returns_only_expected_fields(
  899. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  900. ):
  901. """Verify response contains only slim fields, not full archive data."""
  902. printer = await printer_factory()
  903. await archive_factory(
  904. printer.id,
  905. print_name="Slim Test",
  906. status="completed",
  907. filament_type="PLA",
  908. filament_color="#FF0000",
  909. filament_used_grams=50.0,
  910. print_time_seconds=3600,
  911. cost=1.50,
  912. quantity=2,
  913. )
  914. response = await async_client.get("/api/v1/archives/slim")
  915. assert response.status_code == 200
  916. data = response.json()
  917. assert len(data) == 1
  918. item = data[0]
  919. # Expected fields present
  920. assert item["printer_id"] == printer.id
  921. assert item["print_name"] == "Slim Test"
  922. assert item["status"] == "completed"
  923. assert item["filament_type"] == "PLA"
  924. assert item["filament_color"] == "#FF0000"
  925. assert item["filament_used_grams"] == 50.0
  926. assert item["print_time_seconds"] == 3600
  927. assert item["cost"] == 1.50
  928. # quantity is per-event semantics now (each PrintLogEntry = one run);
  929. # the archive's quantity field is no longer surfaced through this
  930. # endpoint after the #1390 per-event migration.
  931. assert item["quantity"] == 1
  932. assert "created_at" in item
  933. # Full archive fields must NOT be present
  934. assert "id" not in item
  935. assert "filename" not in item
  936. assert "file_path" not in item
  937. assert "file_size" not in item
  938. assert "extra_data" not in item
  939. assert "notes" not in item
  940. assert "tags" not in item
  941. assert "photos" not in item
  942. assert "thumbnail_path" not in item
  943. assert "content_hash" not in item
  944. assert "duplicates" not in item
  945. assert "duplicate_count" not in item
  946. @pytest.mark.asyncio
  947. @pytest.mark.integration
  948. async def test_slim_includes_energy_fields(
  949. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  950. ):
  951. """Per-print smart-plug energy surfaces through /slim so the stats
  952. page can include it in cost records and trends (#1432)."""
  953. printer = await printer_factory()
  954. await archive_factory(
  955. printer.id,
  956. status="completed",
  957. cost=1.50,
  958. energy_kwh=0.421,
  959. energy_cost=0.063,
  960. )
  961. response = await async_client.get("/api/v1/archives/slim")
  962. assert response.status_code == 200
  963. item = response.json()[0]
  964. assert item["energy_kwh"] == 0.421
  965. assert item["energy_cost"] == 0.063
  966. @pytest.mark.asyncio
  967. @pytest.mark.integration
  968. async def test_slim_computes_actual_time(
  969. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  970. ):
  971. """Verify actual_time_seconds is computed from started_at/completed_at."""
  972. from datetime import datetime, timezone
  973. printer = await printer_factory()
  974. started = datetime(2024, 1, 1, 10, 0, 0, tzinfo=timezone.utc)
  975. completed = datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc) # 2 hours = 7200s
  976. await archive_factory(
  977. printer.id,
  978. status="completed",
  979. started_at=started,
  980. completed_at=completed,
  981. )
  982. response = await async_client.get("/api/v1/archives/slim")
  983. assert response.status_code == 200
  984. item = response.json()[0]
  985. assert item["actual_time_seconds"] == 7200
  986. @pytest.mark.asyncio
  987. @pytest.mark.integration
  988. async def test_slim_actual_time_for_failed_includes_elapsed(
  989. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  990. ):
  991. """Failed prints report measured elapsed time so Printer Stats By Time
  992. matches Quick Stats Print Time (#1390). Previously this returned null
  993. and the frontend fell back to the slicer estimate, double-counting the
  994. unfinished portion of the print."""
  995. from datetime import datetime, timezone
  996. printer = await printer_factory()
  997. await archive_factory(
  998. printer.id,
  999. status="failed",
  1000. started_at=datetime(2024, 1, 1, 10, 0, 0, tzinfo=timezone.utc),
  1001. completed_at=datetime(2024, 1, 1, 11, 0, 0, tzinfo=timezone.utc),
  1002. )
  1003. response = await async_client.get("/api/v1/archives/slim")
  1004. assert response.status_code == 200
  1005. item = response.json()[0]
  1006. assert item["actual_time_seconds"] == 3600
  1007. @pytest.mark.asyncio
  1008. @pytest.mark.integration
  1009. async def test_slim_date_filtering(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  1010. """Verify date_from and date_to filters work."""
  1011. from datetime import datetime, timezone
  1012. printer = await printer_factory()
  1013. await archive_factory(
  1014. printer.id,
  1015. print_name="Old Print",
  1016. created_at=datetime(2024, 1, 1, tzinfo=timezone.utc),
  1017. )
  1018. await archive_factory(
  1019. printer.id,
  1020. print_name="New Print",
  1021. created_at=datetime(2024, 6, 15, tzinfo=timezone.utc),
  1022. )
  1023. # Filter to only June 2024
  1024. response = await async_client.get("/api/v1/archives/slim?date_from=2024-06-01&date_to=2024-06-30")
  1025. assert response.status_code == 200
  1026. data = response.json()
  1027. assert len(data) == 1
  1028. assert data[0]["print_name"] == "New Print"
  1029. @pytest.mark.asyncio
  1030. @pytest.mark.integration
  1031. async def test_slim_pagination(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  1032. """Verify limit and offset work."""
  1033. printer = await printer_factory()
  1034. for i in range(5):
  1035. await archive_factory(printer.id, print_name=f"Print {i}")
  1036. response = await async_client.get("/api/v1/archives/slim?limit=2&offset=0")
  1037. assert response.status_code == 200
  1038. assert len(response.json()) == 2
  1039. @pytest.mark.asyncio
  1040. @pytest.mark.integration
  1041. async def test_slim_counts_reprints_as_separate_rows(
  1042. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1043. ):
  1044. """Reprints add events even though the archive row is overwritten (#1390).
  1045. Before the per-event migration, /archives/slim returned one row per
  1046. archive — so an archive that had been reprinted three times appeared
  1047. once and undercounted Filament Used / Cost / Time. The endpoint must
  1048. now return one row per logged event.
  1049. """
  1050. from backend.app.models.print_log import PrintLogEntry
  1051. printer = await printer_factory()
  1052. archive = await archive_factory(
  1053. printer.id,
  1054. print_name="Reprinted Model",
  1055. filament_used_grams=50.0,
  1056. cost=1.50,
  1057. )
  1058. # archive_factory synthesizes one event; add two more to simulate
  1059. # the same archive being reprinted twice more.
  1060. for _ in range(2):
  1061. db_session.add(
  1062. PrintLogEntry(
  1063. archive_id=archive.id,
  1064. printer_id=archive.printer_id,
  1065. status="completed",
  1066. filament_type=archive.filament_type,
  1067. filament_used_grams=archive.filament_used_grams,
  1068. cost=archive.cost,
  1069. print_name=archive.print_name,
  1070. )
  1071. )
  1072. await db_session.commit()
  1073. response = await async_client.get("/api/v1/archives/slim")
  1074. assert response.status_code == 200
  1075. data = response.json()
  1076. assert len(data) == 3, "Each reprint must contribute one row"
  1077. total_filament = sum(item["filament_used_grams"] or 0 for item in data)
  1078. assert total_filament == 150.0, "Sum across events must reflect all three runs"
  1079. @pytest.mark.asyncio
  1080. @pytest.mark.integration
  1081. async def test_slim_includes_orphan_events(self, async_client: AsyncClient, printer_factory, db_session):
  1082. """Events whose archive was hard-deleted still appear (#1390).
  1083. After ON DELETE SET NULL the event row survives with archive_id=NULL.
  1084. The slim endpoint must keep counting it so Quick Stats and the
  1085. archive-iterating widgets stay aligned.
  1086. """
  1087. from backend.app.models.print_log import PrintLogEntry
  1088. printer = await printer_factory()
  1089. db_session.add(
  1090. PrintLogEntry(
  1091. archive_id=None,
  1092. printer_id=printer.id,
  1093. status="completed",
  1094. filament_type="PETG",
  1095. filament_used_grams=25.0,
  1096. cost=0.75,
  1097. print_name="Orphaned Print",
  1098. )
  1099. )
  1100. await db_session.commit()
  1101. response = await async_client.get("/api/v1/archives/slim")
  1102. assert response.status_code == 200
  1103. data = response.json()
  1104. assert len(data) == 1
  1105. assert data[0]["print_name"] == "Orphaned Print"
  1106. assert data[0]["filament_used_grams"] == 25.0
  1107. # print_time_seconds (sliced estimate) comes from the archive table,
  1108. # which orphans no longer have — must surface as null gracefully.
  1109. assert data[0]["print_time_seconds"] is None
  1110. class TestFailureAnalysisAPI:
  1111. """Per-event failure analysis (#1390)."""
  1112. @pytest.mark.asyncio
  1113. @pytest.mark.integration
  1114. async def test_failure_analysis_counts_reprints_and_orphans(
  1115. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1116. ):
  1117. """Failure analysis aggregates per event, not per archive.
  1118. Verifies the dual fix for #1390: a reprint that adds a second failed
  1119. event must count twice, and an orphan failed event (archive deleted)
  1120. must still appear in the totals.
  1121. """
  1122. from backend.app.models.print_log import PrintLogEntry
  1123. printer = await printer_factory()
  1124. archive = await archive_factory(
  1125. printer.id,
  1126. print_name="Failing Model",
  1127. status="failed",
  1128. failure_reason="filament_runout",
  1129. )
  1130. # Add a second failed event for the same archive (a reprint that also
  1131. # failed) and one orphan failed event (archive was deleted).
  1132. db_session.add(
  1133. PrintLogEntry(
  1134. archive_id=archive.id,
  1135. printer_id=printer.id,
  1136. status="failed",
  1137. failure_reason="filament_runout",
  1138. filament_type=archive.filament_type,
  1139. print_name=archive.print_name,
  1140. )
  1141. )
  1142. db_session.add(
  1143. PrintLogEntry(
  1144. archive_id=None,
  1145. printer_id=printer.id,
  1146. status="failed",
  1147. failure_reason="bed_adhesion",
  1148. filament_type="PETG",
  1149. print_name="Orphaned Failed Print",
  1150. )
  1151. )
  1152. await db_session.commit()
  1153. response = await async_client.get("/api/v1/archives/analysis/failures")
  1154. assert response.status_code == 200
  1155. result = response.json()
  1156. assert result["total_prints"] == 3
  1157. assert result["failed_prints"] == 3
  1158. assert result["failures_by_reason"]["filament_runout"] == 2
  1159. assert result["failures_by_reason"]["bed_adhesion"] == 1
  1160. class TestArchiveDataIntegrity:
  1161. """Tests for archive data integrity."""
  1162. @pytest.mark.asyncio
  1163. @pytest.mark.integration
  1164. async def test_archive_linked_to_printer(
  1165. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1166. ):
  1167. """Verify archive is properly linked to printer."""
  1168. printer = await printer_factory(name="My Printer")
  1169. archive = await archive_factory(printer.id)
  1170. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  1171. assert response.status_code == 200
  1172. result = response.json()
  1173. assert result["printer_id"] == printer.id
  1174. @pytest.mark.asyncio
  1175. @pytest.mark.integration
  1176. async def test_archive_stores_print_data(
  1177. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1178. ):
  1179. """Verify archive stores all print data correctly."""
  1180. printer = await printer_factory()
  1181. archive = await archive_factory(
  1182. printer.id,
  1183. print_name="Test Print",
  1184. filename="test.3mf",
  1185. status="completed",
  1186. filament_type="PLA",
  1187. filament_used_grams=75.5,
  1188. print_time_seconds=5400,
  1189. )
  1190. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  1191. assert response.status_code == 200
  1192. result = response.json()
  1193. assert result["print_name"] == "Test Print"
  1194. assert result["filename"] == "test.3mf"
  1195. assert result["status"] == "completed"
  1196. assert result["filament_type"] == "PLA"
  1197. assert result["filament_used_grams"] == 75.5
  1198. assert result["print_time_seconds"] == 5400
  1199. @pytest.mark.asyncio
  1200. @pytest.mark.integration
  1201. async def test_archive_update_persists(
  1202. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1203. ):
  1204. """CRITICAL: Verify archive updates persist."""
  1205. printer = await printer_factory()
  1206. archive = await archive_factory(printer.id, notes="Original notes")
  1207. # Update
  1208. await async_client.patch(f"/api/v1/archives/{archive.id}", json={"notes": "Updated notes", "is_favorite": True})
  1209. # Verify persistence
  1210. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  1211. result = response.json()
  1212. assert result["notes"] == "Updated notes"
  1213. assert result["is_favorite"] is True
  1214. class TestArchiveF3DEndpoints:
  1215. """Tests for F3D (Fusion 360 design file) attachment endpoints."""
  1216. @pytest.mark.asyncio
  1217. @pytest.mark.integration
  1218. async def test_archive_response_includes_f3d_path(
  1219. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1220. ):
  1221. """Verify f3d_path is included in archive response."""
  1222. printer = await printer_factory()
  1223. archive = await archive_factory(printer.id, f3d_path="archives/test/design.f3d")
  1224. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  1225. assert response.status_code == 200
  1226. result = response.json()
  1227. assert "f3d_path" in result
  1228. assert result["f3d_path"] == "archives/test/design.f3d"
  1229. @pytest.mark.asyncio
  1230. @pytest.mark.integration
  1231. async def test_archive_response_f3d_path_null_when_not_set(
  1232. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1233. ):
  1234. """Verify f3d_path is null when no F3D file attached."""
  1235. printer = await printer_factory()
  1236. archive = await archive_factory(printer.id)
  1237. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  1238. assert response.status_code == 200
  1239. result = response.json()
  1240. assert "f3d_path" in result
  1241. assert result["f3d_path"] is None
  1242. @pytest.mark.asyncio
  1243. @pytest.mark.integration
  1244. async def test_upload_f3d_to_nonexistent_archive(self, async_client: AsyncClient):
  1245. """Verify 404 when uploading F3D to non-existent archive."""
  1246. # Create a minimal file-like upload
  1247. files = {"file": ("design.f3d", b"fake f3d content", "application/octet-stream")}
  1248. response = await async_client.post("/api/v1/archives/9999/f3d", files=files)
  1249. assert response.status_code == 404
  1250. @pytest.mark.asyncio
  1251. @pytest.mark.integration
  1252. async def test_download_f3d_not_found_when_no_file(
  1253. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1254. ):
  1255. """Verify 404 when downloading F3D from archive without F3D file."""
  1256. printer = await printer_factory()
  1257. archive = await archive_factory(printer.id)
  1258. response = await async_client.get(f"/api/v1/archives/{archive.id}/f3d")
  1259. assert response.status_code == 404
  1260. @pytest.mark.asyncio
  1261. @pytest.mark.integration
  1262. async def test_download_f3d_nonexistent_archive(self, async_client: AsyncClient):
  1263. """Verify 404 when downloading F3D from non-existent archive."""
  1264. response = await async_client.get("/api/v1/archives/9999/f3d")
  1265. assert response.status_code == 404
  1266. @pytest.mark.asyncio
  1267. @pytest.mark.integration
  1268. async def test_delete_f3d_nonexistent_archive(self, async_client: AsyncClient):
  1269. """Verify 404 when deleting F3D from non-existent archive."""
  1270. response = await async_client.delete("/api/v1/archives/9999/f3d")
  1271. assert response.status_code == 404
  1272. @pytest.mark.asyncio
  1273. @pytest.mark.integration
  1274. async def test_delete_f3d_when_no_file(
  1275. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1276. ):
  1277. """Verify 404 when deleting F3D from archive without F3D file."""
  1278. printer = await printer_factory()
  1279. archive = await archive_factory(printer.id)
  1280. response = await async_client.delete(f"/api/v1/archives/{archive.id}/f3d")
  1281. assert response.status_code == 404
  1282. @pytest.mark.asyncio
  1283. @pytest.mark.integration
  1284. async def test_list_archives_includes_f3d_path(
  1285. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1286. ):
  1287. """Verify f3d_path is included in archive list responses."""
  1288. printer = await printer_factory()
  1289. await archive_factory(printer.id, print_name="With F3D", f3d_path="archives/test/design.f3d")
  1290. await archive_factory(printer.id, print_name="Without F3D")
  1291. response = await async_client.get("/api/v1/archives/")
  1292. assert response.status_code == 200
  1293. data = response.json()
  1294. assert len(data) >= 2
  1295. with_f3d = next((a for a in data if a["print_name"] == "With F3D"), None)
  1296. without_f3d = next((a for a in data if a["print_name"] == "Without F3D"), None)
  1297. assert with_f3d is not None
  1298. assert with_f3d["f3d_path"] == "archives/test/design.f3d"
  1299. assert without_f3d is not None
  1300. assert without_f3d["f3d_path"] is None
  1301. # ========================================================================
  1302. # Multi-Plate 3MF endpoints (Issue #93)
  1303. # ========================================================================
  1304. @pytest.mark.asyncio
  1305. @pytest.mark.integration
  1306. async def test_get_archive_plates_not_found(self, async_client: AsyncClient):
  1307. """Verify 404 when fetching plates for non-existent archive."""
  1308. response = await async_client.get("/api/v1/archives/999999/plates")
  1309. assert response.status_code == 404
  1310. @pytest.mark.asyncio
  1311. @pytest.mark.integration
  1312. async def test_get_plate_thumbnail_not_found(self, async_client: AsyncClient):
  1313. """Verify 404 when fetching plate thumbnail for non-existent archive."""
  1314. response = await async_client.get("/api/v1/archives/999999/plate-thumbnail/1")
  1315. assert response.status_code == 404
  1316. @pytest.mark.asyncio
  1317. @pytest.mark.integration
  1318. async def test_filament_requirements_not_found(self, async_client: AsyncClient):
  1319. """Verify filament-requirements returns 404 for non-existent archive."""
  1320. response = await async_client.get("/api/v1/archives/999999/filament-requirements")
  1321. assert response.status_code == 404
  1322. @pytest.mark.asyncio
  1323. @pytest.mark.integration
  1324. async def test_filament_requirements_with_plate_id_not_found(self, async_client: AsyncClient):
  1325. """Verify filament-requirements with plate_id returns 404 for non-existent archive."""
  1326. response = await async_client.get("/api/v1/archives/999999/filament-requirements?plate_id=1")
  1327. assert response.status_code == 404
  1328. async def _two_plate_archive(self, archive_factory, printer_factory, tmp_path):
  1329. """An archive whose 3MF stores plate 2 ahead of plate 1, as Studio writes it."""
  1330. import zipfile
  1331. printer = await printer_factory()
  1332. path = tmp_path / "two_plates.gcode.3mf"
  1333. with zipfile.ZipFile(path, "w") as zf:
  1334. zf.writestr("Metadata/plate_2.gcode", "; plate two\nG28\n")
  1335. zf.writestr("Metadata/plate_1.gcode", "; plate one\nG28\n")
  1336. # An absolute file_path collapses `settings.base_dir / file_path` onto
  1337. # itself, so the route reads the file written here.
  1338. return await archive_factory(printer.id, file_path=str(path), filename="two_plates.gcode.3mf")
  1339. @pytest.mark.asyncio
  1340. @pytest.mark.integration
  1341. async def test_archive_gcode_without_a_plate_serves_the_first_plate(
  1342. self, async_client: AsyncClient, archive_factory, printer_factory, tmp_path
  1343. ):
  1344. """Zip order is whatever the slicer wrote, so the first member here is
  1345. plate 2. Callers that pass no plate must still land on plate 1."""
  1346. archive = await self._two_plate_archive(archive_factory, printer_factory, tmp_path)
  1347. response = await async_client.get(f"/api/v1/archives/{archive.id}/gcode")
  1348. assert response.status_code == 200
  1349. assert "plate one" in response.text
  1350. @pytest.mark.asyncio
  1351. @pytest.mark.integration
  1352. async def test_archive_gcode_serves_the_requested_plate(
  1353. self, async_client: AsyncClient, archive_factory, printer_factory, tmp_path
  1354. ):
  1355. archive = await self._two_plate_archive(archive_factory, printer_factory, tmp_path)
  1356. first = await async_client.get(f"/api/v1/archives/{archive.id}/gcode?plate=1")
  1357. second = await async_client.get(f"/api/v1/archives/{archive.id}/gcode?plate=2")
  1358. assert "plate one" in first.text
  1359. assert "plate two" in second.text
  1360. @pytest.mark.asyncio
  1361. @pytest.mark.integration
  1362. async def test_archive_gcode_rejects_a_plate_the_file_does_not_hold(
  1363. self, async_client: AsyncClient, archive_factory, printer_factory, tmp_path
  1364. ):
  1365. archive = await self._two_plate_archive(archive_factory, printer_factory, tmp_path)
  1366. missing = await async_client.get(f"/api/v1/archives/{archive.id}/gcode?plate=3")
  1367. zeroth = await async_client.get(f"/api/v1/archives/{archive.id}/gcode?plate=0")
  1368. assert missing.status_code == 404
  1369. assert zeroth.status_code == 400
  1370. # ========================================================================
  1371. # Tag Management endpoints (Issue #183)
  1372. # ========================================================================
  1373. @pytest.mark.asyncio
  1374. @pytest.mark.integration
  1375. async def test_get_tags_empty(self, async_client: AsyncClient):
  1376. """Verify empty list when no tags exist."""
  1377. response = await async_client.get("/api/v1/archives/tags")
  1378. assert response.status_code == 200
  1379. data = response.json()
  1380. assert isinstance(data, list)
  1381. assert len(data) == 0
  1382. @pytest.mark.asyncio
  1383. @pytest.mark.integration
  1384. async def test_get_tags_with_data(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  1385. """Verify tags are returned with counts."""
  1386. printer = await printer_factory()
  1387. await archive_factory(printer.id, print_name="Archive 1", tags="functional, test")
  1388. await archive_factory(printer.id, print_name="Archive 2", tags="functional, calibration")
  1389. await archive_factory(printer.id, print_name="Archive 3", tags="test")
  1390. response = await async_client.get("/api/v1/archives/tags")
  1391. assert response.status_code == 200
  1392. data = response.json()
  1393. assert isinstance(data, list)
  1394. # Convert to dict for easier lookup
  1395. tags_dict = {t["name"]: t["count"] for t in data}
  1396. assert tags_dict.get("functional") == 2
  1397. assert tags_dict.get("test") == 2
  1398. assert tags_dict.get("calibration") == 1
  1399. @pytest.mark.asyncio
  1400. @pytest.mark.integration
  1401. async def test_get_tags_sorted_by_count(
  1402. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1403. ):
  1404. """Verify tags are sorted by count descending, then by name."""
  1405. printer = await printer_factory()
  1406. await archive_factory(printer.id, tags="alpha")
  1407. await archive_factory(printer.id, tags="beta, alpha")
  1408. await archive_factory(printer.id, tags="gamma, beta, alpha")
  1409. response = await async_client.get("/api/v1/archives/tags")
  1410. assert response.status_code == 200
  1411. data = response.json()
  1412. # alpha=3, beta=2, gamma=1
  1413. assert data[0]["name"] == "alpha"
  1414. assert data[0]["count"] == 3
  1415. assert data[1]["name"] == "beta"
  1416. assert data[1]["count"] == 2
  1417. assert data[2]["name"] == "gamma"
  1418. assert data[2]["count"] == 1
  1419. @pytest.mark.asyncio
  1420. @pytest.mark.integration
  1421. async def test_rename_tag(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  1422. """Verify renaming a tag updates all archives."""
  1423. printer = await printer_factory()
  1424. a1 = await archive_factory(printer.id, print_name="Archive 1", tags="old-tag, other")
  1425. a2 = await archive_factory(printer.id, print_name="Archive 2", tags="old-tag")
  1426. await archive_factory(printer.id, print_name="Archive 3", tags="different")
  1427. response = await async_client.put("/api/v1/archives/tags/old-tag", json={"new_name": "new-tag"})
  1428. assert response.status_code == 200
  1429. data = response.json()
  1430. assert data["affected"] == 2
  1431. # Verify the archives were updated
  1432. response = await async_client.get(f"/api/v1/archives/{a1.id}")
  1433. assert "new-tag" in response.json()["tags"]
  1434. assert "old-tag" not in response.json()["tags"]
  1435. response = await async_client.get(f"/api/v1/archives/{a2.id}")
  1436. assert response.json()["tags"] == "new-tag"
  1437. @pytest.mark.asyncio
  1438. @pytest.mark.integration
  1439. async def test_rename_tag_no_change(self, async_client: AsyncClient):
  1440. """Verify renaming to same name returns 0 affected."""
  1441. response = await async_client.put("/api/v1/archives/tags/some-tag", json={"new_name": "some-tag"})
  1442. assert response.status_code == 200
  1443. assert response.json()["affected"] == 0
  1444. @pytest.mark.asyncio
  1445. @pytest.mark.integration
  1446. async def test_rename_tag_empty_name_error(self, async_client: AsyncClient):
  1447. """Verify renaming to empty name returns error."""
  1448. response = await async_client.put("/api/v1/archives/tags/some-tag", json={"new_name": ""})
  1449. assert response.status_code == 400
  1450. @pytest.mark.asyncio
  1451. @pytest.mark.integration
  1452. async def test_delete_tag(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  1453. """Verify deleting a tag removes it from all archives."""
  1454. printer = await printer_factory()
  1455. a1 = await archive_factory(printer.id, print_name="Archive 1", tags="delete-me, keep")
  1456. a2 = await archive_factory(printer.id, print_name="Archive 2", tags="delete-me")
  1457. await archive_factory(printer.id, print_name="Archive 3", tags="different")
  1458. response = await async_client.delete("/api/v1/archives/tags/delete-me")
  1459. assert response.status_code == 200
  1460. data = response.json()
  1461. assert data["affected"] == 2
  1462. # Verify the archives were updated
  1463. response = await async_client.get(f"/api/v1/archives/{a1.id}")
  1464. assert response.json()["tags"] == "keep"
  1465. response = await async_client.get(f"/api/v1/archives/{a2.id}")
  1466. # Should be None or empty when last tag is removed
  1467. assert response.json()["tags"] is None or response.json()["tags"] == ""
  1468. @pytest.mark.asyncio
  1469. @pytest.mark.integration
  1470. async def test_delete_tag_not_found(self, async_client: AsyncClient):
  1471. """Verify deleting non-existent tag returns 0 affected."""
  1472. response = await async_client.delete("/api/v1/archives/tags/nonexistent-tag")
  1473. assert response.status_code == 200
  1474. assert response.json()["affected"] == 0
  1475. class TestUploadSourceThreeMF:
  1476. """Regression for #1531: source-3MF upload on fallback archives."""
  1477. @staticmethod
  1478. def _minimal_3mf_bytes() -> bytes:
  1479. """Smallest valid .3mf — the upload path enforces a zip header check."""
  1480. import io
  1481. import zipfile
  1482. buf = io.BytesIO()
  1483. with zipfile.ZipFile(buf, "w") as zf:
  1484. zf.writestr("[Content_Types].xml", "<types/>")
  1485. return buf.getvalue()
  1486. @pytest.mark.asyncio
  1487. @pytest.mark.integration
  1488. async def test_fallback_archive_source_upload_lands_under_base_dir(
  1489. self, async_client: AsyncClient, archive_factory, printer_factory, monkeypatch, tmp_path
  1490. ):
  1491. """Fallback archive (file_path='') must accept a source upload and store it inside base_dir.
  1492. Pre-fix, ``Path(base_dir) / ''`` collapsed to ``base_dir`` and the
  1493. ``.parent`` walked out of the data volume, sending the file to
  1494. ``/app/source/...`` and crashing on ``relative_to``.
  1495. """
  1496. from backend.app.core.config import settings as app_settings
  1497. monkeypatch.setattr(app_settings, "base_dir", tmp_path)
  1498. printer = await printer_factory()
  1499. archive = await archive_factory(
  1500. printer.id,
  1501. print_name="Cloud Print",
  1502. file_path="", # fallback archive — no source 3MF was archived
  1503. filename="Cloud Print.3mf",
  1504. )
  1505. files = {"file": ("cloud_print.3mf", self._minimal_3mf_bytes(), "application/octet-stream")}
  1506. response = await async_client.post(f"/api/v1/archives/{archive.id}/source", files=files)
  1507. assert response.status_code == 200, response.text
  1508. payload = response.json()
  1509. rel = payload["source_3mf_path"]
  1510. # Stored as a relative path inside base_dir.
  1511. assert not rel.startswith("/"), f"source_3mf_path should be relative, got {rel!r}"
  1512. # File physically landed under base_dir (NOT escaped to /app/source/).
  1513. assert (tmp_path / rel).is_file()
  1514. # Deterministic fallback location keyed off archive id.
  1515. assert rel == f"archive/no_source/{archive.id}/cloud_print.3mf"
  1516. @pytest.mark.asyncio
  1517. @pytest.mark.integration
  1518. async def test_normal_archive_source_upload_unchanged(
  1519. self, async_client: AsyncClient, archive_factory, printer_factory, monkeypatch, tmp_path
  1520. ):
  1521. """Normal archive (file_path set) still nests the source under <archive>/source/."""
  1522. from backend.app.core.config import settings as app_settings
  1523. monkeypatch.setattr(app_settings, "base_dir", tmp_path)
  1524. printer = await printer_factory()
  1525. # archive_factory's default file_path is "archives/test/test_print.gcode.3mf".
  1526. archive = await archive_factory(printer.id, print_name="Real Print")
  1527. files = {"file": ("real_print.3mf", self._minimal_3mf_bytes(), "application/octet-stream")}
  1528. response = await async_client.post(f"/api/v1/archives/{archive.id}/source", files=files)
  1529. assert response.status_code == 200, response.text
  1530. rel = response.json()["source_3mf_path"]
  1531. assert rel == "archives/test/source/real_print.3mf"
  1532. assert (tmp_path / rel).is_file()
  1533. @pytest.mark.asyncio
  1534. @pytest.mark.integration
  1535. async def test_symlinked_data_dir_upload_succeeds(
  1536. self, async_client: AsyncClient, archive_factory, printer_factory, monkeypatch, tmp_path
  1537. ):
  1538. """Regression: DATA_DIR that's a symlink to the real storage must not break the upload.
  1539. Common on TrueNAS / Synology / QNAP storage pools, and any
  1540. ``-v /symlinked/host/path:/app/data`` mount. The helper resolves
  1541. only for the containment check and returns literal paths so the
  1542. caller's ``relative_to(settings.base_dir)`` doesn't trip over a
  1543. canonical-vs-symlink mismatch.
  1544. """
  1545. from backend.app.core.config import settings as app_settings
  1546. real_dir = tmp_path / "real_storage"
  1547. real_dir.mkdir()
  1548. symlink_dir = tmp_path / "data_via_symlink"
  1549. symlink_dir.symlink_to(real_dir)
  1550. monkeypatch.setattr(app_settings, "base_dir", symlink_dir)
  1551. printer = await printer_factory()
  1552. archive = await archive_factory(
  1553. printer.id,
  1554. print_name="Symlinked Print",
  1555. file_path="archives/X1C/print.gcode.3mf",
  1556. filename="print.gcode.3mf",
  1557. )
  1558. files = {"file": ("print.3mf", self._minimal_3mf_bytes(), "application/octet-stream")}
  1559. response = await async_client.post(f"/api/v1/archives/{archive.id}/source", files=files)
  1560. assert response.status_code == 200, response.text
  1561. rel = response.json()["source_3mf_path"]
  1562. assert rel == "archives/X1C/source/print.3mf"
  1563. # Reachable via both the symlink and the canonical path.
  1564. assert (symlink_dir / rel).is_file()
  1565. assert (real_dir / rel).is_file()
  1566. @pytest.mark.asyncio
  1567. @pytest.mark.integration
  1568. async def test_absolute_file_path_rejected_with_clear_500(
  1569. self, async_client: AsyncClient, archive_factory, printer_factory, monkeypatch, tmp_path
  1570. ):
  1571. """A row whose file_path is absolute (corrupted by old import / manual edit)
  1572. must fail with the explicit "outside the data directory" message, not silently
  1573. write outside base_dir."""
  1574. from backend.app.core.config import settings as app_settings
  1575. monkeypatch.setattr(app_settings, "base_dir", tmp_path)
  1576. printer = await printer_factory()
  1577. archive = await archive_factory(
  1578. printer.id,
  1579. print_name="Corrupt Path",
  1580. file_path="/tmp/totally_outside.gcode.3mf", # nosec B108
  1581. filename="totally_outside.gcode.3mf",
  1582. )
  1583. files = {"file": ("totally_outside.3mf", self._minimal_3mf_bytes(), "application/octet-stream")}
  1584. response = await async_client.post(f"/api/v1/archives/{archive.id}/source", files=files)
  1585. assert response.status_code == 500
  1586. assert "outside the data directory" in response.json()["detail"]
  1587. # Did not write anything under the bogus /tmp/source/ either.
  1588. assert not (Path("/tmp") / "source").exists() or not (Path("/tmp") / "source" / "totally_outside.3mf").exists() # nosec B108
  1589. class TestSoftDeletedArchivesAreExcluded:
  1590. """Soft-deleted archives (#1343) must not leak into export or analysis (#2731).
  1591. The soft delete keeps the row so global Quick Stats can still count it, but
  1592. the archive is gone from every listing. Two consumers never got the memo:
  1593. the CSV export handed back rows the UI says do not exist, and per-project
  1594. failure analysis kept counting prints the user had deleted from the project
  1595. — disagreeing with the project's own figures.
  1596. """
  1597. @staticmethod
  1598. async def _soft_delete(db_session, archive) -> int:
  1599. from datetime import datetime, timezone
  1600. archive_id = archive.id
  1601. archive.deleted_at = datetime.now(timezone.utc)
  1602. await db_session.commit()
  1603. return archive_id
  1604. @pytest.mark.asyncio
  1605. @pytest.mark.integration
  1606. async def test_export_omits_soft_deleted_archives(
  1607. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1608. ):
  1609. printer = await printer_factory()
  1610. await archive_factory(printer.id, print_name="Kept Print")
  1611. gone = await archive_factory(printer.id, print_name="Deleted Print")
  1612. await self._soft_delete(db_session, gone)
  1613. response = await async_client.get("/api/v1/archives/export?format=csv")
  1614. assert response.status_code == 200
  1615. body = response.text
  1616. assert "Kept Print" in body
  1617. assert "Deleted Print" not in body
  1618. @pytest.mark.asyncio
  1619. @pytest.mark.integration
  1620. async def test_project_failure_analysis_omits_soft_deleted_archives(
  1621. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1622. ):
  1623. from backend.app.models.project import Project
  1624. project = Project(name="Analysis Project")
  1625. db_session.add(project)
  1626. await db_session.commit()
  1627. await db_session.refresh(project)
  1628. project_id = project.id
  1629. printer = await printer_factory()
  1630. await archive_factory(
  1631. printer.id,
  1632. print_name="Kept Failure",
  1633. status="failed",
  1634. failure_reason="bed_adhesion",
  1635. project_id=project_id,
  1636. )
  1637. gone = await archive_factory(
  1638. printer.id,
  1639. print_name="Deleted Failure",
  1640. status="failed",
  1641. failure_reason="filament_runout",
  1642. project_id=project_id,
  1643. )
  1644. await self._soft_delete(db_session, gone)
  1645. response = await async_client.get(f"/api/v1/archives/analysis/failures?project_id={project_id}")
  1646. assert response.status_code == 200
  1647. result = response.json()
  1648. assert result["failed_prints"] == 1
  1649. assert result["failures_by_reason"] == {"bed_adhesion": 1}
  1650. @pytest.mark.asyncio
  1651. @pytest.mark.integration
  1652. async def test_unscoped_failure_analysis_is_unchanged(
  1653. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1654. ):
  1655. """Only the project-scoped path filters. Global analysis still counts
  1656. every run, including orphans, exactly as #1390 established."""
  1657. printer = await printer_factory()
  1658. gone = await archive_factory(
  1659. printer.id, print_name="Deleted Failure", status="failed", failure_reason="filament_runout"
  1660. )
  1661. await self._soft_delete(db_session, gone)
  1662. response = await async_client.get("/api/v1/archives/analysis/failures")
  1663. assert response.status_code == 200
  1664. assert response.json()["failed_prints"] == 1
  1665. class TestPrintLogSorting:
  1666. """#2636: the Print Log's column headers sort the whole log.
  1667. Sorting is server-side because paging is: ordering the rows the browser
  1668. happens to hold would answer "the most expensive print on this page",
  1669. not "the most expensive print". These pin the ordering contract the
  1670. headers depend on, including the two cases that differ per database
  1671. backend or per query plan if left implicit.
  1672. """
  1673. @staticmethod
  1674. async def _seed(db_session, printer_id: int, rows: list[dict]):
  1675. from datetime import datetime
  1676. from backend.app.models.print_log import PrintLogEntry
  1677. created = []
  1678. for i, row in enumerate(rows):
  1679. entry = PrintLogEntry(
  1680. printer_id=printer_id,
  1681. status=row.get("status", "completed"),
  1682. print_name=row.get("print_name", f"job-{i}"),
  1683. started_at=datetime(2026, 1, 1 + i, 12, 0, 0),
  1684. created_at=datetime(2026, 1, 1 + i, 12, 0, 0),
  1685. filament_used_grams=row.get("grams"),
  1686. cost=row.get("cost"),
  1687. energy_kwh=row.get("kwh"),
  1688. )
  1689. db_session.add(entry)
  1690. created.append(entry)
  1691. await db_session.commit()
  1692. return created
  1693. @pytest.mark.asyncio
  1694. @pytest.mark.integration
  1695. async def test_sorts_by_filament_used_in_both_directions(
  1696. self, async_client: AsyncClient, printer_factory, db_session
  1697. ):
  1698. printer = await printer_factory()
  1699. await self._seed(
  1700. db_session,
  1701. printer.id,
  1702. [{"grams": 5.0}, {"grams": 120.0}, {"grams": 30.0}],
  1703. )
  1704. asc = await async_client.get("/api/v1/print-log/?sort_by=filament_used&sort_dir=asc")
  1705. assert asc.status_code == 200
  1706. assert [e["filament_used_grams"] for e in asc.json()["items"]] == [5.0, 30.0, 120.0]
  1707. desc = await async_client.get("/api/v1/print-log/?sort_by=filament_used&sort_dir=desc")
  1708. assert [e["filament_used_grams"] for e in desc.json()["items"]] == [120.0, 30.0, 5.0]
  1709. @pytest.mark.asyncio
  1710. @pytest.mark.integration
  1711. async def test_empty_values_sort_last_whichever_direction(
  1712. self, async_client: AsyncClient, printer_factory, db_session
  1713. ):
  1714. """Cost is NULL until a spool is priced and energy until a smart plug
  1715. reports, so these columns are half-empty for most people. Postgres
  1716. sorts NULLs high and SQLite sorts them low, so without an explicit
  1717. NULLS LAST the same click gives a different first page depending on
  1718. which database the user deployed — and on one of them, a screenful
  1719. of blanks."""
  1720. printer = await printer_factory()
  1721. await self._seed(
  1722. db_session,
  1723. printer.id,
  1724. [{"cost": None}, {"cost": 2.5}, {"cost": None}, {"cost": 0.75}],
  1725. )
  1726. for direction, expected in (("asc", [0.75, 2.5]), ("desc", [2.5, 0.75])):
  1727. resp = await async_client.get(f"/api/v1/print-log/?sort_by=cost&sort_dir={direction}")
  1728. costs = [e["cost"] for e in resp.json()["items"]]
  1729. assert costs[:2] == expected, (direction, costs)
  1730. assert costs[2:] == [None, None], (direction, costs)
  1731. @pytest.mark.asyncio
  1732. @pytest.mark.integration
  1733. async def test_ties_are_broken_stably_across_pages(self, async_client: AsyncClient, printer_factory, db_session):
  1734. """Sorting by a column where every row shares a value (status) leaves
  1735. the order to the planner unless a tiebreaker is added — and an
  1736. unstable order can show the same row on two pages while another never
  1737. appears at all."""
  1738. printer = await printer_factory()
  1739. await self._seed(db_session, printer.id, [{"status": "completed"} for _ in range(6)])
  1740. first = await async_client.get("/api/v1/print-log/?sort_by=status&sort_dir=asc&limit=3&offset=0")
  1741. second = await async_client.get("/api/v1/print-log/?sort_by=status&sort_dir=asc&limit=3&offset=3")
  1742. page_1 = [e["id"] for e in first.json()["items"]]
  1743. page_2 = [e["id"] for e in second.json()["items"]]
  1744. assert len(set(page_1) & set(page_2)) == 0, "a row appeared on both pages"
  1745. assert len(set(page_1) | set(page_2)) == 6, "a row was never returned"
  1746. # Repeating the same request must give the same page back.
  1747. again = await async_client.get("/api/v1/print-log/?sort_by=status&sort_dir=asc&limit=3&offset=0")
  1748. assert [e["id"] for e in again.json()["items"]] == page_1
  1749. @pytest.mark.asyncio
  1750. @pytest.mark.integration
  1751. async def test_unknown_sort_column_is_rejected(self, async_client: AsyncClient):
  1752. """The client picks the sort key, so the column list is a whitelist —
  1753. anything else would let a request order by any attribute it can name."""
  1754. resp = await async_client.get("/api/v1/print-log/?sort_by=created_by_id")
  1755. assert resp.status_code == 400
  1756. resp = await async_client.get("/api/v1/print-log/?sort_by=1;DROP")
  1757. assert resp.status_code == 400
  1758. @pytest.mark.asyncio
  1759. @pytest.mark.integration
  1760. async def test_invalid_direction_is_rejected(self, async_client: AsyncClient):
  1761. resp = await async_client.get("/api/v1/print-log/?sort_by=date&sort_dir=sideways")
  1762. assert resp.status_code == 422
  1763. @pytest.mark.asyncio
  1764. @pytest.mark.integration
  1765. async def test_defaults_to_newest_first(self, async_client: AsyncClient, printer_factory, db_session):
  1766. """No sort params — the pre-#2636 behaviour, which existing clients
  1767. and the first page load both rely on."""
  1768. printer = await printer_factory()
  1769. await self._seed(db_session, printer.id, [{"print_name": "oldest"}, {"print_name": "newest"}])
  1770. resp = await async_client.get("/api/v1/print-log/")
  1771. assert [e["print_name"] for e in resp.json()["items"]] == ["newest", "oldest"]