test_print_queue_api.py 131 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407
  1. """Integration tests for Print Queue API endpoints."""
  2. import pytest
  3. from httpx import AsyncClient
  4. class TestPrintQueueAPI:
  5. """Integration tests for /api/v1/queue endpoints."""
  6. @pytest.fixture
  7. async def printer_factory(self, db_session):
  8. """Factory to create test printers."""
  9. _counter = [0]
  10. async def _create_printer(**kwargs):
  11. from backend.app.models.printer import Printer
  12. _counter[0] += 1
  13. counter = _counter[0]
  14. defaults = {
  15. "name": f"Test Printer {counter}",
  16. "ip_address": f"192.168.1.{100 + counter}",
  17. "serial_number": f"TESTSERIAL{counter:04d}",
  18. "access_code": "12345678",
  19. "model": "X1C",
  20. }
  21. defaults.update(kwargs)
  22. printer = Printer(**defaults)
  23. db_session.add(printer)
  24. await db_session.commit()
  25. await db_session.refresh(printer)
  26. return printer
  27. return _create_printer
  28. @pytest.fixture
  29. async def archive_factory(self, db_session):
  30. """Factory to create test archives."""
  31. _counter = [0]
  32. async def _create_archive(**kwargs):
  33. from backend.app.models.archive import PrintArchive
  34. _counter[0] += 1
  35. counter = _counter[0]
  36. defaults = {
  37. "filename": f"test_print_{counter}.3mf",
  38. "print_name": f"Test Print {counter}",
  39. "file_path": f"/tmp/test_print_{counter}.3mf",
  40. "file_size": 1024,
  41. "content_hash": f"testhash{counter:08d}",
  42. "status": "completed",
  43. }
  44. defaults.update(kwargs)
  45. archive = PrintArchive(**defaults)
  46. db_session.add(archive)
  47. await db_session.commit()
  48. await db_session.refresh(archive)
  49. return archive
  50. return _create_archive
  51. @pytest.fixture
  52. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  53. """Factory to create test queue items."""
  54. _counter = [0]
  55. async def _create_queue_item(**kwargs):
  56. from backend.app.models.print_queue import PrintQueueItem
  57. _counter[0] += 1
  58. counter = _counter[0]
  59. # Create printer and archive if not provided
  60. if "printer_id" not in kwargs:
  61. printer = await printer_factory()
  62. kwargs["printer_id"] = printer.id
  63. if "archive_id" not in kwargs:
  64. archive = await archive_factory()
  65. kwargs["archive_id"] = archive.id
  66. defaults = {
  67. "status": "pending",
  68. "position": counter,
  69. }
  70. defaults.update(kwargs)
  71. item = PrintQueueItem(**defaults)
  72. db_session.add(item)
  73. await db_session.commit()
  74. await db_session.refresh(item)
  75. return item
  76. return _create_queue_item
  77. @pytest.mark.asyncio
  78. @pytest.mark.integration
  79. async def test_list_queue_empty(self, async_client: AsyncClient):
  80. """Verify empty list when no queue items exist."""
  81. response = await async_client.get("/api/v1/queue/")
  82. assert response.status_code == 200
  83. assert isinstance(response.json(), list)
  84. @pytest.mark.asyncio
  85. @pytest.mark.integration
  86. async def test_add_to_queue(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  87. """Verify item can be added to queue."""
  88. printer = await printer_factory()
  89. archive = await archive_factory()
  90. data = {
  91. "printer_id": printer.id,
  92. "archive_id": archive.id,
  93. }
  94. response = await async_client.post("/api/v1/queue/", json=data)
  95. assert response.status_code == 200
  96. result = response.json()
  97. assert result["printer_id"] == printer.id
  98. assert result["archive_id"] == archive.id
  99. assert result["status"] == "pending"
  100. assert result["manual_start"] is False
  101. @pytest.mark.asyncio
  102. @pytest.mark.integration
  103. async def test_add_to_queue_with_manual_start(
  104. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  105. ):
  106. """Verify item can be added to queue with manual_start=True."""
  107. printer = await printer_factory()
  108. archive = await archive_factory()
  109. data = {
  110. "printer_id": printer.id,
  111. "archive_id": archive.id,
  112. "manual_start": True,
  113. }
  114. response = await async_client.post("/api/v1/queue/", json=data)
  115. assert response.status_code == 200
  116. result = response.json()
  117. assert result["printer_id"] == printer.id
  118. assert result["archive_id"] == archive.id
  119. assert result["status"] == "pending"
  120. assert result["manual_start"] is True
  121. @pytest.mark.asyncio
  122. @pytest.mark.integration
  123. async def test_add_to_queue_with_skip_filament_check(
  124. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  125. ):
  126. """PrintModal "Print Anyway" persists skip_filament_check on creation (#1698-followup)."""
  127. printer = await printer_factory()
  128. archive = await archive_factory()
  129. data = {
  130. "printer_id": printer.id,
  131. "archive_id": archive.id,
  132. "skip_filament_check": True,
  133. }
  134. response = await async_client.post("/api/v1/queue/", json=data)
  135. assert response.status_code == 200
  136. result = response.json()
  137. assert result["skip_filament_check"] is True
  138. @pytest.mark.asyncio
  139. @pytest.mark.integration
  140. async def test_add_to_queue_skip_filament_check_defaults_false(
  141. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  142. ):
  143. """Default add-to-queue has skip_filament_check=False — no silent bypass."""
  144. printer = await printer_factory()
  145. archive = await archive_factory()
  146. data = {"printer_id": printer.id, "archive_id": archive.id}
  147. response = await async_client.post("/api/v1/queue/", json=data)
  148. assert response.status_code == 200
  149. result = response.json()
  150. assert result["skip_filament_check"] is False
  151. @pytest.mark.asyncio
  152. @pytest.mark.integration
  153. async def test_add_to_queue_with_project_id(
  154. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  155. ):
  156. """#932: queue items created from the project view carry project_id forward."""
  157. from backend.app.models.project import Project
  158. printer = await printer_factory()
  159. archive = await archive_factory()
  160. project = Project(name="Queue Project")
  161. db_session.add(project)
  162. await db_session.commit()
  163. await db_session.refresh(project)
  164. data = {
  165. "printer_id": printer.id,
  166. "archive_id": archive.id,
  167. "project_id": project.id,
  168. }
  169. response = await async_client.post("/api/v1/queue/", json=data)
  170. assert response.status_code == 200
  171. result = response.json()
  172. # The response schema may or may not echo project_id; the stored row is
  173. # what matters, so verify via DB.
  174. from sqlalchemy import select
  175. from backend.app.models.print_queue import PrintQueueItem
  176. row = (await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == result["id"]))).scalar_one()
  177. assert row.project_id == project.id
  178. @pytest.mark.asyncio
  179. @pytest.mark.integration
  180. async def test_add_to_queue_invalid_project_id_returns_404(
  181. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  182. ):
  183. """#932: bogus project_id must be rejected before the FK constraint fires.
  184. Regression guard for the pre-check added to add_to_queue. Without the
  185. validation, a nonexistent project_id would reach db.commit() and raise
  186. an IntegrityError → 500. The pre-check must convert that to a 404 so
  187. the UI gets a clean error it can surface.
  188. """
  189. printer = await printer_factory()
  190. archive = await archive_factory()
  191. data = {
  192. "printer_id": printer.id,
  193. "archive_id": archive.id,
  194. "project_id": 999999, # nonexistent
  195. }
  196. response = await async_client.post("/api/v1/queue/", json=data)
  197. assert response.status_code == 404
  198. assert "project" in response.json()["detail"].lower()
  199. @pytest.mark.asyncio
  200. @pytest.mark.integration
  201. async def test_add_to_queue_with_ams_mapping(
  202. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  203. ):
  204. """Verify item can be added to queue with ams_mapping."""
  205. printer = await printer_factory()
  206. archive = await archive_factory()
  207. data = {
  208. "printer_id": printer.id,
  209. "archive_id": archive.id,
  210. "ams_mapping": [5, -1, 2, -1], # Slot 1 -> tray 5, slot 3 -> tray 2
  211. }
  212. response = await async_client.post("/api/v1/queue/", json=data)
  213. assert response.status_code == 200
  214. result = response.json()
  215. assert result["printer_id"] == printer.id
  216. assert result["archive_id"] == archive.id
  217. assert result["ams_mapping"] == [5, -1, 2, -1]
  218. @pytest.mark.asyncio
  219. @pytest.mark.integration
  220. async def test_add_to_queue_falls_back_to_archive_slicer_ams_mapping_when_unset(
  221. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  222. ):
  223. """When the caller sends no explicit ams_mapping, but the archive
  224. carries the slicer's own saved pick for this exact printer
  225. (extra_data.slicer_ams_mapping, written by a VP with "Save AMS
  226. mapping" on), the queue item should inherit it — the same
  227. exact-physical-spool reuse the "Mapping" button gives you, but
  228. automatic when nothing was hand-edited.
  229. """
  230. printer = await printer_factory()
  231. archive = await archive_factory(
  232. extra_data={"slicer_ams_mapping": {"mapping": [5, -1, 2, -1], "printer_id": printer.id}}
  233. )
  234. data = {
  235. "printer_id": printer.id,
  236. "archive_id": archive.id,
  237. }
  238. response = await async_client.post("/api/v1/queue/", json=data)
  239. assert response.status_code == 200
  240. result = response.json()
  241. assert result["ams_mapping"] == [5, -1, 2, -1]
  242. @pytest.mark.asyncio
  243. @pytest.mark.integration
  244. async def test_add_to_queue_ignores_archive_slicer_ams_mapping_for_different_printer(
  245. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  246. ):
  247. """A saved mapping's tray IDs only mean something relative to the
  248. printer they were resolved against. Reprinting the same archive on a
  249. *different* printer must not inherit it — tray 5 on printer A can
  250. hold a completely different spool than tray 5 on printer B.
  251. """
  252. origin_printer = await printer_factory()
  253. other_printer = await printer_factory()
  254. archive = await archive_factory(
  255. extra_data={"slicer_ams_mapping": {"mapping": [5, -1, 2, -1], "printer_id": origin_printer.id}}
  256. )
  257. data = {
  258. "printer_id": other_printer.id,
  259. "archive_id": archive.id,
  260. }
  261. response = await async_client.post("/api/v1/queue/", json=data)
  262. assert response.status_code == 200
  263. result = response.json()
  264. assert result["ams_mapping"] is None
  265. @pytest.mark.asyncio
  266. @pytest.mark.integration
  267. async def test_add_to_queue_ignores_archive_slicer_ams_mapping_for_model_based_dispatch(
  268. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  269. ):
  270. """A model-based item (no fixed printer_id) can't know in advance
  271. which printer the scheduler will pick, so a saved mapping resolved
  272. against one specific printer must never be inherited here either.
  273. """
  274. origin_printer = await printer_factory()
  275. archive = await archive_factory(
  276. extra_data={"slicer_ams_mapping": {"mapping": [5, -1, 2, -1], "printer_id": origin_printer.id}}
  277. )
  278. data = {
  279. "target_model": "X1C",
  280. "archive_id": archive.id,
  281. }
  282. response = await async_client.post("/api/v1/queue/", json=data)
  283. assert response.status_code == 200
  284. result = response.json()
  285. assert result["ams_mapping"] is None
  286. @pytest.mark.asyncio
  287. @pytest.mark.integration
  288. async def test_add_to_queue_explicit_ams_mapping_wins_over_archive_fallback(
  289. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  290. ):
  291. """An explicit ams_mapping in the request (e.g. from the filament
  292. mapping panel) must take priority over the archive's saved slicer
  293. pick — the fallback only fires when the caller sent nothing at all.
  294. """
  295. printer = await printer_factory()
  296. archive = await archive_factory(
  297. extra_data={"slicer_ams_mapping": {"mapping": [5, -1, 2, -1], "printer_id": printer.id}}
  298. )
  299. data = {
  300. "printer_id": printer.id,
  301. "archive_id": archive.id,
  302. "ams_mapping": [9, -1, 1, -1],
  303. }
  304. response = await async_client.post("/api/v1/queue/", json=data)
  305. assert response.status_code == 200
  306. result = response.json()
  307. assert result["ams_mapping"] == [9, -1, 1, -1]
  308. @pytest.mark.asyncio
  309. @pytest.mark.integration
  310. async def test_add_to_queue_archive_extra_data_without_slicer_mapping_key_not_used(
  311. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  312. ):
  313. """extra_data present but without a slicer_ams_mapping key (the
  314. common case — most archives have other metadata but no saved slicer
  315. mapping) must not accidentally trip the fallback."""
  316. printer = await printer_factory()
  317. archive = await archive_factory(extra_data={"filament_slots": []})
  318. data = {
  319. "printer_id": printer.id,
  320. "archive_id": archive.id,
  321. }
  322. response = await async_client.post("/api/v1/queue/", json=data)
  323. assert response.status_code == 200
  324. result = response.json()
  325. assert result["ams_mapping"] is None
  326. @pytest.mark.asyncio
  327. @pytest.mark.integration
  328. async def test_add_to_queue_with_plate_id(
  329. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  330. ):
  331. """Verify item can be added to queue with plate_id for multi-plate 3MF."""
  332. printer = await printer_factory()
  333. archive = await archive_factory()
  334. data = {
  335. "printer_id": printer.id,
  336. "archive_id": archive.id,
  337. "plate_id": 3,
  338. }
  339. response = await async_client.post("/api/v1/queue/", json=data)
  340. assert response.status_code == 200
  341. result = response.json()
  342. assert result["plate_id"] == 3
  343. @pytest.mark.asyncio
  344. @pytest.mark.integration
  345. async def test_add_to_queue_with_print_options(
  346. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  347. ):
  348. """Verify item can be added to queue with print options."""
  349. printer = await printer_factory()
  350. archive = await archive_factory()
  351. data = {
  352. "printer_id": printer.id,
  353. "archive_id": archive.id,
  354. "bed_levelling": "off",
  355. "flow_cali": "on",
  356. "vibration_cali": False,
  357. "layer_inspect": True,
  358. "timelapse": True,
  359. "use_ams": False,
  360. }
  361. response = await async_client.post("/api/v1/queue/", json=data)
  362. assert response.status_code == 200
  363. result = response.json()
  364. assert result["bed_levelling"] == "off"
  365. assert result["flow_cali"] == "on"
  366. assert result["vibration_cali"] is False
  367. assert result["layer_inspect"] is True
  368. assert result["timelapse"] is True
  369. assert result["use_ams"] is False
  370. @pytest.mark.asyncio
  371. @pytest.mark.integration
  372. async def test_update_queue_item_plate_id(self, async_client: AsyncClient, queue_item_factory, db_session):
  373. """Verify queue item plate_id can be updated."""
  374. item = await queue_item_factory()
  375. response = await async_client.patch(f"/api/v1/queue/{item.id}", json={"plate_id": 5})
  376. assert response.status_code == 200
  377. result = response.json()
  378. assert result["plate_id"] == 5
  379. @pytest.mark.asyncio
  380. @pytest.mark.integration
  381. async def test_update_queue_item_print_options(self, async_client: AsyncClient, queue_item_factory, db_session):
  382. """Verify queue item print options can be updated."""
  383. item = await queue_item_factory()
  384. response = await async_client.patch(
  385. f"/api/v1/queue/{item.id}",
  386. json={
  387. "bed_levelling": "off",
  388. "timelapse": True,
  389. },
  390. )
  391. assert response.status_code == 200
  392. result = response.json()
  393. assert result["bed_levelling"] == "off"
  394. assert result["timelapse"] is True
  395. @pytest.mark.asyncio
  396. @pytest.mark.integration
  397. async def test_reassign_rejected_while_dispatching(
  398. self, async_client: AsyncClient, queue_item_factory, printer_factory, db_session
  399. ):
  400. """#2615: a claimed (in-flight) row rejects edits with 409, so its printer
  401. can't be reassigned out from under the running FTP upload."""
  402. from datetime import datetime, timezone
  403. item = await queue_item_factory(dispatching_at=datetime.now(timezone.utc))
  404. other = await printer_factory()
  405. original_printer_id = item.printer_id
  406. response = await async_client.patch(f"/api/v1/queue/{item.id}", json={"printer_id": other.id})
  407. assert response.status_code == 409
  408. await db_session.refresh(item)
  409. assert item.printer_id == original_printer_id, "printer_id must not change on a dispatching row"
  410. @pytest.mark.asyncio
  411. @pytest.mark.integration
  412. async def test_bulk_update_skips_dispatching_item(
  413. self, async_client: AsyncClient, queue_item_factory, printer_factory, db_session
  414. ):
  415. """#2615: bulk edits skip a claimed row rather than splitting it."""
  416. from datetime import datetime, timezone
  417. item = await queue_item_factory(dispatching_at=datetime.now(timezone.utc))
  418. other = await printer_factory()
  419. original_printer_id = item.printer_id
  420. response = await async_client.patch("/api/v1/queue/bulk", json={"item_ids": [item.id], "printer_id": other.id})
  421. assert response.status_code == 200
  422. body = response.json()
  423. assert body["skipped_count"] == 1
  424. assert body["updated_count"] == 0
  425. await db_session.refresh(item)
  426. assert item.printer_id == original_printer_id
  427. @pytest.mark.asyncio
  428. @pytest.mark.integration
  429. async def test_update_allowed_on_unclaimed_pending_item(
  430. self, async_client: AsyncClient, queue_item_factory, db_session
  431. ):
  432. """Regression guard: a normal pending row (no claim) still edits fine."""
  433. item = await queue_item_factory()
  434. response = await async_client.patch(f"/api/v1/queue/{item.id}", json={"plate_id": 7})
  435. assert response.status_code == 200
  436. assert response.json()["plate_id"] == 7
  437. @pytest.mark.asyncio
  438. @pytest.mark.integration
  439. async def test_get_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  440. """Verify single queue item can be retrieved."""
  441. item = await queue_item_factory()
  442. response = await async_client.get(f"/api/v1/queue/{item.id}")
  443. assert response.status_code == 200
  444. assert response.json()["id"] == item.id
  445. @pytest.mark.asyncio
  446. @pytest.mark.integration
  447. async def test_get_queue_item_not_found(self, async_client: AsyncClient):
  448. """Verify 404 for non-existent queue item."""
  449. response = await async_client.get("/api/v1/queue/9999")
  450. assert response.status_code == 404
  451. @pytest.mark.asyncio
  452. @pytest.mark.integration
  453. async def test_update_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  454. """Verify queue item can be updated."""
  455. item = await queue_item_factory()
  456. response = await async_client.patch(f"/api/v1/queue/{item.id}", json={"auto_off_after": True})
  457. assert response.status_code == 200
  458. result = response.json()
  459. assert result["auto_off_after"] is True
  460. @pytest.mark.asyncio
  461. @pytest.mark.integration
  462. async def test_update_queue_item_manual_start(self, async_client: AsyncClient, queue_item_factory, db_session):
  463. """Verify queue item manual_start can be updated."""
  464. item = await queue_item_factory(manual_start=False)
  465. response = await async_client.patch(f"/api/v1/queue/{item.id}", json={"manual_start": True})
  466. assert response.status_code == 200
  467. result = response.json()
  468. assert result["manual_start"] is True
  469. @pytest.mark.asyncio
  470. @pytest.mark.integration
  471. async def test_delete_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  472. """Verify queue item can be deleted."""
  473. item = await queue_item_factory()
  474. response = await async_client.delete(f"/api/v1/queue/{item.id}")
  475. assert response.status_code == 200
  476. assert response.json()["message"] == "Queue item deleted"
  477. @pytest.mark.asyncio
  478. @pytest.mark.integration
  479. async def test_delete_queue_item_not_found(self, async_client: AsyncClient):
  480. """Verify 404 for deleting non-existent queue item."""
  481. response = await async_client.delete("/api/v1/queue/9999")
  482. assert response.status_code == 404
  483. class TestQueueStartEndpoint:
  484. """Tests for the /queue/{item_id}/start endpoint."""
  485. @pytest.fixture
  486. async def printer_factory(self, db_session):
  487. """Factory to create test printers."""
  488. _counter = [0]
  489. async def _create_printer(**kwargs):
  490. from backend.app.models.printer import Printer
  491. _counter[0] += 1
  492. counter = _counter[0]
  493. defaults = {
  494. "name": f"Test Printer {counter}",
  495. "ip_address": f"192.168.1.{100 + counter}",
  496. "serial_number": f"TESTSERIAL{counter:04d}",
  497. "access_code": "12345678",
  498. "model": "X1C",
  499. }
  500. defaults.update(kwargs)
  501. printer = Printer(**defaults)
  502. db_session.add(printer)
  503. await db_session.commit()
  504. await db_session.refresh(printer)
  505. return printer
  506. return _create_printer
  507. @pytest.fixture
  508. async def archive_factory(self, db_session):
  509. """Factory to create test archives."""
  510. _counter = [0]
  511. async def _create_archive(**kwargs):
  512. from backend.app.models.archive import PrintArchive
  513. _counter[0] += 1
  514. counter = _counter[0]
  515. defaults = {
  516. "filename": f"test_print_{counter}.3mf",
  517. "print_name": f"Test Print {counter}",
  518. "file_path": f"/tmp/test_print_{counter}.3mf",
  519. "file_size": 1024,
  520. "content_hash": f"testhash{counter:08d}",
  521. "status": "completed",
  522. }
  523. defaults.update(kwargs)
  524. archive = PrintArchive(**defaults)
  525. db_session.add(archive)
  526. await db_session.commit()
  527. await db_session.refresh(archive)
  528. return archive
  529. return _create_archive
  530. @pytest.fixture
  531. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  532. """Factory to create test queue items."""
  533. _counter = [0]
  534. async def _create_queue_item(**kwargs):
  535. from backend.app.models.print_queue import PrintQueueItem
  536. _counter[0] += 1
  537. counter = _counter[0]
  538. if "printer_id" not in kwargs:
  539. printer = await printer_factory()
  540. kwargs["printer_id"] = printer.id
  541. if "archive_id" not in kwargs:
  542. archive = await archive_factory()
  543. kwargs["archive_id"] = archive.id
  544. defaults = {
  545. "status": "pending",
  546. "position": counter,
  547. }
  548. defaults.update(kwargs)
  549. item = PrintQueueItem(**defaults)
  550. db_session.add(item)
  551. await db_session.commit()
  552. await db_session.refresh(item)
  553. return item
  554. return _create_queue_item
  555. @pytest.mark.asyncio
  556. @pytest.mark.integration
  557. async def test_start_staged_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  558. """Verify starting a staged (manual_start=True) queue item clears the flag."""
  559. item = await queue_item_factory(manual_start=True)
  560. assert item.manual_start is True
  561. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  562. assert response.status_code == 200
  563. result = response.json()
  564. assert result["manual_start"] is False
  565. assert result["status"] == "pending"
  566. @pytest.mark.asyncio
  567. @pytest.mark.integration
  568. async def test_start_non_staged_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  569. """Verify starting a non-staged queue item still works (idempotent)."""
  570. item = await queue_item_factory(manual_start=False)
  571. assert item.manual_start is False
  572. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  573. assert response.status_code == 200
  574. result = response.json()
  575. assert result["manual_start"] is False
  576. @pytest.mark.asyncio
  577. @pytest.mark.integration
  578. async def test_start_queue_item_not_found(self, async_client: AsyncClient):
  579. """Verify 404 for non-existent queue item."""
  580. response = await async_client.post("/api/v1/queue/9999/start")
  581. assert response.status_code == 404
  582. @pytest.mark.asyncio
  583. @pytest.mark.integration
  584. async def test_start_non_pending_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  585. """Verify 400 error when trying to start a non-pending queue item."""
  586. item = await queue_item_factory(status="printing", manual_start=True)
  587. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  588. assert response.status_code == 400
  589. assert "pending" in response.json()["detail"].lower()
  590. @pytest.mark.asyncio
  591. @pytest.mark.integration
  592. async def test_start_completed_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  593. """Verify 400 error when trying to start a completed queue item."""
  594. item = await queue_item_factory(status="completed", manual_start=True)
  595. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  596. assert response.status_code == 400
  597. @pytest.mark.asyncio
  598. @pytest.mark.integration
  599. async def test_start_returns_409_on_filament_deficit(
  600. self,
  601. async_client: AsyncClient,
  602. queue_item_factory,
  603. db_session,
  604. monkeypatch,
  605. ):
  606. """Filament deficit must surface as 409 + structured payload (#1496)."""
  607. from backend.app.services import filament_deficit as fd_module
  608. item = await queue_item_factory(manual_start=True)
  609. async def _fake_deficit(_db, _item):
  610. return [
  611. fd_module.FilamentDeficit(
  612. slot_id=1,
  613. ams_id=0,
  614. tray_id=0,
  615. filament_type="PLA",
  616. required_grams=270.0,
  617. remaining_grams=200.0,
  618. ),
  619. ]
  620. monkeypatch.setattr(
  621. "backend.app.api.routes.print_queue.compute_deficit_for_queue_item",
  622. _fake_deficit,
  623. )
  624. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  625. assert response.status_code == 409
  626. body = response.json()
  627. assert body["detail"]["code"] == "insufficient_filament"
  628. assert len(body["detail"]["deficit"]) == 1
  629. assert body["detail"]["deficit"][0]["slot_id"] == 1
  630. assert body["detail"]["deficit"][0]["required_grams"] == 270.0
  631. assert body["detail"]["deficit"][0]["remaining_grams"] == 200.0
  632. # Item still pending, manual_start unchanged.
  633. await db_session.refresh(item)
  634. assert item.status == "pending"
  635. assert item.manual_start is True
  636. @pytest.mark.asyncio
  637. @pytest.mark.integration
  638. async def test_start_with_skip_flag_bypasses_deficit_check(
  639. self,
  640. async_client: AsyncClient,
  641. queue_item_factory,
  642. db_session,
  643. monkeypatch,
  644. ):
  645. """With skip_filament_check=true the route dispatches even when short (#1496)."""
  646. from backend.app.services import filament_deficit as fd_module
  647. item = await queue_item_factory(manual_start=True, filament_short=True)
  648. called_with = {}
  649. async def _fake_deficit(_db, _item):
  650. called_with["called"] = True
  651. return [
  652. fd_module.FilamentDeficit(
  653. slot_id=1,
  654. ams_id=0,
  655. tray_id=0,
  656. filament_type="PLA",
  657. required_grams=270.0,
  658. remaining_grams=200.0,
  659. ),
  660. ]
  661. monkeypatch.setattr(
  662. "backend.app.api.routes.print_queue.compute_deficit_for_queue_item",
  663. _fake_deficit,
  664. )
  665. response = await async_client.post(f"/api/v1/queue/{item.id}/start?skip_filament_check=true")
  666. assert response.status_code == 200
  667. body = response.json()
  668. assert body["manual_start"] is False
  669. assert body["filament_short"] is False
  670. # Helper not called on the bypass path — we trust the operator's
  671. # decision to print anyway.
  672. assert called_with == {}
  673. @pytest.mark.asyncio
  674. @pytest.mark.integration
  675. async def test_start_with_skip_flag_persists_acknowledgement(
  676. self,
  677. async_client: AsyncClient,
  678. queue_item_factory,
  679. db_session,
  680. ):
  681. """skip_filament_check=true sets the persistent flag on the queue item
  682. so the scheduler doesn't re-flag it on the next tick (#1698-followup).
  683. Without persistence the route's flag-clearing only survives until the
  684. next scheduler tick re-runs the deficit check on identical spool
  685. state and re-promotes the item — the user has to click Play+Confirm
  686. every single tick.
  687. """
  688. item = await queue_item_factory(manual_start=True, filament_short=True)
  689. assert item.skip_filament_check is False
  690. response = await async_client.post(f"/api/v1/queue/{item.id}/start?skip_filament_check=true")
  691. assert response.status_code == 200
  692. body = response.json()
  693. assert body["skip_filament_check"] is True
  694. await db_session.refresh(item)
  695. assert item.skip_filament_check is True
  696. @pytest.mark.asyncio
  697. @pytest.mark.integration
  698. async def test_start_without_skip_flag_does_not_set_acknowledgement(
  699. self,
  700. async_client: AsyncClient,
  701. queue_item_factory,
  702. db_session,
  703. ):
  704. """A successful Play click with no deficit must NOT silently set the
  705. acknowledgement flag — only an explicit Print Anyway should.
  706. """
  707. item = await queue_item_factory(manual_start=False, filament_short=False)
  708. assert item.skip_filament_check is False
  709. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  710. assert response.status_code == 200
  711. await db_session.refresh(item)
  712. assert item.skip_filament_check is False
  713. class TestQueueCancelEndpoint:
  714. """Tests for the /queue/{item_id}/cancel endpoint."""
  715. @pytest.fixture
  716. async def printer_factory(self, db_session):
  717. """Factory to create test printers."""
  718. async def _create_printer(**kwargs):
  719. from backend.app.models.printer import Printer
  720. defaults = {
  721. "name": "Cancel Test Printer",
  722. "ip_address": "192.168.1.200",
  723. "serial_number": "TESTCANCEL001",
  724. "access_code": "12345678",
  725. "model": "X1C",
  726. }
  727. defaults.update(kwargs)
  728. printer = Printer(**defaults)
  729. db_session.add(printer)
  730. await db_session.commit()
  731. await db_session.refresh(printer)
  732. return printer
  733. return _create_printer
  734. @pytest.fixture
  735. async def archive_factory(self, db_session):
  736. """Factory to create test archives."""
  737. async def _create_archive(**kwargs):
  738. from backend.app.models.archive import PrintArchive
  739. defaults = {
  740. "filename": "cancel_test.3mf",
  741. "print_name": "Cancel Test Print",
  742. "file_path": "/tmp/cancel_test.3mf",
  743. "file_size": 1024,
  744. "content_hash": "cancelhash001",
  745. "status": "completed",
  746. }
  747. defaults.update(kwargs)
  748. archive = PrintArchive(**defaults)
  749. db_session.add(archive)
  750. await db_session.commit()
  751. await db_session.refresh(archive)
  752. return archive
  753. return _create_archive
  754. @pytest.fixture
  755. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  756. """Factory to create test queue items."""
  757. async def _create_queue_item(**kwargs):
  758. from backend.app.models.print_queue import PrintQueueItem
  759. if "printer_id" not in kwargs:
  760. printer = await printer_factory()
  761. kwargs["printer_id"] = printer.id
  762. if "archive_id" not in kwargs:
  763. archive = await archive_factory()
  764. kwargs["archive_id"] = archive.id
  765. defaults = {
  766. "status": "pending",
  767. "position": 1,
  768. }
  769. defaults.update(kwargs)
  770. item = PrintQueueItem(**defaults)
  771. db_session.add(item)
  772. await db_session.commit()
  773. await db_session.refresh(item)
  774. return item
  775. return _create_queue_item
  776. @pytest.mark.asyncio
  777. @pytest.mark.integration
  778. async def test_cancel_pending_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  779. """Verify cancelling a pending queue item."""
  780. item = await queue_item_factory(status="pending")
  781. response = await async_client.post(f"/api/v1/queue/{item.id}/cancel")
  782. assert response.status_code == 200
  783. assert response.json()["message"] == "Queue item cancelled"
  784. @pytest.mark.asyncio
  785. @pytest.mark.integration
  786. async def test_cancel_non_pending_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  787. """Verify 400 error when trying to cancel a non-pending queue item."""
  788. item = await queue_item_factory(status="printing")
  789. response = await async_client.post(f"/api/v1/queue/{item.id}/cancel")
  790. assert response.status_code == 400
  791. class TestQueueLibraryFileSupport:
  792. """Tests for queue items with library_file_id (instead of archive_id)."""
  793. @pytest.fixture
  794. async def printer_factory(self, db_session):
  795. """Factory to create test printers."""
  796. _counter = [0]
  797. async def _create_printer(**kwargs):
  798. from backend.app.models.printer import Printer
  799. _counter[0] += 1
  800. counter = _counter[0]
  801. defaults = {
  802. "name": f"Library Test Printer {counter}",
  803. "ip_address": f"192.168.1.{150 + counter}",
  804. "serial_number": f"TESTLIB{counter:04d}",
  805. "access_code": "12345678",
  806. "model": "X1C",
  807. }
  808. defaults.update(kwargs)
  809. printer = Printer(**defaults)
  810. db_session.add(printer)
  811. await db_session.commit()
  812. await db_session.refresh(printer)
  813. return printer
  814. return _create_printer
  815. @pytest.fixture
  816. async def library_file_factory(self, db_session):
  817. """Factory to create test library files."""
  818. _counter = [0]
  819. async def _create_library_file(**kwargs):
  820. from backend.app.models.library import LibraryFile
  821. _counter[0] += 1
  822. counter = _counter[0]
  823. defaults = {
  824. "filename": f"library_test_{counter}.3mf",
  825. "file_path": f"/test/library/library_test_{counter}.3mf",
  826. "file_size": 2048,
  827. "file_type": "3mf",
  828. "file_metadata": {"print_name": f"Library Print {counter}", "print_time_seconds": 3600},
  829. }
  830. defaults.update(kwargs)
  831. lib_file = LibraryFile(**defaults)
  832. db_session.add(lib_file)
  833. await db_session.commit()
  834. await db_session.refresh(lib_file)
  835. return lib_file
  836. return _create_library_file
  837. @pytest.mark.asyncio
  838. @pytest.mark.integration
  839. async def test_add_to_queue_with_library_file(
  840. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  841. ):
  842. """Verify item can be added to queue using library_file_id instead of archive_id."""
  843. printer = await printer_factory()
  844. lib_file = await library_file_factory()
  845. data = {
  846. "printer_id": printer.id,
  847. "library_file_id": lib_file.id,
  848. }
  849. response = await async_client.post("/api/v1/queue/", json=data)
  850. assert response.status_code == 200
  851. result = response.json()
  852. assert result["printer_id"] == printer.id
  853. assert result["library_file_id"] == lib_file.id
  854. assert result["archive_id"] is None
  855. assert result["status"] == "pending"
  856. assert result["library_file_name"] == "Library Print 1"
  857. assert result["print_time_seconds"] == 3600
  858. @pytest.mark.asyncio
  859. @pytest.mark.integration
  860. async def test_add_library_file_rejects_cross_model_mismatch(
  861. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  862. ):
  863. """Cross-model gate (#2578) also reads sliced_for_model from library file metadata."""
  864. await printer_factory(model="H2D")
  865. lib_file = await library_file_factory(file_metadata={"print_name": "Mismatch", "sliced_for_model": "X1C"})
  866. response = await async_client.post(
  867. "/api/v1/queue/",
  868. json={"target_model": "H2D", "library_file_id": lib_file.id},
  869. )
  870. assert response.status_code == 400
  871. assert "sliced for X1C" in response.json()["detail"]
  872. @pytest.mark.asyncio
  873. @pytest.mark.integration
  874. async def test_add_to_queue_library_file_with_options(
  875. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  876. ):
  877. """Verify library file queue item can have all options set."""
  878. printer = await printer_factory()
  879. lib_file = await library_file_factory()
  880. data = {
  881. "printer_id": printer.id,
  882. "library_file_id": lib_file.id,
  883. "ams_mapping": [1, 2, -1, -1],
  884. "plate_id": 2,
  885. "bed_levelling": "off",
  886. "timelapse": True,
  887. "manual_start": True,
  888. }
  889. response = await async_client.post("/api/v1/queue/", json=data)
  890. assert response.status_code == 200
  891. result = response.json()
  892. assert result["library_file_id"] == lib_file.id
  893. assert result["ams_mapping"] == [1, 2, -1, -1]
  894. assert result["plate_id"] == 2
  895. assert result["bed_levelling"] == "off"
  896. assert result["timelapse"] is True
  897. assert result["manual_start"] is True
  898. @pytest.mark.asyncio
  899. @pytest.mark.integration
  900. async def test_add_to_queue_requires_archive_or_library_file(
  901. self, async_client: AsyncClient, printer_factory, db_session
  902. ):
  903. """Verify 400 error when neither archive_id nor library_file_id provided."""
  904. printer = await printer_factory()
  905. data = {
  906. "printer_id": printer.id,
  907. }
  908. response = await async_client.post("/api/v1/queue/", json=data)
  909. assert response.status_code == 400
  910. assert (
  911. "archive_id" in response.json()["detail"].lower() or "library_file_id" in response.json()["detail"].lower()
  912. )
  913. @pytest.mark.asyncio
  914. @pytest.mark.integration
  915. async def test_update_queue_item_with_library_file(
  916. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  917. ):
  918. """Verify queue item with library_file_id can be updated."""
  919. from backend.app.models.print_queue import PrintQueueItem
  920. printer = await printer_factory()
  921. lib_file = await library_file_factory()
  922. # Create queue item directly
  923. item = PrintQueueItem(
  924. printer_id=printer.id,
  925. library_file_id=lib_file.id,
  926. status="pending",
  927. position=1,
  928. )
  929. db_session.add(item)
  930. await db_session.commit()
  931. await db_session.refresh(item)
  932. # Update the item
  933. response = await async_client.patch(
  934. f"/api/v1/queue/{item.id}",
  935. json={"auto_off_after": True, "plate_id": 3},
  936. )
  937. assert response.status_code == 200
  938. result = response.json()
  939. assert result["auto_off_after"] is True
  940. assert result["plate_id"] == 3
  941. assert result["library_file_id"] == lib_file.id
  942. @pytest.mark.asyncio
  943. @pytest.mark.integration
  944. async def test_list_queue_includes_library_file_info(
  945. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  946. ):
  947. """Verify queue list includes library file metadata."""
  948. from backend.app.models.print_queue import PrintQueueItem
  949. printer = await printer_factory()
  950. lib_file = await library_file_factory(
  951. file_metadata={"print_name": "Custom Print Name", "print_time_seconds": 7200}
  952. )
  953. item = PrintQueueItem(
  954. printer_id=printer.id,
  955. library_file_id=lib_file.id,
  956. status="pending",
  957. position=1,
  958. )
  959. db_session.add(item)
  960. await db_session.commit()
  961. response = await async_client.get("/api/v1/queue/")
  962. assert response.status_code == 200
  963. items = response.json()
  964. assert len(items) >= 1
  965. # Find our item
  966. our_item = next((i for i in items if i["library_file_id"] == lib_file.id), None)
  967. assert our_item is not None
  968. assert our_item["library_file_name"] == "Custom Print Name"
  969. assert our_item["print_time_seconds"] == 7200
  970. class TestBulkUpdateEndpoint:
  971. """Tests for the /queue/bulk endpoint."""
  972. @pytest.fixture
  973. async def printer_factory(self, db_session):
  974. """Factory to create test printers."""
  975. _counter = [0]
  976. async def _create_printer(**kwargs):
  977. from backend.app.models.printer import Printer
  978. _counter[0] += 1
  979. counter = _counter[0]
  980. defaults = {
  981. "name": f"Bulk Test Printer {counter}",
  982. "ip_address": f"192.168.1.{150 + counter}",
  983. "serial_number": f"TESTBULK{counter:04d}",
  984. "access_code": "12345678",
  985. "model": "X1C",
  986. }
  987. defaults.update(kwargs)
  988. printer = Printer(**defaults)
  989. db_session.add(printer)
  990. await db_session.commit()
  991. await db_session.refresh(printer)
  992. return printer
  993. return _create_printer
  994. @pytest.fixture
  995. async def archive_factory(self, db_session):
  996. """Factory to create test archives."""
  997. _counter = [0]
  998. async def _create_archive(**kwargs):
  999. from backend.app.models.archive import PrintArchive
  1000. _counter[0] += 1
  1001. counter = _counter[0]
  1002. defaults = {
  1003. "filename": f"bulk_test_{counter}.3mf",
  1004. "print_name": f"Bulk Test Print {counter}",
  1005. "file_path": f"/tmp/bulk_test_{counter}.3mf",
  1006. "file_size": 1024,
  1007. "content_hash": f"bulkhash{counter:04d}",
  1008. "status": "completed",
  1009. }
  1010. defaults.update(kwargs)
  1011. archive = PrintArchive(**defaults)
  1012. db_session.add(archive)
  1013. await db_session.commit()
  1014. await db_session.refresh(archive)
  1015. return archive
  1016. return _create_archive
  1017. @pytest.fixture
  1018. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  1019. """Factory to create test queue items."""
  1020. async def _create_item(**kwargs):
  1021. from backend.app.models.print_queue import PrintQueueItem
  1022. if "printer_id" not in kwargs:
  1023. printer = await printer_factory()
  1024. kwargs["printer_id"] = printer.id
  1025. if "archive_id" not in kwargs:
  1026. archive = await archive_factory()
  1027. kwargs["archive_id"] = archive.id
  1028. defaults = {
  1029. "status": "pending",
  1030. "position": 1,
  1031. "bed_levelling": "on",
  1032. "flow_cali": "off",
  1033. "vibration_cali": True,
  1034. }
  1035. defaults.update(kwargs)
  1036. item = PrintQueueItem(**defaults)
  1037. db_session.add(item)
  1038. await db_session.commit()
  1039. await db_session.refresh(item)
  1040. return item
  1041. return _create_item
  1042. @pytest.mark.asyncio
  1043. @pytest.mark.integration
  1044. async def test_bulk_update_single_field(self, async_client: AsyncClient, queue_item_factory, db_session):
  1045. """Verify bulk update can change a single field on multiple items."""
  1046. item1 = await queue_item_factory(bed_levelling="on")
  1047. item2 = await queue_item_factory(bed_levelling="on")
  1048. response = await async_client.patch(
  1049. "/api/v1/queue/bulk",
  1050. json={"item_ids": [item1.id, item2.id], "bed_levelling": "off"},
  1051. )
  1052. assert response.status_code == 200
  1053. result = response.json()
  1054. assert result["updated_count"] == 2
  1055. assert result["skipped_count"] == 0
  1056. # Verify items were updated
  1057. await db_session.refresh(item1)
  1058. await db_session.refresh(item2)
  1059. assert item1.bed_levelling == "off"
  1060. assert item2.bed_levelling == "off"
  1061. @pytest.mark.asyncio
  1062. @pytest.mark.integration
  1063. async def test_bulk_update_multiple_fields(self, async_client: AsyncClient, queue_item_factory, db_session):
  1064. """Verify bulk update can change multiple fields at once."""
  1065. item1 = await queue_item_factory(bed_levelling="on", flow_cali="off", manual_start=False)
  1066. item2 = await queue_item_factory(bed_levelling="on", flow_cali="off", manual_start=False)
  1067. response = await async_client.patch(
  1068. "/api/v1/queue/bulk",
  1069. json={
  1070. "item_ids": [item1.id, item2.id],
  1071. "bed_levelling": "off",
  1072. "flow_cali": "on",
  1073. "manual_start": True,
  1074. },
  1075. )
  1076. assert response.status_code == 200
  1077. result = response.json()
  1078. assert result["updated_count"] == 2
  1079. await db_session.refresh(item1)
  1080. assert item1.bed_levelling == "off"
  1081. assert item1.flow_cali == "on"
  1082. assert item1.manual_start is True
  1083. @pytest.mark.asyncio
  1084. @pytest.mark.integration
  1085. async def test_bulk_update_skips_non_pending(self, async_client: AsyncClient, queue_item_factory, db_session):
  1086. """Verify bulk update skips non-pending items."""
  1087. pending_item = await queue_item_factory(status="pending", bed_levelling="on")
  1088. printing_item = await queue_item_factory(status="printing", bed_levelling="on")
  1089. completed_item = await queue_item_factory(status="completed", bed_levelling="on")
  1090. response = await async_client.patch(
  1091. "/api/v1/queue/bulk",
  1092. json={
  1093. "item_ids": [pending_item.id, printing_item.id, completed_item.id],
  1094. "bed_levelling": "off",
  1095. },
  1096. )
  1097. assert response.status_code == 200
  1098. result = response.json()
  1099. assert result["updated_count"] == 1
  1100. assert result["skipped_count"] == 2
  1101. # Only pending item should be updated
  1102. await db_session.refresh(pending_item)
  1103. await db_session.refresh(printing_item)
  1104. await db_session.refresh(completed_item)
  1105. assert pending_item.bed_levelling == "off"
  1106. assert printing_item.bed_levelling == "on"
  1107. assert completed_item.bed_levelling == "on"
  1108. @pytest.mark.asyncio
  1109. @pytest.mark.integration
  1110. async def test_bulk_update_change_printer(
  1111. self, async_client: AsyncClient, queue_item_factory, printer_factory, db_session
  1112. ):
  1113. """Verify bulk update can reassign items to a different printer."""
  1114. new_printer = await printer_factory(name="New Target Printer")
  1115. item1 = await queue_item_factory()
  1116. item2 = await queue_item_factory()
  1117. original_printer_id = item1.printer_id
  1118. response = await async_client.patch(
  1119. "/api/v1/queue/bulk",
  1120. json={"item_ids": [item1.id, item2.id], "printer_id": new_printer.id},
  1121. )
  1122. assert response.status_code == 200
  1123. await db_session.refresh(item1)
  1124. await db_session.refresh(item2)
  1125. assert item1.printer_id == new_printer.id
  1126. assert item2.printer_id == new_printer.id
  1127. assert item1.printer_id != original_printer_id
  1128. @pytest.mark.asyncio
  1129. @pytest.mark.integration
  1130. async def test_bulk_update_empty_item_ids(self, async_client: AsyncClient):
  1131. """Verify 400 error when item_ids is empty."""
  1132. response = await async_client.patch(
  1133. "/api/v1/queue/bulk",
  1134. json={"item_ids": [], "bed_levelling": False},
  1135. )
  1136. assert response.status_code == 400
  1137. assert "no item" in response.json()["detail"].lower()
  1138. @pytest.mark.asyncio
  1139. @pytest.mark.integration
  1140. async def test_bulk_update_no_fields(self, async_client: AsyncClient, queue_item_factory):
  1141. """Verify 400 error when no fields to update."""
  1142. item = await queue_item_factory()
  1143. response = await async_client.patch(
  1144. "/api/v1/queue/bulk",
  1145. json={"item_ids": [item.id]},
  1146. )
  1147. assert response.status_code == 400
  1148. assert "no fields" in response.json()["detail"].lower()
  1149. @pytest.mark.asyncio
  1150. @pytest.mark.integration
  1151. async def test_bulk_update_invalid_printer(self, async_client: AsyncClient, queue_item_factory):
  1152. """Verify 400 error when printer_id doesn't exist."""
  1153. item = await queue_item_factory()
  1154. response = await async_client.patch(
  1155. "/api/v1/queue/bulk",
  1156. json={"item_ids": [item.id], "printer_id": 99999},
  1157. )
  1158. assert response.status_code == 400
  1159. assert "printer not found" in response.json()["detail"].lower()
  1160. class TestTargetLocationFeature:
  1161. """Tests for queue items with target_location (Issue #220)."""
  1162. @pytest.fixture
  1163. async def printer_factory(self, db_session):
  1164. """Factory to create test printers."""
  1165. _counter = [0]
  1166. async def _create_printer(**kwargs):
  1167. from backend.app.models.printer import Printer
  1168. _counter[0] += 1
  1169. counter = _counter[0]
  1170. defaults = {
  1171. "name": f"Location Test Printer {counter}",
  1172. "ip_address": f"192.168.1.{50 + counter}",
  1173. "serial_number": f"TESTLOC{counter:04d}",
  1174. "access_code": "12345678",
  1175. "model": "X1C",
  1176. }
  1177. defaults.update(kwargs)
  1178. printer = Printer(**defaults)
  1179. db_session.add(printer)
  1180. await db_session.commit()
  1181. await db_session.refresh(printer)
  1182. return printer
  1183. return _create_printer
  1184. @pytest.fixture
  1185. async def archive_factory(self, db_session):
  1186. """Factory to create test archives."""
  1187. _counter = [0]
  1188. async def _create_archive(**kwargs):
  1189. from backend.app.models.archive import PrintArchive
  1190. _counter[0] += 1
  1191. counter = _counter[0]
  1192. defaults = {
  1193. "filename": f"location_test_{counter}.3mf",
  1194. "print_name": f"Location Test Print {counter}",
  1195. "file_path": f"/tmp/location_test_{counter}.3mf",
  1196. "file_size": 1024,
  1197. "content_hash": f"lochash{counter:08d}",
  1198. "status": "completed",
  1199. }
  1200. defaults.update(kwargs)
  1201. archive = PrintArchive(**defaults)
  1202. db_session.add(archive)
  1203. await db_session.commit()
  1204. await db_session.refresh(archive)
  1205. return archive
  1206. return _create_archive
  1207. @pytest.fixture
  1208. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  1209. """Factory to create test queue items."""
  1210. _counter = [0]
  1211. async def _create_queue_item(**kwargs):
  1212. from backend.app.models.print_queue import PrintQueueItem
  1213. _counter[0] += 1
  1214. counter = _counter[0]
  1215. if "printer_id" not in kwargs and "target_model" not in kwargs:
  1216. printer = await printer_factory()
  1217. kwargs["printer_id"] = printer.id
  1218. if "archive_id" not in kwargs:
  1219. archive = await archive_factory()
  1220. kwargs["archive_id"] = archive.id
  1221. defaults = {
  1222. "status": "pending",
  1223. "position": counter,
  1224. }
  1225. defaults.update(kwargs)
  1226. item = PrintQueueItem(**defaults)
  1227. db_session.add(item)
  1228. await db_session.commit()
  1229. await db_session.refresh(item)
  1230. return item
  1231. return _create_queue_item
  1232. @pytest.mark.asyncio
  1233. @pytest.mark.integration
  1234. async def test_add_to_queue_with_target_location(
  1235. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1236. ):
  1237. """Verify item can be added with target_model and target_location."""
  1238. # Create a printer with model X1C so the API can validate
  1239. await printer_factory(model="X1C", location="Office")
  1240. archive = await archive_factory()
  1241. data = {
  1242. "target_model": "X1C",
  1243. "target_location": "Workbench",
  1244. "archive_id": archive.id,
  1245. }
  1246. response = await async_client.post("/api/v1/queue/", json=data)
  1247. assert response.status_code == 200
  1248. result = response.json()
  1249. assert result["target_model"] == "X1C"
  1250. assert result["target_location"] == "Workbench"
  1251. assert result["printer_id"] is None
  1252. @pytest.mark.asyncio
  1253. @pytest.mark.integration
  1254. async def test_add_to_queue_location_without_model_ignored(
  1255. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1256. ):
  1257. """Verify target_location without target_model is allowed (location is just ignored)."""
  1258. printer = await printer_factory()
  1259. archive = await archive_factory()
  1260. data = {
  1261. "printer_id": printer.id,
  1262. "target_location": "Workbench", # This gets ignored since printer_id is set
  1263. "archive_id": archive.id,
  1264. }
  1265. response = await async_client.post("/api/v1/queue/", json=data)
  1266. # The API accepts this but the location is only used with target_model
  1267. assert response.status_code == 200
  1268. result = response.json()
  1269. assert result["printer_id"] == printer.id
  1270. # Location may or may not be stored since it's meaningless without target_model
  1271. # The important thing is the request succeeds
  1272. @pytest.mark.asyncio
  1273. @pytest.mark.integration
  1274. async def test_queue_item_target_location_in_response(
  1275. self, async_client: AsyncClient, queue_item_factory, db_session
  1276. ):
  1277. """Verify target_location is returned in queue item response."""
  1278. item = await queue_item_factory(
  1279. printer_id=None,
  1280. target_model="X1C",
  1281. target_location="Workshop",
  1282. )
  1283. response = await async_client.get(f"/api/v1/queue/{item.id}")
  1284. assert response.status_code == 200
  1285. result = response.json()
  1286. assert result["target_model"] == "X1C"
  1287. assert result["target_location"] == "Workshop"
  1288. @pytest.mark.asyncio
  1289. @pytest.mark.integration
  1290. async def test_queue_list_includes_target_location(self, async_client: AsyncClient, queue_item_factory, db_session):
  1291. """Verify target_location is included in queue list."""
  1292. await queue_item_factory(
  1293. printer_id=None,
  1294. target_model="P1S",
  1295. target_location="Garage",
  1296. )
  1297. response = await async_client.get("/api/v1/queue/")
  1298. assert response.status_code == 200
  1299. items = response.json()
  1300. assert len(items) >= 1
  1301. # Find our item
  1302. our_item = next((i for i in items if i["target_location"] == "Garage"), None)
  1303. assert our_item is not None
  1304. assert our_item["target_model"] == "P1S"
  1305. @pytest.mark.asyncio
  1306. @pytest.mark.integration
  1307. async def test_update_queue_item_target_location(self, async_client: AsyncClient, queue_item_factory, db_session):
  1308. """Verify target_location can be updated on existing queue item."""
  1309. item = await queue_item_factory(
  1310. printer_id=None,
  1311. target_model="X1C",
  1312. target_location="Office",
  1313. )
  1314. response = await async_client.patch(
  1315. f"/api/v1/queue/{item.id}",
  1316. json={"target_location": "Basement"},
  1317. )
  1318. assert response.status_code == 200
  1319. result = response.json()
  1320. assert result["target_location"] == "Basement"
  1321. @pytest.mark.asyncio
  1322. @pytest.mark.integration
  1323. async def test_clear_target_location(self, async_client: AsyncClient, queue_item_factory, db_session):
  1324. """Verify target_location can be cleared (set to None)."""
  1325. item = await queue_item_factory(
  1326. printer_id=None,
  1327. target_model="X1C",
  1328. target_location="Office",
  1329. )
  1330. # Note: Setting to empty string should clear it
  1331. response = await async_client.patch(
  1332. f"/api/v1/queue/{item.id}",
  1333. json={"target_location": None},
  1334. )
  1335. assert response.status_code == 200
  1336. result = response.json()
  1337. assert result["target_location"] is None
  1338. # ------------------------------------------------------------------
  1339. # Cross-model dispatch gate (#2578): a G-code 3MF sliced for one model
  1340. # must not be queued for model-based dispatch to an incompatible model.
  1341. # ------------------------------------------------------------------
  1342. @pytest.mark.asyncio
  1343. @pytest.mark.integration
  1344. async def test_add_to_queue_rejects_cross_model_mismatch(
  1345. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1346. ):
  1347. """X1C-sliced archive + target_model=H2D must be rejected (#2578)."""
  1348. await printer_factory(model="H2D")
  1349. archive = await archive_factory(sliced_for_model="X1C")
  1350. response = await async_client.post(
  1351. "/api/v1/queue/",
  1352. json={"target_model": "H2D", "archive_id": archive.id},
  1353. )
  1354. assert response.status_code == 400
  1355. assert "sliced for X1C" in response.json()["detail"]
  1356. @pytest.mark.asyncio
  1357. @pytest.mark.integration
  1358. async def test_add_to_queue_allows_gcode_family_target(
  1359. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1360. ):
  1361. """X1C-sliced G-code on a P1S is an intentional mixed-farm workflow —
  1362. same kinematics/volume family, must stay allowed."""
  1363. await printer_factory(model="P1S")
  1364. archive = await archive_factory(sliced_for_model="X1C")
  1365. response = await async_client.post(
  1366. "/api/v1/queue/",
  1367. json={"target_model": "P1S", "archive_id": archive.id},
  1368. )
  1369. assert response.status_code == 200
  1370. assert response.json()["target_model"] == "P1S"
  1371. @pytest.mark.asyncio
  1372. @pytest.mark.integration
  1373. async def test_add_to_queue_without_sliced_metadata_not_blocked(
  1374. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1375. ):
  1376. """Legacy archives without sliced_for_model can't be validated — must keep working."""
  1377. await printer_factory(model="H2D")
  1378. archive = await archive_factory() # no sliced_for_model
  1379. response = await async_client.post(
  1380. "/api/v1/queue/",
  1381. json={"target_model": "H2D", "archive_id": archive.id},
  1382. )
  1383. assert response.status_code == 200
  1384. @pytest.mark.asyncio
  1385. @pytest.mark.integration
  1386. async def test_update_rejects_cross_model_mismatch(
  1387. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory, db_session
  1388. ):
  1389. """Editing an item must not be able to introduce an incompatible target either."""
  1390. await printer_factory(model="X1C")
  1391. await printer_factory(model="H2D")
  1392. archive = await archive_factory(sliced_for_model="X1C")
  1393. item = await queue_item_factory(printer_id=None, target_model="X1C", archive_id=archive.id)
  1394. response = await async_client.patch(f"/api/v1/queue/{item.id}", json={"target_model": "H2D"})
  1395. assert response.status_code == 400
  1396. assert "sliced for X1C" in response.json()["detail"]
  1397. @pytest.mark.asyncio
  1398. @pytest.mark.integration
  1399. async def test_update_can_fix_stale_mismatched_target(
  1400. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory, db_session
  1401. ):
  1402. """A pre-fix DB row with a wrong target (the reporter's rows 78-82) must be
  1403. repairable by editing the target back to the sliced-for model."""
  1404. await printer_factory(model="X1C")
  1405. archive = await archive_factory(sliced_for_model="X1C")
  1406. # Stale mismatched row written directly to the DB (bypasses the API gate)
  1407. item = await queue_item_factory(printer_id=None, target_model="H2D", archive_id=archive.id)
  1408. response = await async_client.patch(f"/api/v1/queue/{item.id}", json={"target_model": "X1C"})
  1409. assert response.status_code == 200
  1410. assert response.json()["target_model"] == "X1C"
  1411. class TestAbortedStatusNormalisation:
  1412. """Tests for issue #558: 'aborted' queue status causes 500 error."""
  1413. @pytest.fixture
  1414. async def printer_factory(self, db_session):
  1415. """Factory to create test printers."""
  1416. _counter = [0]
  1417. async def _create_printer(**kwargs):
  1418. from backend.app.models.printer import Printer
  1419. _counter[0] += 1
  1420. counter = _counter[0]
  1421. defaults = {
  1422. "name": f"Abort Test Printer {counter}",
  1423. "ip_address": f"192.168.1.{60 + counter}",
  1424. "serial_number": f"TESTABORT{counter:04d}",
  1425. "access_code": "12345678",
  1426. "model": "P1S",
  1427. }
  1428. defaults.update(kwargs)
  1429. printer = Printer(**defaults)
  1430. db_session.add(printer)
  1431. await db_session.commit()
  1432. await db_session.refresh(printer)
  1433. return printer
  1434. return _create_printer
  1435. @pytest.fixture
  1436. async def archive_factory(self, db_session):
  1437. """Factory to create test archives."""
  1438. _counter = [0]
  1439. async def _create_archive(**kwargs):
  1440. from backend.app.models.archive import PrintArchive
  1441. _counter[0] += 1
  1442. counter = _counter[0]
  1443. defaults = {
  1444. "filename": f"abort_test_{counter}.3mf",
  1445. "print_name": f"Abort Test Print {counter}",
  1446. "file_path": f"/tmp/abort_test_{counter}.3mf",
  1447. "file_size": 1024,
  1448. "content_hash": f"aborthash{counter:06d}",
  1449. "status": "completed",
  1450. }
  1451. defaults.update(kwargs)
  1452. archive = PrintArchive(**defaults)
  1453. db_session.add(archive)
  1454. await db_session.commit()
  1455. await db_session.refresh(archive)
  1456. return archive
  1457. return _create_archive
  1458. @pytest.fixture
  1459. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  1460. """Factory to create test queue items."""
  1461. _counter = [0]
  1462. async def _create_queue_item(**kwargs):
  1463. from backend.app.models.print_queue import PrintQueueItem
  1464. _counter[0] += 1
  1465. counter = _counter[0]
  1466. if "printer_id" not in kwargs:
  1467. printer = await printer_factory()
  1468. kwargs["printer_id"] = printer.id
  1469. if "archive_id" not in kwargs:
  1470. archive = await archive_factory()
  1471. kwargs["archive_id"] = archive.id
  1472. defaults = {
  1473. "status": "pending",
  1474. "position": counter,
  1475. }
  1476. defaults.update(kwargs)
  1477. item = PrintQueueItem(**defaults)
  1478. db_session.add(item)
  1479. await db_session.commit()
  1480. await db_session.refresh(item)
  1481. return item
  1482. return _create_queue_item
  1483. @pytest.mark.asyncio
  1484. @pytest.mark.integration
  1485. async def test_on_print_complete_normalises_aborted_to_cancelled(self, queue_item_factory, db_session):
  1486. """Verify the completion handler maps 'aborted' → 'cancelled' for queue items."""
  1487. import asyncio
  1488. from unittest.mock import AsyncMock, MagicMock, patch
  1489. item = await queue_item_factory(status="printing")
  1490. # Build a mock session whose execute returns our item
  1491. mock_result = MagicMock()
  1492. mock_result.scalars.return_value.all.return_value = [item]
  1493. mock_session = AsyncMock()
  1494. mock_session.__aenter__ = AsyncMock(return_value=mock_session)
  1495. mock_session.__aexit__ = AsyncMock(return_value=False)
  1496. mock_session.execute = AsyncMock(return_value=mock_result)
  1497. mock_session.commit = AsyncMock()
  1498. tasks_before = set(asyncio.all_tasks())
  1499. with (
  1500. patch("backend.app.main.async_session", return_value=mock_session),
  1501. patch("backend.app.core.database.async_session", return_value=mock_session),
  1502. patch("backend.app.main.ws_manager") as mock_ws,
  1503. patch("backend.app.main.mqtt_relay") as mock_relay,
  1504. patch("backend.app.main.notification_service") as mock_notif,
  1505. patch("backend.app.main.smart_plug_manager") as mock_plug,
  1506. patch("backend.app.main.printer_manager") as mock_pm,
  1507. ):
  1508. mock_ws.send_print_complete = AsyncMock()
  1509. mock_ws.broadcast = AsyncMock()
  1510. mock_relay.on_print_complete = AsyncMock()
  1511. mock_relay.on_queue_job_completed = AsyncMock()
  1512. mock_notif.on_print_complete = AsyncMock()
  1513. mock_plug.on_print_complete = AsyncMock()
  1514. mock_pm.get_printer.return_value = None
  1515. from backend.app.main import on_print_complete
  1516. await on_print_complete(
  1517. item.printer_id,
  1518. {
  1519. "status": "aborted",
  1520. "filename": "test.gcode",
  1521. "subtask_name": "Test",
  1522. "timelapse_was_active": False,
  1523. },
  1524. )
  1525. # Cancel background tasks before leaving mock context
  1526. for task in asyncio.all_tasks() - tasks_before:
  1527. task.cancel()
  1528. try:
  1529. await task
  1530. except (asyncio.CancelledError, Exception):
  1531. pass
  1532. # The item status should be normalised to 'cancelled', not 'aborted'
  1533. assert item.status == "cancelled"
  1534. @pytest.mark.asyncio
  1535. @pytest.mark.integration
  1536. async def test_startup_fixup_converts_aborted_to_cancelled(self, queue_item_factory, db_session):
  1537. """Verify the startup fixup converts existing 'aborted' rows to 'cancelled'."""
  1538. from sqlalchemy import select
  1539. from backend.app.models.print_queue import PrintQueueItem
  1540. # Create items with various statuses including 'aborted'
  1541. item_aborted = await queue_item_factory(status="pending")
  1542. item_pending = await queue_item_factory(status="pending")
  1543. # Manually set the invalid status
  1544. item_aborted.status = "aborted"
  1545. db_session.add(item_aborted)
  1546. await db_session.commit()
  1547. # Run the fixup query (same logic as lifespan)
  1548. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  1549. aborted_items = result.scalars().all()
  1550. for i in aborted_items:
  1551. i.status = "cancelled"
  1552. await db_session.commit()
  1553. # Verify: no more 'aborted' items
  1554. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  1555. assert len(result.scalars().all()) == 0
  1556. # The previously aborted item should now be 'cancelled'
  1557. await db_session.refresh(item_aborted)
  1558. assert item_aborted.status == "cancelled"
  1559. # The pending item should be unchanged
  1560. await db_session.refresh(item_pending)
  1561. assert item_pending.status == "pending"
  1562. @pytest.mark.asyncio
  1563. @pytest.mark.integration
  1564. async def test_completed_status_passes_through_unchanged(self, queue_item_factory, db_session):
  1565. """Verify normal statuses like 'completed' are not affected by normalisation."""
  1566. import asyncio
  1567. from unittest.mock import AsyncMock, MagicMock, patch
  1568. item = await queue_item_factory(status="printing")
  1569. mock_result = MagicMock()
  1570. mock_result.scalars.return_value.all.return_value = [item]
  1571. mock_session = AsyncMock()
  1572. mock_session.__aenter__ = AsyncMock(return_value=mock_session)
  1573. mock_session.__aexit__ = AsyncMock(return_value=False)
  1574. mock_session.execute = AsyncMock(return_value=mock_result)
  1575. mock_session.commit = AsyncMock()
  1576. tasks_before = set(asyncio.all_tasks())
  1577. with (
  1578. patch("backend.app.main.async_session", return_value=mock_session),
  1579. patch("backend.app.core.database.async_session", return_value=mock_session),
  1580. patch("backend.app.main.ws_manager") as mock_ws,
  1581. patch("backend.app.main.mqtt_relay") as mock_relay,
  1582. patch("backend.app.main.notification_service") as mock_notif,
  1583. patch("backend.app.main.smart_plug_manager") as mock_plug,
  1584. patch("backend.app.main.printer_manager") as mock_pm,
  1585. ):
  1586. mock_ws.send_print_complete = AsyncMock()
  1587. mock_ws.broadcast = AsyncMock()
  1588. mock_relay.on_print_complete = AsyncMock()
  1589. mock_relay.on_queue_job_completed = AsyncMock()
  1590. mock_notif.on_print_complete = AsyncMock()
  1591. mock_plug.on_print_complete = AsyncMock()
  1592. mock_pm.get_printer.return_value = None
  1593. from backend.app.main import on_print_complete
  1594. await on_print_complete(
  1595. item.printer_id,
  1596. {
  1597. "status": "completed",
  1598. "filename": "test.gcode",
  1599. "subtask_name": "Test",
  1600. "timelapse_was_active": False,
  1601. },
  1602. )
  1603. # Cancel background tasks before leaving mock context
  1604. for task in asyncio.all_tasks() - tasks_before:
  1605. task.cancel()
  1606. try:
  1607. await task
  1608. except (asyncio.CancelledError, Exception):
  1609. pass
  1610. assert item.status == "completed"
  1611. # ========================================================================
  1612. # Library file usage tracking on print completion (#1008)
  1613. #
  1614. # These exercise the _bump_library_file_usage_if_completed helper directly
  1615. # rather than invoking the whole on_print_complete handler — that path
  1616. # spawns background asyncio tasks (notifications, MQTT relay, smart-plug)
  1617. # that are expensive to mock and have nothing to do with the bump logic.
  1618. # ========================================================================
  1619. @pytest.mark.asyncio
  1620. @pytest.mark.integration
  1621. async def test_bump_library_file_usage_on_completed(self, printer_factory, db_session):
  1622. """Successful completion increments print_count and stamps last_printed_at."""
  1623. from datetime import datetime, timezone
  1624. from backend.app.main import _bump_library_file_usage_if_completed
  1625. from backend.app.models.library import LibraryFile
  1626. from backend.app.models.print_queue import PrintQueueItem
  1627. printer = await printer_factory()
  1628. lib_file = LibraryFile(
  1629. filename="benchy.gcode.3mf",
  1630. file_path="/data/library/benchy.gcode.3mf",
  1631. file_type="gcode.3mf",
  1632. file_size=1024,
  1633. print_count=0,
  1634. last_printed_at=None,
  1635. )
  1636. db_session.add(lib_file)
  1637. await db_session.commit()
  1638. await db_session.refresh(lib_file)
  1639. item = PrintQueueItem(
  1640. printer_id=printer.id,
  1641. library_file_id=lib_file.id,
  1642. status="printing",
  1643. position=1,
  1644. )
  1645. before = datetime.now(timezone.utc).replace(tzinfo=None)
  1646. await _bump_library_file_usage_if_completed(db_session, item, "completed")
  1647. await db_session.commit()
  1648. await db_session.refresh(lib_file)
  1649. assert lib_file.print_count == 1
  1650. assert lib_file.last_printed_at is not None
  1651. assert lib_file.last_printed_at >= before
  1652. @pytest.mark.asyncio
  1653. @pytest.mark.integration
  1654. async def test_bump_library_file_usage_repeated_prints_increment_count(self, printer_factory, db_session):
  1655. """Each successful completion bumps print_count cumulatively."""
  1656. from backend.app.main import _bump_library_file_usage_if_completed
  1657. from backend.app.models.library import LibraryFile
  1658. from backend.app.models.print_queue import PrintQueueItem
  1659. printer = await printer_factory()
  1660. lib_file = LibraryFile(
  1661. filename="repeat.gcode.3mf",
  1662. file_path="/data/library/repeat.gcode.3mf",
  1663. file_type="gcode.3mf",
  1664. file_size=1024,
  1665. print_count=0,
  1666. )
  1667. db_session.add(lib_file)
  1668. await db_session.commit()
  1669. await db_session.refresh(lib_file)
  1670. item = PrintQueueItem(
  1671. printer_id=printer.id,
  1672. library_file_id=lib_file.id,
  1673. status="printing",
  1674. position=1,
  1675. )
  1676. for _ in range(3):
  1677. await _bump_library_file_usage_if_completed(db_session, item, "completed")
  1678. await db_session.commit()
  1679. await db_session.refresh(lib_file)
  1680. assert lib_file.print_count == 3
  1681. @pytest.mark.asyncio
  1682. @pytest.mark.integration
  1683. @pytest.mark.parametrize("terminal_status", ["failed", "cancelled"])
  1684. async def test_bump_library_file_usage_skips_non_completed(self, printer_factory, db_session, terminal_status):
  1685. """Failed and cancelled prints must NOT count as usage."""
  1686. from backend.app.main import _bump_library_file_usage_if_completed
  1687. from backend.app.models.library import LibraryFile
  1688. from backend.app.models.print_queue import PrintQueueItem
  1689. printer = await printer_factory()
  1690. lib_file = LibraryFile(
  1691. filename="broken.gcode.3mf",
  1692. file_path="/data/library/broken.gcode.3mf",
  1693. file_type="gcode.3mf",
  1694. file_size=1024,
  1695. print_count=0,
  1696. last_printed_at=None,
  1697. )
  1698. db_session.add(lib_file)
  1699. await db_session.commit()
  1700. await db_session.refresh(lib_file)
  1701. item = PrintQueueItem(
  1702. printer_id=printer.id,
  1703. library_file_id=lib_file.id,
  1704. status="printing",
  1705. position=1,
  1706. )
  1707. await _bump_library_file_usage_if_completed(db_session, item, terminal_status)
  1708. await db_session.commit()
  1709. await db_session.refresh(lib_file)
  1710. assert lib_file.print_count == 0
  1711. assert lib_file.last_printed_at is None
  1712. @pytest.mark.asyncio
  1713. @pytest.mark.integration
  1714. async def test_bump_library_file_usage_skips_when_no_library_file_id(
  1715. self, printer_factory, archive_factory, db_session
  1716. ):
  1717. """Queue items without library_file_id (e.g. archive reprints) are a no-op."""
  1718. from backend.app.main import _bump_library_file_usage_if_completed
  1719. from backend.app.models.print_queue import PrintQueueItem
  1720. printer = await printer_factory()
  1721. archive = await archive_factory()
  1722. item = PrintQueueItem(
  1723. printer_id=printer.id,
  1724. library_file_id=None,
  1725. archive_id=archive.id,
  1726. status="printing",
  1727. position=1,
  1728. )
  1729. # Must not raise.
  1730. await _bump_library_file_usage_if_completed(db_session, item, "completed")
  1731. # ========================================================================
  1732. # Batch quantity tests
  1733. # ========================================================================
  1734. @pytest.mark.asyncio
  1735. @pytest.mark.integration
  1736. async def test_add_to_queue_quantity_default(
  1737. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1738. ):
  1739. """Verify quantity=1 (default) creates a single item with no batch."""
  1740. printer = await printer_factory()
  1741. archive = await archive_factory()
  1742. data = {
  1743. "printer_id": printer.id,
  1744. "archive_id": archive.id,
  1745. }
  1746. response = await async_client.post("/api/v1/queue/", json=data)
  1747. assert response.status_code == 200
  1748. result = response.json()
  1749. assert result["batch_id"] is None
  1750. assert result["batch_name"] is None
  1751. @pytest.mark.asyncio
  1752. @pytest.mark.integration
  1753. async def test_add_to_queue_quantity_one_explicit(
  1754. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1755. ):
  1756. """Verify quantity=1 explicitly creates a single item with no batch."""
  1757. printer = await printer_factory()
  1758. archive = await archive_factory()
  1759. data = {
  1760. "printer_id": printer.id,
  1761. "archive_id": archive.id,
  1762. "quantity": 1,
  1763. }
  1764. response = await async_client.post("/api/v1/queue/", json=data)
  1765. assert response.status_code == 200
  1766. result = response.json()
  1767. assert result["batch_id"] is None
  1768. assert result["batch_name"] is None
  1769. @pytest.mark.asyncio
  1770. @pytest.mark.integration
  1771. async def test_add_to_queue_quantity_creates_batch(
  1772. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1773. ):
  1774. """Verify quantity > 1 creates a batch and multiple queue items."""
  1775. printer = await printer_factory()
  1776. archive = await archive_factory()
  1777. data = {
  1778. "printer_id": printer.id,
  1779. "archive_id": archive.id,
  1780. "quantity": 3,
  1781. }
  1782. response = await async_client.post("/api/v1/queue/", json=data)
  1783. assert response.status_code == 200
  1784. result = response.json()
  1785. # First item is returned, linked to a batch
  1786. assert result["batch_id"] is not None
  1787. assert result["batch_name"] is not None
  1788. assert "×3" in result["batch_name"]
  1789. # Verify all 3 items were created
  1790. list_response = await async_client.get("/api/v1/queue/")
  1791. items = list_response.json()
  1792. batch_items = [i for i in items if i["batch_id"] == result["batch_id"]]
  1793. assert len(batch_items) == 3
  1794. # All items should have the same settings
  1795. for item in batch_items:
  1796. assert item["printer_id"] == printer.id
  1797. assert item["archive_id"] == archive.id
  1798. assert item["status"] == "pending"
  1799. @pytest.mark.asyncio
  1800. @pytest.mark.integration
  1801. async def test_add_to_queue_quantity_sequential_positions(
  1802. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1803. ):
  1804. """Verify batch items get sequential positions."""
  1805. printer = await printer_factory()
  1806. archive = await archive_factory()
  1807. data = {
  1808. "printer_id": printer.id,
  1809. "archive_id": archive.id,
  1810. "quantity": 3,
  1811. }
  1812. response = await async_client.post("/api/v1/queue/", json=data)
  1813. assert response.status_code == 200
  1814. batch_id = response.json()["batch_id"]
  1815. list_response = await async_client.get("/api/v1/queue/")
  1816. items = list_response.json()
  1817. batch_items = sorted(
  1818. [i for i in items if i["batch_id"] == batch_id],
  1819. key=lambda i: i["position"],
  1820. )
  1821. positions = [i["position"] for i in batch_items]
  1822. assert positions == [positions[0], positions[0] + 1, positions[0] + 2]
  1823. @pytest.mark.asyncio
  1824. @pytest.mark.integration
  1825. async def test_add_to_queue_insert_position_shifts_existing_items(
  1826. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1827. ):
  1828. """Verify priority insertion shifts existing pending items in the same printer queue."""
  1829. printer = await printer_factory()
  1830. first = await archive_factory(print_name="First")
  1831. second = await archive_factory(print_name="Second")
  1832. priority = await archive_factory(print_name="Priority")
  1833. assert (
  1834. await async_client.post("/api/v1/queue/", json={"printer_id": printer.id, "archive_id": first.id})
  1835. ).status_code == 200
  1836. assert (
  1837. await async_client.post("/api/v1/queue/", json={"printer_id": printer.id, "archive_id": second.id})
  1838. ).status_code == 200
  1839. response = await async_client.post(
  1840. "/api/v1/queue/",
  1841. json={
  1842. "printer_id": printer.id,
  1843. "archive_id": priority.id,
  1844. "insert_position": 1,
  1845. },
  1846. )
  1847. assert response.status_code == 200
  1848. list_response = await async_client.get(f"/api/v1/queue/?printer_id={printer.id}")
  1849. items = sorted(list_response.json(), key=lambda item: item["position"])
  1850. assert [item["archive_id"] for item in items[:3]] == [priority.id, first.id, second.id]
  1851. assert [item["position"] for item in items[:3]] == [1, 2, 3]
  1852. @pytest.mark.asyncio
  1853. @pytest.mark.integration
  1854. async def test_add_to_queue_insert_position_quantity_shifts_existing_by_quantity(
  1855. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1856. ):
  1857. """ASAP batch insertion shifts existing pending items by the inserted quantity."""
  1858. printer = await printer_factory()
  1859. first = await archive_factory(print_name="First")
  1860. second = await archive_factory(print_name="Second")
  1861. priority = await archive_factory(print_name="Priority")
  1862. assert (
  1863. await async_client.post("/api/v1/queue/", json={"printer_id": printer.id, "archive_id": first.id})
  1864. ).status_code == 200
  1865. assert (
  1866. await async_client.post("/api/v1/queue/", json={"printer_id": printer.id, "archive_id": second.id})
  1867. ).status_code == 200
  1868. response = await async_client.post(
  1869. "/api/v1/queue/",
  1870. json={
  1871. "printer_id": printer.id,
  1872. "archive_id": priority.id,
  1873. "quantity": 3,
  1874. "insert_position": 1,
  1875. },
  1876. )
  1877. assert response.status_code == 200
  1878. batch_id = response.json()["batch_id"]
  1879. list_response = await async_client.get(f"/api/v1/queue/?printer_id={printer.id}")
  1880. items = sorted(list_response.json(), key=lambda item: item["position"])
  1881. assert [item["archive_id"] for item in items] == [
  1882. priority.id,
  1883. priority.id,
  1884. priority.id,
  1885. first.id,
  1886. second.id,
  1887. ]
  1888. assert [item["position"] for item in items] == [1, 2, 3, 4, 5]
  1889. assert [item["batch_id"] for item in items[:3]] == [batch_id, batch_id, batch_id]
  1890. @pytest.mark.asyncio
  1891. @pytest.mark.integration
  1892. async def test_add_to_queue_insert_position_scopes_unassigned_items(
  1893. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1894. ):
  1895. """Unassigned inserts shift only the unassigned queue scope."""
  1896. printer = await printer_factory()
  1897. unassigned_first = await archive_factory(print_name="Unassigned First")
  1898. unassigned_second = await archive_factory(print_name="Unassigned Second")
  1899. assigned = await archive_factory(print_name="Assigned")
  1900. priority = await archive_factory(print_name="Unassigned Priority")
  1901. assert (await async_client.post("/api/v1/queue/", json={"archive_id": unassigned_first.id})).status_code == 200
  1902. assert (await async_client.post("/api/v1/queue/", json={"archive_id": unassigned_second.id})).status_code == 200
  1903. assigned_response = await async_client.post(
  1904. "/api/v1/queue/",
  1905. json={"printer_id": printer.id, "archive_id": assigned.id},
  1906. )
  1907. assert assigned_response.status_code == 200
  1908. assert assigned_response.json()["position"] == 1
  1909. response = await async_client.post(
  1910. "/api/v1/queue/",
  1911. json={
  1912. "archive_id": priority.id,
  1913. "insert_position": 1,
  1914. },
  1915. )
  1916. assert response.status_code == 200
  1917. unassigned_response = await async_client.get("/api/v1/queue/?printer_id=-1")
  1918. unassigned_items = sorted(unassigned_response.json(), key=lambda item: item["position"])
  1919. assert [item["archive_id"] for item in unassigned_items] == [
  1920. priority.id,
  1921. unassigned_first.id,
  1922. unassigned_second.id,
  1923. ]
  1924. assert [item["position"] for item in unassigned_items] == [1, 2, 3]
  1925. assigned_scope_response = await async_client.get(f"/api/v1/queue/?printer_id={printer.id}&target_model=NONE")
  1926. assigned_items = sorted(assigned_scope_response.json(), key=lambda item: item["position"])
  1927. assert [item["archive_id"] for item in assigned_items] == [assigned.id]
  1928. assert [item["position"] for item in assigned_items] == [1]
  1929. @pytest.mark.asyncio
  1930. @pytest.mark.integration
  1931. async def test_add_to_queue_insert_position_greater_than_max_appends_without_gap(
  1932. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1933. ):
  1934. """Oversized explicit insert_position appends at max+1 instead of creating sparse positions."""
  1935. printer = await printer_factory()
  1936. first = await archive_factory(print_name="First")
  1937. second = await archive_factory(print_name="Second")
  1938. appended = await archive_factory(print_name="Append")
  1939. assert (
  1940. await async_client.post("/api/v1/queue/", json={"printer_id": printer.id, "archive_id": first.id})
  1941. ).status_code == 200
  1942. assert (
  1943. await async_client.post("/api/v1/queue/", json={"printer_id": printer.id, "archive_id": second.id})
  1944. ).status_code == 200
  1945. response = await async_client.post(
  1946. "/api/v1/queue/",
  1947. json={
  1948. "printer_id": printer.id,
  1949. "archive_id": appended.id,
  1950. "insert_position": 99,
  1951. },
  1952. )
  1953. assert response.status_code == 200
  1954. assert response.json()["position"] == 3
  1955. list_response = await async_client.get(f"/api/v1/queue/?printer_id={printer.id}")
  1956. items = sorted(list_response.json(), key=lambda item: item["position"])
  1957. assert [item["archive_id"] for item in items] == [first.id, second.id, appended.id]
  1958. assert [item["position"] for item in items] == [1, 2, 3]
  1959. @pytest.mark.asyncio
  1960. @pytest.mark.integration
  1961. async def test_add_to_queue_consecutive_asap_inserts_stack_in_submission_order(
  1962. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1963. ):
  1964. """Consecutive ASAP inserts to the same printer preserve the client submission order."""
  1965. printer = await printer_factory()
  1966. existing = await archive_factory(print_name="Existing")
  1967. first_asap = await archive_factory(print_name="First ASAP")
  1968. second_asap = await archive_factory(print_name="Second ASAP")
  1969. assert (
  1970. await async_client.post("/api/v1/queue/", json={"printer_id": printer.id, "archive_id": existing.id})
  1971. ).status_code == 200
  1972. first_response = await async_client.post(
  1973. "/api/v1/queue/",
  1974. json={
  1975. "printer_id": printer.id,
  1976. "archive_id": first_asap.id,
  1977. "insert_position": 1,
  1978. },
  1979. )
  1980. assert first_response.status_code == 200
  1981. second_response = await async_client.post(
  1982. "/api/v1/queue/",
  1983. json={
  1984. "printer_id": printer.id,
  1985. "archive_id": second_asap.id,
  1986. "insert_position": 2,
  1987. },
  1988. )
  1989. assert second_response.status_code == 200
  1990. list_response = await async_client.get(f"/api/v1/queue/?printer_id={printer.id}")
  1991. items = sorted(list_response.json(), key=lambda item: item["position"])
  1992. assert [item["archive_id"] for item in items] == [first_asap.id, second_asap.id, existing.id]
  1993. assert [item["position"] for item in items] == [1, 2, 3]
  1994. @pytest.mark.asyncio
  1995. @pytest.mark.integration
  1996. async def test_add_to_queue_quantity_with_print_options(
  1997. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1998. ):
  1999. """Verify print options are applied to all batch items."""
  2000. printer = await printer_factory()
  2001. archive = await archive_factory()
  2002. data = {
  2003. "printer_id": printer.id,
  2004. "archive_id": archive.id,
  2005. "quantity": 2,
  2006. "bed_levelling": "off",
  2007. "timelapse": True,
  2008. }
  2009. response = await async_client.post("/api/v1/queue/", json=data)
  2010. assert response.status_code == 200
  2011. batch_id = response.json()["batch_id"]
  2012. list_response = await async_client.get("/api/v1/queue/")
  2013. batch_items = [i for i in list_response.json() if i["batch_id"] == batch_id]
  2014. assert len(batch_items) == 2
  2015. for item in batch_items:
  2016. assert item["bed_levelling"] == "off"
  2017. assert item["timelapse"] is True
  2018. @pytest.mark.asyncio
  2019. @pytest.mark.integration
  2020. async def test_get_batch(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  2021. """Verify batch can be retrieved with progress stats."""
  2022. printer = await printer_factory()
  2023. archive = await archive_factory()
  2024. # Create a batch of 3
  2025. data = {
  2026. "printer_id": printer.id,
  2027. "archive_id": archive.id,
  2028. "quantity": 3,
  2029. }
  2030. response = await async_client.post("/api/v1/queue/", json=data)
  2031. batch_id = response.json()["batch_id"]
  2032. # Get batch
  2033. response = await async_client.get(f"/api/v1/queue/batches/{batch_id}")
  2034. assert response.status_code == 200
  2035. result = response.json()
  2036. assert result["id"] == batch_id
  2037. assert result["quantity"] == 3
  2038. assert result["status"] == "active"
  2039. assert result["pending_count"] == 3
  2040. assert result["printing_count"] == 0
  2041. assert result["completed_count"] == 0
  2042. @pytest.mark.asyncio
  2043. @pytest.mark.integration
  2044. async def test_list_batches(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  2045. """Verify batches can be listed."""
  2046. printer = await printer_factory()
  2047. archive = await archive_factory()
  2048. # Create two batches
  2049. for qty in [2, 3]:
  2050. await async_client.post(
  2051. "/api/v1/queue/",
  2052. json={"printer_id": printer.id, "archive_id": archive.id, "quantity": qty},
  2053. )
  2054. response = await async_client.get("/api/v1/queue/batches")
  2055. assert response.status_code == 200
  2056. batches = response.json()
  2057. assert len(batches) >= 2
  2058. @pytest.mark.asyncio
  2059. @pytest.mark.integration
  2060. async def test_cancel_batch(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  2061. """Verify cancelling a batch cancels all pending items."""
  2062. printer = await printer_factory()
  2063. archive = await archive_factory()
  2064. data = {
  2065. "printer_id": printer.id,
  2066. "archive_id": archive.id,
  2067. "quantity": 3,
  2068. }
  2069. response = await async_client.post("/api/v1/queue/", json=data)
  2070. batch_id = response.json()["batch_id"]
  2071. # Cancel the batch
  2072. response = await async_client.delete(f"/api/v1/queue/batches/{batch_id}")
  2073. assert response.status_code == 200
  2074. # Verify all items are cancelled
  2075. list_response = await async_client.get("/api/v1/queue/")
  2076. batch_items = [i for i in list_response.json() if i["batch_id"] == batch_id]
  2077. for item in batch_items:
  2078. assert item["status"] == "cancelled"
  2079. # Verify batch status
  2080. batch_response = await async_client.get(f"/api/v1/queue/batches/{batch_id}")
  2081. assert batch_response.json()["status"] == "cancelled"
  2082. @pytest.mark.asyncio
  2083. @pytest.mark.integration
  2084. async def test_get_batch_not_found(self, async_client: AsyncClient):
  2085. """Verify 404 for non-existent batch."""
  2086. response = await async_client.get("/api/v1/queue/batches/9999")
  2087. assert response.status_code == 404
  2088. # ========================================================================
  2089. # Queue redesign: create-empty + group-existing + ungroup
  2090. # ========================================================================
  2091. @pytest.mark.asyncio
  2092. @pytest.mark.integration
  2093. async def test_create_empty_batch_for_client_side_grouping(
  2094. self, async_client: AsyncClient, printer_factory, archive_factory
  2095. ):
  2096. """Verify POST /queue/batches without item_ids creates an empty batch
  2097. whose id can be passed on subsequent /queue/ POSTs (the multi-plate
  2098. auto-batch flow). Subsequent items must end up with the same batch_id."""
  2099. printer = await printer_factory()
  2100. archive = await archive_factory()
  2101. # 1. Pre-create batch
  2102. batch_resp = await async_client.post(
  2103. "/api/v1/queue/batches",
  2104. json={"name": "Plates · 2 plates", "archive_id": archive.id},
  2105. )
  2106. assert batch_resp.status_code == 200
  2107. batch = batch_resp.json()
  2108. assert batch["status"] == "active"
  2109. batch_id = batch["id"]
  2110. # 2. Add two items referencing that batch
  2111. for plate_id in (1, 2):
  2112. item_resp = await async_client.post(
  2113. "/api/v1/queue/",
  2114. json={
  2115. "printer_id": printer.id,
  2116. "archive_id": archive.id,
  2117. "plate_id": plate_id,
  2118. "batch_id": batch_id,
  2119. },
  2120. )
  2121. assert item_resp.status_code == 200
  2122. assert item_resp.json()["batch_id"] == batch_id
  2123. # 3. Verify batch now has 2 pending children
  2124. list_resp = await async_client.get("/api/v1/queue/")
  2125. siblings = [i for i in list_resp.json() if i["batch_id"] == batch_id]
  2126. assert len(siblings) == 2
  2127. assert {i["plate_id"] for i in siblings} == {1, 2}
  2128. @pytest.mark.asyncio
  2129. @pytest.mark.integration
  2130. async def test_group_existing_items_as_batch(
  2131. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory
  2132. ):
  2133. """Verify POST /queue/batches with item_ids assigns batch_id to
  2134. existing pending items (the 'Group as batch' UI action)."""
  2135. printer = await printer_factory()
  2136. archive = await archive_factory()
  2137. item_a = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="pending")
  2138. item_b = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="pending")
  2139. resp = await async_client.post(
  2140. "/api/v1/queue/batches",
  2141. json={"name": "Manual group", "item_ids": [item_a.id, item_b.id]},
  2142. )
  2143. assert resp.status_code == 200
  2144. batch_id = resp.json()["id"]
  2145. list_resp = await async_client.get("/api/v1/queue/")
  2146. grouped = [i for i in list_resp.json() if i["batch_id"] == batch_id]
  2147. assert {i["id"] for i in grouped} == {item_a.id, item_b.id}
  2148. @pytest.mark.asyncio
  2149. @pytest.mark.integration
  2150. async def test_group_skips_non_pending_items(
  2151. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory
  2152. ):
  2153. """Verify grouping doesn't pull in already-completed/cancelled items."""
  2154. printer = await printer_factory()
  2155. archive = await archive_factory()
  2156. pending = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="pending")
  2157. completed = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="completed")
  2158. resp = await async_client.post(
  2159. "/api/v1/queue/batches",
  2160. json={"name": "Mixed", "item_ids": [pending.id, completed.id]},
  2161. )
  2162. assert resp.status_code == 200
  2163. batch_id = resp.json()["id"]
  2164. list_resp = await async_client.get("/api/v1/queue/")
  2165. grouped = [i for i in list_resp.json() if i["batch_id"] == batch_id]
  2166. assert {i["id"] for i in grouped} == {pending.id}
  2167. @pytest.mark.asyncio
  2168. @pytest.mark.integration
  2169. async def test_create_batch_requires_name(self, async_client: AsyncClient):
  2170. """Verify empty / whitespace-only name is rejected with 400."""
  2171. resp = await async_client.post("/api/v1/queue/batches", json={"name": " "})
  2172. assert resp.status_code == 400
  2173. @pytest.mark.asyncio
  2174. @pytest.mark.integration
  2175. async def test_ungroup_batch_clears_batch_id_and_deletes_row(
  2176. self, async_client: AsyncClient, printer_factory, archive_factory
  2177. ):
  2178. """Verify POST /queue/batches/{id}/ungroup clears batch_id from all
  2179. members and deletes the batch row when nothing remains assigned."""
  2180. printer = await printer_factory()
  2181. archive = await archive_factory()
  2182. # Create batch with two items via the existing quantity flow
  2183. add_resp = await async_client.post(
  2184. "/api/v1/queue/",
  2185. json={"printer_id": printer.id, "archive_id": archive.id, "quantity": 2},
  2186. )
  2187. batch_id = add_resp.json()["batch_id"]
  2188. # Ungroup
  2189. ungroup_resp = await async_client.post(f"/api/v1/queue/batches/{batch_id}/ungroup")
  2190. assert ungroup_resp.status_code == 200
  2191. assert ungroup_resp.json()["ungrouped_count"] == 2
  2192. # Verify items still exist but no longer batched
  2193. list_resp = await async_client.get("/api/v1/queue/")
  2194. ex_members = [i for i in list_resp.json() if i["batch_id"] == batch_id]
  2195. assert ex_members == []
  2196. # Batch row was deleted
  2197. get_resp = await async_client.get(f"/api/v1/queue/batches/{batch_id}")
  2198. assert get_resp.status_code == 404
  2199. @pytest.mark.asyncio
  2200. @pytest.mark.integration
  2201. async def test_add_to_queue_with_unknown_batch_id_404(
  2202. self, async_client: AsyncClient, printer_factory, archive_factory
  2203. ):
  2204. """Verify addToQueue with a non-existent batch_id is rejected."""
  2205. printer = await printer_factory()
  2206. archive = await archive_factory()
  2207. resp = await async_client.post(
  2208. "/api/v1/queue/",
  2209. json={
  2210. "printer_id": printer.id,
  2211. "archive_id": archive.id,
  2212. "batch_id": 99999,
  2213. },
  2214. )
  2215. assert resp.status_code == 404
  2216. # ========================================================================
  2217. # Soft-deleted archive handling (#1348 follow-up)
  2218. # ========================================================================
  2219. @pytest.mark.asyncio
  2220. @pytest.mark.integration
  2221. async def test_soft_delete_archive_deletes_all_related_queue_items(
  2222. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory, db_session
  2223. ):
  2224. """Soft-deleting an archive removes every related queue item, regardless
  2225. of status (#1734). Pre-#1734 only ``pending`` rows were flipped to
  2226. ``cancelled`` and stayed in the DB, surprising users who expected the
  2227. queue lines to disappear with the archive — especially on multi-plate
  2228. Send All uploads (#1733), where ONE archive backed N queue items and
  2229. soft-deleting the archive left N "cancelled" rows behind. The change
  2230. keeps the printing guard (a row with ``status='printing'`` blocks the
  2231. delete one layer up at the API route), so we never delete the row of
  2232. an actively-running print here.
  2233. Print history lives in ``PrintLogEntry`` (FK ``ON DELETE SET NULL``) —
  2234. the audit trail survives independently of the queue rows.
  2235. """
  2236. from sqlalchemy import select
  2237. from backend.app.models.print_queue import PrintQueueItem
  2238. from backend.app.services.archive import ArchiveService
  2239. printer = await printer_factory()
  2240. archive = await archive_factory(thumbnail_path="archives/test/test/thumbnail.png")
  2241. pending = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="pending")
  2242. completed = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="completed")
  2243. service = ArchiveService(db_session)
  2244. assert await service.soft_delete_archive(archive.id) is True
  2245. # Every queue row that referenced this archive is gone — both the
  2246. # pending and the completed rows. Print history (PrintLogEntry) is
  2247. # the authoritative record and is preserved by the FK SET NULL.
  2248. remaining = (
  2249. (await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id.in_([pending.id, completed.id]))))
  2250. .scalars()
  2251. .all()
  2252. )
  2253. assert remaining == [], (
  2254. "Soft-deleting the archive must delete every related queue row, "
  2255. f"got {[(r.id, r.status) for r in remaining]} still present"
  2256. )
  2257. @pytest.mark.asyncio
  2258. @pytest.mark.integration
  2259. async def test_queue_api_hides_archive_surface_when_soft_deleted(
  2260. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory, db_session
  2261. ):
  2262. """Queue serializer must NOT populate archive_thumbnail / archive_name
  2263. when the archive is soft-deleted — otherwise the frontend renders a
  2264. broken <img> and 404-storms the thumbnail / plates / plate-thumbnail
  2265. endpoints. archive_deleted=True signals the soft-deleted state so
  2266. the UI can render a 'source deleted' badge."""
  2267. from datetime import datetime, timezone
  2268. printer = await printer_factory()
  2269. archive = await archive_factory(
  2270. print_name="Test Print",
  2271. thumbnail_path="archives/test/test/thumbnail.png",
  2272. deleted_at=datetime.now(timezone.utc), # Pre-soft-deleted
  2273. )
  2274. item = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="cancelled")
  2275. resp = await async_client.get("/api/v1/queue/")
  2276. assert resp.status_code == 200
  2277. body = resp.json()
  2278. row = next((r for r in body if r["id"] == item.id), None)
  2279. assert row is not None
  2280. assert row["archive_deleted"] is True
  2281. assert row["archive_thumbnail"] is None, "must not expose stale thumbnail path for soft-deleted archive"
  2282. assert row["archive_name"] is None
  2283. @pytest.mark.asyncio
  2284. @pytest.mark.integration
  2285. async def test_queue_api_still_exposes_archive_surface_when_live(
  2286. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory, db_session
  2287. ):
  2288. """Sanity guard: the soft-delete suppression must not affect live
  2289. archives. archive_name / archive_thumbnail still flow through and
  2290. archive_deleted stays False."""
  2291. printer = await printer_factory()
  2292. archive = await archive_factory(
  2293. print_name="Live Archive",
  2294. thumbnail_path="archives/test/live/thumbnail.png",
  2295. )
  2296. item = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="pending")
  2297. resp = await async_client.get("/api/v1/queue/")
  2298. assert resp.status_code == 200
  2299. row = next((r for r in resp.json() if r["id"] == item.id), None)
  2300. assert row is not None
  2301. assert row["archive_deleted"] is False
  2302. assert row["archive_name"] == "Live Archive"
  2303. assert row["archive_thumbnail"] == "archives/test/live/thumbnail.png"
  2304. class TestResumeQueueAfterFailure:
  2305. """Integration tests for POST /api/v1/queue/printer/{id}/resume (#1818)."""
  2306. @pytest.fixture
  2307. async def printer_factory(self, db_session):
  2308. _counter = [0]
  2309. async def _create_printer(**kwargs):
  2310. from backend.app.models.printer import Printer
  2311. _counter[0] += 1
  2312. counter = _counter[0]
  2313. defaults = {
  2314. "name": f"Resume Printer {counter}",
  2315. "ip_address": f"192.168.42.{100 + counter}",
  2316. "serial_number": f"RESUMESERIAL{counter:04d}",
  2317. "access_code": "12345678",
  2318. "model": "P1S",
  2319. }
  2320. defaults.update(kwargs)
  2321. printer = Printer(**defaults)
  2322. db_session.add(printer)
  2323. await db_session.commit()
  2324. await db_session.refresh(printer)
  2325. return printer
  2326. return _create_printer
  2327. @pytest.fixture
  2328. async def archive_factory(self, db_session):
  2329. _counter = [0]
  2330. async def _create_archive(**kwargs):
  2331. from backend.app.models.archive import PrintArchive
  2332. _counter[0] += 1
  2333. counter = _counter[0]
  2334. defaults = {
  2335. "filename": f"resume_print_{counter}.3mf",
  2336. "print_name": f"Resume Print {counter}",
  2337. "file_path": f"/tmp/resume_print_{counter}.3mf", # nosec B108
  2338. "file_size": 1024,
  2339. "content_hash": f"resumehash{counter:08d}",
  2340. "status": "completed",
  2341. }
  2342. defaults.update(kwargs)
  2343. archive = PrintArchive(**defaults)
  2344. db_session.add(archive)
  2345. await db_session.commit()
  2346. await db_session.refresh(archive)
  2347. return archive
  2348. return _create_archive
  2349. async def _add_item(self, db_session, printer, archive_factory, **kwargs):
  2350. from backend.app.models.print_queue import PrintQueueItem
  2351. archive = await archive_factory()
  2352. defaults = {
  2353. "printer_id": printer.id,
  2354. "archive_id": archive.id,
  2355. "status": "pending",
  2356. "require_previous_success": True,
  2357. }
  2358. defaults.update(kwargs)
  2359. item = PrintQueueItem(**defaults)
  2360. db_session.add(item)
  2361. await db_session.commit()
  2362. await db_session.refresh(item)
  2363. return item
  2364. @pytest.mark.asyncio
  2365. @pytest.mark.integration
  2366. async def test_resume_unknown_printer_returns_404(self, async_client: AsyncClient):
  2367. resp = await async_client.post("/api/v1/queue/printer/999999/resume")
  2368. assert resp.status_code == 404
  2369. @pytest.mark.asyncio
  2370. @pytest.mark.integration
  2371. async def test_resume_no_op_on_clean_queue(self, async_client: AsyncClient, printer_factory):
  2372. """Calling resume on a printer with no failures and no skipped items
  2373. returns zero counts — endpoint is idempotent and safe to spam."""
  2374. printer = await printer_factory()
  2375. resp = await async_client.post(f"/api/v1/queue/printer/{printer.id}/resume")
  2376. assert resp.status_code == 200
  2377. assert resp.json() == {"acknowledged": 0, "restored": 0}
  2378. @pytest.mark.asyncio
  2379. @pytest.mark.integration
  2380. async def test_resume_acknowledges_failed_and_restores_skipped(
  2381. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2382. ):
  2383. """Reporter's scenario: failed predecessor + N skipped downstream items.
  2384. Resume sets gate_acknowledged on the failure and flips skipped → pending."""
  2385. from sqlalchemy import select
  2386. from backend.app.models.print_queue import PrintQueueItem
  2387. printer = await printer_factory()
  2388. failed = await self._add_item(db_session, printer, archive_factory, status="failed")
  2389. skipped_1 = await self._add_item(
  2390. db_session,
  2391. printer,
  2392. archive_factory,
  2393. status="skipped",
  2394. error_message="Previous print failed or was aborted",
  2395. )
  2396. skipped_2 = await self._add_item(
  2397. db_session,
  2398. printer,
  2399. archive_factory,
  2400. status="skipped",
  2401. error_message="Previous print failed or was aborted",
  2402. )
  2403. resp = await async_client.post(f"/api/v1/queue/printer/{printer.id}/resume")
  2404. assert resp.status_code == 200
  2405. assert resp.json() == {"acknowledged": 1, "restored": 2}
  2406. failed_id = failed.id
  2407. skipped_ids = [skipped_1.id, skipped_2.id]
  2408. db_session.expire_all()
  2409. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == failed_id))
  2410. assert result.scalar_one().gate_acknowledged is True
  2411. for sid in skipped_ids:
  2412. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == sid))
  2413. row = result.scalar_one()
  2414. assert row.status == "pending"
  2415. assert row.error_message is None
  2416. assert row.completed_at is None
  2417. @pytest.mark.asyncio
  2418. @pytest.mark.integration
  2419. async def test_resume_preserves_skipped_items_with_other_reasons(
  2420. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2421. ):
  2422. """Skipped items whose error_message is something OTHER than the
  2423. gate string (e.g. filament-deficit promotion, future skip reasons)
  2424. must not be touched — they encode different user intent."""
  2425. from sqlalchemy import select
  2426. from backend.app.models.print_queue import PrintQueueItem
  2427. printer = await printer_factory()
  2428. gate_skip = await self._add_item(
  2429. db_session,
  2430. printer,
  2431. archive_factory,
  2432. status="skipped",
  2433. error_message="Previous print failed or was aborted",
  2434. )
  2435. other_skip = await self._add_item(
  2436. db_session,
  2437. printer,
  2438. archive_factory,
  2439. status="skipped",
  2440. error_message="User skipped via UI",
  2441. )
  2442. gate_id = gate_skip.id
  2443. other_id = other_skip.id
  2444. resp = await async_client.post(f"/api/v1/queue/printer/{printer.id}/resume")
  2445. assert resp.json() == {"acknowledged": 0, "restored": 1}
  2446. db_session.expire_all()
  2447. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == gate_id))
  2448. assert result.scalar_one().status == "pending"
  2449. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == other_id))
  2450. assert result.scalar_one().status == "skipped"
  2451. @pytest.mark.asyncio
  2452. @pytest.mark.integration
  2453. async def test_resume_scoped_to_printer(
  2454. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2455. ):
  2456. """A resume on printer A must not clear printer B's gate — farms run
  2457. each printer's queue independently."""
  2458. from sqlalchemy import select
  2459. from backend.app.models.print_queue import PrintQueueItem
  2460. p1 = await printer_factory()
  2461. p2 = await printer_factory()
  2462. failed_p1 = await self._add_item(db_session, p1, archive_factory, status="failed")
  2463. failed_p2 = await self._add_item(db_session, p2, archive_factory, status="failed")
  2464. failed_p1_id = failed_p1.id
  2465. failed_p2_id = failed_p2.id
  2466. resp = await async_client.post(f"/api/v1/queue/printer/{p1.id}/resume")
  2467. assert resp.json() == {"acknowledged": 1, "restored": 0}
  2468. db_session.expire_all()
  2469. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == failed_p1_id))
  2470. assert result.scalar_one().gate_acknowledged is True
  2471. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == failed_p2_id))
  2472. assert result.scalar_one().gate_acknowledged is False
  2473. @pytest.mark.asyncio
  2474. @pytest.mark.integration
  2475. async def test_resume_handles_aborted_status(
  2476. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2477. ):
  2478. """Aborted prints (printer-detected mid-print failure) gate the same
  2479. way failed prints do and must also be acknowledgeable."""
  2480. from sqlalchemy import select
  2481. from backend.app.models.print_queue import PrintQueueItem
  2482. printer = await printer_factory()
  2483. aborted = await self._add_item(db_session, printer, archive_factory, status="aborted")
  2484. aborted_id = aborted.id
  2485. resp = await async_client.post(f"/api/v1/queue/printer/{printer.id}/resume")
  2486. assert resp.json() == {"acknowledged": 1, "restored": 0}
  2487. db_session.expire_all()
  2488. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == aborted_id))
  2489. assert result.scalar_one().gate_acknowledged is True
  2490. @pytest.mark.asyncio
  2491. @pytest.mark.integration
  2492. async def test_resume_idempotent_second_call_is_no_op(
  2493. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2494. ):
  2495. """Calling resume twice on the same printer doesn't re-acknowledge
  2496. the same failure — the second call sees acknowledged=0, restored=0."""
  2497. printer = await printer_factory()
  2498. await self._add_item(db_session, printer, archive_factory, status="failed")
  2499. await self._add_item(
  2500. db_session,
  2501. printer,
  2502. archive_factory,
  2503. status="skipped",
  2504. error_message="Previous print failed or was aborted",
  2505. )
  2506. first = await async_client.post(f"/api/v1/queue/printer/{printer.id}/resume")
  2507. assert first.json() == {"acknowledged": 1, "restored": 1}
  2508. second = await async_client.post(f"/api/v1/queue/printer/{printer.id}/resume")
  2509. assert second.json() == {"acknowledged": 0, "restored": 0}
  2510. class TestReorderEndpoint:
  2511. """Tests for the /queue/reorder endpoint (#1625-followup duplicate-position validator)."""
  2512. @pytest.fixture
  2513. async def printer_factory(self, db_session):
  2514. async def _create(**kwargs):
  2515. from backend.app.models.printer import Printer
  2516. defaults = {
  2517. "name": "Reorder Test Printer",
  2518. "ip_address": "192.168.1.220",
  2519. "serial_number": "TESTREORDER001",
  2520. "access_code": "12345678",
  2521. "model": "X1C",
  2522. }
  2523. defaults.update(kwargs)
  2524. printer = Printer(**defaults)
  2525. db_session.add(printer)
  2526. await db_session.commit()
  2527. await db_session.refresh(printer)
  2528. return printer
  2529. return _create
  2530. @pytest.fixture
  2531. async def archive_factory(self, db_session):
  2532. _counter = [0]
  2533. async def _create(**kwargs):
  2534. from backend.app.models.archive import PrintArchive
  2535. _counter[0] += 1
  2536. defaults = {
  2537. "filename": f"reorder_{_counter[0]}.3mf",
  2538. "print_name": f"Reorder {_counter[0]}",
  2539. "file_path": f"/tmp/reorder_{_counter[0]}.3mf", # nosec B108
  2540. "file_size": 1024,
  2541. "content_hash": f"reorderhash{_counter[0]:06d}",
  2542. "status": "completed",
  2543. }
  2544. defaults.update(kwargs)
  2545. archive = PrintArchive(**defaults)
  2546. db_session.add(archive)
  2547. await db_session.commit()
  2548. await db_session.refresh(archive)
  2549. return archive
  2550. return _create
  2551. @pytest.mark.asyncio
  2552. @pytest.mark.integration
  2553. async def test_reorder_rejects_duplicate_positions(
  2554. self, async_client: AsyncClient, db_session, printer_factory, archive_factory
  2555. ):
  2556. """Reorder payload with duplicate positions → 422 at schema layer.
  2557. Regression guard: pre-fix, a buggy client sending two items at the
  2558. same position would leave the queue in an inconsistent state (the
  2559. scheduler's ORDER BY (printer_id, position) tie would be broken by
  2560. physical row order — non-deterministic dispatch order).
  2561. """
  2562. from backend.app.models.print_queue import PrintQueueItem
  2563. printer = await printer_factory()
  2564. a1 = await archive_factory()
  2565. a2 = await archive_factory()
  2566. item1 = PrintQueueItem(printer_id=printer.id, archive_id=a1.id, status="pending", position=1)
  2567. item2 = PrintQueueItem(printer_id=printer.id, archive_id=a2.id, status="pending", position=2)
  2568. db_session.add_all([item1, item2])
  2569. await db_session.commit()
  2570. await db_session.refresh(item1)
  2571. await db_session.refresh(item2)
  2572. response = await async_client.post(
  2573. "/api/v1/queue/reorder",
  2574. json={
  2575. "items": [
  2576. {"id": item1.id, "position": 1},
  2577. {"id": item2.id, "position": 1}, # duplicate
  2578. ]
  2579. },
  2580. )
  2581. assert response.status_code == 422
  2582. body = response.json()
  2583. # Pydantic v2 wraps custom validator errors; the message must mention "Duplicate"
  2584. # so the FE can surface the actionable detail.
  2585. assert any("duplicate" in str(err).lower() for err in body.get("detail", []))
  2586. @pytest.mark.asyncio
  2587. @pytest.mark.integration
  2588. async def test_reorder_accepts_unique_positions(
  2589. self, async_client: AsyncClient, db_session, printer_factory, archive_factory
  2590. ):
  2591. """Reorder with unique positions succeeds and updates them in DB."""
  2592. from backend.app.models.print_queue import PrintQueueItem
  2593. printer = await printer_factory()
  2594. a1 = await archive_factory()
  2595. a2 = await archive_factory()
  2596. item1 = PrintQueueItem(printer_id=printer.id, archive_id=a1.id, status="pending", position=1)
  2597. item2 = PrintQueueItem(printer_id=printer.id, archive_id=a2.id, status="pending", position=2)
  2598. db_session.add_all([item1, item2])
  2599. await db_session.commit()
  2600. await db_session.refresh(item1)
  2601. await db_session.refresh(item2)
  2602. response = await async_client.post(
  2603. "/api/v1/queue/reorder",
  2604. json={
  2605. "items": [
  2606. {"id": item1.id, "position": 2},
  2607. {"id": item2.id, "position": 1},
  2608. ]
  2609. },
  2610. )
  2611. assert response.status_code == 200
  2612. await db_session.refresh(item1)
  2613. await db_session.refresh(item2)
  2614. assert item1.position == 2
  2615. assert item2.position == 1
  2616. class TestForceColorOverridesAreScopedToThePlate:
  2617. """Queueing several plates of one 3MF must not make each plate wait on the
  2618. colours of its siblings (#2551).
  2619. The print dialog builds one override list from every selected plate and posts
  2620. that same list with each plate's item, so the API is what has to keep only the
  2621. slots the plate prints -- a ``force_color_match`` entry blocks dispatch until
  2622. the printer has that exact colour loaded.
  2623. """
  2624. THREE_PLATES = """<?xml version="1.0" encoding="UTF-8"?>
  2625. <config>
  2626. <plate>
  2627. <metadata key="index" value="1"/>
  2628. <filament id="1" used_g="50.0" type="PLA" color="#0B2C7A"/>
  2629. </plate>
  2630. <plate>
  2631. <metadata key="index" value="2"/>
  2632. <filament id="2" used_g="40.0" type="PLA" color="#9B9EA0"/>
  2633. </plate>
  2634. <plate>
  2635. <metadata key="index" value="3"/>
  2636. <filament id="3" used_g="30.0" type="PLA" color="#F4EE2A"/>
  2637. </plate>
  2638. </config>
  2639. """
  2640. # What the dialog posts for every plate: the union of all three plates'
  2641. # filaments, each one force-matched.
  2642. ALL_THREE_COLORS = [
  2643. {"slot_id": 1, "type": "PLA", "color": "#0B2C7A", "color_name": "Army Blue", "force_color_match": True},
  2644. {"slot_id": 2, "type": "PLA", "color": "#9B9EA0", "color_name": "Ash Grey", "force_color_match": True},
  2645. {"slot_id": 3, "type": "PLA", "color": "#F4EE2A", "color_name": "Sunshine Yellow", "force_color_match": True},
  2646. ]
  2647. @pytest.fixture
  2648. async def multi_plate_archive(self, db_session, tmp_path):
  2649. """An archive whose 3MF really exists on disk, one colour per plate."""
  2650. import zipfile
  2651. from backend.app.models.archive import PrintArchive
  2652. file_path = tmp_path / "three_plates.gcode.3mf"
  2653. with zipfile.ZipFile(file_path, "w") as zf:
  2654. zf.writestr("Metadata/slice_info.config", self.THREE_PLATES)
  2655. archive = PrintArchive(
  2656. filename="three_plates.gcode.3mf",
  2657. print_name="Three Plates",
  2658. file_path=str(file_path),
  2659. file_size=file_path.stat().st_size,
  2660. content_hash="platehash0001",
  2661. status="completed",
  2662. )
  2663. db_session.add(archive)
  2664. await db_session.commit()
  2665. await db_session.refresh(archive)
  2666. return archive
  2667. @pytest.fixture
  2668. async def x1c(self, db_session):
  2669. from backend.app.models.printer import Printer
  2670. printer = Printer(
  2671. name="Force Color X1C",
  2672. ip_address="192.168.1.210",
  2673. serial_number="FORCECOLOR01",
  2674. access_code="12345678",
  2675. model="X1C",
  2676. )
  2677. db_session.add(printer)
  2678. await db_session.commit()
  2679. await db_session.refresh(printer)
  2680. return printer
  2681. @pytest.mark.asyncio
  2682. @pytest.mark.integration
  2683. async def test_each_plate_keeps_only_the_colour_it_prints(
  2684. self, async_client: AsyncClient, multi_plate_archive, x1c
  2685. ):
  2686. """The bug: plate 1 prints Army Blue only, but was stored demanding all three."""
  2687. stored = {}
  2688. for plate_id in (1, 2, 3):
  2689. response = await async_client.post(
  2690. "/api/v1/queue/",
  2691. json={
  2692. "target_model": "X1C",
  2693. "archive_id": multi_plate_archive.id,
  2694. "plate_id": plate_id,
  2695. "filament_overrides": self.ALL_THREE_COLORS,
  2696. },
  2697. )
  2698. assert response.status_code == 200
  2699. stored[plate_id] = response.json()["filament_overrides"]
  2700. assert [o["color_name"] for o in stored[1]] == ["Army Blue"]
  2701. assert [o["color_name"] for o in stored[2]] == ["Ash Grey"]
  2702. assert [o["color_name"] for o in stored[3]] == ["Sunshine Yellow"]
  2703. # The slot each entry maps to has to survive narrowing untouched, or the
  2704. # dispatch-time AMS mapping would key the override onto the wrong slot.
  2705. assert [o["slot_id"] for o in stored[2]] == [2]
  2706. @pytest.mark.asyncio
  2707. @pytest.mark.integration
  2708. async def test_whole_file_queue_keeps_every_colour(self, async_client: AsyncClient, multi_plate_archive, x1c):
  2709. """No plate_id means the job prints the whole file, so every colour is needed."""
  2710. response = await async_client.post(
  2711. "/api/v1/queue/",
  2712. json={
  2713. "target_model": "X1C",
  2714. "archive_id": multi_plate_archive.id,
  2715. "filament_overrides": self.ALL_THREE_COLORS,
  2716. },
  2717. )
  2718. assert response.status_code == 200
  2719. assert len(response.json()["filament_overrides"]) == 3
  2720. @pytest.mark.asyncio
  2721. @pytest.mark.integration
  2722. async def test_unreadable_3mf_keeps_every_colour(self, async_client: AsyncClient, db_session, tmp_path, x1c):
  2723. """When the plate's slots can't be read, keep the overrides rather than drop them.
  2724. An item waiting on a colour it doesn't need is visible and fixable; one that
  2725. silently lost its forced colour would dispatch in the wrong filament.
  2726. """
  2727. from backend.app.models.archive import PrintArchive
  2728. file_path = tmp_path / "not_a_zip.gcode.3mf"
  2729. file_path.write_text("this is not a 3mf")
  2730. archive = PrintArchive(
  2731. filename="not_a_zip.gcode.3mf",
  2732. print_name="Corrupt",
  2733. file_path=str(file_path),
  2734. file_size=file_path.stat().st_size,
  2735. content_hash="platehash0002",
  2736. status="completed",
  2737. )
  2738. db_session.add(archive)
  2739. await db_session.commit()
  2740. await db_session.refresh(archive)
  2741. response = await async_client.post(
  2742. "/api/v1/queue/",
  2743. json={
  2744. "target_model": "X1C",
  2745. "archive_id": archive.id,
  2746. "plate_id": 1,
  2747. "filament_overrides": self.ALL_THREE_COLORS,
  2748. },
  2749. )
  2750. assert response.status_code == 200
  2751. assert len(response.json()["filament_overrides"]) == 3
  2752. @pytest.mark.asyncio
  2753. @pytest.mark.integration
  2754. async def test_required_types_stay_scoped_to_the_plate(self, async_client: AsyncClient, db_session, tmp_path, x1c):
  2755. """Override types are merged into required_filament_types, so a shared list
  2756. also widened the type gate -- a PLA-only plate demanded PETG as well."""
  2757. import zipfile
  2758. from backend.app.models.archive import PrintArchive
  2759. xml = """<?xml version="1.0" encoding="UTF-8"?>
  2760. <config>
  2761. <plate>
  2762. <metadata key="index" value="1"/>
  2763. <filament id="1" used_g="50.0" type="PLA" color="#0B2C7A"/>
  2764. </plate>
  2765. <plate>
  2766. <metadata key="index" value="2"/>
  2767. <filament id="2" used_g="40.0" type="PETG" color="#9B9EA0"/>
  2768. </plate>
  2769. </config>
  2770. """
  2771. file_path = tmp_path / "mixed_types.gcode.3mf"
  2772. with zipfile.ZipFile(file_path, "w") as zf:
  2773. zf.writestr("Metadata/slice_info.config", xml)
  2774. archive = PrintArchive(
  2775. filename="mixed_types.gcode.3mf",
  2776. print_name="Mixed",
  2777. file_path=str(file_path),
  2778. file_size=file_path.stat().st_size,
  2779. content_hash="platehash0003",
  2780. status="completed",
  2781. )
  2782. db_session.add(archive)
  2783. await db_session.commit()
  2784. await db_session.refresh(archive)
  2785. response = await async_client.post(
  2786. "/api/v1/queue/",
  2787. json={
  2788. "target_model": "X1C",
  2789. "archive_id": archive.id,
  2790. "plate_id": 1,
  2791. "filament_overrides": [
  2792. {"slot_id": 1, "type": "PLA", "color": "#0B2C7A", "force_color_match": True},
  2793. {"slot_id": 2, "type": "PETG", "color": "#9B9EA0", "force_color_match": True},
  2794. ],
  2795. },
  2796. )
  2797. assert response.status_code == 200
  2798. assert response.json()["required_filament_types"] == ["PLA"]
  2799. @pytest.mark.asyncio
  2800. @pytest.mark.integration
  2801. async def test_editing_an_item_narrows_the_overrides_too(
  2802. self, async_client: AsyncClient, db_session, multi_plate_archive, x1c
  2803. ):
  2804. """The edit dialog posts the same shared list, so PATCH narrows it as well."""
  2805. from backend.app.models.print_queue import PrintQueueItem
  2806. item = PrintQueueItem(
  2807. target_model="X1C",
  2808. archive_id=multi_plate_archive.id,
  2809. plate_id=2,
  2810. status="pending",
  2811. position=1,
  2812. )
  2813. db_session.add(item)
  2814. await db_session.commit()
  2815. await db_session.refresh(item)
  2816. response = await async_client.patch(
  2817. f"/api/v1/queue/{item.id}",
  2818. json={"filament_overrides": self.ALL_THREE_COLORS},
  2819. )
  2820. assert response.status_code == 200
  2821. assert [o["color_name"] for o in response.json()["filament_overrides"]] == ["Ash Grey"]
  2822. @pytest.mark.asyncio
  2823. @pytest.mark.integration
  2824. async def test_editing_the_plate_renarrows_against_the_new_plate(
  2825. self, async_client: AsyncClient, db_session, multi_plate_archive, x1c
  2826. ):
  2827. """Moving an item to another plate must re-scope its colours to that plate."""
  2828. from backend.app.models.print_queue import PrintQueueItem
  2829. item = PrintQueueItem(
  2830. target_model="X1C",
  2831. archive_id=multi_plate_archive.id,
  2832. plate_id=1,
  2833. status="pending",
  2834. position=1,
  2835. )
  2836. db_session.add(item)
  2837. await db_session.commit()
  2838. await db_session.refresh(item)
  2839. response = await async_client.patch(
  2840. f"/api/v1/queue/{item.id}",
  2841. json={"plate_id": 3, "filament_overrides": self.ALL_THREE_COLORS},
  2842. )
  2843. assert response.status_code == 200
  2844. assert [o["color_name"] for o in response.json()["filament_overrides"]] == ["Sunshine Yellow"]
  2845. @pytest.mark.asyncio
  2846. async def test_stop_offline_reconciles_linked_archive_status_2603(
  2847. async_client: AsyncClient, printer_factory, archive_factory, db_session
  2848. ):
  2849. """Stopping a printing item while the printer is offline must also close out its
  2850. archive (#2603).
  2851. When the stop command reaches the printer, the later MQTT completion event flips
  2852. the archive to cancelled. When the printer is offline no such event ever arrives,
  2853. so without this the archive stays "printing" forever while the queue row is
  2854. already cancelled — the reporter's archive 436. The offline branch reconciles the
  2855. archive directly.
  2856. """
  2857. from unittest.mock import MagicMock, patch
  2858. from backend.app.models.print_queue import PrintQueueItem
  2859. printer = await printer_factory(name="Offline printer")
  2860. archive = await archive_factory(
  2861. printer.id, status="printing", plate_id=22, filename="heart 3.gcode.3mf", with_run=False
  2862. )
  2863. item = PrintQueueItem(printer_id=printer.id, archive_id=archive.id, status="printing")
  2864. db_session.add(item)
  2865. await db_session.commit()
  2866. await db_session.refresh(item)
  2867. # stop_print returns False => printer offline / not connected.
  2868. with patch(
  2869. "backend.app.services.printer_manager.printer_manager.stop_print",
  2870. MagicMock(return_value=False),
  2871. ):
  2872. resp = await async_client.post(f"/api/v1/queue/{item.id}/stop")
  2873. assert resp.status_code == 200
  2874. await db_session.refresh(item)
  2875. await db_session.refresh(archive)
  2876. assert item.status == "cancelled"
  2877. assert archive.status == "cancelled", "an offline stop must reconcile the archive, not leave it 'printing'"
  2878. assert archive.completed_at is not None
  2879. assert archive.failure_reason == "Stopped by user (printer was offline)"
  2880. @pytest.mark.asyncio
  2881. async def test_stop_online_leaves_archive_for_mqtt_to_reconcile_2603(
  2882. async_client: AsyncClient, printer_factory, archive_factory, db_session
  2883. ):
  2884. """When the stop command reaches the printer, the archive is left to the MQTT
  2885. completion path — the offline reconcile must NOT fire and pre-empt it."""
  2886. from unittest.mock import MagicMock, patch
  2887. from backend.app.models.print_queue import PrintQueueItem
  2888. printer = await printer_factory(name="Online printer")
  2889. archive = await archive_factory(printer.id, status="printing", filename="heart 3.gcode.3mf", with_run=False)
  2890. item = PrintQueueItem(printer_id=printer.id, archive_id=archive.id, status="printing")
  2891. db_session.add(item)
  2892. await db_session.commit()
  2893. await db_session.refresh(item)
  2894. with patch(
  2895. "backend.app.services.printer_manager.printer_manager.stop_print",
  2896. MagicMock(return_value=True),
  2897. ):
  2898. resp = await async_client.post(f"/api/v1/queue/{item.id}/stop")
  2899. assert resp.status_code == 200
  2900. await db_session.refresh(item)
  2901. await db_session.refresh(archive)
  2902. assert item.status == "cancelled"
  2903. assert archive.status == "printing", "an online stop must leave the archive for the MQTT completion path"