test_print_queue_api.py 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835
  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_project_id(
  124. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  125. ):
  126. """#932: queue items created from the project view carry project_id forward."""
  127. from backend.app.models.project import Project
  128. printer = await printer_factory()
  129. archive = await archive_factory()
  130. project = Project(name="Queue Project")
  131. db_session.add(project)
  132. await db_session.commit()
  133. await db_session.refresh(project)
  134. data = {
  135. "printer_id": printer.id,
  136. "archive_id": archive.id,
  137. "project_id": project.id,
  138. }
  139. response = await async_client.post("/api/v1/queue/", json=data)
  140. assert response.status_code == 200
  141. result = response.json()
  142. # The response schema may or may not echo project_id; the stored row is
  143. # what matters, so verify via DB.
  144. from sqlalchemy import select
  145. from backend.app.models.print_queue import PrintQueueItem
  146. row = (await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == result["id"]))).scalar_one()
  147. assert row.project_id == project.id
  148. @pytest.mark.asyncio
  149. @pytest.mark.integration
  150. async def test_add_to_queue_invalid_project_id_returns_404(
  151. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  152. ):
  153. """#932: bogus project_id must be rejected before the FK constraint fires.
  154. Regression guard for the pre-check added to add_to_queue. Without the
  155. validation, a nonexistent project_id would reach db.commit() and raise
  156. an IntegrityError → 500. The pre-check must convert that to a 404 so
  157. the UI gets a clean error it can surface.
  158. """
  159. printer = await printer_factory()
  160. archive = await archive_factory()
  161. data = {
  162. "printer_id": printer.id,
  163. "archive_id": archive.id,
  164. "project_id": 999999, # nonexistent
  165. }
  166. response = await async_client.post("/api/v1/queue/", json=data)
  167. assert response.status_code == 404
  168. assert "project" in response.json()["detail"].lower()
  169. @pytest.mark.asyncio
  170. @pytest.mark.integration
  171. async def test_add_to_queue_with_ams_mapping(
  172. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  173. ):
  174. """Verify item can be added to queue with ams_mapping."""
  175. printer = await printer_factory()
  176. archive = await archive_factory()
  177. data = {
  178. "printer_id": printer.id,
  179. "archive_id": archive.id,
  180. "ams_mapping": [5, -1, 2, -1], # Slot 1 -> tray 5, slot 3 -> tray 2
  181. }
  182. response = await async_client.post("/api/v1/queue/", json=data)
  183. assert response.status_code == 200
  184. result = response.json()
  185. assert result["printer_id"] == printer.id
  186. assert result["archive_id"] == archive.id
  187. assert result["ams_mapping"] == [5, -1, 2, -1]
  188. @pytest.mark.asyncio
  189. @pytest.mark.integration
  190. async def test_add_to_queue_with_plate_id(
  191. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  192. ):
  193. """Verify item can be added to queue with plate_id for multi-plate 3MF."""
  194. printer = await printer_factory()
  195. archive = await archive_factory()
  196. data = {
  197. "printer_id": printer.id,
  198. "archive_id": archive.id,
  199. "plate_id": 3,
  200. }
  201. response = await async_client.post("/api/v1/queue/", json=data)
  202. assert response.status_code == 200
  203. result = response.json()
  204. assert result["plate_id"] == 3
  205. @pytest.mark.asyncio
  206. @pytest.mark.integration
  207. async def test_add_to_queue_with_print_options(
  208. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  209. ):
  210. """Verify item can be added to queue with print options."""
  211. printer = await printer_factory()
  212. archive = await archive_factory()
  213. data = {
  214. "printer_id": printer.id,
  215. "archive_id": archive.id,
  216. "bed_levelling": False,
  217. "flow_cali": True,
  218. "vibration_cali": False,
  219. "layer_inspect": True,
  220. "timelapse": True,
  221. "use_ams": False,
  222. }
  223. response = await async_client.post("/api/v1/queue/", json=data)
  224. assert response.status_code == 200
  225. result = response.json()
  226. assert result["bed_levelling"] is False
  227. assert result["flow_cali"] is True
  228. assert result["vibration_cali"] is False
  229. assert result["layer_inspect"] is True
  230. assert result["timelapse"] is True
  231. assert result["use_ams"] is False
  232. @pytest.mark.asyncio
  233. @pytest.mark.integration
  234. async def test_update_queue_item_plate_id(self, async_client: AsyncClient, queue_item_factory, db_session):
  235. """Verify queue item plate_id can be updated."""
  236. item = await queue_item_factory()
  237. response = await async_client.patch(f"/api/v1/queue/{item.id}", json={"plate_id": 5})
  238. assert response.status_code == 200
  239. result = response.json()
  240. assert result["plate_id"] == 5
  241. @pytest.mark.asyncio
  242. @pytest.mark.integration
  243. async def test_update_queue_item_print_options(self, async_client: AsyncClient, queue_item_factory, db_session):
  244. """Verify queue item print options can be updated."""
  245. item = await queue_item_factory()
  246. response = await async_client.patch(
  247. f"/api/v1/queue/{item.id}",
  248. json={
  249. "bed_levelling": False,
  250. "timelapse": True,
  251. },
  252. )
  253. assert response.status_code == 200
  254. result = response.json()
  255. assert result["bed_levelling"] is False
  256. assert result["timelapse"] is True
  257. @pytest.mark.asyncio
  258. @pytest.mark.integration
  259. async def test_get_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  260. """Verify single queue item can be retrieved."""
  261. item = await queue_item_factory()
  262. response = await async_client.get(f"/api/v1/queue/{item.id}")
  263. assert response.status_code == 200
  264. assert response.json()["id"] == item.id
  265. @pytest.mark.asyncio
  266. @pytest.mark.integration
  267. async def test_get_queue_item_not_found(self, async_client: AsyncClient):
  268. """Verify 404 for non-existent queue item."""
  269. response = await async_client.get("/api/v1/queue/9999")
  270. assert response.status_code == 404
  271. @pytest.mark.asyncio
  272. @pytest.mark.integration
  273. async def test_update_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  274. """Verify queue item can be updated."""
  275. item = await queue_item_factory()
  276. response = await async_client.patch(f"/api/v1/queue/{item.id}", json={"auto_off_after": True})
  277. assert response.status_code == 200
  278. result = response.json()
  279. assert result["auto_off_after"] is True
  280. @pytest.mark.asyncio
  281. @pytest.mark.integration
  282. async def test_update_queue_item_manual_start(self, async_client: AsyncClient, queue_item_factory, db_session):
  283. """Verify queue item manual_start can be updated."""
  284. item = await queue_item_factory(manual_start=False)
  285. response = await async_client.patch(f"/api/v1/queue/{item.id}", json={"manual_start": True})
  286. assert response.status_code == 200
  287. result = response.json()
  288. assert result["manual_start"] is True
  289. @pytest.mark.asyncio
  290. @pytest.mark.integration
  291. async def test_delete_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  292. """Verify queue item can be deleted."""
  293. item = await queue_item_factory()
  294. response = await async_client.delete(f"/api/v1/queue/{item.id}")
  295. assert response.status_code == 200
  296. assert response.json()["message"] == "Queue item deleted"
  297. @pytest.mark.asyncio
  298. @pytest.mark.integration
  299. async def test_delete_queue_item_not_found(self, async_client: AsyncClient):
  300. """Verify 404 for deleting non-existent queue item."""
  301. response = await async_client.delete("/api/v1/queue/9999")
  302. assert response.status_code == 404
  303. class TestQueueStartEndpoint:
  304. """Tests for the /queue/{item_id}/start endpoint."""
  305. @pytest.fixture
  306. async def printer_factory(self, db_session):
  307. """Factory to create test printers."""
  308. _counter = [0]
  309. async def _create_printer(**kwargs):
  310. from backend.app.models.printer import Printer
  311. _counter[0] += 1
  312. counter = _counter[0]
  313. defaults = {
  314. "name": f"Test Printer {counter}",
  315. "ip_address": f"192.168.1.{100 + counter}",
  316. "serial_number": f"TESTSERIAL{counter:04d}",
  317. "access_code": "12345678",
  318. "model": "X1C",
  319. }
  320. defaults.update(kwargs)
  321. printer = Printer(**defaults)
  322. db_session.add(printer)
  323. await db_session.commit()
  324. await db_session.refresh(printer)
  325. return printer
  326. return _create_printer
  327. @pytest.fixture
  328. async def archive_factory(self, db_session):
  329. """Factory to create test archives."""
  330. _counter = [0]
  331. async def _create_archive(**kwargs):
  332. from backend.app.models.archive import PrintArchive
  333. _counter[0] += 1
  334. counter = _counter[0]
  335. defaults = {
  336. "filename": f"test_print_{counter}.3mf",
  337. "print_name": f"Test Print {counter}",
  338. "file_path": f"/tmp/test_print_{counter}.3mf",
  339. "file_size": 1024,
  340. "content_hash": f"testhash{counter:08d}",
  341. "status": "completed",
  342. }
  343. defaults.update(kwargs)
  344. archive = PrintArchive(**defaults)
  345. db_session.add(archive)
  346. await db_session.commit()
  347. await db_session.refresh(archive)
  348. return archive
  349. return _create_archive
  350. @pytest.fixture
  351. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  352. """Factory to create test queue items."""
  353. _counter = [0]
  354. async def _create_queue_item(**kwargs):
  355. from backend.app.models.print_queue import PrintQueueItem
  356. _counter[0] += 1
  357. counter = _counter[0]
  358. if "printer_id" not in kwargs:
  359. printer = await printer_factory()
  360. kwargs["printer_id"] = printer.id
  361. if "archive_id" not in kwargs:
  362. archive = await archive_factory()
  363. kwargs["archive_id"] = archive.id
  364. defaults = {
  365. "status": "pending",
  366. "position": counter,
  367. }
  368. defaults.update(kwargs)
  369. item = PrintQueueItem(**defaults)
  370. db_session.add(item)
  371. await db_session.commit()
  372. await db_session.refresh(item)
  373. return item
  374. return _create_queue_item
  375. @pytest.mark.asyncio
  376. @pytest.mark.integration
  377. async def test_start_staged_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  378. """Verify starting a staged (manual_start=True) queue item clears the flag."""
  379. item = await queue_item_factory(manual_start=True)
  380. assert item.manual_start is True
  381. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  382. assert response.status_code == 200
  383. result = response.json()
  384. assert result["manual_start"] is False
  385. assert result["status"] == "pending"
  386. @pytest.mark.asyncio
  387. @pytest.mark.integration
  388. async def test_start_non_staged_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  389. """Verify starting a non-staged queue item still works (idempotent)."""
  390. item = await queue_item_factory(manual_start=False)
  391. assert item.manual_start is False
  392. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  393. assert response.status_code == 200
  394. result = response.json()
  395. assert result["manual_start"] is False
  396. @pytest.mark.asyncio
  397. @pytest.mark.integration
  398. async def test_start_queue_item_not_found(self, async_client: AsyncClient):
  399. """Verify 404 for non-existent queue item."""
  400. response = await async_client.post("/api/v1/queue/9999/start")
  401. assert response.status_code == 404
  402. @pytest.mark.asyncio
  403. @pytest.mark.integration
  404. async def test_start_non_pending_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  405. """Verify 400 error when trying to start a non-pending queue item."""
  406. item = await queue_item_factory(status="printing", manual_start=True)
  407. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  408. assert response.status_code == 400
  409. assert "pending" in response.json()["detail"].lower()
  410. @pytest.mark.asyncio
  411. @pytest.mark.integration
  412. async def test_start_completed_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  413. """Verify 400 error when trying to start a completed queue item."""
  414. item = await queue_item_factory(status="completed", manual_start=True)
  415. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  416. assert response.status_code == 400
  417. class TestQueueCancelEndpoint:
  418. """Tests for the /queue/{item_id}/cancel endpoint."""
  419. @pytest.fixture
  420. async def printer_factory(self, db_session):
  421. """Factory to create test printers."""
  422. async def _create_printer(**kwargs):
  423. from backend.app.models.printer import Printer
  424. defaults = {
  425. "name": "Cancel Test Printer",
  426. "ip_address": "192.168.1.200",
  427. "serial_number": "TESTCANCEL001",
  428. "access_code": "12345678",
  429. "model": "X1C",
  430. }
  431. defaults.update(kwargs)
  432. printer = Printer(**defaults)
  433. db_session.add(printer)
  434. await db_session.commit()
  435. await db_session.refresh(printer)
  436. return printer
  437. return _create_printer
  438. @pytest.fixture
  439. async def archive_factory(self, db_session):
  440. """Factory to create test archives."""
  441. async def _create_archive(**kwargs):
  442. from backend.app.models.archive import PrintArchive
  443. defaults = {
  444. "filename": "cancel_test.3mf",
  445. "print_name": "Cancel Test Print",
  446. "file_path": "/tmp/cancel_test.3mf",
  447. "file_size": 1024,
  448. "content_hash": "cancelhash001",
  449. "status": "completed",
  450. }
  451. defaults.update(kwargs)
  452. archive = PrintArchive(**defaults)
  453. db_session.add(archive)
  454. await db_session.commit()
  455. await db_session.refresh(archive)
  456. return archive
  457. return _create_archive
  458. @pytest.fixture
  459. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  460. """Factory to create test queue items."""
  461. async def _create_queue_item(**kwargs):
  462. from backend.app.models.print_queue import PrintQueueItem
  463. if "printer_id" not in kwargs:
  464. printer = await printer_factory()
  465. kwargs["printer_id"] = printer.id
  466. if "archive_id" not in kwargs:
  467. archive = await archive_factory()
  468. kwargs["archive_id"] = archive.id
  469. defaults = {
  470. "status": "pending",
  471. "position": 1,
  472. }
  473. defaults.update(kwargs)
  474. item = PrintQueueItem(**defaults)
  475. db_session.add(item)
  476. await db_session.commit()
  477. await db_session.refresh(item)
  478. return item
  479. return _create_queue_item
  480. @pytest.mark.asyncio
  481. @pytest.mark.integration
  482. async def test_cancel_pending_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  483. """Verify cancelling a pending queue item."""
  484. item = await queue_item_factory(status="pending")
  485. response = await async_client.post(f"/api/v1/queue/{item.id}/cancel")
  486. assert response.status_code == 200
  487. assert response.json()["message"] == "Queue item cancelled"
  488. @pytest.mark.asyncio
  489. @pytest.mark.integration
  490. async def test_cancel_non_pending_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  491. """Verify 400 error when trying to cancel a non-pending queue item."""
  492. item = await queue_item_factory(status="printing")
  493. response = await async_client.post(f"/api/v1/queue/{item.id}/cancel")
  494. assert response.status_code == 400
  495. class TestQueueLibraryFileSupport:
  496. """Tests for queue items with library_file_id (instead of archive_id)."""
  497. @pytest.fixture
  498. async def printer_factory(self, db_session):
  499. """Factory to create test printers."""
  500. _counter = [0]
  501. async def _create_printer(**kwargs):
  502. from backend.app.models.printer import Printer
  503. _counter[0] += 1
  504. counter = _counter[0]
  505. defaults = {
  506. "name": f"Library Test Printer {counter}",
  507. "ip_address": f"192.168.1.{150 + counter}",
  508. "serial_number": f"TESTLIB{counter:04d}",
  509. "access_code": "12345678",
  510. "model": "X1C",
  511. }
  512. defaults.update(kwargs)
  513. printer = Printer(**defaults)
  514. db_session.add(printer)
  515. await db_session.commit()
  516. await db_session.refresh(printer)
  517. return printer
  518. return _create_printer
  519. @pytest.fixture
  520. async def library_file_factory(self, db_session):
  521. """Factory to create test library files."""
  522. _counter = [0]
  523. async def _create_library_file(**kwargs):
  524. from backend.app.models.library import LibraryFile
  525. _counter[0] += 1
  526. counter = _counter[0]
  527. defaults = {
  528. "filename": f"library_test_{counter}.3mf",
  529. "file_path": f"/test/library/library_test_{counter}.3mf",
  530. "file_size": 2048,
  531. "file_type": "3mf",
  532. "file_metadata": {"print_name": f"Library Print {counter}", "print_time_seconds": 3600},
  533. }
  534. defaults.update(kwargs)
  535. lib_file = LibraryFile(**defaults)
  536. db_session.add(lib_file)
  537. await db_session.commit()
  538. await db_session.refresh(lib_file)
  539. return lib_file
  540. return _create_library_file
  541. @pytest.mark.asyncio
  542. @pytest.mark.integration
  543. async def test_add_to_queue_with_library_file(
  544. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  545. ):
  546. """Verify item can be added to queue using library_file_id instead of archive_id."""
  547. printer = await printer_factory()
  548. lib_file = await library_file_factory()
  549. data = {
  550. "printer_id": printer.id,
  551. "library_file_id": lib_file.id,
  552. }
  553. response = await async_client.post("/api/v1/queue/", json=data)
  554. assert response.status_code == 200
  555. result = response.json()
  556. assert result["printer_id"] == printer.id
  557. assert result["library_file_id"] == lib_file.id
  558. assert result["archive_id"] is None
  559. assert result["status"] == "pending"
  560. assert result["library_file_name"] == "Library Print 1"
  561. assert result["print_time_seconds"] == 3600
  562. @pytest.mark.asyncio
  563. @pytest.mark.integration
  564. async def test_add_to_queue_library_file_with_options(
  565. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  566. ):
  567. """Verify library file queue item can have all options set."""
  568. printer = await printer_factory()
  569. lib_file = await library_file_factory()
  570. data = {
  571. "printer_id": printer.id,
  572. "library_file_id": lib_file.id,
  573. "ams_mapping": [1, 2, -1, -1],
  574. "plate_id": 2,
  575. "bed_levelling": False,
  576. "timelapse": True,
  577. "manual_start": True,
  578. }
  579. response = await async_client.post("/api/v1/queue/", json=data)
  580. assert response.status_code == 200
  581. result = response.json()
  582. assert result["library_file_id"] == lib_file.id
  583. assert result["ams_mapping"] == [1, 2, -1, -1]
  584. assert result["plate_id"] == 2
  585. assert result["bed_levelling"] is False
  586. assert result["timelapse"] is True
  587. assert result["manual_start"] is True
  588. @pytest.mark.asyncio
  589. @pytest.mark.integration
  590. async def test_add_to_queue_requires_archive_or_library_file(
  591. self, async_client: AsyncClient, printer_factory, db_session
  592. ):
  593. """Verify 400 error when neither archive_id nor library_file_id provided."""
  594. printer = await printer_factory()
  595. data = {
  596. "printer_id": printer.id,
  597. }
  598. response = await async_client.post("/api/v1/queue/", json=data)
  599. assert response.status_code == 400
  600. assert (
  601. "archive_id" in response.json()["detail"].lower() or "library_file_id" in response.json()["detail"].lower()
  602. )
  603. @pytest.mark.asyncio
  604. @pytest.mark.integration
  605. async def test_update_queue_item_with_library_file(
  606. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  607. ):
  608. """Verify queue item with library_file_id can be updated."""
  609. from backend.app.models.print_queue import PrintQueueItem
  610. printer = await printer_factory()
  611. lib_file = await library_file_factory()
  612. # Create queue item directly
  613. item = PrintQueueItem(
  614. printer_id=printer.id,
  615. library_file_id=lib_file.id,
  616. status="pending",
  617. position=1,
  618. )
  619. db_session.add(item)
  620. await db_session.commit()
  621. await db_session.refresh(item)
  622. # Update the item
  623. response = await async_client.patch(
  624. f"/api/v1/queue/{item.id}",
  625. json={"auto_off_after": True, "plate_id": 3},
  626. )
  627. assert response.status_code == 200
  628. result = response.json()
  629. assert result["auto_off_after"] is True
  630. assert result["plate_id"] == 3
  631. assert result["library_file_id"] == lib_file.id
  632. @pytest.mark.asyncio
  633. @pytest.mark.integration
  634. async def test_list_queue_includes_library_file_info(
  635. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  636. ):
  637. """Verify queue list includes library file metadata."""
  638. from backend.app.models.print_queue import PrintQueueItem
  639. printer = await printer_factory()
  640. lib_file = await library_file_factory(
  641. file_metadata={"print_name": "Custom Print Name", "print_time_seconds": 7200}
  642. )
  643. item = PrintQueueItem(
  644. printer_id=printer.id,
  645. library_file_id=lib_file.id,
  646. status="pending",
  647. position=1,
  648. )
  649. db_session.add(item)
  650. await db_session.commit()
  651. response = await async_client.get("/api/v1/queue/")
  652. assert response.status_code == 200
  653. items = response.json()
  654. assert len(items) >= 1
  655. # Find our item
  656. our_item = next((i for i in items if i["library_file_id"] == lib_file.id), None)
  657. assert our_item is not None
  658. assert our_item["library_file_name"] == "Custom Print Name"
  659. assert our_item["print_time_seconds"] == 7200
  660. class TestBulkUpdateEndpoint:
  661. """Tests for the /queue/bulk endpoint."""
  662. @pytest.fixture
  663. async def printer_factory(self, db_session):
  664. """Factory to create test printers."""
  665. _counter = [0]
  666. async def _create_printer(**kwargs):
  667. from backend.app.models.printer import Printer
  668. _counter[0] += 1
  669. counter = _counter[0]
  670. defaults = {
  671. "name": f"Bulk Test Printer {counter}",
  672. "ip_address": f"192.168.1.{150 + counter}",
  673. "serial_number": f"TESTBULK{counter:04d}",
  674. "access_code": "12345678",
  675. "model": "X1C",
  676. }
  677. defaults.update(kwargs)
  678. printer = Printer(**defaults)
  679. db_session.add(printer)
  680. await db_session.commit()
  681. await db_session.refresh(printer)
  682. return printer
  683. return _create_printer
  684. @pytest.fixture
  685. async def archive_factory(self, db_session):
  686. """Factory to create test archives."""
  687. _counter = [0]
  688. async def _create_archive(**kwargs):
  689. from backend.app.models.archive import PrintArchive
  690. _counter[0] += 1
  691. counter = _counter[0]
  692. defaults = {
  693. "filename": f"bulk_test_{counter}.3mf",
  694. "print_name": f"Bulk Test Print {counter}",
  695. "file_path": f"/tmp/bulk_test_{counter}.3mf",
  696. "file_size": 1024,
  697. "content_hash": f"bulkhash{counter:04d}",
  698. "status": "completed",
  699. }
  700. defaults.update(kwargs)
  701. archive = PrintArchive(**defaults)
  702. db_session.add(archive)
  703. await db_session.commit()
  704. await db_session.refresh(archive)
  705. return archive
  706. return _create_archive
  707. @pytest.fixture
  708. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  709. """Factory to create test queue items."""
  710. async def _create_item(**kwargs):
  711. from backend.app.models.print_queue import PrintQueueItem
  712. if "printer_id" not in kwargs:
  713. printer = await printer_factory()
  714. kwargs["printer_id"] = printer.id
  715. if "archive_id" not in kwargs:
  716. archive = await archive_factory()
  717. kwargs["archive_id"] = archive.id
  718. defaults = {
  719. "status": "pending",
  720. "position": 1,
  721. "bed_levelling": True,
  722. "flow_cali": False,
  723. "vibration_cali": True,
  724. }
  725. defaults.update(kwargs)
  726. item = PrintQueueItem(**defaults)
  727. db_session.add(item)
  728. await db_session.commit()
  729. await db_session.refresh(item)
  730. return item
  731. return _create_item
  732. @pytest.mark.asyncio
  733. @pytest.mark.integration
  734. async def test_bulk_update_single_field(self, async_client: AsyncClient, queue_item_factory, db_session):
  735. """Verify bulk update can change a single field on multiple items."""
  736. item1 = await queue_item_factory(bed_levelling=True)
  737. item2 = await queue_item_factory(bed_levelling=True)
  738. response = await async_client.patch(
  739. "/api/v1/queue/bulk",
  740. json={"item_ids": [item1.id, item2.id], "bed_levelling": False},
  741. )
  742. assert response.status_code == 200
  743. result = response.json()
  744. assert result["updated_count"] == 2
  745. assert result["skipped_count"] == 0
  746. # Verify items were updated
  747. await db_session.refresh(item1)
  748. await db_session.refresh(item2)
  749. assert item1.bed_levelling is False
  750. assert item2.bed_levelling is False
  751. @pytest.mark.asyncio
  752. @pytest.mark.integration
  753. async def test_bulk_update_multiple_fields(self, async_client: AsyncClient, queue_item_factory, db_session):
  754. """Verify bulk update can change multiple fields at once."""
  755. item1 = await queue_item_factory(bed_levelling=True, flow_cali=False, manual_start=False)
  756. item2 = await queue_item_factory(bed_levelling=True, flow_cali=False, manual_start=False)
  757. response = await async_client.patch(
  758. "/api/v1/queue/bulk",
  759. json={
  760. "item_ids": [item1.id, item2.id],
  761. "bed_levelling": False,
  762. "flow_cali": True,
  763. "manual_start": True,
  764. },
  765. )
  766. assert response.status_code == 200
  767. result = response.json()
  768. assert result["updated_count"] == 2
  769. await db_session.refresh(item1)
  770. assert item1.bed_levelling is False
  771. assert item1.flow_cali is True
  772. assert item1.manual_start is True
  773. @pytest.mark.asyncio
  774. @pytest.mark.integration
  775. async def test_bulk_update_skips_non_pending(self, async_client: AsyncClient, queue_item_factory, db_session):
  776. """Verify bulk update skips non-pending items."""
  777. pending_item = await queue_item_factory(status="pending", bed_levelling=True)
  778. printing_item = await queue_item_factory(status="printing", bed_levelling=True)
  779. completed_item = await queue_item_factory(status="completed", bed_levelling=True)
  780. response = await async_client.patch(
  781. "/api/v1/queue/bulk",
  782. json={
  783. "item_ids": [pending_item.id, printing_item.id, completed_item.id],
  784. "bed_levelling": False,
  785. },
  786. )
  787. assert response.status_code == 200
  788. result = response.json()
  789. assert result["updated_count"] == 1
  790. assert result["skipped_count"] == 2
  791. # Only pending item should be updated
  792. await db_session.refresh(pending_item)
  793. await db_session.refresh(printing_item)
  794. await db_session.refresh(completed_item)
  795. assert pending_item.bed_levelling is False
  796. assert printing_item.bed_levelling is True
  797. assert completed_item.bed_levelling is True
  798. @pytest.mark.asyncio
  799. @pytest.mark.integration
  800. async def test_bulk_update_change_printer(
  801. self, async_client: AsyncClient, queue_item_factory, printer_factory, db_session
  802. ):
  803. """Verify bulk update can reassign items to a different printer."""
  804. new_printer = await printer_factory(name="New Target Printer")
  805. item1 = await queue_item_factory()
  806. item2 = await queue_item_factory()
  807. original_printer_id = item1.printer_id
  808. response = await async_client.patch(
  809. "/api/v1/queue/bulk",
  810. json={"item_ids": [item1.id, item2.id], "printer_id": new_printer.id},
  811. )
  812. assert response.status_code == 200
  813. await db_session.refresh(item1)
  814. await db_session.refresh(item2)
  815. assert item1.printer_id == new_printer.id
  816. assert item2.printer_id == new_printer.id
  817. assert item1.printer_id != original_printer_id
  818. @pytest.mark.asyncio
  819. @pytest.mark.integration
  820. async def test_bulk_update_empty_item_ids(self, async_client: AsyncClient):
  821. """Verify 400 error when item_ids is empty."""
  822. response = await async_client.patch(
  823. "/api/v1/queue/bulk",
  824. json={"item_ids": [], "bed_levelling": False},
  825. )
  826. assert response.status_code == 400
  827. assert "no item" in response.json()["detail"].lower()
  828. @pytest.mark.asyncio
  829. @pytest.mark.integration
  830. async def test_bulk_update_no_fields(self, async_client: AsyncClient, queue_item_factory):
  831. """Verify 400 error when no fields to update."""
  832. item = await queue_item_factory()
  833. response = await async_client.patch(
  834. "/api/v1/queue/bulk",
  835. json={"item_ids": [item.id]},
  836. )
  837. assert response.status_code == 400
  838. assert "no fields" in response.json()["detail"].lower()
  839. @pytest.mark.asyncio
  840. @pytest.mark.integration
  841. async def test_bulk_update_invalid_printer(self, async_client: AsyncClient, queue_item_factory):
  842. """Verify 400 error when printer_id doesn't exist."""
  843. item = await queue_item_factory()
  844. response = await async_client.patch(
  845. "/api/v1/queue/bulk",
  846. json={"item_ids": [item.id], "printer_id": 99999},
  847. )
  848. assert response.status_code == 400
  849. assert "printer not found" in response.json()["detail"].lower()
  850. class TestTargetLocationFeature:
  851. """Tests for queue items with target_location (Issue #220)."""
  852. @pytest.fixture
  853. async def printer_factory(self, db_session):
  854. """Factory to create test printers."""
  855. _counter = [0]
  856. async def _create_printer(**kwargs):
  857. from backend.app.models.printer import Printer
  858. _counter[0] += 1
  859. counter = _counter[0]
  860. defaults = {
  861. "name": f"Location Test Printer {counter}",
  862. "ip_address": f"192.168.1.{50 + counter}",
  863. "serial_number": f"TESTLOC{counter:04d}",
  864. "access_code": "12345678",
  865. "model": "X1C",
  866. }
  867. defaults.update(kwargs)
  868. printer = Printer(**defaults)
  869. db_session.add(printer)
  870. await db_session.commit()
  871. await db_session.refresh(printer)
  872. return printer
  873. return _create_printer
  874. @pytest.fixture
  875. async def archive_factory(self, db_session):
  876. """Factory to create test archives."""
  877. _counter = [0]
  878. async def _create_archive(**kwargs):
  879. from backend.app.models.archive import PrintArchive
  880. _counter[0] += 1
  881. counter = _counter[0]
  882. defaults = {
  883. "filename": f"location_test_{counter}.3mf",
  884. "print_name": f"Location Test Print {counter}",
  885. "file_path": f"/tmp/location_test_{counter}.3mf",
  886. "file_size": 1024,
  887. "content_hash": f"lochash{counter:08d}",
  888. "status": "completed",
  889. }
  890. defaults.update(kwargs)
  891. archive = PrintArchive(**defaults)
  892. db_session.add(archive)
  893. await db_session.commit()
  894. await db_session.refresh(archive)
  895. return archive
  896. return _create_archive
  897. @pytest.fixture
  898. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  899. """Factory to create test queue items."""
  900. _counter = [0]
  901. async def _create_queue_item(**kwargs):
  902. from backend.app.models.print_queue import PrintQueueItem
  903. _counter[0] += 1
  904. counter = _counter[0]
  905. if "printer_id" not in kwargs and "target_model" not in kwargs:
  906. printer = await printer_factory()
  907. kwargs["printer_id"] = printer.id
  908. if "archive_id" not in kwargs:
  909. archive = await archive_factory()
  910. kwargs["archive_id"] = archive.id
  911. defaults = {
  912. "status": "pending",
  913. "position": counter,
  914. }
  915. defaults.update(kwargs)
  916. item = PrintQueueItem(**defaults)
  917. db_session.add(item)
  918. await db_session.commit()
  919. await db_session.refresh(item)
  920. return item
  921. return _create_queue_item
  922. @pytest.mark.asyncio
  923. @pytest.mark.integration
  924. async def test_add_to_queue_with_target_location(
  925. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  926. ):
  927. """Verify item can be added with target_model and target_location."""
  928. # Create a printer with model X1C so the API can validate
  929. await printer_factory(model="X1C", location="Office")
  930. archive = await archive_factory()
  931. data = {
  932. "target_model": "X1C",
  933. "target_location": "Workbench",
  934. "archive_id": archive.id,
  935. }
  936. response = await async_client.post("/api/v1/queue/", json=data)
  937. assert response.status_code == 200
  938. result = response.json()
  939. assert result["target_model"] == "X1C"
  940. assert result["target_location"] == "Workbench"
  941. assert result["printer_id"] is None
  942. @pytest.mark.asyncio
  943. @pytest.mark.integration
  944. async def test_add_to_queue_location_without_model_ignored(
  945. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  946. ):
  947. """Verify target_location without target_model is allowed (location is just ignored)."""
  948. printer = await printer_factory()
  949. archive = await archive_factory()
  950. data = {
  951. "printer_id": printer.id,
  952. "target_location": "Workbench", # This gets ignored since printer_id is set
  953. "archive_id": archive.id,
  954. }
  955. response = await async_client.post("/api/v1/queue/", json=data)
  956. # The API accepts this but the location is only used with target_model
  957. assert response.status_code == 200
  958. result = response.json()
  959. assert result["printer_id"] == printer.id
  960. # Location may or may not be stored since it's meaningless without target_model
  961. # The important thing is the request succeeds
  962. @pytest.mark.asyncio
  963. @pytest.mark.integration
  964. async def test_queue_item_target_location_in_response(
  965. self, async_client: AsyncClient, queue_item_factory, db_session
  966. ):
  967. """Verify target_location is returned in queue item response."""
  968. item = await queue_item_factory(
  969. printer_id=None,
  970. target_model="X1C",
  971. target_location="Workshop",
  972. )
  973. response = await async_client.get(f"/api/v1/queue/{item.id}")
  974. assert response.status_code == 200
  975. result = response.json()
  976. assert result["target_model"] == "X1C"
  977. assert result["target_location"] == "Workshop"
  978. @pytest.mark.asyncio
  979. @pytest.mark.integration
  980. async def test_queue_list_includes_target_location(self, async_client: AsyncClient, queue_item_factory, db_session):
  981. """Verify target_location is included in queue list."""
  982. await queue_item_factory(
  983. printer_id=None,
  984. target_model="P1S",
  985. target_location="Garage",
  986. )
  987. response = await async_client.get("/api/v1/queue/")
  988. assert response.status_code == 200
  989. items = response.json()
  990. assert len(items) >= 1
  991. # Find our item
  992. our_item = next((i for i in items if i["target_location"] == "Garage"), None)
  993. assert our_item is not None
  994. assert our_item["target_model"] == "P1S"
  995. @pytest.mark.asyncio
  996. @pytest.mark.integration
  997. async def test_update_queue_item_target_location(self, async_client: AsyncClient, queue_item_factory, db_session):
  998. """Verify target_location can be updated on existing queue item."""
  999. item = await queue_item_factory(
  1000. printer_id=None,
  1001. target_model="X1C",
  1002. target_location="Office",
  1003. )
  1004. response = await async_client.patch(
  1005. f"/api/v1/queue/{item.id}",
  1006. json={"target_location": "Basement"},
  1007. )
  1008. assert response.status_code == 200
  1009. result = response.json()
  1010. assert result["target_location"] == "Basement"
  1011. @pytest.mark.asyncio
  1012. @pytest.mark.integration
  1013. async def test_clear_target_location(self, async_client: AsyncClient, queue_item_factory, db_session):
  1014. """Verify target_location can be cleared (set to None)."""
  1015. item = await queue_item_factory(
  1016. printer_id=None,
  1017. target_model="X1C",
  1018. target_location="Office",
  1019. )
  1020. # Note: Setting to empty string should clear it
  1021. response = await async_client.patch(
  1022. f"/api/v1/queue/{item.id}",
  1023. json={"target_location": None},
  1024. )
  1025. assert response.status_code == 200
  1026. result = response.json()
  1027. assert result["target_location"] is None
  1028. class TestAbortedStatusNormalisation:
  1029. """Tests for issue #558: 'aborted' queue status causes 500 error."""
  1030. @pytest.fixture
  1031. async def printer_factory(self, db_session):
  1032. """Factory to create test printers."""
  1033. _counter = [0]
  1034. async def _create_printer(**kwargs):
  1035. from backend.app.models.printer import Printer
  1036. _counter[0] += 1
  1037. counter = _counter[0]
  1038. defaults = {
  1039. "name": f"Abort Test Printer {counter}",
  1040. "ip_address": f"192.168.1.{60 + counter}",
  1041. "serial_number": f"TESTABORT{counter:04d}",
  1042. "access_code": "12345678",
  1043. "model": "P1S",
  1044. }
  1045. defaults.update(kwargs)
  1046. printer = Printer(**defaults)
  1047. db_session.add(printer)
  1048. await db_session.commit()
  1049. await db_session.refresh(printer)
  1050. return printer
  1051. return _create_printer
  1052. @pytest.fixture
  1053. async def archive_factory(self, db_session):
  1054. """Factory to create test archives."""
  1055. _counter = [0]
  1056. async def _create_archive(**kwargs):
  1057. from backend.app.models.archive import PrintArchive
  1058. _counter[0] += 1
  1059. counter = _counter[0]
  1060. defaults = {
  1061. "filename": f"abort_test_{counter}.3mf",
  1062. "print_name": f"Abort Test Print {counter}",
  1063. "file_path": f"/tmp/abort_test_{counter}.3mf",
  1064. "file_size": 1024,
  1065. "content_hash": f"aborthash{counter:06d}",
  1066. "status": "completed",
  1067. }
  1068. defaults.update(kwargs)
  1069. archive = PrintArchive(**defaults)
  1070. db_session.add(archive)
  1071. await db_session.commit()
  1072. await db_session.refresh(archive)
  1073. return archive
  1074. return _create_archive
  1075. @pytest.fixture
  1076. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  1077. """Factory to create test queue items."""
  1078. _counter = [0]
  1079. async def _create_queue_item(**kwargs):
  1080. from backend.app.models.print_queue import PrintQueueItem
  1081. _counter[0] += 1
  1082. counter = _counter[0]
  1083. if "printer_id" not in kwargs:
  1084. printer = await printer_factory()
  1085. kwargs["printer_id"] = printer.id
  1086. if "archive_id" not in kwargs:
  1087. archive = await archive_factory()
  1088. kwargs["archive_id"] = archive.id
  1089. defaults = {
  1090. "status": "pending",
  1091. "position": counter,
  1092. }
  1093. defaults.update(kwargs)
  1094. item = PrintQueueItem(**defaults)
  1095. db_session.add(item)
  1096. await db_session.commit()
  1097. await db_session.refresh(item)
  1098. return item
  1099. return _create_queue_item
  1100. @pytest.mark.asyncio
  1101. @pytest.mark.integration
  1102. async def test_on_print_complete_normalises_aborted_to_cancelled(self, queue_item_factory, db_session):
  1103. """Verify the completion handler maps 'aborted' → 'cancelled' for queue items."""
  1104. import asyncio
  1105. from unittest.mock import AsyncMock, MagicMock, patch
  1106. item = await queue_item_factory(status="printing")
  1107. # Build a mock session whose execute returns our item
  1108. mock_result = MagicMock()
  1109. mock_result.scalars.return_value.all.return_value = [item]
  1110. mock_session = AsyncMock()
  1111. mock_session.__aenter__ = AsyncMock(return_value=mock_session)
  1112. mock_session.__aexit__ = AsyncMock(return_value=False)
  1113. mock_session.execute = AsyncMock(return_value=mock_result)
  1114. mock_session.commit = AsyncMock()
  1115. tasks_before = set(asyncio.all_tasks())
  1116. with (
  1117. patch("backend.app.main.async_session", return_value=mock_session),
  1118. patch("backend.app.core.database.async_session", return_value=mock_session),
  1119. patch("backend.app.main.ws_manager") as mock_ws,
  1120. patch("backend.app.main.mqtt_relay") as mock_relay,
  1121. patch("backend.app.main.notification_service") as mock_notif,
  1122. patch("backend.app.main.smart_plug_manager") as mock_plug,
  1123. patch("backend.app.main.printer_manager") as mock_pm,
  1124. ):
  1125. mock_ws.send_print_complete = AsyncMock()
  1126. mock_ws.broadcast = AsyncMock()
  1127. mock_relay.on_print_complete = AsyncMock()
  1128. mock_relay.on_queue_job_completed = AsyncMock()
  1129. mock_notif.on_print_complete = AsyncMock()
  1130. mock_plug.on_print_complete = AsyncMock()
  1131. mock_pm.get_printer.return_value = None
  1132. from backend.app.main import on_print_complete
  1133. await on_print_complete(
  1134. item.printer_id,
  1135. {
  1136. "status": "aborted",
  1137. "filename": "test.gcode",
  1138. "subtask_name": "Test",
  1139. "timelapse_was_active": False,
  1140. },
  1141. )
  1142. # Cancel background tasks before leaving mock context
  1143. for task in asyncio.all_tasks() - tasks_before:
  1144. task.cancel()
  1145. try:
  1146. await task
  1147. except (asyncio.CancelledError, Exception):
  1148. pass
  1149. # The item status should be normalised to 'cancelled', not 'aborted'
  1150. assert item.status == "cancelled"
  1151. @pytest.mark.asyncio
  1152. @pytest.mark.integration
  1153. async def test_startup_fixup_converts_aborted_to_cancelled(self, queue_item_factory, db_session):
  1154. """Verify the startup fixup converts existing 'aborted' rows to 'cancelled'."""
  1155. from sqlalchemy import select
  1156. from backend.app.models.print_queue import PrintQueueItem
  1157. # Create items with various statuses including 'aborted'
  1158. item_aborted = await queue_item_factory(status="pending")
  1159. item_pending = await queue_item_factory(status="pending")
  1160. # Manually set the invalid status
  1161. item_aborted.status = "aborted"
  1162. db_session.add(item_aborted)
  1163. await db_session.commit()
  1164. # Run the fixup query (same logic as lifespan)
  1165. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  1166. aborted_items = result.scalars().all()
  1167. for i in aborted_items:
  1168. i.status = "cancelled"
  1169. await db_session.commit()
  1170. # Verify: no more 'aborted' items
  1171. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  1172. assert len(result.scalars().all()) == 0
  1173. # The previously aborted item should now be 'cancelled'
  1174. await db_session.refresh(item_aborted)
  1175. assert item_aborted.status == "cancelled"
  1176. # The pending item should be unchanged
  1177. await db_session.refresh(item_pending)
  1178. assert item_pending.status == "pending"
  1179. @pytest.mark.asyncio
  1180. @pytest.mark.integration
  1181. async def test_completed_status_passes_through_unchanged(self, queue_item_factory, db_session):
  1182. """Verify normal statuses like 'completed' are not affected by normalisation."""
  1183. import asyncio
  1184. from unittest.mock import AsyncMock, MagicMock, patch
  1185. item = await queue_item_factory(status="printing")
  1186. mock_result = MagicMock()
  1187. mock_result.scalars.return_value.all.return_value = [item]
  1188. mock_session = AsyncMock()
  1189. mock_session.__aenter__ = AsyncMock(return_value=mock_session)
  1190. mock_session.__aexit__ = AsyncMock(return_value=False)
  1191. mock_session.execute = AsyncMock(return_value=mock_result)
  1192. mock_session.commit = AsyncMock()
  1193. tasks_before = set(asyncio.all_tasks())
  1194. with (
  1195. patch("backend.app.main.async_session", return_value=mock_session),
  1196. patch("backend.app.core.database.async_session", return_value=mock_session),
  1197. patch("backend.app.main.ws_manager") as mock_ws,
  1198. patch("backend.app.main.mqtt_relay") as mock_relay,
  1199. patch("backend.app.main.notification_service") as mock_notif,
  1200. patch("backend.app.main.smart_plug_manager") as mock_plug,
  1201. patch("backend.app.main.printer_manager") as mock_pm,
  1202. ):
  1203. mock_ws.send_print_complete = AsyncMock()
  1204. mock_ws.broadcast = AsyncMock()
  1205. mock_relay.on_print_complete = AsyncMock()
  1206. mock_relay.on_queue_job_completed = AsyncMock()
  1207. mock_notif.on_print_complete = AsyncMock()
  1208. mock_plug.on_print_complete = AsyncMock()
  1209. mock_pm.get_printer.return_value = None
  1210. from backend.app.main import on_print_complete
  1211. await on_print_complete(
  1212. item.printer_id,
  1213. {
  1214. "status": "completed",
  1215. "filename": "test.gcode",
  1216. "subtask_name": "Test",
  1217. "timelapse_was_active": False,
  1218. },
  1219. )
  1220. # Cancel background tasks before leaving mock context
  1221. for task in asyncio.all_tasks() - tasks_before:
  1222. task.cancel()
  1223. try:
  1224. await task
  1225. except (asyncio.CancelledError, Exception):
  1226. pass
  1227. assert item.status == "completed"
  1228. # ========================================================================
  1229. # Library file usage tracking on print completion (#1008)
  1230. #
  1231. # These exercise the _bump_library_file_usage_if_completed helper directly
  1232. # rather than invoking the whole on_print_complete handler — that path
  1233. # spawns background asyncio tasks (notifications, MQTT relay, smart-plug)
  1234. # that are expensive to mock and have nothing to do with the bump logic.
  1235. # ========================================================================
  1236. @pytest.mark.asyncio
  1237. @pytest.mark.integration
  1238. async def test_bump_library_file_usage_on_completed(self, printer_factory, db_session):
  1239. """Successful completion increments print_count and stamps last_printed_at."""
  1240. from datetime import datetime, timezone
  1241. from backend.app.main import _bump_library_file_usage_if_completed
  1242. from backend.app.models.library import LibraryFile
  1243. from backend.app.models.print_queue import PrintQueueItem
  1244. printer = await printer_factory()
  1245. lib_file = LibraryFile(
  1246. filename="benchy.gcode.3mf",
  1247. file_path="/data/library/benchy.gcode.3mf",
  1248. file_type="gcode.3mf",
  1249. file_size=1024,
  1250. print_count=0,
  1251. last_printed_at=None,
  1252. )
  1253. db_session.add(lib_file)
  1254. await db_session.commit()
  1255. await db_session.refresh(lib_file)
  1256. item = PrintQueueItem(
  1257. printer_id=printer.id,
  1258. library_file_id=lib_file.id,
  1259. status="printing",
  1260. position=1,
  1261. )
  1262. before = datetime.now(timezone.utc).replace(tzinfo=None)
  1263. await _bump_library_file_usage_if_completed(db_session, item, "completed")
  1264. await db_session.commit()
  1265. await db_session.refresh(lib_file)
  1266. assert lib_file.print_count == 1
  1267. assert lib_file.last_printed_at is not None
  1268. assert lib_file.last_printed_at >= before
  1269. @pytest.mark.asyncio
  1270. @pytest.mark.integration
  1271. async def test_bump_library_file_usage_repeated_prints_increment_count(self, printer_factory, db_session):
  1272. """Each successful completion bumps print_count cumulatively."""
  1273. from backend.app.main import _bump_library_file_usage_if_completed
  1274. from backend.app.models.library import LibraryFile
  1275. from backend.app.models.print_queue import PrintQueueItem
  1276. printer = await printer_factory()
  1277. lib_file = LibraryFile(
  1278. filename="repeat.gcode.3mf",
  1279. file_path="/data/library/repeat.gcode.3mf",
  1280. file_type="gcode.3mf",
  1281. file_size=1024,
  1282. print_count=0,
  1283. )
  1284. db_session.add(lib_file)
  1285. await db_session.commit()
  1286. await db_session.refresh(lib_file)
  1287. item = PrintQueueItem(
  1288. printer_id=printer.id,
  1289. library_file_id=lib_file.id,
  1290. status="printing",
  1291. position=1,
  1292. )
  1293. for _ in range(3):
  1294. await _bump_library_file_usage_if_completed(db_session, item, "completed")
  1295. await db_session.commit()
  1296. await db_session.refresh(lib_file)
  1297. assert lib_file.print_count == 3
  1298. @pytest.mark.asyncio
  1299. @pytest.mark.integration
  1300. @pytest.mark.parametrize("terminal_status", ["failed", "cancelled"])
  1301. async def test_bump_library_file_usage_skips_non_completed(self, printer_factory, db_session, terminal_status):
  1302. """Failed and cancelled prints must NOT count as usage."""
  1303. from backend.app.main import _bump_library_file_usage_if_completed
  1304. from backend.app.models.library import LibraryFile
  1305. from backend.app.models.print_queue import PrintQueueItem
  1306. printer = await printer_factory()
  1307. lib_file = LibraryFile(
  1308. filename="broken.gcode.3mf",
  1309. file_path="/data/library/broken.gcode.3mf",
  1310. file_type="gcode.3mf",
  1311. file_size=1024,
  1312. print_count=0,
  1313. last_printed_at=None,
  1314. )
  1315. db_session.add(lib_file)
  1316. await db_session.commit()
  1317. await db_session.refresh(lib_file)
  1318. item = PrintQueueItem(
  1319. printer_id=printer.id,
  1320. library_file_id=lib_file.id,
  1321. status="printing",
  1322. position=1,
  1323. )
  1324. await _bump_library_file_usage_if_completed(db_session, item, terminal_status)
  1325. await db_session.commit()
  1326. await db_session.refresh(lib_file)
  1327. assert lib_file.print_count == 0
  1328. assert lib_file.last_printed_at is None
  1329. @pytest.mark.asyncio
  1330. @pytest.mark.integration
  1331. async def test_bump_library_file_usage_skips_when_no_library_file_id(
  1332. self, printer_factory, archive_factory, db_session
  1333. ):
  1334. """Queue items without library_file_id (e.g. archive reprints) are a no-op."""
  1335. from backend.app.main import _bump_library_file_usage_if_completed
  1336. from backend.app.models.print_queue import PrintQueueItem
  1337. printer = await printer_factory()
  1338. archive = await archive_factory()
  1339. item = PrintQueueItem(
  1340. printer_id=printer.id,
  1341. library_file_id=None,
  1342. archive_id=archive.id,
  1343. status="printing",
  1344. position=1,
  1345. )
  1346. # Must not raise.
  1347. await _bump_library_file_usage_if_completed(db_session, item, "completed")
  1348. # ========================================================================
  1349. # Batch quantity tests
  1350. # ========================================================================
  1351. @pytest.mark.asyncio
  1352. @pytest.mark.integration
  1353. async def test_add_to_queue_quantity_default(
  1354. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1355. ):
  1356. """Verify quantity=1 (default) creates a single item with no batch."""
  1357. printer = await printer_factory()
  1358. archive = await archive_factory()
  1359. data = {
  1360. "printer_id": printer.id,
  1361. "archive_id": archive.id,
  1362. }
  1363. response = await async_client.post("/api/v1/queue/", json=data)
  1364. assert response.status_code == 200
  1365. result = response.json()
  1366. assert result["batch_id"] is None
  1367. assert result["batch_name"] is None
  1368. @pytest.mark.asyncio
  1369. @pytest.mark.integration
  1370. async def test_add_to_queue_quantity_one_explicit(
  1371. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1372. ):
  1373. """Verify quantity=1 explicitly creates a single item with no batch."""
  1374. printer = await printer_factory()
  1375. archive = await archive_factory()
  1376. data = {
  1377. "printer_id": printer.id,
  1378. "archive_id": archive.id,
  1379. "quantity": 1,
  1380. }
  1381. response = await async_client.post("/api/v1/queue/", json=data)
  1382. assert response.status_code == 200
  1383. result = response.json()
  1384. assert result["batch_id"] is None
  1385. assert result["batch_name"] is None
  1386. @pytest.mark.asyncio
  1387. @pytest.mark.integration
  1388. async def test_add_to_queue_quantity_creates_batch(
  1389. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1390. ):
  1391. """Verify quantity > 1 creates a batch and multiple queue items."""
  1392. printer = await printer_factory()
  1393. archive = await archive_factory()
  1394. data = {
  1395. "printer_id": printer.id,
  1396. "archive_id": archive.id,
  1397. "quantity": 3,
  1398. }
  1399. response = await async_client.post("/api/v1/queue/", json=data)
  1400. assert response.status_code == 200
  1401. result = response.json()
  1402. # First item is returned, linked to a batch
  1403. assert result["batch_id"] is not None
  1404. assert result["batch_name"] is not None
  1405. assert "×3" in result["batch_name"]
  1406. # Verify all 3 items were created
  1407. list_response = await async_client.get("/api/v1/queue/")
  1408. items = list_response.json()
  1409. batch_items = [i for i in items if i["batch_id"] == result["batch_id"]]
  1410. assert len(batch_items) == 3
  1411. # All items should have the same settings
  1412. for item in batch_items:
  1413. assert item["printer_id"] == printer.id
  1414. assert item["archive_id"] == archive.id
  1415. assert item["status"] == "pending"
  1416. @pytest.mark.asyncio
  1417. @pytest.mark.integration
  1418. async def test_add_to_queue_quantity_sequential_positions(
  1419. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1420. ):
  1421. """Verify batch items get sequential positions."""
  1422. printer = await printer_factory()
  1423. archive = await archive_factory()
  1424. data = {
  1425. "printer_id": printer.id,
  1426. "archive_id": archive.id,
  1427. "quantity": 3,
  1428. }
  1429. response = await async_client.post("/api/v1/queue/", json=data)
  1430. assert response.status_code == 200
  1431. batch_id = response.json()["batch_id"]
  1432. list_response = await async_client.get("/api/v1/queue/")
  1433. items = list_response.json()
  1434. batch_items = sorted(
  1435. [i for i in items if i["batch_id"] == batch_id],
  1436. key=lambda i: i["position"],
  1437. )
  1438. positions = [i["position"] for i in batch_items]
  1439. assert positions == [positions[0], positions[0] + 1, positions[0] + 2]
  1440. @pytest.mark.asyncio
  1441. @pytest.mark.integration
  1442. async def test_add_to_queue_quantity_with_print_options(
  1443. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1444. ):
  1445. """Verify print options are applied to all batch items."""
  1446. printer = await printer_factory()
  1447. archive = await archive_factory()
  1448. data = {
  1449. "printer_id": printer.id,
  1450. "archive_id": archive.id,
  1451. "quantity": 2,
  1452. "bed_levelling": False,
  1453. "timelapse": True,
  1454. }
  1455. response = await async_client.post("/api/v1/queue/", json=data)
  1456. assert response.status_code == 200
  1457. batch_id = response.json()["batch_id"]
  1458. list_response = await async_client.get("/api/v1/queue/")
  1459. batch_items = [i for i in list_response.json() if i["batch_id"] == batch_id]
  1460. assert len(batch_items) == 2
  1461. for item in batch_items:
  1462. assert item["bed_levelling"] is False
  1463. assert item["timelapse"] is True
  1464. @pytest.mark.asyncio
  1465. @pytest.mark.integration
  1466. async def test_get_batch(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  1467. """Verify batch can be retrieved with progress stats."""
  1468. printer = await printer_factory()
  1469. archive = await archive_factory()
  1470. # Create a batch of 3
  1471. data = {
  1472. "printer_id": printer.id,
  1473. "archive_id": archive.id,
  1474. "quantity": 3,
  1475. }
  1476. response = await async_client.post("/api/v1/queue/", json=data)
  1477. batch_id = response.json()["batch_id"]
  1478. # Get batch
  1479. response = await async_client.get(f"/api/v1/queue/batches/{batch_id}")
  1480. assert response.status_code == 200
  1481. result = response.json()
  1482. assert result["id"] == batch_id
  1483. assert result["quantity"] == 3
  1484. assert result["status"] == "active"
  1485. assert result["pending_count"] == 3
  1486. assert result["printing_count"] == 0
  1487. assert result["completed_count"] == 0
  1488. @pytest.mark.asyncio
  1489. @pytest.mark.integration
  1490. async def test_list_batches(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  1491. """Verify batches can be listed."""
  1492. printer = await printer_factory()
  1493. archive = await archive_factory()
  1494. # Create two batches
  1495. for qty in [2, 3]:
  1496. await async_client.post(
  1497. "/api/v1/queue/",
  1498. json={"printer_id": printer.id, "archive_id": archive.id, "quantity": qty},
  1499. )
  1500. response = await async_client.get("/api/v1/queue/batches")
  1501. assert response.status_code == 200
  1502. batches = response.json()
  1503. assert len(batches) >= 2
  1504. @pytest.mark.asyncio
  1505. @pytest.mark.integration
  1506. async def test_cancel_batch(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  1507. """Verify cancelling a batch cancels all pending items."""
  1508. printer = await printer_factory()
  1509. archive = await archive_factory()
  1510. data = {
  1511. "printer_id": printer.id,
  1512. "archive_id": archive.id,
  1513. "quantity": 3,
  1514. }
  1515. response = await async_client.post("/api/v1/queue/", json=data)
  1516. batch_id = response.json()["batch_id"]
  1517. # Cancel the batch
  1518. response = await async_client.delete(f"/api/v1/queue/batches/{batch_id}")
  1519. assert response.status_code == 200
  1520. # Verify all items are cancelled
  1521. list_response = await async_client.get("/api/v1/queue/")
  1522. batch_items = [i for i in list_response.json() if i["batch_id"] == batch_id]
  1523. for item in batch_items:
  1524. assert item["status"] == "cancelled"
  1525. # Verify batch status
  1526. batch_response = await async_client.get(f"/api/v1/queue/batches/{batch_id}")
  1527. assert batch_response.json()["status"] == "cancelled"
  1528. @pytest.mark.asyncio
  1529. @pytest.mark.integration
  1530. async def test_get_batch_not_found(self, async_client: AsyncClient):
  1531. """Verify 404 for non-existent batch."""
  1532. response = await async_client.get("/api/v1/queue/batches/9999")
  1533. assert response.status_code == 404