test_archives_api.py 123 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972
  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_items_printed_accepts_zero_for_a_ruined_plate(
  785. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  786. ):
  787. """A jam can ruin every part on the plate while the printer still
  788. reports success (#3051). The project's completed-items count sums this
  789. column, so zero has to be storable, not floored to one.
  790. """
  791. printer = await printer_factory()
  792. archive = await archive_factory(printer.id, quantity=4)
  793. response = await async_client.patch(f"/api/v1/archives/{archive.id}", json={"quantity": 0})
  794. assert response.status_code == 200, response.text
  795. assert response.json()["quantity"] == 0
  796. await db_session.refresh(archive)
  797. assert archive.quantity == 0
  798. @pytest.mark.asyncio
  799. @pytest.mark.integration
  800. async def test_items_printed_refuses_a_negative_count(
  801. self, async_client: AsyncClient, archive_factory, printer_factory
  802. ):
  803. """Zero means "nothing came off the plate"; below that would subtract
  804. from the project totals this column feeds."""
  805. printer = await printer_factory()
  806. archive = await archive_factory(printer.id, quantity=4)
  807. response = await async_client.patch(f"/api/v1/archives/{archive.id}", json={"quantity": -1})
  808. assert response.status_code == 422, response.text
  809. @pytest.mark.asyncio
  810. @pytest.mark.integration
  811. async def test_update_archive_failure_reason_mirrors_to_print_log_entry(
  812. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  813. ):
  814. """#1444: PATCH /archives/{id} with failure_reason must mirror to the
  815. latest PrintLogEntry so the Stats page Failure Analysis widget
  816. (which reads PrintLogEntry.failure_reason) reflects the user's
  817. reclassification instead of showing "Unknown" forever.
  818. """
  819. from sqlalchemy import select
  820. from backend.app.models.print_log import PrintLogEntry
  821. printer = await printer_factory()
  822. # archive_factory auto-creates a matching PrintLogEntry (failure_reason
  823. # carried from the archive, which is NULL here — same shape as the bug
  824. # repro: print completed → log entry written with NULL → user goes to
  825. # classify the failure afterwards).
  826. archive = await archive_factory(printer.id, print_name="Failed Print", status="failed", run_status="failed")
  827. response = await async_client.patch(
  828. f"/api/v1/archives/{archive.id}",
  829. json={"failure_reason": "Adhesion failure"},
  830. )
  831. assert response.status_code == 200
  832. result = await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  833. mirrored = result.scalar_one()
  834. assert mirrored.failure_reason == "Adhesion failure"
  835. @pytest.mark.asyncio
  836. @pytest.mark.integration
  837. async def test_update_archive_status_mirrors_to_print_log_entry(
  838. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  839. ):
  840. """#1444: PATCH /archives/{id} with status must mirror to the latest
  841. PrintLogEntry so stats that filter on PrintLogEntry.status see the
  842. user's reclassification.
  843. """
  844. from sqlalchemy import select
  845. from backend.app.models.print_log import PrintLogEntry
  846. printer = await printer_factory()
  847. archive = await archive_factory(printer.id, run_status="completed")
  848. response = await async_client.patch(
  849. f"/api/v1/archives/{archive.id}",
  850. json={"status": "failed"},
  851. )
  852. assert response.status_code == 200
  853. result = await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  854. mirrored = result.scalar_one()
  855. assert mirrored.status == "failed"
  856. @pytest.mark.asyncio
  857. @pytest.mark.integration
  858. async def test_update_archive_failure_reason_only_touches_latest_entry(
  859. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  860. ):
  861. """#1444: For an archive with multiple runs (reprints), only the
  862. latest PrintLogEntry should receive the reclassification. Earlier
  863. runs were classified at their own time and must not be retroactively
  864. overwritten.
  865. """
  866. from backend.app.models.print_log import PrintLogEntry
  867. printer = await printer_factory()
  868. # First run — created by the factory's auto-run with its own reason.
  869. archive = await archive_factory(printer.id, status="failed", run_status="failed")
  870. from sqlalchemy import select
  871. first_run = (
  872. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  873. ).scalar_one()
  874. first_run.failure_reason = "Filament tangle"
  875. await db_session.commit()
  876. # Second run — the reprint that just finished with NULL classification.
  877. latest_run = PrintLogEntry(archive_id=archive.id, status="failed", failure_reason=None)
  878. db_session.add(latest_run)
  879. await db_session.commit()
  880. response = await async_client.patch(
  881. f"/api/v1/archives/{archive.id}",
  882. json={"failure_reason": "Adhesion failure"},
  883. )
  884. assert response.status_code == 200
  885. await db_session.refresh(first_run)
  886. await db_session.refresh(latest_run)
  887. assert first_run.failure_reason == "Filament tangle"
  888. assert latest_run.failure_reason == "Adhesion failure"
  889. # ========================================================================
  890. # Delete endpoints
  891. # ========================================================================
  892. @pytest.mark.asyncio
  893. @pytest.mark.integration
  894. async def test_delete_archive(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  895. """Verify archive can be deleted."""
  896. printer = await printer_factory()
  897. archive = await archive_factory(printer.id)
  898. archive_id = archive.id
  899. response = await async_client.delete(f"/api/v1/archives/{archive_id}")
  900. assert response.status_code == 200
  901. # Verify deleted
  902. response = await async_client.get(f"/api/v1/archives/{archive_id}")
  903. assert response.status_code == 404
  904. @pytest.mark.asyncio
  905. @pytest.mark.integration
  906. async def test_delete_nonexistent_archive(self, async_client: AsyncClient):
  907. """Verify deleting non-existent archive returns 404."""
  908. response = await async_client.delete("/api/v1/archives/9999")
  909. assert response.status_code == 404
  910. @pytest.mark.asyncio
  911. @pytest.mark.integration
  912. async def test_delete_archive_blocked_when_related_queue_item_printing(
  913. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  914. ):
  915. """#1734: archive delete must 409 when a related queue item is currently
  916. mid-print — deleting the archive would strip the dispatcher's metadata
  917. trail (filament / plate / ams_mapping) out from under the running print.
  918. Both soft and hard delete are gated by the same precondition.
  919. """
  920. from backend.app.models.print_queue import PrintQueueItem
  921. printer = await printer_factory()
  922. archive = await archive_factory(printer.id)
  923. db_session.add(PrintQueueItem(printer_id=printer.id, archive_id=archive.id, status="printing", position=1))
  924. await db_session.commit()
  925. soft = await async_client.delete(f"/api/v1/archives/{archive.id}")
  926. assert soft.status_code == 409
  927. assert "printing" in soft.json()["detail"].lower()
  928. hard = await async_client.delete(f"/api/v1/archives/{archive.id}?purge_stats=true")
  929. assert hard.status_code == 409
  930. @pytest.mark.asyncio
  931. @pytest.mark.integration
  932. async def test_archive_delete_impact_reports_counts(
  933. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  934. ):
  935. """#1734: the delete-impact pre-flight endpoint reports the total
  936. number of related queue items AND how many are currently printing,
  937. so the frontend can both warn the user before they confirm AND
  938. disable the confirm button when the printing count is non-zero.
  939. """
  940. from backend.app.models.print_queue import PrintQueueItem
  941. printer = await printer_factory()
  942. archive = await archive_factory(printer.id)
  943. # Build a mixed-status set the way a Send All upload + later in-flight
  944. # dispatch looks at the wire (#1733).
  945. db_session.add_all(
  946. [
  947. PrintQueueItem(printer_id=printer.id, archive_id=archive.id, status="pending", position=1),
  948. PrintQueueItem(printer_id=printer.id, archive_id=archive.id, status="pending", position=2),
  949. PrintQueueItem(printer_id=printer.id, archive_id=archive.id, status="printing", position=3),
  950. ]
  951. )
  952. # An unrelated archive's queue rows must not bleed into the count.
  953. other = await archive_factory(printer.id)
  954. db_session.add(PrintQueueItem(printer_id=printer.id, archive_id=other.id, status="pending", position=4))
  955. await db_session.commit()
  956. resp = await async_client.get(f"/api/v1/archives/{archive.id}/delete-impact")
  957. assert resp.status_code == 200
  958. body = resp.json()
  959. assert body["related_queue_items"] == 3
  960. assert body["currently_printing"] == 1
  961. @pytest.mark.asyncio
  962. @pytest.mark.integration
  963. async def test_soft_delete_preserves_stats_contribution(
  964. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  965. ):
  966. """#1343: deleting an archive without ``purge_stats`` keeps its
  967. contribution in Quick Stats. The row vanishes from listings but the
  968. filament / time / cost totals stay intact.
  969. """
  970. printer = await printer_factory()
  971. await archive_factory(
  972. printer.id,
  973. status="completed",
  974. print_time_seconds=3600,
  975. filament_used_grams=50.0,
  976. cost=1.50,
  977. )
  978. archive_to_delete = await archive_factory(
  979. printer.id,
  980. status="completed",
  981. print_time_seconds=7200,
  982. filament_used_grams=100.0,
  983. cost=3.00,
  984. )
  985. # Pre-delete: stats include both archives.
  986. pre = (await async_client.get("/api/v1/archives/stats")).json()
  987. assert pre["total_prints"] == 2
  988. assert pre["total_filament_grams"] == 150.0
  989. assert pre["total_cost"] == 4.50
  990. # Soft delete (default — no purge_stats param).
  991. resp = await async_client.delete(f"/api/v1/archives/{archive_to_delete.id}")
  992. assert resp.status_code == 200
  993. body = resp.json()
  994. assert body["purged_from_stats"] is False
  995. # Listing hides the deleted archive…
  996. listing = (await async_client.get("/api/v1/archives/")).json()
  997. assert all(a["id"] != archive_to_delete.id for a in listing)
  998. # …but stats still reflect both prints (the whole point of #1343).
  999. post = (await async_client.get("/api/v1/archives/stats")).json()
  1000. assert post["total_prints"] == 2
  1001. assert post["total_filament_grams"] == 150.0
  1002. assert post["total_cost"] == 4.50
  1003. @pytest.mark.asyncio
  1004. @pytest.mark.integration
  1005. async def test_soft_delete_clears_thumbnail_path_on_linked_log_entries(
  1006. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1007. ):
  1008. """#1348 follow-up: soft-deleting an archive removes its files from disk;
  1009. the cached thumbnail_path on linked PrintLogEntry rows must be NULLed
  1010. in the same transaction so the print-log view doesn't 404-storm on the
  1011. now-deleted thumbnail file."""
  1012. from sqlalchemy import select
  1013. from backend.app.models.print_log import PrintLogEntry
  1014. printer = await printer_factory()
  1015. archive = await archive_factory(
  1016. printer.id,
  1017. status="completed",
  1018. thumbnail_path="archives/test/test_print/thumbnail.png",
  1019. )
  1020. # The factory's auto-PrintLogEntry doesn't copy thumbnail_path; set it
  1021. # manually to mirror what the production write_log_entry path stores.
  1022. run_query = await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  1023. run = run_query.scalar_one()
  1024. run.thumbnail_path = "archives/test/test_print/thumbnail.png"
  1025. await db_session.commit()
  1026. assert run.thumbnail_path is not None
  1027. resp = await async_client.delete(f"/api/v1/archives/{archive.id}")
  1028. assert resp.status_code == 200
  1029. assert resp.json()["purged_from_stats"] is False
  1030. await db_session.refresh(run)
  1031. assert run.thumbnail_path is None, "soft-delete must NULL thumbnail_path on linked log entry"
  1032. # The log entry itself survives the soft delete (its filament/cost
  1033. # contribution still needs to flow into stats per #1343).
  1034. assert run.id is not None
  1035. assert run.archive_id == archive.id
  1036. @pytest.mark.asyncio
  1037. @pytest.mark.integration
  1038. async def test_hard_delete_clears_thumbnail_path_before_fk_cascade(
  1039. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1040. ):
  1041. """#1348 follow-up: the auto-purge sweeper (and any caller of
  1042. ArchiveService.delete_archive) hard-deletes the archive row but leaves
  1043. PrintLogEntry rows alive via ON DELETE SET NULL. The eager
  1044. thumbnail_path clear must run inside delete_archive so even orphaned
  1045. log entries don't surface stale paths."""
  1046. from sqlalchemy import select
  1047. from backend.app.models.print_log import PrintLogEntry
  1048. from backend.app.services.archive import ArchiveService
  1049. printer = await printer_factory()
  1050. archive = await archive_factory(
  1051. printer.id,
  1052. status="completed",
  1053. thumbnail_path="archives/test/test_print/thumbnail.png",
  1054. )
  1055. run_query = await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  1056. run = run_query.scalar_one()
  1057. run.thumbnail_path = "archives/test/test_print/thumbnail.png"
  1058. await db_session.commit()
  1059. run_id = run.id
  1060. service = ArchiveService(db_session)
  1061. assert await service.delete_archive(archive.id) is True
  1062. # Log entry survives the hard-delete (the FK is ON DELETE SET NULL
  1063. # in production; SQLite test config doesn't enable foreign_keys=ON
  1064. # by default so archive_id may still be set, but the row itself
  1065. # remains for audit). The thumbnail_path was cleared eagerly by
  1066. # _null_print_log_thumbnail_paths before db.delete(archive).
  1067. refetch = await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.id == run_id))
  1068. survivor = refetch.scalar_one()
  1069. assert survivor.thumbnail_path is None, (
  1070. "delete_archive must NULL thumbnail_path before removing the archive row"
  1071. )
  1072. @pytest.mark.asyncio
  1073. @pytest.mark.integration
  1074. async def test_print_log_thumbnail_route_lazy_nulls_missing_file(
  1075. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1076. ):
  1077. """#1348 follow-up: GET /print-log/{id}/thumbnail self-heals when the
  1078. thumbnail_path on a log entry points at a missing file (failed print
  1079. whose thumbnail was never written, or a stale path that escaped the
  1080. delete-time cleanup)."""
  1081. from sqlalchemy import select
  1082. from backend.app.models.print_log import PrintLogEntry
  1083. printer = await printer_factory()
  1084. archive = await archive_factory(printer.id, status="failed")
  1085. run_query = await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  1086. run = run_query.scalar_one()
  1087. # Path points at a file that never existed (failed-print case where
  1088. # archive.thumbnail_path was set but the extractor never produced one).
  1089. run.thumbnail_path = "archives/missing/never_written/thumbnail.png"
  1090. await db_session.commit()
  1091. # Auth is disabled in the integration test config, so the stream-token
  1092. # guard is bypassed — the route runs the lazy-NULL branch directly.
  1093. resp = await async_client.get(f"/api/v1/print-log/{run.id}/thumbnail")
  1094. assert resp.status_code == 404
  1095. await db_session.refresh(run)
  1096. assert run.thumbnail_path is None, "missing file must self-heal to NULL"
  1097. @pytest.mark.asyncio
  1098. @pytest.mark.integration
  1099. async def test_purge_stats_drops_archive_from_quick_stats(
  1100. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1101. ):
  1102. """#1343: deleting with ``?purge_stats=true`` hard-deletes the row,
  1103. dropping its contribution from Quick Stats (the original behaviour,
  1104. now opt-in)."""
  1105. printer = await printer_factory()
  1106. keep = await archive_factory(printer.id, status="completed", filament_used_grams=50.0)
  1107. purge = await archive_factory(printer.id, status="completed", filament_used_grams=100.0)
  1108. resp = await async_client.delete(f"/api/v1/archives/{purge.id}?purge_stats=true")
  1109. assert resp.status_code == 200
  1110. assert resp.json()["purged_from_stats"] is True
  1111. stats = (await async_client.get("/api/v1/archives/stats")).json()
  1112. assert stats["total_prints"] == 1
  1113. assert stats["total_filament_grams"] == 50.0
  1114. # The kept archive is still listed.
  1115. listing = (await async_client.get("/api/v1/archives/")).json()
  1116. assert [a["id"] for a in listing] == [keep.id]
  1117. @pytest.mark.asyncio
  1118. @pytest.mark.integration
  1119. async def test_soft_deleted_archive_404_on_detail(
  1120. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1121. ):
  1122. """A soft-deleted archive must 404 on GET — a stale bookmark or
  1123. direct URL should not expose a row the user has already removed."""
  1124. printer = await printer_factory()
  1125. archive = await archive_factory(printer.id)
  1126. await async_client.delete(f"/api/v1/archives/{archive.id}")
  1127. resp = await async_client.get(f"/api/v1/archives/{archive.id}")
  1128. assert resp.status_code == 404
  1129. @pytest.mark.asyncio
  1130. @pytest.mark.integration
  1131. async def test_soft_deleted_archive_hidden_from_search(
  1132. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1133. ):
  1134. """Search must skip soft-deleted archives. Uses the LIKE fallback by
  1135. querying a single-character pattern that the SQLite FTS5 rejects, so
  1136. the test covers the fallback path that the production FTS path also
  1137. respects."""
  1138. printer = await printer_factory()
  1139. archive = await archive_factory(printer.id, print_name="UniqueSoftDeleteCandidate")
  1140. await async_client.delete(f"/api/v1/archives/{archive.id}")
  1141. resp = await async_client.get("/api/v1/archives/search?q=UniqueSoftDeleteCandidate")
  1142. assert resp.status_code == 200
  1143. assert resp.json() == []
  1144. # ========================================================================
  1145. # Statistics endpoints
  1146. # ========================================================================
  1147. @pytest.mark.asyncio
  1148. @pytest.mark.integration
  1149. async def test_get_archive_stats(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  1150. """Verify archive statistics can be retrieved."""
  1151. printer = await printer_factory()
  1152. await archive_factory(
  1153. printer.id,
  1154. status="completed",
  1155. print_time_seconds=3600,
  1156. filament_used_grams=50.0,
  1157. )
  1158. await archive_factory(
  1159. printer.id,
  1160. status="completed",
  1161. print_time_seconds=7200,
  1162. filament_used_grams=100.0,
  1163. )
  1164. response = await async_client.get("/api/v1/archives/stats")
  1165. assert response.status_code == 200
  1166. result = response.json()
  1167. # Check for actual stats fields
  1168. assert "total_prints" in result
  1169. assert "successful_prints" in result
  1170. class TestNo3MFWarning:
  1171. """`GET /archives/no-3mf-warning` — install step 4 reactive nudge.
  1172. The connection diagnostic's external_storage check only catches the
  1173. printer-side variant of the setting (newer firmware). For older slicers
  1174. where the toggle lives only in BambuStudio, the printer never reports
  1175. it. The fallback path in main.py creates the archive with
  1176. extra_data.no_3mf_available=True; this endpoint exposes that as a
  1177. boolean so the frontend can surface a one-time banner.
  1178. """
  1179. @pytest.mark.asyncio
  1180. @pytest.mark.integration
  1181. async def test_returns_true_when_recent_fallback_exists(
  1182. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1183. ):
  1184. printer = await printer_factory()
  1185. await archive_factory(printer.id, extra_data={"no_3mf_available": True})
  1186. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  1187. assert response.status_code == 200
  1188. assert response.json() == {"has_fallback": True, "reason": None}
  1189. @pytest.mark.asyncio
  1190. @pytest.mark.integration
  1191. async def test_returns_false_when_no_archives(self, async_client: AsyncClient):
  1192. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  1193. assert response.status_code == 200
  1194. assert response.json() == {"has_fallback": False, "reason": None}
  1195. @pytest.mark.asyncio
  1196. @pytest.mark.integration
  1197. async def test_returns_false_when_only_normal_archives(
  1198. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1199. ):
  1200. printer = await printer_factory()
  1201. # extra_data has other keys but no_3mf_available is absent — normal
  1202. # archives must not trigger the nudge.
  1203. await archive_factory(printer.id, extra_data={"makerworld_url": "https://example"})
  1204. await archive_factory(printer.id, extra_data=None)
  1205. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  1206. assert response.status_code == 200
  1207. assert response.json() == {"has_fallback": False, "reason": None}
  1208. @pytest.mark.asyncio
  1209. @pytest.mark.integration
  1210. async def test_ignores_archives_older_than_30_days(
  1211. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1212. ):
  1213. from datetime import datetime, timedelta, timezone
  1214. from backend.app.models.archive import PrintArchive
  1215. printer = await printer_factory()
  1216. archive = await archive_factory(printer.id, extra_data={"no_3mf_available": True})
  1217. # Backdate past the 30-day window — old fallbacks are forgiven.
  1218. archive.created_at = datetime.now(timezone.utc) - timedelta(days=45)
  1219. await db_session.commit()
  1220. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  1221. assert response.status_code == 200
  1222. assert response.json() == {"has_fallback": False, "reason": None}
  1223. # Sanity: row really is in the DB, we just don't surface it.
  1224. assert (await db_session.get(PrintArchive, archive.id)) is not None
  1225. @pytest.mark.asyncio
  1226. @pytest.mark.integration
  1227. async def test_ignores_soft_deleted_fallbacks(
  1228. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1229. ):
  1230. from datetime import datetime, timezone
  1231. printer = await printer_factory()
  1232. archive = await archive_factory(printer.id, extra_data={"no_3mf_available": True})
  1233. archive.deleted_at = datetime.now(timezone.utc)
  1234. await db_session.commit()
  1235. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  1236. assert response.status_code == 200
  1237. # Soft-deleted fallbacks have been actioned (user clearing the
  1238. # evidence). Stop nudging.
  1239. assert response.json() == {"has_fallback": False, "reason": None}
  1240. class TestNo3MFWarningReason:
  1241. """Which explanation the banner shows (#2780).
  1242. The endpoint used to return a bare boolean and the banner had one wording:
  1243. "Store sent files on external storage" is off in the slicer, go turn it on.
  1244. For H2-series and P2S that is wrong twice over -- the setting is already on
  1245. and turning it on changes nothing, because the printer keeps the file on
  1246. internal storage FTPS does not serve. Sending people to re-do a step that
  1247. cannot help is worse than saying nothing, so the reason travels with the
  1248. flag.
  1249. """
  1250. @pytest.mark.asyncio
  1251. @pytest.mark.integration
  1252. async def test_internal_storage_is_reported(
  1253. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1254. ):
  1255. printer = await printer_factory()
  1256. await archive_factory(
  1257. printer.id,
  1258. extra_data={"no_3mf_available": True, "no_3mf_reason": "internal_storage"},
  1259. )
  1260. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  1261. assert response.json() == {"has_fallback": True, "reason": "internal_storage"}
  1262. @pytest.mark.asyncio
  1263. @pytest.mark.integration
  1264. async def test_an_empty_slot_is_reported(
  1265. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1266. ):
  1267. printer = await printer_factory()
  1268. await archive_factory(
  1269. printer.id,
  1270. extra_data={"no_3mf_available": True, "no_3mf_reason": "no_external_storage"},
  1271. )
  1272. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  1273. assert response.json() == {"has_fallback": True, "reason": "no_external_storage"}
  1274. @pytest.mark.asyncio
  1275. @pytest.mark.integration
  1276. async def test_a_known_reason_outranks_archives_that_carry_none(
  1277. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1278. ):
  1279. """Every archive written before this field exists carries no reason,
  1280. and a farm usually has more than one printer. One H2C among four
  1281. printers should still get the H2C explanation rather than have it
  1282. drowned out by older rows.
  1283. """
  1284. printer = await printer_factory()
  1285. await archive_factory(printer.id, extra_data={"no_3mf_available": True})
  1286. await archive_factory(printer.id, extra_data={"no_3mf_available": True, "no_3mf_reason": "internal_storage"})
  1287. await archive_factory(printer.id, extra_data={"no_3mf_available": True})
  1288. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  1289. assert response.json() == {"has_fallback": True, "reason": "internal_storage"}
  1290. @pytest.mark.asyncio
  1291. @pytest.mark.integration
  1292. async def test_internal_storage_outranks_an_empty_slot(
  1293. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1294. ):
  1295. """Both are real, and only one of them is surprising. "Put a card in"
  1296. is advice the user can act on unprompted; "this model keeps prints
  1297. somewhere Bambuddy cannot read" is the one they need told.
  1298. """
  1299. printer = await printer_factory()
  1300. await archive_factory(printer.id, extra_data={"no_3mf_available": True, "no_3mf_reason": "no_external_storage"})
  1301. await archive_factory(printer.id, extra_data={"no_3mf_available": True, "no_3mf_reason": "internal_storage"})
  1302. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  1303. assert response.json() == {"has_fallback": True, "reason": "internal_storage"}
  1304. @pytest.mark.asyncio
  1305. @pytest.mark.integration
  1306. async def test_a_reason_on_a_non_fallback_archive_is_not_reported(
  1307. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1308. ):
  1309. """The reason only means anything alongside the flag it explains."""
  1310. printer = await printer_factory()
  1311. await archive_factory(printer.id, extra_data={"no_3mf_reason": "internal_storage"})
  1312. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  1313. assert response.json() == {"has_fallback": False, "reason": None}
  1314. @pytest.mark.asyncio
  1315. @pytest.mark.integration
  1316. async def test_a_refused_handshake_is_reported(
  1317. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1318. ):
  1319. """#2957 stamps this slug and #2780 never taught the banner about it, so
  1320. an install whose only empty archives came from a printer refusing TLS on
  1321. port 990 was told the slicer had not written the file to the card. The
  1322. slicer had; nothing could read it back. The reporter could see the file
  1323. on the stick from his own computer, which is exactly why the advice read
  1324. as Bambuddy being broken.
  1325. """
  1326. printer = await printer_factory()
  1327. await archive_factory(
  1328. printer.id,
  1329. extra_data={"no_3mf_available": True, "no_3mf_reason": "ftps_cooloff"},
  1330. )
  1331. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  1332. assert response.json() == {"has_fallback": True, "reason": "ftps_cooloff"}
  1333. @pytest.mark.asyncio
  1334. @pytest.mark.integration
  1335. async def test_a_refused_handshake_outranks_every_settled_cause(
  1336. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1337. ):
  1338. """The other three describe an install working as configured. This one
  1339. reports a printer doing something we cannot yet explain, and the banner
  1340. dismisses one-shot into localStorage -- so a reason ranked below another
  1341. is not deferred, it is never shown to that user at all.
  1342. """
  1343. printer = await printer_factory()
  1344. for reason in ("internal_storage", "no_external_storage", "internal_history"):
  1345. await archive_factory(printer.id, extra_data={"no_3mf_available": True, "no_3mf_reason": reason})
  1346. await archive_factory(printer.id, extra_data={"no_3mf_available": True, "no_3mf_reason": "ftps_cooloff"})
  1347. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  1348. assert response.json() == {"has_fallback": True, "reason": "ftps_cooloff"}
  1349. @pytest.mark.asyncio
  1350. @pytest.mark.integration
  1351. async def test_the_settled_causes_keep_their_order_behind_it(
  1352. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1353. ):
  1354. """Adding a new leader must not disturb the ranking underneath it: an
  1355. install with no refused handshake still gets exactly what it got before.
  1356. """
  1357. printer = await printer_factory()
  1358. await archive_factory(printer.id, extra_data={"no_3mf_available": True, "no_3mf_reason": "internal_history"})
  1359. await archive_factory(printer.id, extra_data={"no_3mf_available": True, "no_3mf_reason": "no_external_storage"})
  1360. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  1361. assert response.json() == {"has_fallback": True, "reason": "no_external_storage"}
  1362. @pytest.mark.asyncio
  1363. @pytest.mark.integration
  1364. async def test_a_transfer_that_ran_out_of_time_is_reported(
  1365. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1366. ):
  1367. """#3063's P1S had the file on its card and served it three times in the
  1368. two minutes after the archive flow gave up on it. Told to switch on
  1369. "Store sent files on external storage", that reporter would be switching
  1370. on a setting that was already on and had already worked.
  1371. """
  1372. printer = await printer_factory()
  1373. await archive_factory(
  1374. printer.id,
  1375. extra_data={"no_3mf_available": True, "no_3mf_reason": "ftp_transfer_failed"},
  1376. )
  1377. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  1378. assert response.json() == {"has_fallback": True, "reason": "ftp_transfer_failed"}
  1379. @pytest.mark.asyncio
  1380. @pytest.mark.integration
  1381. async def test_a_slow_transfer_outranks_the_settled_causes_but_not_a_refused_handshake(
  1382. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1383. ):
  1384. """Both temporary causes describe a file still sitting on the card, so
  1385. both outrank the three that describe an install working as configured.
  1386. Between the two, a printer that will not complete a TLS handshake is the
  1387. worse fault and keeps the banner.
  1388. """
  1389. printer = await printer_factory()
  1390. for reason in ("internal_storage", "no_external_storage", "internal_history"):
  1391. await archive_factory(printer.id, extra_data={"no_3mf_available": True, "no_3mf_reason": reason})
  1392. await archive_factory(printer.id, extra_data={"no_3mf_available": True, "no_3mf_reason": "ftp_transfer_failed"})
  1393. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  1394. assert response.json() == {"has_fallback": True, "reason": "ftp_transfer_failed"}
  1395. await archive_factory(printer.id, extra_data={"no_3mf_available": True, "no_3mf_reason": "ftps_cooloff"})
  1396. response = await async_client.get("/api/v1/archives/no-3mf-warning")
  1397. assert response.json() == {"has_fallback": True, "reason": "ftps_cooloff"}
  1398. class TestPrintLogEntryDelete:
  1399. """#1687: per-row delete on the Print Log page.
  1400. Pin the route's three contracts: (1) deleting a row drops its filament
  1401. / cost / count contribution from /archives/stats in the same response
  1402. cycle; (2) the matching archive (if any) is untouched; (3) missing IDs
  1403. return 404 rather than 200-silently.
  1404. """
  1405. @pytest.mark.asyncio
  1406. @pytest.mark.integration
  1407. async def test_delete_print_log_entry_drops_from_stats(
  1408. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1409. ):
  1410. from sqlalchemy import select
  1411. from backend.app.models.print_log import PrintLogEntry
  1412. printer = await printer_factory()
  1413. keep = await archive_factory(printer.id, status="completed", filament_used_grams=50.0)
  1414. drop = await archive_factory(printer.id, status="completed", filament_used_grams=125.0)
  1415. drop_run = (
  1416. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == drop.id))
  1417. ).scalar_one()
  1418. resp = await async_client.delete(f"/api/v1/print-log/{drop_run.id}")
  1419. assert resp.status_code == 200
  1420. assert resp.json()["status"] == "deleted"
  1421. assert resp.json()["id"] == drop_run.id
  1422. # The linked archive survives — the row was a stats row, not the archive.
  1423. listing = (await async_client.get("/api/v1/archives/")).json()
  1424. assert {a["id"] for a in listing} == {keep.id, drop.id}
  1425. # /stats no longer counts the dropped run's filament contribution.
  1426. stats = (await async_client.get("/api/v1/archives/stats")).json()
  1427. assert stats["total_prints"] == 1
  1428. assert stats["total_filament_grams"] == 50.0
  1429. @pytest.mark.asyncio
  1430. @pytest.mark.integration
  1431. async def test_delete_print_log_entry_404_when_missing(self, async_client: AsyncClient):
  1432. resp = await async_client.delete("/api/v1/print-log/999999")
  1433. assert resp.status_code == 404
  1434. @pytest.mark.asyncio
  1435. @pytest.mark.integration
  1436. async def test_delete_print_log_entry_does_not_clear_others(
  1437. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1438. ):
  1439. """Deleting one row must not touch siblings — guard against an accidental
  1440. ``delete(PrintLogEntry)`` without a ``where`` clause (cf. clear_print_log
  1441. which intentionally drops everything)."""
  1442. from sqlalchemy import select
  1443. from backend.app.models.print_log import PrintLogEntry
  1444. printer = await printer_factory()
  1445. a = await archive_factory(printer.id, status="completed", filament_used_grams=10.0)
  1446. b = await archive_factory(printer.id, status="completed", filament_used_grams=20.0)
  1447. c = await archive_factory(printer.id, status="completed", filament_used_grams=30.0)
  1448. runs = {r.archive_id: r for r in (await db_session.execute(select(PrintLogEntry))).scalars().all()}
  1449. resp = await async_client.delete(f"/api/v1/print-log/{runs[b.id].id}")
  1450. assert resp.status_code == 200
  1451. survivors = (await db_session.execute(select(PrintLogEntry.archive_id))).scalars().all()
  1452. assert set(survivors) == {a.id, c.id}
  1453. class TestPrintLogEntryUpdate:
  1454. """Tests for ``PATCH /print-log/{entry_id}`` (#1687 part 4).
  1455. Pin the route's contracts: (1) GET serialiser actually surfaces
  1456. ``failure_reason`` (previously it was silently dropped from the response
  1457. even when set in the DB); (2) PATCH persists ``failure_reason`` and
  1458. ``status``; (3) unknown vocabulary returns 400 rather than getting stored
  1459. as raw garbage; (4) missing IDs return 404.
  1460. """
  1461. @pytest.mark.asyncio
  1462. @pytest.mark.integration
  1463. async def test_get_surfaces_failure_reason(
  1464. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1465. ):
  1466. """Pre-fix the GET endpoint built PrintLogEntrySchema without
  1467. ``failure_reason`` even though the column was populated, so the Print
  1468. Log table couldn't render what the Failure Analysis widget already
  1469. groups by. Regression guard for the silent-drop bug.
  1470. """
  1471. from sqlalchemy import select
  1472. from backend.app.models.print_log import PrintLogEntry
  1473. printer = await printer_factory()
  1474. archive = await archive_factory(printer.id, status="failed")
  1475. entry = (
  1476. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  1477. ).scalar_one()
  1478. entry.failure_reason = "spaghettiDetached"
  1479. await db_session.commit()
  1480. body = (await async_client.get("/api/v1/print-log/")).json()
  1481. match = next(item for item in body["items"] if item["id"] == entry.id)
  1482. assert match["failure_reason"] == "spaghettiDetached"
  1483. # archive_id should also flow through so the frontend can tell orphan
  1484. # entries apart from archive-linked ones.
  1485. assert match["archive_id"] == archive.id
  1486. @pytest.mark.asyncio
  1487. @pytest.mark.integration
  1488. async def test_patch_sets_failure_reason(
  1489. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1490. ):
  1491. from sqlalchemy import select
  1492. from backend.app.models.print_log import PrintLogEntry
  1493. printer = await printer_factory()
  1494. archive = await archive_factory(printer.id, status="failed")
  1495. entry = (
  1496. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  1497. ).scalar_one()
  1498. assert entry.failure_reason is None
  1499. resp = await async_client.patch(
  1500. f"/api/v1/print-log/{entry.id}",
  1501. json={"failure_reason": "cloggedNozzle"},
  1502. )
  1503. assert resp.status_code == 200
  1504. assert resp.json()["failure_reason"] == "cloggedNozzle"
  1505. await db_session.refresh(entry)
  1506. assert entry.failure_reason == "cloggedNozzle"
  1507. @pytest.mark.asyncio
  1508. @pytest.mark.integration
  1509. async def test_patch_can_clear_failure_reason(
  1510. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1511. ):
  1512. """Empty-string failure_reason stores back as NULL (the column's
  1513. nullable=True intent is preserved end-to-end)."""
  1514. from sqlalchemy import select
  1515. from backend.app.models.print_log import PrintLogEntry
  1516. printer = await printer_factory()
  1517. archive = await archive_factory(printer.id, status="failed")
  1518. entry = (
  1519. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  1520. ).scalar_one()
  1521. entry.failure_reason = "warping"
  1522. await db_session.commit()
  1523. resp = await async_client.patch(
  1524. f"/api/v1/print-log/{entry.id}",
  1525. json={"failure_reason": ""},
  1526. )
  1527. assert resp.status_code == 200
  1528. assert resp.json()["failure_reason"] is None
  1529. await db_session.refresh(entry)
  1530. assert entry.failure_reason is None
  1531. @pytest.mark.asyncio
  1532. @pytest.mark.integration
  1533. async def test_patch_rejects_unknown_failure_reason(
  1534. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1535. ):
  1536. """Unknown values must 400 — otherwise the UI would render raw garbage
  1537. because the i18n layer maps the value back through the canonical
  1538. vocabulary."""
  1539. from sqlalchemy import select
  1540. from backend.app.models.print_log import PrintLogEntry
  1541. printer = await printer_factory()
  1542. archive = await archive_factory(printer.id, status="failed")
  1543. entry = (
  1544. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  1545. ).scalar_one()
  1546. resp = await async_client.patch(
  1547. f"/api/v1/print-log/{entry.id}",
  1548. json={"failure_reason": "completely-made-up"},
  1549. )
  1550. assert resp.status_code == 400
  1551. @pytest.mark.asyncio
  1552. @pytest.mark.integration
  1553. async def test_patch_updates_status(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  1554. from sqlalchemy import select
  1555. from backend.app.models.print_log import PrintLogEntry
  1556. printer = await printer_factory()
  1557. archive = await archive_factory(printer.id, status="completed")
  1558. entry = (
  1559. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  1560. ).scalar_one()
  1561. entry.status = "completed"
  1562. await db_session.commit()
  1563. resp = await async_client.patch(
  1564. f"/api/v1/print-log/{entry.id}",
  1565. json={"status": "failed", "failure_reason": "layerShift"},
  1566. )
  1567. assert resp.status_code == 200
  1568. assert resp.json()["status"] == "failed"
  1569. assert resp.json()["failure_reason"] == "layerShift"
  1570. @pytest.mark.asyncio
  1571. @pytest.mark.integration
  1572. async def test_patch_rejects_unknown_status(
  1573. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1574. ):
  1575. from sqlalchemy import select
  1576. from backend.app.models.print_log import PrintLogEntry
  1577. printer = await printer_factory()
  1578. archive = await archive_factory(printer.id, status="failed")
  1579. entry = (
  1580. await db_session.execute(select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id))
  1581. ).scalar_one()
  1582. resp = await async_client.patch(
  1583. f"/api/v1/print-log/{entry.id}",
  1584. json={"status": "bogus-status"},
  1585. )
  1586. assert resp.status_code == 400
  1587. @pytest.mark.asyncio
  1588. @pytest.mark.integration
  1589. async def test_patch_404_when_missing(self, async_client: AsyncClient):
  1590. resp = await async_client.patch(
  1591. "/api/v1/print-log/999999",
  1592. json={"failure_reason": "cloggedNozzle"},
  1593. )
  1594. assert resp.status_code == 404
  1595. @pytest.mark.asyncio
  1596. @pytest.mark.integration
  1597. async def test_patch_works_on_orphan_entry(self, async_client: AsyncClient, printer_factory, db_session):
  1598. """Orphan log entries (no archive_id) are the actual reason this
  1599. endpoint exists — the Archive Edit modal can't reach them. Make sure
  1600. the PATCH works for those rows specifically."""
  1601. from backend.app.models.print_log import PrintLogEntry
  1602. printer = await printer_factory()
  1603. orphan = PrintLogEntry(
  1604. archive_id=None,
  1605. print_name="failed-before-archive-created",
  1606. printer_id=printer.id,
  1607. status="failed",
  1608. failure_reason=None,
  1609. )
  1610. db_session.add(orphan)
  1611. await db_session.commit()
  1612. await db_session.refresh(orphan)
  1613. assert orphan.archive_id is None
  1614. resp = await async_client.patch(
  1615. f"/api/v1/print-log/{orphan.id}",
  1616. json={"failure_reason": "powerFailure"},
  1617. )
  1618. assert resp.status_code == 200
  1619. assert resp.json()["failure_reason"] == "powerFailure"
  1620. assert resp.json()["archive_id"] is None
  1621. class TestArchivesSlimAPI:
  1622. """Integration tests for /api/v1/archives/slim endpoint."""
  1623. @pytest.mark.asyncio
  1624. @pytest.mark.integration
  1625. async def test_slim_empty(self, async_client: AsyncClient):
  1626. """Verify empty list when no archives exist."""
  1627. response = await async_client.get("/api/v1/archives/slim")
  1628. assert response.status_code == 200
  1629. assert response.json() == []
  1630. @pytest.mark.asyncio
  1631. @pytest.mark.integration
  1632. async def test_slim_returns_only_expected_fields(
  1633. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1634. ):
  1635. """Verify response contains only slim fields, not full archive data."""
  1636. printer = await printer_factory()
  1637. await archive_factory(
  1638. printer.id,
  1639. print_name="Slim Test",
  1640. status="completed",
  1641. filament_type="PLA",
  1642. filament_color="#FF0000",
  1643. filament_used_grams=50.0,
  1644. print_time_seconds=3600,
  1645. cost=1.50,
  1646. quantity=2,
  1647. )
  1648. response = await async_client.get("/api/v1/archives/slim")
  1649. assert response.status_code == 200
  1650. data = response.json()
  1651. assert len(data) == 1
  1652. item = data[0]
  1653. # Expected fields present
  1654. assert item["printer_id"] == printer.id
  1655. assert item["print_name"] == "Slim Test"
  1656. assert item["status"] == "completed"
  1657. assert item["filament_type"] == "PLA"
  1658. assert item["filament_color"] == "#FF0000"
  1659. assert item["filament_used_grams"] == 50.0
  1660. assert item["print_time_seconds"] == 3600
  1661. assert item["cost"] == 1.50
  1662. # quantity is per-event semantics now (each PrintLogEntry = one run);
  1663. # the archive's quantity field is no longer surfaced through this
  1664. # endpoint after the #1390 per-event migration.
  1665. assert item["quantity"] == 1
  1666. assert "created_at" in item
  1667. # Full archive fields must NOT be present
  1668. assert "id" not in item
  1669. assert "filename" not in item
  1670. assert "file_path" not in item
  1671. assert "file_size" not in item
  1672. assert "extra_data" not in item
  1673. assert "notes" not in item
  1674. assert "tags" not in item
  1675. assert "photos" not in item
  1676. assert "thumbnail_path" not in item
  1677. assert "content_hash" not in item
  1678. assert "duplicates" not in item
  1679. assert "duplicate_count" not in item
  1680. @pytest.mark.asyncio
  1681. @pytest.mark.integration
  1682. async def test_slim_includes_energy_fields(
  1683. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1684. ):
  1685. """Per-print smart-plug energy surfaces through /slim so the stats
  1686. page can include it in cost records and trends (#1432)."""
  1687. printer = await printer_factory()
  1688. await archive_factory(
  1689. printer.id,
  1690. status="completed",
  1691. cost=1.50,
  1692. energy_kwh=0.421,
  1693. energy_cost=0.063,
  1694. )
  1695. response = await async_client.get("/api/v1/archives/slim")
  1696. assert response.status_code == 200
  1697. item = response.json()[0]
  1698. assert item["energy_kwh"] == 0.421
  1699. assert item["energy_cost"] == 0.063
  1700. @pytest.mark.asyncio
  1701. @pytest.mark.integration
  1702. async def test_slim_computes_actual_time(
  1703. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1704. ):
  1705. """Verify actual_time_seconds is computed from started_at/completed_at."""
  1706. from datetime import datetime, timezone
  1707. printer = await printer_factory()
  1708. started = datetime(2024, 1, 1, 10, 0, 0, tzinfo=timezone.utc)
  1709. completed = datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc) # 2 hours = 7200s
  1710. await archive_factory(
  1711. printer.id,
  1712. status="completed",
  1713. started_at=started,
  1714. completed_at=completed,
  1715. )
  1716. response = await async_client.get("/api/v1/archives/slim")
  1717. assert response.status_code == 200
  1718. item = response.json()[0]
  1719. assert item["actual_time_seconds"] == 7200
  1720. @pytest.mark.asyncio
  1721. @pytest.mark.integration
  1722. async def test_slim_actual_time_for_failed_includes_elapsed(
  1723. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1724. ):
  1725. """Failed prints report measured elapsed time so Printer Stats By Time
  1726. matches Quick Stats Print Time (#1390). Previously this returned null
  1727. and the frontend fell back to the slicer estimate, double-counting the
  1728. unfinished portion of the print."""
  1729. from datetime import datetime, timezone
  1730. printer = await printer_factory()
  1731. await archive_factory(
  1732. printer.id,
  1733. status="failed",
  1734. started_at=datetime(2024, 1, 1, 10, 0, 0, tzinfo=timezone.utc),
  1735. completed_at=datetime(2024, 1, 1, 11, 0, 0, tzinfo=timezone.utc),
  1736. )
  1737. response = await async_client.get("/api/v1/archives/slim")
  1738. assert response.status_code == 200
  1739. item = response.json()[0]
  1740. assert item["actual_time_seconds"] == 3600
  1741. @pytest.mark.asyncio
  1742. @pytest.mark.integration
  1743. async def test_slim_date_filtering(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  1744. """Verify date_from and date_to filters work."""
  1745. from datetime import datetime, timezone
  1746. printer = await printer_factory()
  1747. await archive_factory(
  1748. printer.id,
  1749. print_name="Old Print",
  1750. created_at=datetime(2024, 1, 1, tzinfo=timezone.utc),
  1751. )
  1752. await archive_factory(
  1753. printer.id,
  1754. print_name="New Print",
  1755. created_at=datetime(2024, 6, 15, tzinfo=timezone.utc),
  1756. )
  1757. # Filter to only June 2024
  1758. response = await async_client.get("/api/v1/archives/slim?date_from=2024-06-01&date_to=2024-06-30")
  1759. assert response.status_code == 200
  1760. data = response.json()
  1761. assert len(data) == 1
  1762. assert data[0]["print_name"] == "New Print"
  1763. @pytest.mark.asyncio
  1764. @pytest.mark.integration
  1765. async def test_slim_pagination(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  1766. """Verify limit and offset work."""
  1767. printer = await printer_factory()
  1768. for i in range(5):
  1769. await archive_factory(printer.id, print_name=f"Print {i}")
  1770. response = await async_client.get("/api/v1/archives/slim?limit=2&offset=0")
  1771. assert response.status_code == 200
  1772. assert len(response.json()) == 2
  1773. @pytest.mark.asyncio
  1774. @pytest.mark.integration
  1775. async def test_slim_counts_reprints_as_separate_rows(
  1776. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1777. ):
  1778. """Reprints add events even though the archive row is overwritten (#1390).
  1779. Before the per-event migration, /archives/slim returned one row per
  1780. archive — so an archive that had been reprinted three times appeared
  1781. once and undercounted Filament Used / Cost / Time. The endpoint must
  1782. now return one row per logged event.
  1783. """
  1784. from backend.app.models.print_log import PrintLogEntry
  1785. printer = await printer_factory()
  1786. archive = await archive_factory(
  1787. printer.id,
  1788. print_name="Reprinted Model",
  1789. filament_used_grams=50.0,
  1790. cost=1.50,
  1791. )
  1792. # archive_factory synthesizes one event; add two more to simulate
  1793. # the same archive being reprinted twice more.
  1794. for _ in range(2):
  1795. db_session.add(
  1796. PrintLogEntry(
  1797. archive_id=archive.id,
  1798. printer_id=archive.printer_id,
  1799. status="completed",
  1800. filament_type=archive.filament_type,
  1801. filament_used_grams=archive.filament_used_grams,
  1802. cost=archive.cost,
  1803. print_name=archive.print_name,
  1804. )
  1805. )
  1806. await db_session.commit()
  1807. response = await async_client.get("/api/v1/archives/slim")
  1808. assert response.status_code == 200
  1809. data = response.json()
  1810. assert len(data) == 3, "Each reprint must contribute one row"
  1811. total_filament = sum(item["filament_used_grams"] or 0 for item in data)
  1812. assert total_filament == 150.0, "Sum across events must reflect all three runs"
  1813. @pytest.mark.asyncio
  1814. @pytest.mark.integration
  1815. async def test_slim_includes_orphan_events(self, async_client: AsyncClient, printer_factory, db_session):
  1816. """Events whose archive was hard-deleted still appear (#1390).
  1817. After ON DELETE SET NULL the event row survives with archive_id=NULL.
  1818. The slim endpoint must keep counting it so Quick Stats and the
  1819. archive-iterating widgets stay aligned.
  1820. """
  1821. from backend.app.models.print_log import PrintLogEntry
  1822. printer = await printer_factory()
  1823. db_session.add(
  1824. PrintLogEntry(
  1825. archive_id=None,
  1826. printer_id=printer.id,
  1827. status="completed",
  1828. filament_type="PETG",
  1829. filament_used_grams=25.0,
  1830. cost=0.75,
  1831. print_name="Orphaned Print",
  1832. )
  1833. )
  1834. await db_session.commit()
  1835. response = await async_client.get("/api/v1/archives/slim")
  1836. assert response.status_code == 200
  1837. data = response.json()
  1838. assert len(data) == 1
  1839. assert data[0]["print_name"] == "Orphaned Print"
  1840. assert data[0]["filament_used_grams"] == 25.0
  1841. # print_time_seconds (sliced estimate) comes from the archive table,
  1842. # which orphans no longer have — must surface as null gracefully.
  1843. assert data[0]["print_time_seconds"] is None
  1844. class TestFailureAnalysisAPI:
  1845. """Per-event failure analysis (#1390)."""
  1846. @pytest.mark.asyncio
  1847. @pytest.mark.integration
  1848. async def test_failure_analysis_counts_reprints_and_orphans(
  1849. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1850. ):
  1851. """Failure analysis aggregates per event, not per archive.
  1852. Verifies the dual fix for #1390: a reprint that adds a second failed
  1853. event must count twice, and an orphan failed event (archive deleted)
  1854. must still appear in the totals.
  1855. """
  1856. from backend.app.models.print_log import PrintLogEntry
  1857. printer = await printer_factory()
  1858. archive = await archive_factory(
  1859. printer.id,
  1860. print_name="Failing Model",
  1861. status="failed",
  1862. failure_reason="filament_runout",
  1863. )
  1864. # Add a second failed event for the same archive (a reprint that also
  1865. # failed) and one orphan failed event (archive was deleted).
  1866. db_session.add(
  1867. PrintLogEntry(
  1868. archive_id=archive.id,
  1869. printer_id=printer.id,
  1870. status="failed",
  1871. failure_reason="filament_runout",
  1872. filament_type=archive.filament_type,
  1873. print_name=archive.print_name,
  1874. )
  1875. )
  1876. db_session.add(
  1877. PrintLogEntry(
  1878. archive_id=None,
  1879. printer_id=printer.id,
  1880. status="failed",
  1881. failure_reason="bed_adhesion",
  1882. filament_type="PETG",
  1883. print_name="Orphaned Failed Print",
  1884. )
  1885. )
  1886. await db_session.commit()
  1887. response = await async_client.get("/api/v1/archives/analysis/failures")
  1888. assert response.status_code == 200
  1889. result = response.json()
  1890. assert result["total_prints"] == 3
  1891. assert result["failed_prints"] == 3
  1892. assert result["failures_by_reason"]["filament_runout"] == 2
  1893. assert result["failures_by_reason"]["bed_adhesion"] == 1
  1894. class TestArchiveDataIntegrity:
  1895. """Tests for archive data integrity."""
  1896. @pytest.mark.asyncio
  1897. @pytest.mark.integration
  1898. async def test_archive_linked_to_printer(
  1899. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1900. ):
  1901. """Verify archive is properly linked to printer."""
  1902. printer = await printer_factory(name="My Printer")
  1903. archive = await archive_factory(printer.id)
  1904. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  1905. assert response.status_code == 200
  1906. result = response.json()
  1907. assert result["printer_id"] == printer.id
  1908. @pytest.mark.asyncio
  1909. @pytest.mark.integration
  1910. async def test_archive_stores_print_data(
  1911. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1912. ):
  1913. """Verify archive stores all print data correctly."""
  1914. printer = await printer_factory()
  1915. archive = await archive_factory(
  1916. printer.id,
  1917. print_name="Test Print",
  1918. filename="test.3mf",
  1919. status="completed",
  1920. filament_type="PLA",
  1921. filament_used_grams=75.5,
  1922. print_time_seconds=5400,
  1923. )
  1924. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  1925. assert response.status_code == 200
  1926. result = response.json()
  1927. assert result["print_name"] == "Test Print"
  1928. assert result["filename"] == "test.3mf"
  1929. assert result["status"] == "completed"
  1930. assert result["filament_type"] == "PLA"
  1931. assert result["filament_used_grams"] == 75.5
  1932. assert result["print_time_seconds"] == 5400
  1933. @pytest.mark.asyncio
  1934. @pytest.mark.integration
  1935. async def test_archive_update_persists(
  1936. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1937. ):
  1938. """CRITICAL: Verify archive updates persist."""
  1939. printer = await printer_factory()
  1940. archive = await archive_factory(printer.id, notes="Original notes")
  1941. # Update
  1942. await async_client.patch(f"/api/v1/archives/{archive.id}", json={"notes": "Updated notes", "is_favorite": True})
  1943. # Verify persistence
  1944. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  1945. result = response.json()
  1946. assert result["notes"] == "Updated notes"
  1947. assert result["is_favorite"] is True
  1948. class TestArchiveF3DEndpoints:
  1949. """Tests for F3D (Fusion 360 design file) attachment endpoints."""
  1950. @pytest.mark.asyncio
  1951. @pytest.mark.integration
  1952. async def test_archive_response_includes_f3d_path(
  1953. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1954. ):
  1955. """Verify f3d_path is included in archive response."""
  1956. printer = await printer_factory()
  1957. archive = await archive_factory(printer.id, f3d_path="archives/test/design.f3d")
  1958. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  1959. assert response.status_code == 200
  1960. result = response.json()
  1961. assert "f3d_path" in result
  1962. assert result["f3d_path"] == "archives/test/design.f3d"
  1963. @pytest.mark.asyncio
  1964. @pytest.mark.integration
  1965. async def test_archive_response_f3d_path_null_when_not_set(
  1966. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1967. ):
  1968. """Verify f3d_path is null when no F3D file attached."""
  1969. printer = await printer_factory()
  1970. archive = await archive_factory(printer.id)
  1971. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  1972. assert response.status_code == 200
  1973. result = response.json()
  1974. assert "f3d_path" in result
  1975. assert result["f3d_path"] is None
  1976. @pytest.mark.asyncio
  1977. @pytest.mark.integration
  1978. async def test_upload_f3d_to_nonexistent_archive(self, async_client: AsyncClient):
  1979. """Verify 404 when uploading F3D to non-existent archive."""
  1980. # Create a minimal file-like upload
  1981. files = {"file": ("design.f3d", b"fake f3d content", "application/octet-stream")}
  1982. response = await async_client.post("/api/v1/archives/9999/f3d", files=files)
  1983. assert response.status_code == 404
  1984. @pytest.mark.asyncio
  1985. @pytest.mark.integration
  1986. async def test_download_f3d_not_found_when_no_file(
  1987. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  1988. ):
  1989. """Verify 404 when downloading F3D from archive without F3D file."""
  1990. printer = await printer_factory()
  1991. archive = await archive_factory(printer.id)
  1992. response = await async_client.get(f"/api/v1/archives/{archive.id}/f3d")
  1993. assert response.status_code == 404
  1994. @pytest.mark.asyncio
  1995. @pytest.mark.integration
  1996. async def test_download_f3d_nonexistent_archive(self, async_client: AsyncClient):
  1997. """Verify 404 when downloading F3D from non-existent archive."""
  1998. response = await async_client.get("/api/v1/archives/9999/f3d")
  1999. assert response.status_code == 404
  2000. @pytest.mark.asyncio
  2001. @pytest.mark.integration
  2002. async def test_delete_f3d_nonexistent_archive(self, async_client: AsyncClient):
  2003. """Verify 404 when deleting F3D from non-existent archive."""
  2004. response = await async_client.delete("/api/v1/archives/9999/f3d")
  2005. assert response.status_code == 404
  2006. @pytest.mark.asyncio
  2007. @pytest.mark.integration
  2008. async def test_delete_f3d_when_no_file(
  2009. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  2010. ):
  2011. """Verify 404 when deleting F3D from archive without F3D file."""
  2012. printer = await printer_factory()
  2013. archive = await archive_factory(printer.id)
  2014. response = await async_client.delete(f"/api/v1/archives/{archive.id}/f3d")
  2015. assert response.status_code == 404
  2016. @pytest.mark.asyncio
  2017. @pytest.mark.integration
  2018. async def test_list_archives_includes_f3d_path(
  2019. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  2020. ):
  2021. """Verify f3d_path is included in archive list responses."""
  2022. printer = await printer_factory()
  2023. await archive_factory(printer.id, print_name="With F3D", f3d_path="archives/test/design.f3d")
  2024. await archive_factory(printer.id, print_name="Without F3D")
  2025. response = await async_client.get("/api/v1/archives/")
  2026. assert response.status_code == 200
  2027. data = response.json()
  2028. assert len(data) >= 2
  2029. with_f3d = next((a for a in data if a["print_name"] == "With F3D"), None)
  2030. without_f3d = next((a for a in data if a["print_name"] == "Without F3D"), None)
  2031. assert with_f3d is not None
  2032. assert with_f3d["f3d_path"] == "archives/test/design.f3d"
  2033. assert without_f3d is not None
  2034. assert without_f3d["f3d_path"] is None
  2035. # ========================================================================
  2036. # Multi-Plate 3MF endpoints (Issue #93)
  2037. # ========================================================================
  2038. @pytest.mark.asyncio
  2039. @pytest.mark.integration
  2040. async def test_get_archive_plates_not_found(self, async_client: AsyncClient):
  2041. """Verify 404 when fetching plates for non-existent archive."""
  2042. response = await async_client.get("/api/v1/archives/999999/plates")
  2043. assert response.status_code == 404
  2044. @pytest.mark.asyncio
  2045. @pytest.mark.integration
  2046. async def test_get_plate_thumbnail_not_found(self, async_client: AsyncClient):
  2047. """Verify 404 when fetching plate thumbnail for non-existent archive."""
  2048. response = await async_client.get("/api/v1/archives/999999/plate-thumbnail/1")
  2049. assert response.status_code == 404
  2050. @pytest.mark.asyncio
  2051. @pytest.mark.integration
  2052. async def test_filament_requirements_not_found(self, async_client: AsyncClient):
  2053. """Verify filament-requirements returns 404 for non-existent archive."""
  2054. response = await async_client.get("/api/v1/archives/999999/filament-requirements")
  2055. assert response.status_code == 404
  2056. @pytest.mark.asyncio
  2057. @pytest.mark.integration
  2058. async def test_filament_requirements_with_plate_id_not_found(self, async_client: AsyncClient):
  2059. """Verify filament-requirements with plate_id returns 404 for non-existent archive."""
  2060. response = await async_client.get("/api/v1/archives/999999/filament-requirements?plate_id=1")
  2061. assert response.status_code == 404
  2062. async def _two_plate_archive(self, archive_factory, printer_factory, tmp_path):
  2063. """An archive whose 3MF stores plate 2 ahead of plate 1, as Studio writes it."""
  2064. import zipfile
  2065. printer = await printer_factory()
  2066. path = tmp_path / "two_plates.gcode.3mf"
  2067. with zipfile.ZipFile(path, "w") as zf:
  2068. zf.writestr("Metadata/plate_2.gcode", "; plate two\nG28\n")
  2069. zf.writestr("Metadata/plate_1.gcode", "; plate one\nG28\n")
  2070. # An absolute file_path collapses `settings.base_dir / file_path` onto
  2071. # itself, so the route reads the file written here.
  2072. return await archive_factory(printer.id, file_path=str(path), filename="two_plates.gcode.3mf")
  2073. @pytest.mark.asyncio
  2074. @pytest.mark.integration
  2075. async def test_archive_gcode_without_a_plate_serves_the_first_plate(
  2076. self, async_client: AsyncClient, archive_factory, printer_factory, tmp_path
  2077. ):
  2078. """Zip order is whatever the slicer wrote, so the first member here is
  2079. plate 2. Callers that pass no plate must still land on plate 1."""
  2080. archive = await self._two_plate_archive(archive_factory, printer_factory, tmp_path)
  2081. response = await async_client.get(f"/api/v1/archives/{archive.id}/gcode")
  2082. assert response.status_code == 200
  2083. assert "plate one" in response.text
  2084. @pytest.mark.asyncio
  2085. @pytest.mark.integration
  2086. async def test_archive_gcode_serves_the_requested_plate(
  2087. self, async_client: AsyncClient, archive_factory, printer_factory, tmp_path
  2088. ):
  2089. archive = await self._two_plate_archive(archive_factory, printer_factory, tmp_path)
  2090. first = await async_client.get(f"/api/v1/archives/{archive.id}/gcode?plate=1")
  2091. second = await async_client.get(f"/api/v1/archives/{archive.id}/gcode?plate=2")
  2092. assert "plate one" in first.text
  2093. assert "plate two" in second.text
  2094. @pytest.mark.asyncio
  2095. @pytest.mark.integration
  2096. async def test_archive_gcode_rejects_a_plate_the_file_does_not_hold(
  2097. self, async_client: AsyncClient, archive_factory, printer_factory, tmp_path
  2098. ):
  2099. archive = await self._two_plate_archive(archive_factory, printer_factory, tmp_path)
  2100. missing = await async_client.get(f"/api/v1/archives/{archive.id}/gcode?plate=3")
  2101. zeroth = await async_client.get(f"/api/v1/archives/{archive.id}/gcode?plate=0")
  2102. assert missing.status_code == 404
  2103. assert zeroth.status_code == 400
  2104. # ========================================================================
  2105. # Tag Management endpoints (Issue #183)
  2106. # ========================================================================
  2107. @pytest.mark.asyncio
  2108. @pytest.mark.integration
  2109. async def test_get_tags_empty(self, async_client: AsyncClient):
  2110. """Verify empty list when no tags exist."""
  2111. response = await async_client.get("/api/v1/archives/tags")
  2112. assert response.status_code == 200
  2113. data = response.json()
  2114. assert isinstance(data, list)
  2115. assert len(data) == 0
  2116. @pytest.mark.asyncio
  2117. @pytest.mark.integration
  2118. async def test_get_tags_with_data(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  2119. """Verify tags are returned with counts."""
  2120. printer = await printer_factory()
  2121. await archive_factory(printer.id, print_name="Archive 1", tags="functional, test")
  2122. await archive_factory(printer.id, print_name="Archive 2", tags="functional, calibration")
  2123. await archive_factory(printer.id, print_name="Archive 3", tags="test")
  2124. response = await async_client.get("/api/v1/archives/tags")
  2125. assert response.status_code == 200
  2126. data = response.json()
  2127. assert isinstance(data, list)
  2128. # Convert to dict for easier lookup
  2129. tags_dict = {t["name"]: t["count"] for t in data}
  2130. assert tags_dict.get("functional") == 2
  2131. assert tags_dict.get("test") == 2
  2132. assert tags_dict.get("calibration") == 1
  2133. @pytest.mark.asyncio
  2134. @pytest.mark.integration
  2135. async def test_get_tags_sorted_by_count(
  2136. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  2137. ):
  2138. """Verify tags are sorted by count descending, then by name."""
  2139. printer = await printer_factory()
  2140. await archive_factory(printer.id, tags="alpha")
  2141. await archive_factory(printer.id, tags="beta, alpha")
  2142. await archive_factory(printer.id, tags="gamma, beta, alpha")
  2143. response = await async_client.get("/api/v1/archives/tags")
  2144. assert response.status_code == 200
  2145. data = response.json()
  2146. # alpha=3, beta=2, gamma=1
  2147. assert data[0]["name"] == "alpha"
  2148. assert data[0]["count"] == 3
  2149. assert data[1]["name"] == "beta"
  2150. assert data[1]["count"] == 2
  2151. assert data[2]["name"] == "gamma"
  2152. assert data[2]["count"] == 1
  2153. @pytest.mark.asyncio
  2154. @pytest.mark.integration
  2155. async def test_rename_tag(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  2156. """Verify renaming a tag updates all archives."""
  2157. printer = await printer_factory()
  2158. a1 = await archive_factory(printer.id, print_name="Archive 1", tags="old-tag, other")
  2159. a2 = await archive_factory(printer.id, print_name="Archive 2", tags="old-tag")
  2160. await archive_factory(printer.id, print_name="Archive 3", tags="different")
  2161. response = await async_client.put("/api/v1/archives/tags/old-tag", json={"new_name": "new-tag"})
  2162. assert response.status_code == 200
  2163. data = response.json()
  2164. assert data["affected"] == 2
  2165. # Verify the archives were updated
  2166. response = await async_client.get(f"/api/v1/archives/{a1.id}")
  2167. assert "new-tag" in response.json()["tags"]
  2168. assert "old-tag" not in response.json()["tags"]
  2169. response = await async_client.get(f"/api/v1/archives/{a2.id}")
  2170. assert response.json()["tags"] == "new-tag"
  2171. @pytest.mark.asyncio
  2172. @pytest.mark.integration
  2173. async def test_rename_tag_no_change(self, async_client: AsyncClient):
  2174. """Verify renaming to same name returns 0 affected."""
  2175. response = await async_client.put("/api/v1/archives/tags/some-tag", json={"new_name": "some-tag"})
  2176. assert response.status_code == 200
  2177. assert response.json()["affected"] == 0
  2178. @pytest.mark.asyncio
  2179. @pytest.mark.integration
  2180. async def test_rename_tag_empty_name_error(self, async_client: AsyncClient):
  2181. """Verify renaming to empty name returns error."""
  2182. response = await async_client.put("/api/v1/archives/tags/some-tag", json={"new_name": ""})
  2183. assert response.status_code == 400
  2184. @pytest.mark.asyncio
  2185. @pytest.mark.integration
  2186. async def test_delete_tag(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  2187. """Verify deleting a tag removes it from all archives."""
  2188. printer = await printer_factory()
  2189. a1 = await archive_factory(printer.id, print_name="Archive 1", tags="delete-me, keep")
  2190. a2 = await archive_factory(printer.id, print_name="Archive 2", tags="delete-me")
  2191. await archive_factory(printer.id, print_name="Archive 3", tags="different")
  2192. response = await async_client.delete("/api/v1/archives/tags/delete-me")
  2193. assert response.status_code == 200
  2194. data = response.json()
  2195. assert data["affected"] == 2
  2196. # Verify the archives were updated
  2197. response = await async_client.get(f"/api/v1/archives/{a1.id}")
  2198. assert response.json()["tags"] == "keep"
  2199. response = await async_client.get(f"/api/v1/archives/{a2.id}")
  2200. # Should be None or empty when last tag is removed
  2201. assert response.json()["tags"] is None or response.json()["tags"] == ""
  2202. @pytest.mark.asyncio
  2203. @pytest.mark.integration
  2204. async def test_delete_tag_not_found(self, async_client: AsyncClient):
  2205. """Verify deleting non-existent tag returns 0 affected."""
  2206. response = await async_client.delete("/api/v1/archives/tags/nonexistent-tag")
  2207. assert response.status_code == 200
  2208. assert response.json()["affected"] == 0
  2209. class TestUploadSourceThreeMF:
  2210. """Regression for #1531: source-3MF upload on fallback archives."""
  2211. @staticmethod
  2212. def _minimal_3mf_bytes() -> bytes:
  2213. """Smallest valid .3mf — the upload path enforces a zip header check."""
  2214. import io
  2215. import zipfile
  2216. buf = io.BytesIO()
  2217. with zipfile.ZipFile(buf, "w") as zf:
  2218. zf.writestr("[Content_Types].xml", "<types/>")
  2219. return buf.getvalue()
  2220. @pytest.mark.asyncio
  2221. @pytest.mark.integration
  2222. async def test_fallback_archive_source_upload_lands_under_base_dir(
  2223. self, async_client: AsyncClient, archive_factory, printer_factory, monkeypatch, tmp_path
  2224. ):
  2225. """Fallback archive (file_path='') must accept a source upload and store it inside base_dir.
  2226. Pre-fix, ``Path(base_dir) / ''`` collapsed to ``base_dir`` and the
  2227. ``.parent`` walked out of the data volume, sending the file to
  2228. ``/app/source/...`` and crashing on ``relative_to``.
  2229. """
  2230. from backend.app.core.config import settings as app_settings
  2231. monkeypatch.setattr(app_settings, "base_dir", tmp_path)
  2232. printer = await printer_factory()
  2233. archive = await archive_factory(
  2234. printer.id,
  2235. print_name="Cloud Print",
  2236. file_path="", # fallback archive — no source 3MF was archived
  2237. filename="Cloud Print.3mf",
  2238. )
  2239. files = {"file": ("cloud_print.3mf", self._minimal_3mf_bytes(), "application/octet-stream")}
  2240. response = await async_client.post(f"/api/v1/archives/{archive.id}/source", files=files)
  2241. assert response.status_code == 200, response.text
  2242. payload = response.json()
  2243. rel = payload["source_3mf_path"]
  2244. # Stored as a relative path inside base_dir.
  2245. assert not rel.startswith("/"), f"source_3mf_path should be relative, got {rel!r}"
  2246. # File physically landed under base_dir (NOT escaped to /app/source/).
  2247. assert (tmp_path / rel).is_file()
  2248. # Deterministic fallback location keyed off archive id.
  2249. assert rel == f"archive/no_source/{archive.id}/cloud_print.3mf"
  2250. @pytest.mark.asyncio
  2251. @pytest.mark.integration
  2252. async def test_normal_archive_source_upload_unchanged(
  2253. self, async_client: AsyncClient, archive_factory, printer_factory, monkeypatch, tmp_path
  2254. ):
  2255. """Normal archive (file_path set) still nests the source under <archive>/source/."""
  2256. from backend.app.core.config import settings as app_settings
  2257. monkeypatch.setattr(app_settings, "base_dir", tmp_path)
  2258. printer = await printer_factory()
  2259. # archive_factory's default file_path is "archives/test/test_print.gcode.3mf".
  2260. archive = await archive_factory(printer.id, print_name="Real Print")
  2261. files = {"file": ("real_print.3mf", self._minimal_3mf_bytes(), "application/octet-stream")}
  2262. response = await async_client.post(f"/api/v1/archives/{archive.id}/source", files=files)
  2263. assert response.status_code == 200, response.text
  2264. rel = response.json()["source_3mf_path"]
  2265. assert rel == "archives/test/source/real_print.3mf"
  2266. assert (tmp_path / rel).is_file()
  2267. @pytest.mark.asyncio
  2268. @pytest.mark.integration
  2269. async def test_symlinked_data_dir_upload_succeeds(
  2270. self, async_client: AsyncClient, archive_factory, printer_factory, monkeypatch, tmp_path
  2271. ):
  2272. """Regression: DATA_DIR that's a symlink to the real storage must not break the upload.
  2273. Common on TrueNAS / Synology / QNAP storage pools, and any
  2274. ``-v /symlinked/host/path:/app/data`` mount. The helper resolves
  2275. only for the containment check and returns literal paths so the
  2276. caller's ``relative_to(settings.base_dir)`` doesn't trip over a
  2277. canonical-vs-symlink mismatch.
  2278. """
  2279. from backend.app.core.config import settings as app_settings
  2280. real_dir = tmp_path / "real_storage"
  2281. real_dir.mkdir()
  2282. symlink_dir = tmp_path / "data_via_symlink"
  2283. symlink_dir.symlink_to(real_dir)
  2284. monkeypatch.setattr(app_settings, "base_dir", symlink_dir)
  2285. printer = await printer_factory()
  2286. archive = await archive_factory(
  2287. printer.id,
  2288. print_name="Symlinked Print",
  2289. file_path="archives/X1C/print.gcode.3mf",
  2290. filename="print.gcode.3mf",
  2291. )
  2292. files = {"file": ("print.3mf", self._minimal_3mf_bytes(), "application/octet-stream")}
  2293. response = await async_client.post(f"/api/v1/archives/{archive.id}/source", files=files)
  2294. assert response.status_code == 200, response.text
  2295. rel = response.json()["source_3mf_path"]
  2296. assert rel == "archives/X1C/source/print.3mf"
  2297. # Reachable via both the symlink and the canonical path.
  2298. assert (symlink_dir / rel).is_file()
  2299. assert (real_dir / rel).is_file()
  2300. @pytest.mark.asyncio
  2301. @pytest.mark.integration
  2302. async def test_absolute_file_path_rejected_with_clear_500(
  2303. self, async_client: AsyncClient, archive_factory, printer_factory, monkeypatch, tmp_path
  2304. ):
  2305. """A row whose file_path is absolute (corrupted by old import / manual edit)
  2306. must fail with the explicit "outside the data directory" message, not silently
  2307. write outside base_dir."""
  2308. from backend.app.core.config import settings as app_settings
  2309. monkeypatch.setattr(app_settings, "base_dir", tmp_path)
  2310. printer = await printer_factory()
  2311. archive = await archive_factory(
  2312. printer.id,
  2313. print_name="Corrupt Path",
  2314. file_path="/tmp/totally_outside.gcode.3mf", # nosec B108
  2315. filename="totally_outside.gcode.3mf",
  2316. )
  2317. files = {"file": ("totally_outside.3mf", self._minimal_3mf_bytes(), "application/octet-stream")}
  2318. response = await async_client.post(f"/api/v1/archives/{archive.id}/source", files=files)
  2319. assert response.status_code == 500
  2320. assert "outside the data directory" in response.json()["detail"]
  2321. # Did not write anything under the bogus /tmp/source/ either.
  2322. assert not (Path("/tmp") / "source").exists() or not (Path("/tmp") / "source" / "totally_outside.3mf").exists() # nosec B108
  2323. class TestSoftDeletedArchivesAreExcluded:
  2324. """Soft-deleted archives (#1343) must not leak into export or analysis (#2731).
  2325. The soft delete keeps the row so global Quick Stats can still count it, but
  2326. the archive is gone from every listing. Two consumers never got the memo:
  2327. the CSV export handed back rows the UI says do not exist, and per-project
  2328. failure analysis kept counting prints the user had deleted from the project
  2329. — disagreeing with the project's own figures.
  2330. """
  2331. @staticmethod
  2332. async def _soft_delete(db_session, archive) -> int:
  2333. from datetime import datetime, timezone
  2334. archive_id = archive.id
  2335. archive.deleted_at = datetime.now(timezone.utc)
  2336. await db_session.commit()
  2337. return archive_id
  2338. @pytest.mark.asyncio
  2339. @pytest.mark.integration
  2340. async def test_export_omits_soft_deleted_archives(
  2341. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  2342. ):
  2343. printer = await printer_factory()
  2344. await archive_factory(printer.id, print_name="Kept Print")
  2345. gone = await archive_factory(printer.id, print_name="Deleted Print")
  2346. await self._soft_delete(db_session, gone)
  2347. response = await async_client.get("/api/v1/archives/export?format=csv")
  2348. assert response.status_code == 200
  2349. body = response.text
  2350. assert "Kept Print" in body
  2351. assert "Deleted Print" not in body
  2352. @pytest.mark.asyncio
  2353. @pytest.mark.integration
  2354. async def test_project_failure_analysis_omits_soft_deleted_archives(
  2355. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  2356. ):
  2357. from backend.app.models.project import Project
  2358. project = Project(name="Analysis Project")
  2359. db_session.add(project)
  2360. await db_session.commit()
  2361. await db_session.refresh(project)
  2362. project_id = project.id
  2363. printer = await printer_factory()
  2364. await archive_factory(
  2365. printer.id,
  2366. print_name="Kept Failure",
  2367. status="failed",
  2368. failure_reason="bed_adhesion",
  2369. project_id=project_id,
  2370. )
  2371. gone = await archive_factory(
  2372. printer.id,
  2373. print_name="Deleted Failure",
  2374. status="failed",
  2375. failure_reason="filament_runout",
  2376. project_id=project_id,
  2377. )
  2378. await self._soft_delete(db_session, gone)
  2379. response = await async_client.get(f"/api/v1/archives/analysis/failures?project_id={project_id}")
  2380. assert response.status_code == 200
  2381. result = response.json()
  2382. assert result["failed_prints"] == 1
  2383. assert result["failures_by_reason"] == {"bed_adhesion": 1}
  2384. @pytest.mark.asyncio
  2385. @pytest.mark.integration
  2386. async def test_unscoped_failure_analysis_is_unchanged(
  2387. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  2388. ):
  2389. """Only the project-scoped path filters. Global analysis still counts
  2390. every run, including orphans, exactly as #1390 established."""
  2391. printer = await printer_factory()
  2392. gone = await archive_factory(
  2393. printer.id, print_name="Deleted Failure", status="failed", failure_reason="filament_runout"
  2394. )
  2395. await self._soft_delete(db_session, gone)
  2396. response = await async_client.get("/api/v1/archives/analysis/failures")
  2397. assert response.status_code == 200
  2398. assert response.json()["failed_prints"] == 1
  2399. class TestPrintLogSorting:
  2400. """#2636: the Print Log's column headers sort the whole log.
  2401. Sorting is server-side because paging is: ordering the rows the browser
  2402. happens to hold would answer "the most expensive print on this page",
  2403. not "the most expensive print". These pin the ordering contract the
  2404. headers depend on, including the two cases that differ per database
  2405. backend or per query plan if left implicit.
  2406. """
  2407. @staticmethod
  2408. async def _seed(db_session, printer_id: int, rows: list[dict]):
  2409. from datetime import datetime
  2410. from backend.app.models.print_log import PrintLogEntry
  2411. created = []
  2412. for i, row in enumerate(rows):
  2413. entry = PrintLogEntry(
  2414. printer_id=printer_id,
  2415. status=row.get("status", "completed"),
  2416. print_name=row.get("print_name", f"job-{i}"),
  2417. started_at=datetime(2026, 1, 1 + i, 12, 0, 0),
  2418. created_at=datetime(2026, 1, 1 + i, 12, 0, 0),
  2419. filament_used_grams=row.get("grams"),
  2420. cost=row.get("cost"),
  2421. energy_kwh=row.get("kwh"),
  2422. )
  2423. db_session.add(entry)
  2424. created.append(entry)
  2425. await db_session.commit()
  2426. return created
  2427. @pytest.mark.asyncio
  2428. @pytest.mark.integration
  2429. async def test_sorts_by_filament_used_in_both_directions(
  2430. self, async_client: AsyncClient, printer_factory, db_session
  2431. ):
  2432. printer = await printer_factory()
  2433. await self._seed(
  2434. db_session,
  2435. printer.id,
  2436. [{"grams": 5.0}, {"grams": 120.0}, {"grams": 30.0}],
  2437. )
  2438. asc = await async_client.get("/api/v1/print-log/?sort_by=filament_used&sort_dir=asc")
  2439. assert asc.status_code == 200
  2440. assert [e["filament_used_grams"] for e in asc.json()["items"]] == [5.0, 30.0, 120.0]
  2441. desc = await async_client.get("/api/v1/print-log/?sort_by=filament_used&sort_dir=desc")
  2442. assert [e["filament_used_grams"] for e in desc.json()["items"]] == [120.0, 30.0, 5.0]
  2443. @pytest.mark.asyncio
  2444. @pytest.mark.integration
  2445. async def test_empty_values_sort_last_whichever_direction(
  2446. self, async_client: AsyncClient, printer_factory, db_session
  2447. ):
  2448. """Cost is NULL until a spool is priced and energy until a smart plug
  2449. reports, so these columns are half-empty for most people. Postgres
  2450. sorts NULLs high and SQLite sorts them low, so without an explicit
  2451. NULLS LAST the same click gives a different first page depending on
  2452. which database the user deployed — and on one of them, a screenful
  2453. of blanks."""
  2454. printer = await printer_factory()
  2455. await self._seed(
  2456. db_session,
  2457. printer.id,
  2458. [{"cost": None}, {"cost": 2.5}, {"cost": None}, {"cost": 0.75}],
  2459. )
  2460. for direction, expected in (("asc", [0.75, 2.5]), ("desc", [2.5, 0.75])):
  2461. resp = await async_client.get(f"/api/v1/print-log/?sort_by=cost&sort_dir={direction}")
  2462. costs = [e["cost"] for e in resp.json()["items"]]
  2463. assert costs[:2] == expected, (direction, costs)
  2464. assert costs[2:] == [None, None], (direction, costs)
  2465. @pytest.mark.asyncio
  2466. @pytest.mark.integration
  2467. async def test_ties_are_broken_stably_across_pages(self, async_client: AsyncClient, printer_factory, db_session):
  2468. """Sorting by a column where every row shares a value (status) leaves
  2469. the order to the planner unless a tiebreaker is added — and an
  2470. unstable order can show the same row on two pages while another never
  2471. appears at all."""
  2472. printer = await printer_factory()
  2473. await self._seed(db_session, printer.id, [{"status": "completed"} for _ in range(6)])
  2474. first = await async_client.get("/api/v1/print-log/?sort_by=status&sort_dir=asc&limit=3&offset=0")
  2475. second = await async_client.get("/api/v1/print-log/?sort_by=status&sort_dir=asc&limit=3&offset=3")
  2476. page_1 = [e["id"] for e in first.json()["items"]]
  2477. page_2 = [e["id"] for e in second.json()["items"]]
  2478. assert len(set(page_1) & set(page_2)) == 0, "a row appeared on both pages"
  2479. assert len(set(page_1) | set(page_2)) == 6, "a row was never returned"
  2480. # Repeating the same request must give the same page back.
  2481. again = await async_client.get("/api/v1/print-log/?sort_by=status&sort_dir=asc&limit=3&offset=0")
  2482. assert [e["id"] for e in again.json()["items"]] == page_1
  2483. @pytest.mark.asyncio
  2484. @pytest.mark.integration
  2485. async def test_unknown_sort_column_is_rejected(self, async_client: AsyncClient):
  2486. """The client picks the sort key, so the column list is a whitelist —
  2487. anything else would let a request order by any attribute it can name."""
  2488. resp = await async_client.get("/api/v1/print-log/?sort_by=created_by_id")
  2489. assert resp.status_code == 400
  2490. resp = await async_client.get("/api/v1/print-log/?sort_by=1;DROP")
  2491. assert resp.status_code == 400
  2492. @pytest.mark.asyncio
  2493. @pytest.mark.integration
  2494. async def test_invalid_direction_is_rejected(self, async_client: AsyncClient):
  2495. resp = await async_client.get("/api/v1/print-log/?sort_by=date&sort_dir=sideways")
  2496. assert resp.status_code == 422
  2497. @pytest.mark.asyncio
  2498. @pytest.mark.integration
  2499. async def test_defaults_to_newest_first(self, async_client: AsyncClient, printer_factory, db_session):
  2500. """No sort params — the pre-#2636 behaviour, which existing clients
  2501. and the first page load both rely on."""
  2502. printer = await printer_factory()
  2503. await self._seed(db_session, printer.id, [{"print_name": "oldest"}, {"print_name": "newest"}])
  2504. resp = await async_client.get("/api/v1/print-log/")
  2505. assert [e["print_name"] for e in resp.json()["items"]] == ["newest", "oldest"]