test_archives_api.py 99 KB

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