test_archives_api.py 98 KB

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