test_archives_api.py 117 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839
  1. """Integration tests for Archives API endpoints.
  2. Tests the full request/response cycle for /api/v1/archives/ endpoints.
  3. """
  4. from datetime import datetime
  5. from pathlib import Path
  6. from unittest.mock import AsyncMock, patch
  7. import pytest
  8. from httpx import AsyncClient
  9. from backend.app.core.config import settings
  10. from backend.app.services.bambu_ftp import FileListResult
  11. class TestArchivesAPI:
  12. """Integration tests for /api/v1/archives/ endpoints."""
  13. # ========================================================================
  14. # Upload endpoint
  15. # ========================================================================
  16. @pytest.mark.asyncio
  17. @pytest.mark.integration
  18. @pytest.mark.parametrize("prefer_filename_for_name", [True, False])
  19. async def test_upload_archive_forwards_prefer_filename_for_name(
  20. self, async_client: AsyncClient, archive_factory, printer_factory, prefer_filename_for_name
  21. ):
  22. """POST /archives/upload must forward prefer_filename_for_name to
  23. ArchiveService.archive_print unchanged — this flag lets a caller (e.g.
  24. the manual upload UI or an external integration) ask for the uploaded
  25. filename to win over the 3MF's embedded print_name (#1152 follow-up:
  26. the flag existed on the service but wasn't exposed on this route).
  27. archive_print is mocked (real 3MF metadata extraction isn't under test
  28. here) but its return value is a real PrintArchive row from the
  29. factory, so ArchiveResponse.model_validate in the route still exercises
  30. real serialization instead of masking a broken response behind a bare
  31. MagicMock.
  32. """
  33. printer = await printer_factory()
  34. archive = await archive_factory(printer.id, print_name="Mocked Return Archive")
  35. archive_print_mock = AsyncMock(return_value=archive)
  36. files = {"file": ("My Print (final).gcode.3mf", b"PK\x03\x04fake3mf", "application/octet-stream")}
  37. params = {"prefer_filename_for_name": prefer_filename_for_name}
  38. with patch(
  39. "backend.app.api.routes.archives.ArchiveService.archive_print",
  40. archive_print_mock,
  41. ):
  42. response = await async_client.post("/api/v1/archives/upload", files=files, params=params)
  43. assert response.status_code == 200
  44. assert archive_print_mock.await_count == 1
  45. kwargs = archive_print_mock.await_args.kwargs
  46. assert kwargs.get("prefer_filename_for_name") is prefer_filename_for_name
  47. @pytest.mark.asyncio
  48. @pytest.mark.integration
  49. async def test_upload_archive_defaults_prefer_filename_for_name_false(
  50. self, async_client: AsyncClient, archive_factory, printer_factory
  51. ):
  52. """Omitting the query param must not change existing behavior for
  53. callers that predate this flag."""
  54. printer = await printer_factory()
  55. archive = await archive_factory(printer.id, print_name="Mocked Return Archive")
  56. archive_print_mock = AsyncMock(return_value=archive)
  57. files = {"file": ("existing-caller.gcode.3mf", b"PK\x03\x04fake3mf", "application/octet-stream")}
  58. with patch(
  59. "backend.app.api.routes.archives.ArchiveService.archive_print",
  60. archive_print_mock,
  61. ):
  62. response = await async_client.post("/api/v1/archives/upload", files=files)
  63. assert response.status_code == 200
  64. kwargs = archive_print_mock.await_args.kwargs
  65. assert kwargs.get("prefer_filename_for_name") is False
  66. @pytest.mark.asyncio
  67. @pytest.mark.integration
  68. @pytest.mark.parametrize("prefer_filename_for_name", [True, False])
  69. async def test_upload_archives_bulk_forwards_prefer_filename_for_name(
  70. self, async_client: AsyncClient, archive_factory, printer_factory, prefer_filename_for_name
  71. ):
  72. """POST /archives/upload-bulk must forward prefer_filename_for_name to
  73. ArchiveService.archive_print for every file in the batch, keeping this
  74. route consistent with the single-file /archives/upload endpoint."""
  75. printer = await printer_factory()
  76. archive = await archive_factory(printer.id, print_name="Mocked Return Archive")
  77. archive_print_mock = AsyncMock(return_value=archive)
  78. files = [
  79. ("files", ("first.gcode.3mf", b"PK\x03\x04fake3mf", "application/octet-stream")),
  80. ("files", ("second.gcode.3mf", b"PK\x03\x04fake3mf", "application/octet-stream")),
  81. ]
  82. params = {"prefer_filename_for_name": prefer_filename_for_name}
  83. with patch(
  84. "backend.app.api.routes.archives.ArchiveService.archive_print",
  85. archive_print_mock,
  86. ):
  87. response = await async_client.post("/api/v1/archives/upload-bulk", files=files, params=params)
  88. assert response.status_code == 200
  89. assert archive_print_mock.await_count == 2
  90. for call in archive_print_mock.await_args_list:
  91. assert call.kwargs.get("prefer_filename_for_name") is prefer_filename_for_name
  92. @pytest.mark.asyncio
  93. @pytest.mark.integration
  94. async def test_upload_archives_bulk_defaults_prefer_filename_for_name_false(
  95. self, async_client: AsyncClient, archive_factory, printer_factory
  96. ):
  97. """Omitting the query param on the bulk route must not change existing
  98. behavior for callers that predate this flag."""
  99. printer = await printer_factory()
  100. archive = await archive_factory(printer.id, print_name="Mocked Return Archive")
  101. archive_print_mock = AsyncMock(return_value=archive)
  102. files = [("files", ("existing-caller.gcode.3mf", b"PK\x03\x04fake3mf", "application/octet-stream"))]
  103. with patch(
  104. "backend.app.api.routes.archives.ArchiveService.archive_print",
  105. archive_print_mock,
  106. ):
  107. response = await async_client.post("/api/v1/archives/upload-bulk", files=files)
  108. assert response.status_code == 200
  109. kwargs = archive_print_mock.await_args.kwargs
  110. assert kwargs.get("prefer_filename_for_name") is False
  111. # ========================================================================
  112. # List endpoints
  113. # ========================================================================
  114. @pytest.mark.asyncio
  115. @pytest.mark.integration
  116. async def test_list_archives_empty(self, async_client: AsyncClient):
  117. """Verify empty list is returned when no archives exist."""
  118. response = await async_client.get("/api/v1/archives/")
  119. assert response.status_code == 200
  120. data = response.json()
  121. assert isinstance(data, list)
  122. assert len(data) == 0
  123. @pytest.mark.asyncio
  124. @pytest.mark.integration
  125. async def test_list_archives_with_data(
  126. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  127. ):
  128. """Verify list returns existing archives."""
  129. printer = await printer_factory()
  130. await archive_factory(printer.id, print_name="Test Archive")
  131. response = await async_client.get("/api/v1/archives/")
  132. assert response.status_code == 200
  133. data = response.json()
  134. assert isinstance(data, list)
  135. assert len(data) >= 1
  136. assert any(a["print_name"] == "Test Archive" for a in data)
  137. @pytest.mark.asyncio
  138. @pytest.mark.integration
  139. async def test_list_archives_pagination(
  140. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  141. ):
  142. """Verify pagination works correctly."""
  143. printer = await printer_factory()
  144. # Create 5 archives
  145. for i in range(5):
  146. await archive_factory(printer.id, print_name=f"Archive {i}")
  147. # Get first page with limit 2
  148. response = await async_client.get("/api/v1/archives/?limit=2&offset=0")
  149. assert response.status_code == 200
  150. data = response.json()
  151. assert isinstance(data, list)
  152. assert len(data) == 2
  153. @pytest.mark.asyncio
  154. @pytest.mark.integration
  155. async def test_list_archives_filter_by_printer(
  156. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  157. ):
  158. """Verify filtering by printer_id works."""
  159. printer1 = await printer_factory(name="Printer 1", serial_number="00M09A000000001")
  160. printer2 = await printer_factory(name="Printer 2", serial_number="00M09A000000002")
  161. await archive_factory(printer1.id, print_name="Printer 1 Archive")
  162. await archive_factory(printer2.id, print_name="Printer 2 Archive")
  163. response = await async_client.get(f"/api/v1/archives/?printer_id={printer1.id}")
  164. assert response.status_code == 200
  165. data = response.json()
  166. assert all(a["printer_id"] == printer1.id for a in data)
  167. # ========================================================================
  168. # Get single endpoint
  169. # ========================================================================
  170. @pytest.mark.asyncio
  171. @pytest.mark.integration
  172. async def test_get_archive(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  173. """Verify single archive can be retrieved."""
  174. printer = await printer_factory()
  175. archive = await archive_factory(printer.id, print_name="Get Test Archive")
  176. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  177. assert response.status_code == 200
  178. result = response.json()
  179. assert result["id"] == archive.id
  180. assert result["print_name"] == "Get Test Archive"
  181. @pytest.mark.asyncio
  182. @pytest.mark.integration
  183. async def test_archive_response_exposes_selected_plate(
  184. self, async_client: AsyncClient, archive_factory, printer_factory
  185. ):
  186. """Both archive endpoints must report the stored plate (#2796).
  187. archive_to_response builds its response dict field by field and left
  188. plate_id out. ArchiveResponse.plate_id defaults to None, so every
  189. archive came back as plate_id: null and nothing raised an error.
  190. List and detail share the helper, so both are checked here. The archive
  191. without a plate guards a fix that substitutes a fallback plate.
  192. """
  193. printer = await printer_factory()
  194. with_plate = await archive_factory(printer.id, print_name="Plate 22 of a multi-plate 3MF", plate_id=22)
  195. without_plate = await archive_factory(printer.id, print_name="Single-plate print")
  196. listed = await async_client.get("/api/v1/archives/")
  197. assert listed.status_code == 200
  198. rows = {a["id"]: a for a in listed.json()}
  199. assert rows[with_plate.id]["plate_id"] == 22
  200. assert rows[without_plate.id]["plate_id"] is None
  201. detail = await async_client.get(f"/api/v1/archives/{with_plate.id}")
  202. assert detail.status_code == 200
  203. assert detail.json()["plate_id"] == 22
  204. @pytest.mark.asyncio
  205. @pytest.mark.integration
  206. async def test_get_archive_not_found(self, async_client: AsyncClient):
  207. """Verify 404 for non-existent archive."""
  208. response = await async_client.get("/api/v1/archives/9999")
  209. assert response.status_code == 404
  210. @pytest.mark.asyncio
  211. @pytest.mark.integration
  212. async def test_get_archive_printer_media_matches_timelapse_and_ipcam_chunks(
  213. self,
  214. async_client: AsyncClient,
  215. archive_factory,
  216. printer_factory,
  217. db_session,
  218. ):
  219. printer = await printer_factory()
  220. archive = await archive_factory(
  221. printer.id,
  222. started_at=datetime(2026, 8, 12, 10, 0),
  223. completed_at=datetime(2026, 8, 12, 11, 0),
  224. timelapse_path=None,
  225. )
  226. list_timeouts = []
  227. async def fake_list(_ip, _code, path, **kwargs):
  228. list_timeouts.append(kwargs.get("timeout"))
  229. if path == "/timelapse":
  230. return FileListResult(
  231. files=[
  232. {
  233. "name": "video_2026-08-12_18-00-00.mp4",
  234. "path": "/timelapse/video_2026-08-12_18-00-00.mp4",
  235. "size": 123,
  236. "mtime": datetime(2026, 8, 12, 11, 1),
  237. "is_directory": False,
  238. }
  239. ],
  240. available=True,
  241. )
  242. if path == "/ipcam":
  243. return FileListResult(
  244. files=[
  245. {
  246. "name": "ipcam-record.1.mp4",
  247. "path": "/ipcam/ipcam-record.1.mp4",
  248. "size": 250_000_000,
  249. "mtime": datetime(2026, 8, 12, 10, 5),
  250. "is_directory": False,
  251. },
  252. {
  253. "name": "ipcam-record.after.mp4",
  254. "path": "/ipcam/ipcam-record.after.mp4",
  255. "size": 250_000_000,
  256. "mtime": datetime(2026, 8, 12, 11, 30),
  257. "is_directory": False,
  258. },
  259. ],
  260. available=True,
  261. )
  262. return FileListResult(files=[], available=False)
  263. with (
  264. patch("backend.app.api.routes.archives.list_files_result_async", new=AsyncMock(side_effect=fake_list)),
  265. patch("backend.app.api.routes.archives.ftps_handshake_blocked", return_value=False),
  266. ):
  267. response = await async_client.get(f"/api/v1/archives/{archive.id}/printer-media")
  268. assert response.status_code == 200
  269. data = response.json()
  270. assert data["local_timelapse"] is None
  271. assert [(file["kind"], file["name"]) for file in data["remote_files"]] == [
  272. ("timelapse", "video_2026-08-12_18-00-00.mp4"),
  273. ("ipcam", "ipcam-record.1.mp4"),
  274. ]
  275. assert list_timeouts == [8.0, 8.0]
  276. @pytest.mark.asyncio
  277. @pytest.mark.integration
  278. async def test_archive_printer_media_skips_ftp_during_handshake_cooloff(
  279. self,
  280. async_client: AsyncClient,
  281. archive_factory,
  282. printer_factory,
  283. ):
  284. printer = await printer_factory()
  285. archive = await archive_factory(
  286. printer.id,
  287. started_at=datetime(2026, 8, 12, 10, 0),
  288. completed_at=datetime(2026, 8, 12, 11, 0),
  289. timelapse_path=None,
  290. )
  291. list_files = AsyncMock()
  292. with (
  293. patch("backend.app.api.routes.archives.ftps_handshake_blocked", return_value=True),
  294. patch("backend.app.api.routes.archives.list_files_result_async", new=list_files),
  295. ):
  296. response = await async_client.get(f"/api/v1/archives/{archive.id}/printer-media")
  297. assert response.status_code == 200
  298. assert response.json()["remote_files"] == []
  299. assert response.json()["warnings"] == ["timelapse_unavailable", "ipcam_unavailable"]
  300. list_files.assert_not_awaited()
  301. @pytest.mark.asyncio
  302. @pytest.mark.integration
  303. async def test_archive_printer_media_checks_alternate_timelapse_directories_after_empty_listing(
  304. self,
  305. async_client: AsyncClient,
  306. archive_factory,
  307. printer_factory,
  308. ):
  309. printer = await printer_factory()
  310. archive = await archive_factory(
  311. printer.id,
  312. started_at=datetime(2026, 8, 12, 10, 0),
  313. completed_at=datetime(2026, 8, 12, 11, 0),
  314. timelapse_path=None,
  315. )
  316. paths: list[str] = []
  317. async def fake_list(_ip, _code, path, **_kwargs):
  318. paths.append(path)
  319. if path == "/timelapse/video":
  320. return FileListResult(
  321. files=[
  322. {
  323. "name": "video_2026-08-12_11-01-00.mp4",
  324. "path": "/timelapse/video/video_2026-08-12_11-01-00.mp4",
  325. "size": 321,
  326. "mtime": datetime(2026, 8, 12, 11, 1),
  327. "is_directory": False,
  328. }
  329. ],
  330. available=True,
  331. )
  332. return FileListResult(files=[], available=True)
  333. with (
  334. patch("backend.app.api.routes.archives.list_files_result_async", new=AsyncMock(side_effect=fake_list)),
  335. patch("backend.app.api.routes.archives.ftps_handshake_blocked", return_value=False),
  336. ):
  337. response = await async_client.get(f"/api/v1/archives/{archive.id}/printer-media")
  338. assert response.status_code == 200
  339. assert response.json()["remote_files"][0]["path"].startswith("/timelapse/video/")
  340. assert paths == ["/timelapse", "/timelapse/video", "/ipcam"]
  341. @pytest.mark.asyncio
  342. @pytest.mark.integration
  343. async def test_archive_printer_media_releases_db_session_before_ftp(
  344. self,
  345. async_client: AsyncClient,
  346. archive_factory,
  347. printer_factory,
  348. monkeypatch,
  349. ):
  350. from backend.app.api.routes import archives as archives_routes
  351. printer = await printer_factory()
  352. archive = await archive_factory(
  353. printer.id,
  354. started_at=datetime(2026, 8, 12, 10, 0),
  355. timelapse_path=None,
  356. )
  357. real_factory = archives_routes.database.async_session
  358. session_closed = False
  359. class TrackingSession:
  360. async def __aenter__(self):
  361. self.context = real_factory()
  362. return await self.context.__aenter__()
  363. async def __aexit__(self, *args):
  364. nonlocal session_closed
  365. result = await self.context.__aexit__(*args)
  366. session_closed = True
  367. return result
  368. async def fake_list(*_args, **_kwargs):
  369. assert session_closed
  370. return FileListResult(files=[], available=True)
  371. monkeypatch.setattr(archives_routes.database, "async_session", TrackingSession)
  372. with (
  373. patch("backend.app.api.routes.archives.list_files_result_async", new=AsyncMock(side_effect=fake_list)),
  374. patch("backend.app.api.routes.archives.ftps_handshake_blocked", return_value=False),
  375. ):
  376. response = await async_client.get(f"/api/v1/archives/{archive.id}/printer-media")
  377. assert response.status_code == 200
  378. @pytest.mark.asyncio
  379. @pytest.mark.integration
  380. async def test_archive_printer_media_baseline_excludes_old_timestamp_match(
  381. self,
  382. async_client: AsyncClient,
  383. archive_factory,
  384. printer_factory,
  385. ):
  386. printer = await printer_factory()
  387. archive = await archive_factory(
  388. printer.id,
  389. started_at=datetime(2026, 8, 12, 10, 0),
  390. completed_at=datetime(2026, 8, 12, 11, 0),
  391. timelapse_path=None,
  392. timelapse_baseline=["old.mp4"],
  393. )
  394. async def fake_list(_ip, _code, path, **_kwargs):
  395. if path == "/timelapse":
  396. return FileListResult(
  397. files=[
  398. {
  399. "name": "old.mp4",
  400. "path": "/timelapse/old.mp4",
  401. "size": 10,
  402. "mtime": datetime(2026, 8, 12, 11, 0),
  403. "is_directory": False,
  404. },
  405. {
  406. "name": "new.mp4",
  407. "path": "/timelapse/new.mp4",
  408. "size": 20,
  409. "mtime": datetime(2020, 1, 1),
  410. "is_directory": False,
  411. },
  412. ],
  413. available=True,
  414. )
  415. return FileListResult(files=[], available=True)
  416. with (
  417. patch("backend.app.api.routes.archives.list_files_result_async", new=AsyncMock(side_effect=fake_list)),
  418. patch("backend.app.api.routes.archives.ftps_handshake_blocked", return_value=False),
  419. ):
  420. response = await async_client.get(f"/api/v1/archives/{archive.id}/printer-media")
  421. assert response.status_code == 200
  422. timelapses = [item for item in response.json()["remote_files"] if item["kind"] == "timelapse"]
  423. assert [item["name"] for item in timelapses] == ["new.mp4"]
  424. @pytest.mark.asyncio
  425. @pytest.mark.integration
  426. async def test_archive_printer_media_requires_printer_files_permission(
  427. self,
  428. async_client: AsyncClient,
  429. archive_factory,
  430. printer_factory,
  431. tmp_path,
  432. monkeypatch,
  433. ):
  434. printer = await printer_factory()
  435. monkeypatch.setattr(settings, "base_dir", tmp_path)
  436. timelapse = tmp_path / "timelapses" / "attached.mp4"
  437. timelapse.parent.mkdir()
  438. timelapse.write_bytes(b"attached video")
  439. archive = await archive_factory(
  440. printer.id,
  441. started_at=datetime(2026, 8, 12, 10, 0),
  442. timelapse_path="timelapses/attached.mp4",
  443. )
  444. setup = await async_client.post(
  445. "/api/v1/auth/setup",
  446. json={
  447. "auth_enabled": True,
  448. "admin_username": "mediaadmin",
  449. "admin_password": "AdminPass1!",
  450. },
  451. )
  452. assert setup.status_code == 200, setup.text
  453. admin_login = await async_client.post(
  454. "/api/v1/auth/login",
  455. json={"username": "mediaadmin", "password": "AdminPass1!"},
  456. )
  457. admin_headers = {"Authorization": f"Bearer {admin_login.json()['access_token']}"}
  458. group = await async_client.post(
  459. "/api/v1/groups/",
  460. headers=admin_headers,
  461. json={"name": "archive-only-media", "permissions": ["archives:read_all"]},
  462. )
  463. assert group.status_code == 201, group.text
  464. user = await async_client.post(
  465. "/api/v1/users/",
  466. headers=admin_headers,
  467. json={
  468. "username": "archiveonlymedia",
  469. "password": "ArchivePass1!",
  470. "group_ids": [group.json()["id"]],
  471. },
  472. )
  473. assert user.status_code == 201, user.text
  474. login = await async_client.post(
  475. "/api/v1/auth/login",
  476. json={"username": "archiveonlymedia", "password": "ArchivePass1!"},
  477. )
  478. list_files = AsyncMock()
  479. with patch("backend.app.api.routes.archives.list_files_result_async", new=list_files):
  480. response = await async_client.get(
  481. f"/api/v1/archives/{archive.id}/printer-media",
  482. headers={"Authorization": f"Bearer {login.json()['access_token']}"},
  483. )
  484. assert response.status_code == 200
  485. assert response.json()["local_timelapse"] == {"name": "attached.mp4", "size": 14}
  486. assert response.json()["remote_files"] == []
  487. assert response.json()["warnings"] == ["printer_files_forbidden"]
  488. list_files.assert_not_awaited()
  489. token_response = await async_client.post(
  490. f"/api/v1/archives/{archive.id}/media-download-token",
  491. headers={"Authorization": f"Bearer {login.json()['access_token']}"},
  492. )
  493. assert token_response.status_code == 200
  494. download = await async_client.get(
  495. f"/api/v1/archives/{archive.id}/media/dl/{token_response.json()['token']}/attached.mp4"
  496. )
  497. assert download.status_code == 200
  498. assert download.content == b"attached video"
  499. @pytest.mark.asyncio
  500. @pytest.mark.integration
  501. async def test_archive_media_token_is_archive_bound_single_use(
  502. self,
  503. async_client: AsyncClient,
  504. archive_factory,
  505. printer_factory,
  506. tmp_path,
  507. monkeypatch,
  508. ):
  509. printer = await printer_factory()
  510. monkeypatch.setattr(settings, "base_dir", tmp_path)
  511. media = tmp_path / "timelapses" / "bound.mp4"
  512. media.parent.mkdir()
  513. media.write_bytes(b"bound media")
  514. archive_a = await archive_factory(printer.id, timelapse_path="timelapses/bound.mp4")
  515. archive_b = await archive_factory(printer.id, timelapse_path="timelapses/bound.mp4")
  516. minted = await async_client.post(f"/api/v1/archives/{archive_a.id}/media-download-token")
  517. assert minted.status_code == 200
  518. token = minted.json()["token"]
  519. wrong = await async_client.get(f"/api/v1/archives/{archive_b.id}/media/dl/{token}/bound.mp4")
  520. assert wrong.status_code == 403
  521. correct = await async_client.get(f"/api/v1/archives/{archive_a.id}/media/dl/{token}/bound.mp4")
  522. assert correct.status_code == 200
  523. replay = await async_client.get(f"/api/v1/archives/{archive_a.id}/media/dl/{token}/bound.mp4")
  524. assert replay.status_code == 403
  525. @pytest.mark.asyncio
  526. @pytest.mark.integration
  527. async def test_archive_printer_media_enforces_api_key_printer_scope(
  528. self,
  529. async_client: AsyncClient,
  530. archive_factory,
  531. printer_factory,
  532. db_session,
  533. ):
  534. from backend.app.core.auth import generate_api_key
  535. from backend.app.models.api_key import APIKey
  536. printer_a = await printer_factory(name="Media Scope A", serial_number="MEDIASCOPEA00001")
  537. printer_b = await printer_factory(name="Media Scope B", serial_number="MEDIASCOPEB00001")
  538. archive = await archive_factory(
  539. printer_b.id,
  540. started_at=datetime(2026, 8, 12, 10, 0),
  541. timelapse_path=None,
  542. )
  543. setup = await async_client.post(
  544. "/api/v1/auth/setup",
  545. json={
  546. "auth_enabled": True,
  547. "admin_username": "mediascopeadmin",
  548. "admin_password": "AdminPass1!",
  549. },
  550. )
  551. assert setup.status_code == 200, setup.text
  552. full_key, key_hash, key_prefix = generate_api_key()
  553. db_session.add(
  554. APIKey(
  555. name="media-printer-scope",
  556. key_hash=key_hash,
  557. key_prefix=key_prefix,
  558. can_read_status=True,
  559. can_control_printer=True,
  560. printer_ids=[printer_a.id],
  561. enabled=True,
  562. )
  563. )
  564. await db_session.commit()
  565. listing = AsyncMock()
  566. with patch("backend.app.api.routes.archives.list_files_result_async", new=listing):
  567. response = await async_client.get(
  568. f"/api/v1/archives/{archive.id}/printer-media",
  569. headers={"X-API-Key": full_key},
  570. )
  571. assert response.status_code == 403
  572. listing.assert_not_awaited()
  573. @pytest.mark.asyncio
  574. @pytest.mark.integration
  575. async def test_camera_only_user_cannot_mint_archive_media_token(
  576. self,
  577. async_client: AsyncClient,
  578. archive_factory,
  579. printer_factory,
  580. tmp_path,
  581. monkeypatch,
  582. ):
  583. printer = await printer_factory()
  584. monkeypatch.setattr(settings, "base_dir", tmp_path)
  585. media = tmp_path / "timelapses" / "private.mp4"
  586. media.parent.mkdir()
  587. media.write_bytes(b"private")
  588. archive = await archive_factory(printer.id, timelapse_path="timelapses/private.mp4")
  589. setup = await async_client.post(
  590. "/api/v1/auth/setup",
  591. json={
  592. "auth_enabled": True,
  593. "admin_username": "cameraadmin",
  594. "admin_password": "AdminPass1!",
  595. },
  596. )
  597. assert setup.status_code == 200, setup.text
  598. admin_login = await async_client.post(
  599. "/api/v1/auth/login",
  600. json={"username": "cameraadmin", "password": "AdminPass1!"},
  601. )
  602. admin_headers = {"Authorization": f"Bearer {admin_login.json()['access_token']}"}
  603. group = await async_client.post(
  604. "/api/v1/groups/",
  605. headers=admin_headers,
  606. json={"name": "camera-only-media", "permissions": ["camera:view"]},
  607. )
  608. assert group.status_code == 201, group.text
  609. user = await async_client.post(
  610. "/api/v1/users/",
  611. headers=admin_headers,
  612. json={
  613. "username": "cameraonlymedia",
  614. "password": "CameraPass1!",
  615. "group_ids": [group.json()["id"]],
  616. },
  617. )
  618. assert user.status_code == 201, user.text
  619. login = await async_client.post(
  620. "/api/v1/auth/login",
  621. json={"username": "cameraonlymedia", "password": "CameraPass1!"},
  622. )
  623. response = await async_client.post(
  624. f"/api/v1/archives/{archive.id}/media-download-token",
  625. headers={"Authorization": f"Bearer {login.json()['access_token']}"},
  626. )
  627. assert response.status_code == 403
  628. # ========================================================================
  629. # Update endpoints
  630. # ========================================================================
  631. @pytest.mark.asyncio
  632. @pytest.mark.integration
  633. async def test_update_archive_name(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  634. """Verify archive name can be updated."""
  635. printer = await printer_factory()
  636. archive = await archive_factory(printer.id, print_name="Original Name")
  637. response = await async_client.patch(f"/api/v1/archives/{archive.id}", json={"print_name": "Updated Name"})
  638. assert response.status_code == 200
  639. assert response.json()["print_name"] == "Updated Name"
  640. @pytest.mark.asyncio
  641. @pytest.mark.integration
  642. async def test_update_archive_notes(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  643. """Verify archive notes can be updated."""
  644. printer = await printer_factory()
  645. archive = await archive_factory(printer.id)
  646. response = await async_client.patch(f"/api/v1/archives/{archive.id}", json={"notes": "Great print!"})
  647. assert response.status_code == 200
  648. assert response.json()["notes"] == "Great print!"
  649. @pytest.mark.asyncio
  650. @pytest.mark.integration
  651. async def test_update_archive_favorite(
  652. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  653. ):
  654. """Verify archive favorite status can be updated."""
  655. printer = await printer_factory()
  656. archive = await archive_factory(printer.id)
  657. response = await async_client.patch(f"/api/v1/archives/{archive.id}", json={"is_favorite": True})
  658. assert response.status_code == 200
  659. assert response.json()["is_favorite"] is True
  660. @pytest.mark.asyncio
  661. @pytest.mark.integration
  662. async def test_update_archive_external_url(
  663. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  664. ):
  665. """Verify archive external_url can be updated."""
  666. printer = await printer_factory()
  667. archive = await archive_factory(printer.id)
  668. response = await async_client.patch(
  669. f"/api/v1/archives/{archive.id}", json={"external_url": "https://printables.com/model/12345"}
  670. )
  671. assert response.status_code == 200
  672. assert response.json()["external_url"] == "https://printables.com/model/12345"
  673. # Verify it can be cleared
  674. response = await async_client.patch(f"/api/v1/archives/{archive.id}", json={"external_url": None})
  675. assert response.status_code == 200
  676. assert response.json()["external_url"] is None
  677. @pytest.mark.asyncio
  678. @pytest.mark.integration
  679. async def test_filament_grams_can_be_set_by_hand(
  680. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  681. ):
  682. """#1820: a print that archived without its 3MF has no filament figure
  683. and no way to recover one — rescan needs a file this archive does not
  684. have. The edit is the only route, so it has to reach the log entry too:
  685. the Projects roll-up and the Prometheus counter sum PrintLogEntry, not
  686. the archive.
  687. """
  688. from sqlalchemy import select
  689. from backend.app.models.print_log import PrintLogEntry
  690. printer = await printer_factory()
  691. archive = await archive_factory(printer.id, print_name="JOB_C")
  692. response = await async_client.patch(
  693. f"/api/v1/archives/{archive.id}",
  694. json={"filament_used_grams": 46.16},
  695. )
  696. assert response.status_code == 200, response.text
  697. assert response.json()["filament_used_grams"] == 46.16
  698. mirrored = (
  699. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  700. ).scalar_one()
  701. assert mirrored.filament_used_grams == 46.16
  702. @pytest.mark.asyncio
  703. @pytest.mark.integration
  704. async def test_clearing_the_figure_takes_the_mirrored_copy_with_it(
  705. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  706. ):
  707. """Undo has to be as complete as the correction: a run that only holds
  708. the figure because this archive gave it one must not keep it after the
  709. archive's is cleared, or the totals stay wrong with nothing on the card
  710. to explain them."""
  711. from sqlalchemy import select
  712. from backend.app.models.print_log import PrintLogEntry
  713. printer = await printer_factory()
  714. archive = await archive_factory(printer.id, filament_used_grams=None)
  715. entry = (
  716. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  717. ).scalar_one()
  718. assert entry.filament_used_grams is None
  719. await async_client.patch(f"/api/v1/archives/{archive.id}", json={"filament_used_grams": 46.16})
  720. await db_session.refresh(entry)
  721. assert entry.filament_used_grams == 46.16
  722. response = await async_client.patch(f"/api/v1/archives/{archive.id}", json={"filament_used_grams": None})
  723. assert response.status_code == 200, response.text
  724. await db_session.refresh(entry)
  725. assert entry.filament_used_grams is None
  726. @pytest.mark.asyncio
  727. @pytest.mark.integration
  728. async def test_a_measured_run_keeps_its_own_filament_figure(
  729. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  730. ):
  731. """A run whose grams came from the tracked spool delta measured itself.
  732. The archive's number is an estimate, so an edit of the estimate must not
  733. overwrite the measurement — the mirror only fills in a run that has no
  734. figure, or one that was copied from this archive in the first place.
  735. """
  736. from sqlalchemy import select
  737. from backend.app.models.print_log import PrintLogEntry
  738. printer = await printer_factory()
  739. archive = await archive_factory(printer.id, filament_used_grams=50.0)
  740. entry = (
  741. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  742. ).scalar_one()
  743. entry.filament_used_grams = 48.2 # what the spool actually lost
  744. await db_session.commit()
  745. response = await async_client.patch(
  746. f"/api/v1/archives/{archive.id}",
  747. json={"filament_used_grams": 61.0},
  748. )
  749. assert response.status_code == 200, response.text
  750. assert response.json()["filament_used_grams"] == 61.0
  751. await db_session.refresh(entry)
  752. assert entry.filament_used_grams == 48.2
  753. @pytest.mark.asyncio
  754. @pytest.mark.integration
  755. async def test_filament_grams_refuses_a_negative_figure(
  756. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  757. ):
  758. """It feeds the filament totals, so a value that would subtract from
  759. them is rejected rather than stored."""
  760. printer = await printer_factory()
  761. archive = await archive_factory(printer.id)
  762. response = await async_client.patch(
  763. f"/api/v1/archives/{archive.id}",
  764. json={"filament_used_grams": -5},
  765. )
  766. assert response.status_code == 422, response.text
  767. @pytest.mark.asyncio
  768. @pytest.mark.integration
  769. async def test_an_edit_that_leaves_filament_grams_alone_does_not_clear_it(
  770. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  771. ):
  772. """The field is optional on the schema, so an ordinary save of some
  773. other field must not read as "set grams to null"."""
  774. printer = await printer_factory()
  775. archive = await archive_factory(printer.id, filament_used_grams=12.5)
  776. response = await async_client.patch(
  777. f"/api/v1/archives/{archive.id}",
  778. json={"notes": "left the grams alone"},
  779. )
  780. assert response.status_code == 200, response.text
  781. assert response.json()["filament_used_grams"] == 12.5
  782. @pytest.mark.asyncio
  783. @pytest.mark.integration
  784. async def test_update_archive_failure_reason_mirrors_to_print_log_entry(
  785. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  786. ):
  787. """#1444: PATCH /archives/{id} with failure_reason must mirror to the
  788. latest PrintLogEntry so the Stats page Failure Analysis widget
  789. (which reads PrintLogEntry.failure_reason) reflects the user's
  790. reclassification instead of showing "Unknown" forever.
  791. """
  792. from sqlalchemy import select
  793. from backend.app.models.print_log import PrintLogEntry
  794. printer = await printer_factory()
  795. # archive_factory auto-creates a matching PrintLogEntry (failure_reason
  796. # carried from the archive, which is NULL here — same shape as the bug
  797. # repro: print completed → log entry written with NULL → user goes to
  798. # classify the failure afterwards).
  799. archive = await archive_factory(printer.id, print_name="Failed Print", status="failed", run_status="failed")
  800. response = await async_client.patch(
  801. f"/api/v1/archives/{archive.id}",
  802. json={"failure_reason": "Adhesion failure"},
  803. )
  804. assert response.status_code == 200
  805. result = await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  806. mirrored = result.scalar_one()
  807. assert mirrored.failure_reason == "Adhesion failure"
  808. @pytest.mark.asyncio
  809. @pytest.mark.integration
  810. async def test_update_archive_status_mirrors_to_print_log_entry(
  811. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  812. ):
  813. """#1444: PATCH /archives/{id} with status must mirror to the latest
  814. PrintLogEntry so stats that filter on PrintLogEntry.status see the
  815. user's reclassification.
  816. """
  817. from sqlalchemy import select
  818. from backend.app.models.print_log import PrintLogEntry
  819. printer = await printer_factory()
  820. archive = await archive_factory(printer.id, run_status="completed")
  821. response = await async_client.patch(
  822. f"/api/v1/archives/{archive.id}",
  823. json={"status": "failed"},
  824. )
  825. assert response.status_code == 200
  826. result = await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  827. mirrored = result.scalar_one()
  828. assert mirrored.status == "failed"
  829. @pytest.mark.asyncio
  830. @pytest.mark.integration
  831. async def test_update_archive_failure_reason_only_touches_latest_entry(
  832. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  833. ):
  834. """#1444: For an archive with multiple runs (reprints), only the
  835. latest PrintLogEntry should receive the reclassification. Earlier
  836. runs were classified at their own time and must not be retroactively
  837. overwritten.
  838. """
  839. from backend.app.models.print_log import PrintLogEntry
  840. printer = await printer_factory()
  841. # First run — created by the factory's auto-run with its own reason.
  842. archive = await archive_factory(printer.id, status="failed", run_status="failed")
  843. from sqlalchemy import select
  844. first_run = (
  845. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  846. ).scalar_one()
  847. first_run.failure_reason = "Filament tangle"
  848. await db_session.commit()
  849. # Second run — the reprint that just finished with NULL classification.
  850. latest_run = PrintLogEntry(archive_id=archive.id, status="failed", failure_reason=None)
  851. db_session.add(latest_run)
  852. await db_session.commit()
  853. response = await async_client.patch(
  854. f"/api/v1/archives/{archive.id}",
  855. json={"failure_reason": "Adhesion failure"},
  856. )
  857. assert response.status_code == 200
  858. await db_session.refresh(first_run)
  859. await db_session.refresh(latest_run)
  860. assert first_run.failure_reason == "Filament tangle"
  861. assert latest_run.failure_reason == "Adhesion failure"
  862. # ========================================================================
  863. # Delete endpoints
  864. # ========================================================================
  865. @pytest.mark.asyncio
  866. @pytest.mark.integration
  867. async def test_delete_archive(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  868. """Verify archive can be deleted."""
  869. printer = await printer_factory()
  870. archive = await archive_factory(printer.id)
  871. archive_id = archive.id
  872. response = await async_client.delete(f"/api/v1/archives/{archive_id}")
  873. assert response.status_code == 200
  874. # Verify deleted
  875. response = await async_client.get(f"/api/v1/archives/{archive_id}")
  876. assert response.status_code == 404
  877. @pytest.mark.asyncio
  878. @pytest.mark.integration
  879. async def test_delete_nonexistent_archive(self, async_client: AsyncClient):
  880. """Verify deleting non-existent archive returns 404."""
  881. response = await async_client.delete("/api/v1/archives/9999")
  882. assert response.status_code == 404
  883. @pytest.mark.asyncio
  884. @pytest.mark.integration
  885. async def test_delete_archive_blocked_when_related_queue_item_printing(
  886. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  887. ):
  888. """#1734: archive delete must 409 when a related queue item is currently
  889. mid-print — deleting the archive would strip the dispatcher's metadata
  890. trail (filament / plate / ams_mapping) out from under the running print.
  891. Both soft and hard delete are gated by the same precondition.
  892. """
  893. from backend.app.models.print_queue import PrintQueueItem
  894. printer = await printer_factory()
  895. archive = await archive_factory(printer.id)
  896. db_session.add(PrintQueueItem(printer_id=printer.id, archive_id=archive.id, status="printing", position=1))
  897. await db_session.commit()
  898. soft = await async_client.delete(f"/api/v1/archives/{archive.id}")
  899. assert soft.status_code == 409
  900. assert "printing" in soft.json()["detail"].lower()
  901. hard = await async_client.delete(f"/api/v1/archives/{archive.id}?purge_stats=true")
  902. assert hard.status_code == 409
  903. @pytest.mark.asyncio
  904. @pytest.mark.integration
  905. async def test_archive_delete_impact_reports_counts(
  906. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  907. ):
  908. """#1734: the delete-impact pre-flight endpoint reports the total
  909. number of related queue items AND how many are currently printing,
  910. so the frontend can both warn the user before they confirm AND
  911. disable the confirm button when the printing count is non-zero.
  912. """
  913. from backend.app.models.print_queue import PrintQueueItem
  914. printer = await printer_factory()
  915. archive = await archive_factory(printer.id)
  916. # Build a mixed-status set the way a Send All upload + later in-flight
  917. # dispatch looks at the wire (#1733).
  918. db_session.add_all(
  919. [
  920. PrintQueueItem(printer_id=printer.id, archive_id=archive.id, status="pending", position=1),
  921. PrintQueueItem(printer_id=printer.id, archive_id=archive.id, status="pending", position=2),
  922. PrintQueueItem(printer_id=printer.id, archive_id=archive.id, status="printing", position=3),
  923. ]
  924. )
  925. # An unrelated archive's queue rows must not bleed into the count.
  926. other = await archive_factory(printer.id)
  927. db_session.add(PrintQueueItem(printer_id=printer.id, archive_id=other.id, status="pending", position=4))
  928. await db_session.commit()
  929. resp = await async_client.get(f"/api/v1/archives/{archive.id}/delete-impact")
  930. assert resp.status_code == 200
  931. body = resp.json()
  932. assert body["related_queue_items"] == 3
  933. assert body["currently_printing"] == 1
  934. @pytest.mark.asyncio
  935. @pytest.mark.integration
  936. async def test_soft_delete_preserves_stats_contribution(
  937. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  938. ):
  939. """#1343: deleting an archive without ``purge_stats`` keeps its
  940. contribution in Quick Stats. The row vanishes from listings but the
  941. filament / time / cost totals stay intact.
  942. """
  943. printer = await printer_factory()
  944. await archive_factory(
  945. printer.id,
  946. status="completed",
  947. print_time_seconds=3600,
  948. filament_used_grams=50.0,
  949. cost=1.50,
  950. )
  951. archive_to_delete = await archive_factory(
  952. printer.id,
  953. status="completed",
  954. print_time_seconds=7200,
  955. filament_used_grams=100.0,
  956. cost=3.00,
  957. )
  958. # Pre-delete: stats include both archives.
  959. pre = (await async_client.get("/api/v1/archives/stats")).json()
  960. assert pre["total_prints"] == 2
  961. assert pre["total_filament_grams"] == 150.0
  962. assert pre["total_cost"] == 4.50
  963. # Soft delete (default — no purge_stats param).
  964. resp = await async_client.delete(f"/api/v1/archives/{archive_to_delete.id}")
  965. assert resp.status_code == 200
  966. body = resp.json()
  967. assert body["purged_from_stats"] is False
  968. # Listing hides the deleted archive…
  969. listing = (await async_client.get("/api/v1/archives/")).json()
  970. assert all(a["id"] != archive_to_delete.id for a in listing)
  971. # …but stats still reflect both prints (the whole point of #1343).
  972. post = (await async_client.get("/api/v1/archives/stats")).json()
  973. assert post["total_prints"] == 2
  974. assert post["total_filament_grams"] == 150.0
  975. assert post["total_cost"] == 4.50
  976. @pytest.mark.asyncio
  977. @pytest.mark.integration
  978. async def test_soft_delete_clears_thumbnail_path_on_linked_log_entries(
  979. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  980. ):
  981. """#1348 follow-up: soft-deleting an archive removes its files from disk;
  982. the cached thumbnail_path on linked PrintLogEntry rows must be NULLed
  983. in the same transaction so the print-log view doesn't 404-storm on the
  984. now-deleted thumbnail file."""
  985. from sqlalchemy import select
  986. from backend.app.models.print_log import PrintLogEntry
  987. printer = await printer_factory()
  988. archive = await archive_factory(
  989. printer.id,
  990. status="completed",
  991. thumbnail_path="archives/test/test_print/thumbnail.png",
  992. )
  993. # The factory's auto-PrintLogEntry doesn't copy thumbnail_path; set it
  994. # manually to mirror what the production write_log_entry path stores.
  995. run_query = await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  996. run = run_query.scalar_one()
  997. run.thumbnail_path = "archives/test/test_print/thumbnail.png"
  998. await db_session.commit()
  999. assert run.thumbnail_path is not None
  1000. resp = await async_client.delete(f"/api/v1/archives/{archive.id}")
  1001. assert resp.status_code == 200
  1002. assert resp.json()["purged_from_stats"] is False
  1003. await db_session.refresh(run)
  1004. assert run.thumbnail_path is None, "soft-delete must NULL thumbnail_path on linked log entry"
  1005. # The log entry itself survives the soft delete (its filament/cost
  1006. # contribution still needs to flow into stats per #1343).
  1007. assert run.id is not None
  1008. assert run.archive_id == archive.id
  1009. @pytest.mark.asyncio
  1010. @pytest.mark.integration
  1011. async def test_hard_delete_clears_thumbnail_path_before_fk_cascade(
  1012. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1013. ):
  1014. """#1348 follow-up: the auto-purge sweeper (and any caller of
  1015. ArchiveService.delete_archive) hard-deletes the archive row but leaves
  1016. PrintLogEntry rows alive via ON DELETE SET NULL. The eager
  1017. thumbnail_path clear must run inside delete_archive so even orphaned
  1018. log entries don't surface stale paths."""
  1019. from sqlalchemy import select
  1020. from backend.app.models.print_log import PrintLogEntry
  1021. from backend.app.services.archive import ArchiveService
  1022. printer = await printer_factory()
  1023. archive = await archive_factory(
  1024. printer.id,
  1025. status="completed",
  1026. thumbnail_path="archives/test/test_print/thumbnail.png",
  1027. )
  1028. run_query = await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  1029. run = run_query.scalar_one()
  1030. run.thumbnail_path = "archives/test/test_print/thumbnail.png"
  1031. await db_session.commit()
  1032. run_id = run.id
  1033. service = ArchiveService(db_session)
  1034. assert await service.delete_archive(archive.id) is True
  1035. # Log entry survives the hard-delete (the FK is ON DELETE SET NULL
  1036. # in production; SQLite test config doesn't enable foreign_keys=ON
  1037. # by default so archive_id may still be set, but the row itself
  1038. # remains for audit). The thumbnail_path was cleared eagerly by
  1039. # _null_print_log_thumbnail_paths before db.delete(archive).
  1040. refetch = await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.id == run_id))
  1041. survivor = refetch.scalar_one()
  1042. assert survivor.thumbnail_path is None, (
  1043. "delete_archive must NULL thumbnail_path before removing the archive row"
  1044. )
  1045. @pytest.mark.asyncio
  1046. @pytest.mark.integration
  1047. async def test_print_log_thumbnail_route_lazy_nulls_missing_file(
  1048. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1049. ):
  1050. """#1348 follow-up: GET /print-log/{id}/thumbnail self-heals when the
  1051. thumbnail_path on a log entry points at a missing file (failed print
  1052. whose thumbnail was never written, or a stale path that escaped the
  1053. delete-time cleanup)."""
  1054. from sqlalchemy import select
  1055. from backend.app.models.print_log import PrintLogEntry
  1056. printer = await printer_factory()
  1057. archive = await archive_factory(printer.id, status="failed")
  1058. run_query = await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  1059. run = run_query.scalar_one()
  1060. # Path points at a file that never existed (failed-print case where
  1061. # archive.thumbnail_path was set but the extractor never produced one).
  1062. run.thumbnail_path = "archives/missing/never_written/thumbnail.png"
  1063. await db_session.commit()
  1064. # Auth is disabled in the integration test config, so the stream-token
  1065. # guard is bypassed — the route runs the lazy-NULL branch directly.
  1066. resp = await async_client.get(f"/api/v1/print-log/{run.id}/thumbnail")
  1067. assert resp.status_code == 404
  1068. await db_session.refresh(run)
  1069. assert run.thumbnail_path is None, "missing file must self-heal to NULL"
  1070. @pytest.mark.asyncio
  1071. @pytest.mark.integration
  1072. async def test_purge_stats_drops_archive_from_quick_stats(
  1073. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1074. ):
  1075. """#1343: deleting with ``?purge_stats=true`` hard-deletes the row,
  1076. dropping its contribution from Quick Stats (the original behaviour,
  1077. now opt-in)."""
  1078. printer = await printer_factory()
  1079. keep = await archive_factory(printer.id, status="completed", filament_used_grams=50.0)
  1080. purge = await archive_factory(printer.id, status="completed", filament_used_grams=100.0)
  1081. resp = await async_client.delete(f"/api/v1/archives/{purge.id}?purge_stats=true")
  1082. assert resp.status_code == 200
  1083. assert resp.json()["purged_from_stats"] is True
  1084. stats = (await async_client.get("/api/v1/archives/stats")).json()
  1085. assert stats["total_prints"] == 1
  1086. assert stats["total_filament_grams"] == 50.0
  1087. # The kept archive is still listed.
  1088. listing = (await async_client.get("/api/v1/archives/")).json()
  1089. assert [a["id"] for a in listing] == [keep.id]
  1090. @pytest.mark.asyncio
  1091. @pytest.mark.integration
  1092. async def test_soft_deleted_archive_404_on_detail(
  1093. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1094. ):
  1095. """A soft-deleted archive must 404 on GET — a stale bookmark or
  1096. direct URL should not expose a row the user has already removed."""
  1097. printer = await printer_factory()
  1098. archive = await archive_factory(printer.id)
  1099. await async_client.delete(f"/api/v1/archives/{archive.id}")
  1100. resp = await async_client.get(f"/api/v1/archives/{archive.id}")
  1101. assert resp.status_code == 404
  1102. @pytest.mark.asyncio
  1103. @pytest.mark.integration
  1104. async def test_soft_deleted_archive_hidden_from_search(
  1105. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1106. ):
  1107. """Search must skip soft-deleted archives. Uses the LIKE fallback by
  1108. querying a single-character pattern that the SQLite FTS5 rejects, so
  1109. the test covers the fallback path that the production FTS path also
  1110. respects."""
  1111. printer = await printer_factory()
  1112. archive = await archive_factory(printer.id, print_name="UniqueSoftDeleteCandidate")
  1113. await async_client.delete(f"/api/v1/archives/{archive.id}")
  1114. resp = await async_client.get("/api/v1/archives/search?q=UniqueSoftDeleteCandidate")
  1115. assert resp.status_code == 200
  1116. assert resp.json() == []
  1117. # ========================================================================
  1118. # Statistics endpoints
  1119. # ========================================================================
  1120. @pytest.mark.asyncio
  1121. @pytest.mark.integration
  1122. async def test_get_archive_stats(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  1123. """Verify archive statistics can be retrieved."""
  1124. printer = await printer_factory()
  1125. await archive_factory(
  1126. printer.id,
  1127. status="completed",
  1128. print_time_seconds=3600,
  1129. filament_used_grams=50.0,
  1130. )
  1131. await archive_factory(
  1132. printer.id,
  1133. status="completed",
  1134. print_time_seconds=7200,
  1135. filament_used_grams=100.0,
  1136. )
  1137. response = await async_client.get("/api/v1/archives/stats")
  1138. assert response.status_code == 200
  1139. result = response.json()
  1140. # Check for actual stats fields
  1141. assert "total_prints" in result
  1142. assert "successful_prints" in result
  1143. class TestNo3MFWarning:
  1144. """`GET /archives/no-3mf-warning` — install step 4 reactive nudge.
  1145. The connection diagnostic's external_storage check only catches the
  1146. printer-side variant of the setting (newer firmware). For older slicers
  1147. where the toggle lives only in BambuStudio, the printer never reports
  1148. it. The fallback path in main.py creates the archive with
  1149. extra_data.no_3mf_available=True; this endpoint exposes that as a
  1150. boolean so the frontend can surface a one-time banner.
  1151. """
  1152. @pytest.mark.asyncio
  1153. @pytest.mark.integration
  1154. async def test_returns_true_when_recent_fallback_exists(
  1155. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1156. ):
  1157. printer = await printer_factory()
  1158. await archive_factory(printer.id, extra_data={"no_3mf_available": True})
  1159. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  1160. assert response.status_code == 200
  1161. assert response.json() == {"has_fallback": True, "reason": None}
  1162. @pytest.mark.asyncio
  1163. @pytest.mark.integration
  1164. async def test_returns_false_when_no_archives(self, async_client: AsyncClient):
  1165. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  1166. assert response.status_code == 200
  1167. assert response.json() == {"has_fallback": False, "reason": None}
  1168. @pytest.mark.asyncio
  1169. @pytest.mark.integration
  1170. async def test_returns_false_when_only_normal_archives(
  1171. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1172. ):
  1173. printer = await printer_factory()
  1174. # extra_data has other keys but no_3mf_available is absent — normal
  1175. # archives must not trigger the nudge.
  1176. await archive_factory(printer.id, extra_data={"makerworld_url": "https://example"})
  1177. await archive_factory(printer.id, extra_data=None)
  1178. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  1179. assert response.status_code == 200
  1180. assert response.json() == {"has_fallback": False, "reason": None}
  1181. @pytest.mark.asyncio
  1182. @pytest.mark.integration
  1183. async def test_ignores_archives_older_than_30_days(
  1184. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1185. ):
  1186. from datetime import datetime, timedelta, timezone
  1187. from backend.app.models.archive import PrintArchive
  1188. printer = await printer_factory()
  1189. archive = await archive_factory(printer.id, extra_data={"no_3mf_available": True})
  1190. # Backdate past the 30-day window — old fallbacks are forgiven.
  1191. archive.created_at = datetime.now(timezone.utc) - timedelta(days=45)
  1192. await db_session.commit()
  1193. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  1194. assert response.status_code == 200
  1195. assert response.json() == {"has_fallback": False, "reason": None}
  1196. # Sanity: row really is in the DB, we just don't surface it.
  1197. assert (await db_session.get(PrintArchive, archive.id)) is not None
  1198. @pytest.mark.asyncio
  1199. @pytest.mark.integration
  1200. async def test_ignores_soft_deleted_fallbacks(
  1201. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1202. ):
  1203. from datetime import datetime, timezone
  1204. printer = await printer_factory()
  1205. archive = await archive_factory(printer.id, extra_data={"no_3mf_available": True})
  1206. archive.deleted_at = datetime.now(timezone.utc)
  1207. await db_session.commit()
  1208. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  1209. assert response.status_code == 200
  1210. # Soft-deleted fallbacks have been actioned (user clearing the
  1211. # evidence). Stop nudging.
  1212. assert response.json() == {"has_fallback": False, "reason": None}
  1213. class TestNo3MFWarningReason:
  1214. """Which explanation the banner shows (#2780).
  1215. The endpoint used to return a bare boolean and the banner had one wording:
  1216. "Store sent files on external storage" is off in the slicer, go turn it on.
  1217. For H2-series and P2S that is wrong twice over -- the setting is already on
  1218. and turning it on changes nothing, because the printer keeps the file on
  1219. internal storage FTPS does not serve. Sending people to re-do a step that
  1220. cannot help is worse than saying nothing, so the reason travels with the
  1221. flag.
  1222. """
  1223. @pytest.mark.asyncio
  1224. @pytest.mark.integration
  1225. async def test_internal_storage_is_reported(
  1226. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1227. ):
  1228. printer = await printer_factory()
  1229. await archive_factory(
  1230. printer.id,
  1231. extra_data={"no_3mf_available": True, "no_3mf_reason": "internal_storage"},
  1232. )
  1233. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  1234. assert response.json() == {"has_fallback": True, "reason": "internal_storage"}
  1235. @pytest.mark.asyncio
  1236. @pytest.mark.integration
  1237. async def test_an_empty_slot_is_reported(
  1238. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1239. ):
  1240. printer = await printer_factory()
  1241. await archive_factory(
  1242. printer.id,
  1243. extra_data={"no_3mf_available": True, "no_3mf_reason": "no_external_storage"},
  1244. )
  1245. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  1246. assert response.json() == {"has_fallback": True, "reason": "no_external_storage"}
  1247. @pytest.mark.asyncio
  1248. @pytest.mark.integration
  1249. async def test_a_known_reason_outranks_archives_that_carry_none(
  1250. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1251. ):
  1252. """Every archive written before this field exists carries no reason,
  1253. and a farm usually has more than one printer. One H2C among four
  1254. printers should still get the H2C explanation rather than have it
  1255. drowned out by older rows.
  1256. """
  1257. printer = await printer_factory()
  1258. await archive_factory(printer.id, extra_data={"no_3mf_available": True})
  1259. await archive_factory(printer.id, extra_data={"no_3mf_available": True, "no_3mf_reason": "internal_storage"})
  1260. await archive_factory(printer.id, extra_data={"no_3mf_available": True})
  1261. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  1262. assert response.json() == {"has_fallback": True, "reason": "internal_storage"}
  1263. @pytest.mark.asyncio
  1264. @pytest.mark.integration
  1265. async def test_internal_storage_outranks_an_empty_slot(
  1266. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1267. ):
  1268. """Both are real, and only one of them is surprising. "Put a card in"
  1269. is advice the user can act on unprompted; "this model keeps prints
  1270. somewhere Bambuddy cannot read" is the one they need told.
  1271. """
  1272. printer = await printer_factory()
  1273. await archive_factory(printer.id, extra_data={"no_3mf_available": True, "no_3mf_reason": "no_external_storage"})
  1274. await archive_factory(printer.id, extra_data={"no_3mf_available": True, "no_3mf_reason": "internal_storage"})
  1275. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  1276. assert response.json() == {"has_fallback": True, "reason": "internal_storage"}
  1277. @pytest.mark.asyncio
  1278. @pytest.mark.integration
  1279. async def test_a_reason_on_a_non_fallback_archive_is_not_reported(
  1280. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1281. ):
  1282. """The reason only means anything alongside the flag it explains."""
  1283. printer = await printer_factory()
  1284. await archive_factory(printer.id, extra_data={"no_3mf_reason": "internal_storage"})
  1285. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  1286. assert response.json() == {"has_fallback": False, "reason": None}
  1287. class TestPrintLogEntryDelete:
  1288. """#1687: per-row delete on the Print Log page.
  1289. Pin the route's three contracts: (1) deleting a row drops its filament
  1290. / cost / count contribution from /archives/stats in the same response
  1291. cycle; (2) the matching archive (if any) is untouched; (3) missing IDs
  1292. return 404 rather than 200-silently.
  1293. """
  1294. @pytest.mark.asyncio
  1295. @pytest.mark.integration
  1296. async def test_delete_print_log_entry_drops_from_stats(
  1297. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1298. ):
  1299. from sqlalchemy import select
  1300. from backend.app.models.print_log import PrintLogEntry
  1301. printer = await printer_factory()
  1302. keep = await archive_factory(printer.id, status="completed", filament_used_grams=50.0)
  1303. drop = await archive_factory(printer.id, status="completed", filament_used_grams=125.0)
  1304. drop_run = (
  1305. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == drop.id))
  1306. ).scalar_one()
  1307. resp = await async_client.delete(f"/api/v1/print-log/{drop_run.id}")
  1308. assert resp.status_code == 200
  1309. assert resp.json()["status"] == "deleted"
  1310. assert resp.json()["id"] == drop_run.id
  1311. # The linked archive survives — the row was a stats row, not the archive.
  1312. listing = (await async_client.get("/api/v1/archives/")).json()
  1313. assert {a["id"] for a in listing} == {keep.id, drop.id}
  1314. # /stats no longer counts the dropped run's filament contribution.
  1315. stats = (await async_client.get("/api/v1/archives/stats")).json()
  1316. assert stats["total_prints"] == 1
  1317. assert stats["total_filament_grams"] == 50.0
  1318. @pytest.mark.asyncio
  1319. @pytest.mark.integration
  1320. async def test_delete_print_log_entry_404_when_missing(self, async_client: AsyncClient):
  1321. resp = await async_client.delete("/api/v1/print-log/999999")
  1322. assert resp.status_code == 404
  1323. @pytest.mark.asyncio
  1324. @pytest.mark.integration
  1325. async def test_delete_print_log_entry_does_not_clear_others(
  1326. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1327. ):
  1328. """Deleting one row must not touch siblings — guard against an accidental
  1329. ``delete(PrintLogEntry)`` without a ``where`` clause (cf. clear_print_log
  1330. which intentionally drops everything)."""
  1331. from sqlalchemy import select
  1332. from backend.app.models.print_log import PrintLogEntry
  1333. printer = await printer_factory()
  1334. a = await archive_factory(printer.id, status="completed", filament_used_grams=10.0)
  1335. b = await archive_factory(printer.id, status="completed", filament_used_grams=20.0)
  1336. c = await archive_factory(printer.id, status="completed", filament_used_grams=30.0)
  1337. runs = {r.archive_id: r for r in (await db_session.execute(select(PrintLogEntry))).scalars().all()}
  1338. resp = await async_client.delete(f"/api/v1/print-log/{runs[b.id].id}")
  1339. assert resp.status_code == 200
  1340. survivors = (await db_session.execute(select(PrintLogEntry.archive_id))).scalars().all()
  1341. assert set(survivors) == {a.id, c.id}
  1342. class TestPrintLogEntryUpdate:
  1343. """Tests for ``PATCH /print-log/{entry_id}`` (#1687 part 4).
  1344. Pin the route's contracts: (1) GET serialiser actually surfaces
  1345. ``failure_reason`` (previously it was silently dropped from the response
  1346. even when set in the DB); (2) PATCH persists ``failure_reason`` and
  1347. ``status``; (3) unknown vocabulary returns 400 rather than getting stored
  1348. as raw garbage; (4) missing IDs return 404.
  1349. """
  1350. @pytest.mark.asyncio
  1351. @pytest.mark.integration
  1352. async def test_get_surfaces_failure_reason(
  1353. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1354. ):
  1355. """Pre-fix the GET endpoint built PrintLogEntrySchema without
  1356. ``failure_reason`` even though the column was populated, so the Print
  1357. Log table couldn't render what the Failure Analysis widget already
  1358. groups by. Regression guard for the silent-drop bug.
  1359. """
  1360. from sqlalchemy import select
  1361. from backend.app.models.print_log import PrintLogEntry
  1362. printer = await printer_factory()
  1363. archive = await archive_factory(printer.id, status="failed")
  1364. entry = (
  1365. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  1366. ).scalar_one()
  1367. entry.failure_reason = "spaghettiDetached"
  1368. await db_session.commit()
  1369. body = (await async_client.get("/api/v1/print-log/")).json()
  1370. match = next(item for item in body["items"] if item["id"] == entry.id)
  1371. assert match["failure_reason"] == "spaghettiDetached"
  1372. # archive_id should also flow through so the frontend can tell orphan
  1373. # entries apart from archive-linked ones.
  1374. assert match["archive_id"] == archive.id
  1375. @pytest.mark.asyncio
  1376. @pytest.mark.integration
  1377. async def test_patch_sets_failure_reason(
  1378. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1379. ):
  1380. from sqlalchemy import select
  1381. from backend.app.models.print_log import PrintLogEntry
  1382. printer = await printer_factory()
  1383. archive = await archive_factory(printer.id, status="failed")
  1384. entry = (
  1385. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  1386. ).scalar_one()
  1387. assert entry.failure_reason is None
  1388. resp = await async_client.patch(
  1389. f"/api/v1/print-log/{entry.id}",
  1390. json={"failure_reason": "cloggedNozzle"},
  1391. )
  1392. assert resp.status_code == 200
  1393. assert resp.json()["failure_reason"] == "cloggedNozzle"
  1394. await db_session.refresh(entry)
  1395. assert entry.failure_reason == "cloggedNozzle"
  1396. @pytest.mark.asyncio
  1397. @pytest.mark.integration
  1398. async def test_patch_can_clear_failure_reason(
  1399. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1400. ):
  1401. """Empty-string failure_reason stores back as NULL (the column's
  1402. nullable=True intent is preserved end-to-end)."""
  1403. from sqlalchemy import select
  1404. from backend.app.models.print_log import PrintLogEntry
  1405. printer = await printer_factory()
  1406. archive = await archive_factory(printer.id, status="failed")
  1407. entry = (
  1408. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  1409. ).scalar_one()
  1410. entry.failure_reason = "warping"
  1411. await db_session.commit()
  1412. resp = await async_client.patch(
  1413. f"/api/v1/print-log/{entry.id}",
  1414. json={"failure_reason": ""},
  1415. )
  1416. assert resp.status_code == 200
  1417. assert resp.json()["failure_reason"] is None
  1418. await db_session.refresh(entry)
  1419. assert entry.failure_reason is None
  1420. @pytest.mark.asyncio
  1421. @pytest.mark.integration
  1422. async def test_patch_rejects_unknown_failure_reason(
  1423. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1424. ):
  1425. """Unknown values must 400 — otherwise the UI would render raw garbage
  1426. because the i18n layer maps the value back through the canonical
  1427. vocabulary."""
  1428. from sqlalchemy import select
  1429. from backend.app.models.print_log import PrintLogEntry
  1430. printer = await printer_factory()
  1431. archive = await archive_factory(printer.id, status="failed")
  1432. entry = (
  1433. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  1434. ).scalar_one()
  1435. resp = await async_client.patch(
  1436. f"/api/v1/print-log/{entry.id}",
  1437. json={"failure_reason": "completely-made-up"},
  1438. )
  1439. assert resp.status_code == 400
  1440. @pytest.mark.asyncio
  1441. @pytest.mark.integration
  1442. async def test_patch_updates_status(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  1443. from sqlalchemy import select
  1444. from backend.app.models.print_log import PrintLogEntry
  1445. printer = await printer_factory()
  1446. archive = await archive_factory(printer.id, status="completed")
  1447. entry = (
  1448. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  1449. ).scalar_one()
  1450. entry.status = "completed"
  1451. await db_session.commit()
  1452. resp = await async_client.patch(
  1453. f"/api/v1/print-log/{entry.id}",
  1454. json={"status": "failed", "failure_reason": "layerShift"},
  1455. )
  1456. assert resp.status_code == 200
  1457. assert resp.json()["status"] == "failed"
  1458. assert resp.json()["failure_reason"] == "layerShift"
  1459. @pytest.mark.asyncio
  1460. @pytest.mark.integration
  1461. async def test_patch_rejects_unknown_status(
  1462. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1463. ):
  1464. from sqlalchemy import select
  1465. from backend.app.models.print_log import PrintLogEntry
  1466. printer = await printer_factory()
  1467. archive = await archive_factory(printer.id, status="failed")
  1468. entry = (
  1469. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  1470. ).scalar_one()
  1471. resp = await async_client.patch(
  1472. f"/api/v1/print-log/{entry.id}",
  1473. json={"status": "bogus-status"},
  1474. )
  1475. assert resp.status_code == 400
  1476. @pytest.mark.asyncio
  1477. @pytest.mark.integration
  1478. async def test_patch_404_when_missing(self, async_client: AsyncClient):
  1479. resp = await async_client.patch(
  1480. "/api/v1/print-log/999999",
  1481. json={"failure_reason": "cloggedNozzle"},
  1482. )
  1483. assert resp.status_code == 404
  1484. @pytest.mark.asyncio
  1485. @pytest.mark.integration
  1486. async def test_patch_works_on_orphan_entry(self, async_client: AsyncClient, printer_factory, db_session):
  1487. """Orphan log entries (no archive_id) are the actual reason this
  1488. endpoint exists — the Archive Edit modal can't reach them. Make sure
  1489. the PATCH works for those rows specifically."""
  1490. from backend.app.models.print_log import PrintLogEntry
  1491. printer = await printer_factory()
  1492. orphan = PrintLogEntry(
  1493. archive_id=None,
  1494. print_name="failed-before-archive-created",
  1495. printer_id=printer.id,
  1496. status="failed",
  1497. failure_reason=None,
  1498. )
  1499. db_session.add(orphan)
  1500. await db_session.commit()
  1501. await db_session.refresh(orphan)
  1502. assert orphan.archive_id is None
  1503. resp = await async_client.patch(
  1504. f"/api/v1/print-log/{orphan.id}",
  1505. json={"failure_reason": "powerFailure"},
  1506. )
  1507. assert resp.status_code == 200
  1508. assert resp.json()["failure_reason"] == "powerFailure"
  1509. assert resp.json()["archive_id"] is None
  1510. class TestArchivesSlimAPI:
  1511. """Integration tests for /api/v1/archives/slim endpoint."""
  1512. @pytest.mark.asyncio
  1513. @pytest.mark.integration
  1514. async def test_slim_empty(self, async_client: AsyncClient):
  1515. """Verify empty list when no archives exist."""
  1516. response = await async_client.get("/api/v1/archives/slim")
  1517. assert response.status_code == 200
  1518. assert response.json() == []
  1519. @pytest.mark.asyncio
  1520. @pytest.mark.integration
  1521. async def test_slim_returns_only_expected_fields(
  1522. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1523. ):
  1524. """Verify response contains only slim fields, not full archive data."""
  1525. printer = await printer_factory()
  1526. await archive_factory(
  1527. printer.id,
  1528. print_name="Slim Test",
  1529. status="completed",
  1530. filament_type="PLA",
  1531. filament_color="#FF0000",
  1532. filament_used_grams=50.0,
  1533. print_time_seconds=3600,
  1534. cost=1.50,
  1535. quantity=2,
  1536. )
  1537. response = await async_client.get("/api/v1/archives/slim")
  1538. assert response.status_code == 200
  1539. data = response.json()
  1540. assert len(data) == 1
  1541. item = data[0]
  1542. # Expected fields present
  1543. assert item["printer_id"] == printer.id
  1544. assert item["print_name"] == "Slim Test"
  1545. assert item["status"] == "completed"
  1546. assert item["filament_type"] == "PLA"
  1547. assert item["filament_color"] == "#FF0000"
  1548. assert item["filament_used_grams"] == 50.0
  1549. assert item["print_time_seconds"] == 3600
  1550. assert item["cost"] == 1.50
  1551. # quantity is per-event semantics now (each PrintLogEntry = one run);
  1552. # the archive's quantity field is no longer surfaced through this
  1553. # endpoint after the #1390 per-event migration.
  1554. assert item["quantity"] == 1
  1555. assert "created_at" in item
  1556. # Full archive fields must NOT be present
  1557. assert "id" not in item
  1558. assert "filename" not in item
  1559. assert "file_path" not in item
  1560. assert "file_size" not in item
  1561. assert "extra_data" not in item
  1562. assert "notes" not in item
  1563. assert "tags" not in item
  1564. assert "photos" not in item
  1565. assert "thumbnail_path" not in item
  1566. assert "content_hash" not in item
  1567. assert "duplicates" not in item
  1568. assert "duplicate_count" not in item
  1569. @pytest.mark.asyncio
  1570. @pytest.mark.integration
  1571. async def test_slim_includes_energy_fields(
  1572. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1573. ):
  1574. """Per-print smart-plug energy surfaces through /slim so the stats
  1575. page can include it in cost records and trends (#1432)."""
  1576. printer = await printer_factory()
  1577. await archive_factory(
  1578. printer.id,
  1579. status="completed",
  1580. cost=1.50,
  1581. energy_kwh=0.421,
  1582. energy_cost=0.063,
  1583. )
  1584. response = await async_client.get("/api/v1/archives/slim")
  1585. assert response.status_code == 200
  1586. item = response.json()[0]
  1587. assert item["energy_kwh"] == 0.421
  1588. assert item["energy_cost"] == 0.063
  1589. @pytest.mark.asyncio
  1590. @pytest.mark.integration
  1591. async def test_slim_computes_actual_time(
  1592. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1593. ):
  1594. """Verify actual_time_seconds is computed from started_at/completed_at."""
  1595. from datetime import datetime, timezone
  1596. printer = await printer_factory()
  1597. started = datetime(2024, 1, 1, 10, 0, 0, tzinfo=timezone.utc)
  1598. completed = datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc) # 2 hours = 7200s
  1599. await archive_factory(
  1600. printer.id,
  1601. status="completed",
  1602. started_at=started,
  1603. completed_at=completed,
  1604. )
  1605. response = await async_client.get("/api/v1/archives/slim")
  1606. assert response.status_code == 200
  1607. item = response.json()[0]
  1608. assert item["actual_time_seconds"] == 7200
  1609. @pytest.mark.asyncio
  1610. @pytest.mark.integration
  1611. async def test_slim_actual_time_for_failed_includes_elapsed(
  1612. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1613. ):
  1614. """Failed prints report measured elapsed time so Printer Stats By Time
  1615. matches Quick Stats Print Time (#1390). Previously this returned null
  1616. and the frontend fell back to the slicer estimate, double-counting the
  1617. unfinished portion of the print."""
  1618. from datetime import datetime, timezone
  1619. printer = await printer_factory()
  1620. await archive_factory(
  1621. printer.id,
  1622. status="failed",
  1623. started_at=datetime(2024, 1, 1, 10, 0, 0, tzinfo=timezone.utc),
  1624. completed_at=datetime(2024, 1, 1, 11, 0, 0, tzinfo=timezone.utc),
  1625. )
  1626. response = await async_client.get("/api/v1/archives/slim")
  1627. assert response.status_code == 200
  1628. item = response.json()[0]
  1629. assert item["actual_time_seconds"] == 3600
  1630. @pytest.mark.asyncio
  1631. @pytest.mark.integration
  1632. async def test_slim_date_filtering(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  1633. """Verify date_from and date_to filters work."""
  1634. from datetime import datetime, timezone
  1635. printer = await printer_factory()
  1636. await archive_factory(
  1637. printer.id,
  1638. print_name="Old Print",
  1639. created_at=datetime(2024, 1, 1, tzinfo=timezone.utc),
  1640. )
  1641. await archive_factory(
  1642. printer.id,
  1643. print_name="New Print",
  1644. created_at=datetime(2024, 6, 15, tzinfo=timezone.utc),
  1645. )
  1646. # Filter to only June 2024
  1647. response = await async_client.get("/api/v1/archives/slim?date_from=2024-06-01&date_to=2024-06-30")
  1648. assert response.status_code == 200
  1649. data = response.json()
  1650. assert len(data) == 1
  1651. assert data[0]["print_name"] == "New Print"
  1652. @pytest.mark.asyncio
  1653. @pytest.mark.integration
  1654. async def test_slim_pagination(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  1655. """Verify limit and offset work."""
  1656. printer = await printer_factory()
  1657. for i in range(5):
  1658. await archive_factory(printer.id, print_name=f"Print {i}")
  1659. response = await async_client.get("/api/v1/archives/slim?limit=2&offset=0")
  1660. assert response.status_code == 200
  1661. assert len(response.json()) == 2
  1662. @pytest.mark.asyncio
  1663. @pytest.mark.integration
  1664. async def test_slim_counts_reprints_as_separate_rows(
  1665. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1666. ):
  1667. """Reprints add events even though the archive row is overwritten (#1390).
  1668. Before the per-event migration, /archives/slim returned one row per
  1669. archive — so an archive that had been reprinted three times appeared
  1670. once and undercounted Filament Used / Cost / Time. The endpoint must
  1671. now return one row per logged event.
  1672. """
  1673. from backend.app.models.print_log import PrintLogEntry
  1674. printer = await printer_factory()
  1675. archive = await archive_factory(
  1676. printer.id,
  1677. print_name="Reprinted Model",
  1678. filament_used_grams=50.0,
  1679. cost=1.50,
  1680. )
  1681. # archive_factory synthesizes one event; add two more to simulate
  1682. # the same archive being reprinted twice more.
  1683. for _ in range(2):
  1684. db_session.add(
  1685. PrintLogEntry(
  1686. archive_id=archive.id,
  1687. printer_id=archive.printer_id,
  1688. status="completed",
  1689. filament_type=archive.filament_type,
  1690. filament_used_grams=archive.filament_used_grams,
  1691. cost=archive.cost,
  1692. print_name=archive.print_name,
  1693. )
  1694. )
  1695. await db_session.commit()
  1696. response = await async_client.get("/api/v1/archives/slim")
  1697. assert response.status_code == 200
  1698. data = response.json()
  1699. assert len(data) == 3, "Each reprint must contribute one row"
  1700. total_filament = sum(item["filament_used_grams"] or 0 for item in data)
  1701. assert total_filament == 150.0, "Sum across events must reflect all three runs"
  1702. @pytest.mark.asyncio
  1703. @pytest.mark.integration
  1704. async def test_slim_includes_orphan_events(self, async_client: AsyncClient, printer_factory, db_session):
  1705. """Events whose archive was hard-deleted still appear (#1390).
  1706. After ON DELETE SET NULL the event row survives with archive_id=NULL.
  1707. The slim endpoint must keep counting it so Quick Stats and the
  1708. archive-iterating widgets stay aligned.
  1709. """
  1710. from backend.app.models.print_log import PrintLogEntry
  1711. printer = await printer_factory()
  1712. db_session.add(
  1713. PrintLogEntry(
  1714. archive_id=None,
  1715. printer_id=printer.id,
  1716. status="completed",
  1717. filament_type="PETG",
  1718. filament_used_grams=25.0,
  1719. cost=0.75,
  1720. print_name="Orphaned Print",
  1721. )
  1722. )
  1723. await db_session.commit()
  1724. response = await async_client.get("/api/v1/archives/slim")
  1725. assert response.status_code == 200
  1726. data = response.json()
  1727. assert len(data) == 1
  1728. assert data[0]["print_name"] == "Orphaned Print"
  1729. assert data[0]["filament_used_grams"] == 25.0
  1730. # print_time_seconds (sliced estimate) comes from the archive table,
  1731. # which orphans no longer have — must surface as null gracefully.
  1732. assert data[0]["print_time_seconds"] is None
  1733. class TestFailureAnalysisAPI:
  1734. """Per-event failure analysis (#1390)."""
  1735. @pytest.mark.asyncio
  1736. @pytest.mark.integration
  1737. async def test_failure_analysis_counts_reprints_and_orphans(
  1738. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1739. ):
  1740. """Failure analysis aggregates per event, not per archive.
  1741. Verifies the dual fix for #1390: a reprint that adds a second failed
  1742. event must count twice, and an orphan failed event (archive deleted)
  1743. must still appear in the totals.
  1744. """
  1745. from backend.app.models.print_log import PrintLogEntry
  1746. printer = await printer_factory()
  1747. archive = await archive_factory(
  1748. printer.id,
  1749. print_name="Failing Model",
  1750. status="failed",
  1751. failure_reason="filament_runout",
  1752. )
  1753. # Add a second failed event for the same archive (a reprint that also
  1754. # failed) and one orphan failed event (archive was deleted).
  1755. db_session.add(
  1756. PrintLogEntry(
  1757. archive_id=archive.id,
  1758. printer_id=printer.id,
  1759. status="failed",
  1760. failure_reason="filament_runout",
  1761. filament_type=archive.filament_type,
  1762. print_name=archive.print_name,
  1763. )
  1764. )
  1765. db_session.add(
  1766. PrintLogEntry(
  1767. archive_id=None,
  1768. printer_id=printer.id,
  1769. status="failed",
  1770. failure_reason="bed_adhesion",
  1771. filament_type="PETG",
  1772. print_name="Orphaned Failed Print",
  1773. )
  1774. )
  1775. await db_session.commit()
  1776. response = await async_client.get("/api/v1/archives/analysis/failures")
  1777. assert response.status_code == 200
  1778. result = response.json()
  1779. assert result["total_prints"] == 3
  1780. assert result["failed_prints"] == 3
  1781. assert result["failures_by_reason"]["filament_runout"] == 2
  1782. assert result["failures_by_reason"]["bed_adhesion"] == 1
  1783. class TestArchiveDataIntegrity:
  1784. """Tests for archive data integrity."""
  1785. @pytest.mark.asyncio
  1786. @pytest.mark.integration
  1787. async def test_archive_linked_to_printer(
  1788. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1789. ):
  1790. """Verify archive is properly linked to printer."""
  1791. printer = await printer_factory(name="My Printer")
  1792. archive = await archive_factory(printer.id)
  1793. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  1794. assert response.status_code == 200
  1795. result = response.json()
  1796. assert result["printer_id"] == printer.id
  1797. @pytest.mark.asyncio
  1798. @pytest.mark.integration
  1799. async def test_archive_stores_print_data(
  1800. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1801. ):
  1802. """Verify archive stores all print data correctly."""
  1803. printer = await printer_factory()
  1804. archive = await archive_factory(
  1805. printer.id,
  1806. print_name="Test Print",
  1807. filename="test.3mf",
  1808. status="completed",
  1809. filament_type="PLA",
  1810. filament_used_grams=75.5,
  1811. print_time_seconds=5400,
  1812. )
  1813. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  1814. assert response.status_code == 200
  1815. result = response.json()
  1816. assert result["print_name"] == "Test Print"
  1817. assert result["filename"] == "test.3mf"
  1818. assert result["status"] == "completed"
  1819. assert result["filament_type"] == "PLA"
  1820. assert result["filament_used_grams"] == 75.5
  1821. assert result["print_time_seconds"] == 5400
  1822. @pytest.mark.asyncio
  1823. @pytest.mark.integration
  1824. async def test_archive_update_persists(
  1825. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1826. ):
  1827. """CRITICAL: Verify archive updates persist."""
  1828. printer = await printer_factory()
  1829. archive = await archive_factory(printer.id, notes="Original notes")
  1830. # Update
  1831. await async_client.patch(f"/api/v1/archives/{archive.id}", json={"notes": "Updated notes", "is_favorite": True})
  1832. # Verify persistence
  1833. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  1834. result = response.json()
  1835. assert result["notes"] == "Updated notes"
  1836. assert result["is_favorite"] is True
  1837. class TestArchiveF3DEndpoints:
  1838. """Tests for F3D (Fusion 360 design file) attachment endpoints."""
  1839. @pytest.mark.asyncio
  1840. @pytest.mark.integration
  1841. async def test_archive_response_includes_f3d_path(
  1842. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1843. ):
  1844. """Verify f3d_path is included in archive response."""
  1845. printer = await printer_factory()
  1846. archive = await archive_factory(printer.id, f3d_path="archives/test/design.f3d")
  1847. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  1848. assert response.status_code == 200
  1849. result = response.json()
  1850. assert "f3d_path" in result
  1851. assert result["f3d_path"] == "archives/test/design.f3d"
  1852. @pytest.mark.asyncio
  1853. @pytest.mark.integration
  1854. async def test_archive_response_f3d_path_null_when_not_set(
  1855. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1856. ):
  1857. """Verify f3d_path is null when no F3D file attached."""
  1858. printer = await printer_factory()
  1859. archive = await archive_factory(printer.id)
  1860. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  1861. assert response.status_code == 200
  1862. result = response.json()
  1863. assert "f3d_path" in result
  1864. assert result["f3d_path"] is None
  1865. @pytest.mark.asyncio
  1866. @pytest.mark.integration
  1867. async def test_upload_f3d_to_nonexistent_archive(self, async_client: AsyncClient):
  1868. """Verify 404 when uploading F3D to non-existent archive."""
  1869. # Create a minimal file-like upload
  1870. files = {"file": ("design.f3d", b"fake f3d content", "application/octet-stream")}
  1871. response = await async_client.post("/api/v1/archives/9999/f3d", files=files)
  1872. assert response.status_code == 404
  1873. @pytest.mark.asyncio
  1874. @pytest.mark.integration
  1875. async def test_download_f3d_not_found_when_no_file(
  1876. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1877. ):
  1878. """Verify 404 when downloading F3D from archive without F3D file."""
  1879. printer = await printer_factory()
  1880. archive = await archive_factory(printer.id)
  1881. response = await async_client.get(f"/api/v1/archives/{archive.id}/f3d")
  1882. assert response.status_code == 404
  1883. @pytest.mark.asyncio
  1884. @pytest.mark.integration
  1885. async def test_download_f3d_nonexistent_archive(self, async_client: AsyncClient):
  1886. """Verify 404 when downloading F3D from non-existent archive."""
  1887. response = await async_client.get("/api/v1/archives/9999/f3d")
  1888. assert response.status_code == 404
  1889. @pytest.mark.asyncio
  1890. @pytest.mark.integration
  1891. async def test_delete_f3d_nonexistent_archive(self, async_client: AsyncClient):
  1892. """Verify 404 when deleting F3D from non-existent archive."""
  1893. response = await async_client.delete("/api/v1/archives/9999/f3d")
  1894. assert response.status_code == 404
  1895. @pytest.mark.asyncio
  1896. @pytest.mark.integration
  1897. async def test_delete_f3d_when_no_file(
  1898. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1899. ):
  1900. """Verify 404 when deleting F3D from archive without F3D file."""
  1901. printer = await printer_factory()
  1902. archive = await archive_factory(printer.id)
  1903. response = await async_client.delete(f"/api/v1/archives/{archive.id}/f3d")
  1904. assert response.status_code == 404
  1905. @pytest.mark.asyncio
  1906. @pytest.mark.integration
  1907. async def test_list_archives_includes_f3d_path(
  1908. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1909. ):
  1910. """Verify f3d_path is included in archive list responses."""
  1911. printer = await printer_factory()
  1912. await archive_factory(printer.id, print_name="With F3D", f3d_path="archives/test/design.f3d")
  1913. await archive_factory(printer.id, print_name="Without F3D")
  1914. response = await async_client.get("/api/v1/archives/")
  1915. assert response.status_code == 200
  1916. data = response.json()
  1917. assert len(data) >= 2
  1918. with_f3d = next((a for a in data if a["print_name"] == "With F3D"), None)
  1919. without_f3d = next((a for a in data if a["print_name"] == "Without F3D"), None)
  1920. assert with_f3d is not None
  1921. assert with_f3d["f3d_path"] == "archives/test/design.f3d"
  1922. assert without_f3d is not None
  1923. assert without_f3d["f3d_path"] is None
  1924. # ========================================================================
  1925. # Multi-Plate 3MF endpoints (Issue #93)
  1926. # ========================================================================
  1927. @pytest.mark.asyncio
  1928. @pytest.mark.integration
  1929. async def test_get_archive_plates_not_found(self, async_client: AsyncClient):
  1930. """Verify 404 when fetching plates for non-existent archive."""
  1931. response = await async_client.get("/api/v1/archives/999999/plates")
  1932. assert response.status_code == 404
  1933. @pytest.mark.asyncio
  1934. @pytest.mark.integration
  1935. async def test_get_plate_thumbnail_not_found(self, async_client: AsyncClient):
  1936. """Verify 404 when fetching plate thumbnail for non-existent archive."""
  1937. response = await async_client.get("/api/v1/archives/999999/plate-thumbnail/1")
  1938. assert response.status_code == 404
  1939. @pytest.mark.asyncio
  1940. @pytest.mark.integration
  1941. async def test_filament_requirements_not_found(self, async_client: AsyncClient):
  1942. """Verify filament-requirements returns 404 for non-existent archive."""
  1943. response = await async_client.get("/api/v1/archives/999999/filament-requirements")
  1944. assert response.status_code == 404
  1945. @pytest.mark.asyncio
  1946. @pytest.mark.integration
  1947. async def test_filament_requirements_with_plate_id_not_found(self, async_client: AsyncClient):
  1948. """Verify filament-requirements with plate_id returns 404 for non-existent archive."""
  1949. response = await async_client.get("/api/v1/archives/999999/filament-requirements?plate_id=1")
  1950. assert response.status_code == 404
  1951. async def _two_plate_archive(self, archive_factory, printer_factory, tmp_path):
  1952. """An archive whose 3MF stores plate 2 ahead of plate 1, as Studio writes it."""
  1953. import zipfile
  1954. printer = await printer_factory()
  1955. path = tmp_path / "two_plates.gcode.3mf"
  1956. with zipfile.ZipFile(path, "w") as zf:
  1957. zf.writestr("Metadata/plate_2.gcode", "; plate two\nG28\n")
  1958. zf.writestr("Metadata/plate_1.gcode", "; plate one\nG28\n")
  1959. # An absolute file_path collapses `settings.base_dir / file_path` onto
  1960. # itself, so the route reads the file written here.
  1961. return await archive_factory(printer.id, file_path=str(path), filename="two_plates.gcode.3mf")
  1962. @pytest.mark.asyncio
  1963. @pytest.mark.integration
  1964. async def test_archive_gcode_without_a_plate_serves_the_first_plate(
  1965. self, async_client: AsyncClient, archive_factory, printer_factory, tmp_path
  1966. ):
  1967. """Zip order is whatever the slicer wrote, so the first member here is
  1968. plate 2. Callers that pass no plate must still land on plate 1."""
  1969. archive = await self._two_plate_archive(archive_factory, printer_factory, tmp_path)
  1970. response = await async_client.get(f"/api/v1/archives/{archive.id}/gcode")
  1971. assert response.status_code == 200
  1972. assert "plate one" in response.text
  1973. @pytest.mark.asyncio
  1974. @pytest.mark.integration
  1975. async def test_archive_gcode_serves_the_requested_plate(
  1976. self, async_client: AsyncClient, archive_factory, printer_factory, tmp_path
  1977. ):
  1978. archive = await self._two_plate_archive(archive_factory, printer_factory, tmp_path)
  1979. first = await async_client.get(f"/api/v1/archives/{archive.id}/gcode?plate=1")
  1980. second = await async_client.get(f"/api/v1/archives/{archive.id}/gcode?plate=2")
  1981. assert "plate one" in first.text
  1982. assert "plate two" in second.text
  1983. @pytest.mark.asyncio
  1984. @pytest.mark.integration
  1985. async def test_archive_gcode_rejects_a_plate_the_file_does_not_hold(
  1986. self, async_client: AsyncClient, archive_factory, printer_factory, tmp_path
  1987. ):
  1988. archive = await self._two_plate_archive(archive_factory, printer_factory, tmp_path)
  1989. missing = await async_client.get(f"/api/v1/archives/{archive.id}/gcode?plate=3")
  1990. zeroth = await async_client.get(f"/api/v1/archives/{archive.id}/gcode?plate=0")
  1991. assert missing.status_code == 404
  1992. assert zeroth.status_code == 400
  1993. # ========================================================================
  1994. # Tag Management endpoints (Issue #183)
  1995. # ========================================================================
  1996. @pytest.mark.asyncio
  1997. @pytest.mark.integration
  1998. async def test_get_tags_empty(self, async_client: AsyncClient):
  1999. """Verify empty list when no tags exist."""
  2000. response = await async_client.get("/api/v1/archives/tags")
  2001. assert response.status_code == 200
  2002. data = response.json()
  2003. assert isinstance(data, list)
  2004. assert len(data) == 0
  2005. @pytest.mark.asyncio
  2006. @pytest.mark.integration
  2007. async def test_get_tags_with_data(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  2008. """Verify tags are returned with counts."""
  2009. printer = await printer_factory()
  2010. await archive_factory(printer.id, print_name="Archive 1", tags="functional, test")
  2011. await archive_factory(printer.id, print_name="Archive 2", tags="functional, calibration")
  2012. await archive_factory(printer.id, print_name="Archive 3", tags="test")
  2013. response = await async_client.get("/api/v1/archives/tags")
  2014. assert response.status_code == 200
  2015. data = response.json()
  2016. assert isinstance(data, list)
  2017. # Convert to dict for easier lookup
  2018. tags_dict = {t["name"]: t["count"] for t in data}
  2019. assert tags_dict.get("functional") == 2
  2020. assert tags_dict.get("test") == 2
  2021. assert tags_dict.get("calibration") == 1
  2022. @pytest.mark.asyncio
  2023. @pytest.mark.integration
  2024. async def test_get_tags_sorted_by_count(
  2025. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  2026. ):
  2027. """Verify tags are sorted by count descending, then by name."""
  2028. printer = await printer_factory()
  2029. await archive_factory(printer.id, tags="alpha")
  2030. await archive_factory(printer.id, tags="beta, alpha")
  2031. await archive_factory(printer.id, tags="gamma, beta, alpha")
  2032. response = await async_client.get("/api/v1/archives/tags")
  2033. assert response.status_code == 200
  2034. data = response.json()
  2035. # alpha=3, beta=2, gamma=1
  2036. assert data[0]["name"] == "alpha"
  2037. assert data[0]["count"] == 3
  2038. assert data[1]["name"] == "beta"
  2039. assert data[1]["count"] == 2
  2040. assert data[2]["name"] == "gamma"
  2041. assert data[2]["count"] == 1
  2042. @pytest.mark.asyncio
  2043. @pytest.mark.integration
  2044. async def test_rename_tag(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  2045. """Verify renaming a tag updates all archives."""
  2046. printer = await printer_factory()
  2047. a1 = await archive_factory(printer.id, print_name="Archive 1", tags="old-tag, other")
  2048. a2 = await archive_factory(printer.id, print_name="Archive 2", tags="old-tag")
  2049. await archive_factory(printer.id, print_name="Archive 3", tags="different")
  2050. response = await async_client.put("/api/v1/archives/tags/old-tag", json={"new_name": "new-tag"})
  2051. assert response.status_code == 200
  2052. data = response.json()
  2053. assert data["affected"] == 2
  2054. # Verify the archives were updated
  2055. response = await async_client.get(f"/api/v1/archives/{a1.id}")
  2056. assert "new-tag" in response.json()["tags"]
  2057. assert "old-tag" not in response.json()["tags"]
  2058. response = await async_client.get(f"/api/v1/archives/{a2.id}")
  2059. assert response.json()["tags"] == "new-tag"
  2060. @pytest.mark.asyncio
  2061. @pytest.mark.integration
  2062. async def test_rename_tag_no_change(self, async_client: AsyncClient):
  2063. """Verify renaming to same name returns 0 affected."""
  2064. response = await async_client.put("/api/v1/archives/tags/some-tag", json={"new_name": "some-tag"})
  2065. assert response.status_code == 200
  2066. assert response.json()["affected"] == 0
  2067. @pytest.mark.asyncio
  2068. @pytest.mark.integration
  2069. async def test_rename_tag_empty_name_error(self, async_client: AsyncClient):
  2070. """Verify renaming to empty name returns error."""
  2071. response = await async_client.put("/api/v1/archives/tags/some-tag", json={"new_name": ""})
  2072. assert response.status_code == 400
  2073. @pytest.mark.asyncio
  2074. @pytest.mark.integration
  2075. async def test_delete_tag(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  2076. """Verify deleting a tag removes it from all archives."""
  2077. printer = await printer_factory()
  2078. a1 = await archive_factory(printer.id, print_name="Archive 1", tags="delete-me, keep")
  2079. a2 = await archive_factory(printer.id, print_name="Archive 2", tags="delete-me")
  2080. await archive_factory(printer.id, print_name="Archive 3", tags="different")
  2081. response = await async_client.delete("/api/v1/archives/tags/delete-me")
  2082. assert response.status_code == 200
  2083. data = response.json()
  2084. assert data["affected"] == 2
  2085. # Verify the archives were updated
  2086. response = await async_client.get(f"/api/v1/archives/{a1.id}")
  2087. assert response.json()["tags"] == "keep"
  2088. response = await async_client.get(f"/api/v1/archives/{a2.id}")
  2089. # Should be None or empty when last tag is removed
  2090. assert response.json()["tags"] is None or response.json()["tags"] == ""
  2091. @pytest.mark.asyncio
  2092. @pytest.mark.integration
  2093. async def test_delete_tag_not_found(self, async_client: AsyncClient):
  2094. """Verify deleting non-existent tag returns 0 affected."""
  2095. response = await async_client.delete("/api/v1/archives/tags/nonexistent-tag")
  2096. assert response.status_code == 200
  2097. assert response.json()["affected"] == 0
  2098. class TestUploadSourceThreeMF:
  2099. """Regression for #1531: source-3MF upload on fallback archives."""
  2100. @staticmethod
  2101. def _minimal_3mf_bytes() -> bytes:
  2102. """Smallest valid .3mf — the upload path enforces a zip header check."""
  2103. import io
  2104. import zipfile
  2105. buf = io.BytesIO()
  2106. with zipfile.ZipFile(buf, "w") as zf:
  2107. zf.writestr("[Content_Types].xml", "<types/>")
  2108. return buf.getvalue()
  2109. @pytest.mark.asyncio
  2110. @pytest.mark.integration
  2111. async def test_fallback_archive_source_upload_lands_under_base_dir(
  2112. self, async_client: AsyncClient, archive_factory, printer_factory, monkeypatch, tmp_path
  2113. ):
  2114. """Fallback archive (file_path='') must accept a source upload and store it inside base_dir.
  2115. Pre-fix, ``Path(base_dir) / ''`` collapsed to ``base_dir`` and the
  2116. ``.parent`` walked out of the data volume, sending the file to
  2117. ``/app/source/...`` and crashing on ``relative_to``.
  2118. """
  2119. from backend.app.core.config import settings as app_settings
  2120. monkeypatch.setattr(app_settings, "base_dir", tmp_path)
  2121. printer = await printer_factory()
  2122. archive = await archive_factory(
  2123. printer.id,
  2124. print_name="Cloud Print",
  2125. file_path="", # fallback archive — no source 3MF was archived
  2126. filename="Cloud Print.3mf",
  2127. )
  2128. files = {"file": ("cloud_print.3mf", self._minimal_3mf_bytes(), "application/octet-stream")}
  2129. response = await async_client.post(f"/api/v1/archives/{archive.id}/source", files=files)
  2130. assert response.status_code == 200, response.text
  2131. payload = response.json()
  2132. rel = payload["source_3mf_path"]
  2133. # Stored as a relative path inside base_dir.
  2134. assert not rel.startswith("/"), f"source_3mf_path should be relative, got {rel!r}"
  2135. # File physically landed under base_dir (NOT escaped to /app/source/).
  2136. assert (tmp_path / rel).is_file()
  2137. # Deterministic fallback location keyed off archive id.
  2138. assert rel == f"archive/no_source/{archive.id}/cloud_print.3mf"
  2139. @pytest.mark.asyncio
  2140. @pytest.mark.integration
  2141. async def test_normal_archive_source_upload_unchanged(
  2142. self, async_client: AsyncClient, archive_factory, printer_factory, monkeypatch, tmp_path
  2143. ):
  2144. """Normal archive (file_path set) still nests the source under <archive>/source/."""
  2145. from backend.app.core.config import settings as app_settings
  2146. monkeypatch.setattr(app_settings, "base_dir", tmp_path)
  2147. printer = await printer_factory()
  2148. # archive_factory's default file_path is "archives/test/test_print.gcode.3mf".
  2149. archive = await archive_factory(printer.id, print_name="Real Print")
  2150. files = {"file": ("real_print.3mf", self._minimal_3mf_bytes(), "application/octet-stream")}
  2151. response = await async_client.post(f"/api/v1/archives/{archive.id}/source", files=files)
  2152. assert response.status_code == 200, response.text
  2153. rel = response.json()["source_3mf_path"]
  2154. assert rel == "archives/test/source/real_print.3mf"
  2155. assert (tmp_path / rel).is_file()
  2156. @pytest.mark.asyncio
  2157. @pytest.mark.integration
  2158. async def test_symlinked_data_dir_upload_succeeds(
  2159. self, async_client: AsyncClient, archive_factory, printer_factory, monkeypatch, tmp_path
  2160. ):
  2161. """Regression: DATA_DIR that's a symlink to the real storage must not break the upload.
  2162. Common on TrueNAS / Synology / QNAP storage pools, and any
  2163. ``-v /symlinked/host/path:/app/data`` mount. The helper resolves
  2164. only for the containment check and returns literal paths so the
  2165. caller's ``relative_to(settings.base_dir)`` doesn't trip over a
  2166. canonical-vs-symlink mismatch.
  2167. """
  2168. from backend.app.core.config import settings as app_settings
  2169. real_dir = tmp_path / "real_storage"
  2170. real_dir.mkdir()
  2171. symlink_dir = tmp_path / "data_via_symlink"
  2172. symlink_dir.symlink_to(real_dir)
  2173. monkeypatch.setattr(app_settings, "base_dir", symlink_dir)
  2174. printer = await printer_factory()
  2175. archive = await archive_factory(
  2176. printer.id,
  2177. print_name="Symlinked Print",
  2178. file_path="archives/X1C/print.gcode.3mf",
  2179. filename="print.gcode.3mf",
  2180. )
  2181. files = {"file": ("print.3mf", self._minimal_3mf_bytes(), "application/octet-stream")}
  2182. response = await async_client.post(f"/api/v1/archives/{archive.id}/source", files=files)
  2183. assert response.status_code == 200, response.text
  2184. rel = response.json()["source_3mf_path"]
  2185. assert rel == "archives/X1C/source/print.3mf"
  2186. # Reachable via both the symlink and the canonical path.
  2187. assert (symlink_dir / rel).is_file()
  2188. assert (real_dir / rel).is_file()
  2189. @pytest.mark.asyncio
  2190. @pytest.mark.integration
  2191. async def test_absolute_file_path_rejected_with_clear_500(
  2192. self, async_client: AsyncClient, archive_factory, printer_factory, monkeypatch, tmp_path
  2193. ):
  2194. """A row whose file_path is absolute (corrupted by old import / manual edit)
  2195. must fail with the explicit "outside the data directory" message, not silently
  2196. write outside base_dir."""
  2197. from backend.app.core.config import settings as app_settings
  2198. monkeypatch.setattr(app_settings, "base_dir", tmp_path)
  2199. printer = await printer_factory()
  2200. archive = await archive_factory(
  2201. printer.id,
  2202. print_name="Corrupt Path",
  2203. file_path="/tmp/totally_outside.gcode.3mf", # nosec B108
  2204. filename="totally_outside.gcode.3mf",
  2205. )
  2206. files = {"file": ("totally_outside.3mf", self._minimal_3mf_bytes(), "application/octet-stream")}
  2207. response = await async_client.post(f"/api/v1/archives/{archive.id}/source", files=files)
  2208. assert response.status_code == 500
  2209. assert "outside the data directory" in response.json()["detail"]
  2210. # Did not write anything under the bogus /tmp/source/ either.
  2211. assert not (Path("/tmp") / "source").exists() or not (Path("/tmp") / "source" / "totally_outside.3mf").exists() # nosec B108
  2212. class TestSoftDeletedArchivesAreExcluded:
  2213. """Soft-deleted archives (#1343) must not leak into export or analysis (#2731).
  2214. The soft delete keeps the row so global Quick Stats can still count it, but
  2215. the archive is gone from every listing. Two consumers never got the memo:
  2216. the CSV export handed back rows the UI says do not exist, and per-project
  2217. failure analysis kept counting prints the user had deleted from the project
  2218. — disagreeing with the project's own figures.
  2219. """
  2220. @staticmethod
  2221. async def _soft_delete(db_session, archive) -> int:
  2222. from datetime import datetime, timezone
  2223. archive_id = archive.id
  2224. archive.deleted_at = datetime.now(timezone.utc)
  2225. await db_session.commit()
  2226. return archive_id
  2227. @pytest.mark.asyncio
  2228. @pytest.mark.integration
  2229. async def test_export_omits_soft_deleted_archives(
  2230. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  2231. ):
  2232. printer = await printer_factory()
  2233. await archive_factory(printer.id, print_name="Kept Print")
  2234. gone = await archive_factory(printer.id, print_name="Deleted Print")
  2235. await self._soft_delete(db_session, gone)
  2236. response = await async_client.get("/api/v1/archives/export?format=csv")
  2237. assert response.status_code == 200
  2238. body = response.text
  2239. assert "Kept Print" in body
  2240. assert "Deleted Print" not in body
  2241. @pytest.mark.asyncio
  2242. @pytest.mark.integration
  2243. async def test_project_failure_analysis_omits_soft_deleted_archives(
  2244. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  2245. ):
  2246. from backend.app.models.project import Project
  2247. project = Project(name="Analysis Project")
  2248. db_session.add(project)
  2249. await db_session.commit()
  2250. await db_session.refresh(project)
  2251. project_id = project.id
  2252. printer = await printer_factory()
  2253. await archive_factory(
  2254. printer.id,
  2255. print_name="Kept Failure",
  2256. status="failed",
  2257. failure_reason="bed_adhesion",
  2258. project_id=project_id,
  2259. )
  2260. gone = await archive_factory(
  2261. printer.id,
  2262. print_name="Deleted Failure",
  2263. status="failed",
  2264. failure_reason="filament_runout",
  2265. project_id=project_id,
  2266. )
  2267. await self._soft_delete(db_session, gone)
  2268. response = await async_client.get(f"/api/v1/archives/analysis/failures?project_id={project_id}")
  2269. assert response.status_code == 200
  2270. result = response.json()
  2271. assert result["failed_prints"] == 1
  2272. assert result["failures_by_reason"] == {"bed_adhesion": 1}
  2273. @pytest.mark.asyncio
  2274. @pytest.mark.integration
  2275. async def test_unscoped_failure_analysis_is_unchanged(
  2276. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  2277. ):
  2278. """Only the project-scoped path filters. Global analysis still counts
  2279. every run, including orphans, exactly as #1390 established."""
  2280. printer = await printer_factory()
  2281. gone = await archive_factory(
  2282. printer.id, print_name="Deleted Failure", status="failed", failure_reason="filament_runout"
  2283. )
  2284. await self._soft_delete(db_session, gone)
  2285. response = await async_client.get("/api/v1/archives/analysis/failures")
  2286. assert response.status_code == 200
  2287. assert response.json()["failed_prints"] == 1
  2288. class TestPrintLogSorting:
  2289. """#2636: the Print Log's column headers sort the whole log.
  2290. Sorting is server-side because paging is: ordering the rows the browser
  2291. happens to hold would answer "the most expensive print on this page",
  2292. not "the most expensive print". These pin the ordering contract the
  2293. headers depend on, including the two cases that differ per database
  2294. backend or per query plan if left implicit.
  2295. """
  2296. @staticmethod
  2297. async def _seed(db_session, printer_id: int, rows: list[dict]):
  2298. from datetime import datetime
  2299. from backend.app.models.print_log import PrintLogEntry
  2300. created = []
  2301. for i, row in enumerate(rows):
  2302. entry = PrintLogEntry(
  2303. printer_id=printer_id,
  2304. status=row.get("status", "completed"),
  2305. print_name=row.get("print_name", f"job-{i}"),
  2306. started_at=datetime(2026, 1, 1 + i, 12, 0, 0),
  2307. created_at=datetime(2026, 1, 1 + i, 12, 0, 0),
  2308. filament_used_grams=row.get("grams"),
  2309. cost=row.get("cost"),
  2310. energy_kwh=row.get("kwh"),
  2311. )
  2312. db_session.add(entry)
  2313. created.append(entry)
  2314. await db_session.commit()
  2315. return created
  2316. @pytest.mark.asyncio
  2317. @pytest.mark.integration
  2318. async def test_sorts_by_filament_used_in_both_directions(
  2319. self, async_client: AsyncClient, printer_factory, db_session
  2320. ):
  2321. printer = await printer_factory()
  2322. await self._seed(
  2323. db_session,
  2324. printer.id,
  2325. [{"grams": 5.0}, {"grams": 120.0}, {"grams": 30.0}],
  2326. )
  2327. asc = await async_client.get("/api/v1/print-log/?sort_by=filament_used&sort_dir=asc")
  2328. assert asc.status_code == 200
  2329. assert [e["filament_used_grams"] for e in asc.json()["items"]] == [5.0, 30.0, 120.0]
  2330. desc = await async_client.get("/api/v1/print-log/?sort_by=filament_used&sort_dir=desc")
  2331. assert [e["filament_used_grams"] for e in desc.json()["items"]] == [120.0, 30.0, 5.0]
  2332. @pytest.mark.asyncio
  2333. @pytest.mark.integration
  2334. async def test_empty_values_sort_last_whichever_direction(
  2335. self, async_client: AsyncClient, printer_factory, db_session
  2336. ):
  2337. """Cost is NULL until a spool is priced and energy until a smart plug
  2338. reports, so these columns are half-empty for most people. Postgres
  2339. sorts NULLs high and SQLite sorts them low, so without an explicit
  2340. NULLS LAST the same click gives a different first page depending on
  2341. which database the user deployed — and on one of them, a screenful
  2342. of blanks."""
  2343. printer = await printer_factory()
  2344. await self._seed(
  2345. db_session,
  2346. printer.id,
  2347. [{"cost": None}, {"cost": 2.5}, {"cost": None}, {"cost": 0.75}],
  2348. )
  2349. for direction, expected in (("asc", [0.75, 2.5]), ("desc", [2.5, 0.75])):
  2350. resp = await async_client.get(f"/api/v1/print-log/?sort_by=cost&sort_dir={direction}")
  2351. costs = [e["cost"] for e in resp.json()["items"]]
  2352. assert costs[:2] == expected, (direction, costs)
  2353. assert costs[2:] == [None, None], (direction, costs)
  2354. @pytest.mark.asyncio
  2355. @pytest.mark.integration
  2356. async def test_ties_are_broken_stably_across_pages(self, async_client: AsyncClient, printer_factory, db_session):
  2357. """Sorting by a column where every row shares a value (status) leaves
  2358. the order to the planner unless a tiebreaker is added — and an
  2359. unstable order can show the same row on two pages while another never
  2360. appears at all."""
  2361. printer = await printer_factory()
  2362. await self._seed(db_session, printer.id, [{"status": "completed"} for _ in range(6)])
  2363. first = await async_client.get("/api/v1/print-log/?sort_by=status&sort_dir=asc&limit=3&offset=0")
  2364. second = await async_client.get("/api/v1/print-log/?sort_by=status&sort_dir=asc&limit=3&offset=3")
  2365. page_1 = [e["id"] for e in first.json()["items"]]
  2366. page_2 = [e["id"] for e in second.json()["items"]]
  2367. assert len(set(page_1) & set(page_2)) == 0, "a row appeared on both pages"
  2368. assert len(set(page_1) | set(page_2)) == 6, "a row was never returned"
  2369. # Repeating the same request must give the same page back.
  2370. again = await async_client.get("/api/v1/print-log/?sort_by=status&sort_dir=asc&limit=3&offset=0")
  2371. assert [e["id"] for e in again.json()["items"]] == page_1
  2372. @pytest.mark.asyncio
  2373. @pytest.mark.integration
  2374. async def test_unknown_sort_column_is_rejected(self, async_client: AsyncClient):
  2375. """The client picks the sort key, so the column list is a whitelist —
  2376. anything else would let a request order by any attribute it can name."""
  2377. resp = await async_client.get("/api/v1/print-log/?sort_by=created_by_id")
  2378. assert resp.status_code == 400
  2379. resp = await async_client.get("/api/v1/print-log/?sort_by=1;DROP")
  2380. assert resp.status_code == 400
  2381. @pytest.mark.asyncio
  2382. @pytest.mark.integration
  2383. async def test_invalid_direction_is_rejected(self, async_client: AsyncClient):
  2384. resp = await async_client.get("/api/v1/print-log/?sort_by=date&sort_dir=sideways")
  2385. assert resp.status_code == 422
  2386. @pytest.mark.asyncio
  2387. @pytest.mark.integration
  2388. async def test_defaults_to_newest_first(self, async_client: AsyncClient, printer_factory, db_session):
  2389. """No sort params — the pre-#2636 behaviour, which existing clients
  2390. and the first page load both rely on."""
  2391. printer = await printer_factory()
  2392. await self._seed(db_session, printer.id, [{"print_name": "oldest"}, {"print_name": "newest"}])
  2393. resp = await async_client.get("/api/v1/print-log/")
  2394. assert [e["print_name"] for e in resp.json()["items"]] == ["newest", "oldest"]