test_print_queue_api.py 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695
  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. # Batch quantity tests
  1230. # ========================================================================
  1231. @pytest.mark.asyncio
  1232. @pytest.mark.integration
  1233. async def test_add_to_queue_quantity_default(
  1234. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1235. ):
  1236. """Verify quantity=1 (default) creates a single item with no batch."""
  1237. printer = await printer_factory()
  1238. archive = await archive_factory()
  1239. data = {
  1240. "printer_id": printer.id,
  1241. "archive_id": archive.id,
  1242. }
  1243. response = await async_client.post("/api/v1/queue/", json=data)
  1244. assert response.status_code == 200
  1245. result = response.json()
  1246. assert result["batch_id"] is None
  1247. assert result["batch_name"] is None
  1248. @pytest.mark.asyncio
  1249. @pytest.mark.integration
  1250. async def test_add_to_queue_quantity_one_explicit(
  1251. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1252. ):
  1253. """Verify quantity=1 explicitly creates a single item with no batch."""
  1254. printer = await printer_factory()
  1255. archive = await archive_factory()
  1256. data = {
  1257. "printer_id": printer.id,
  1258. "archive_id": archive.id,
  1259. "quantity": 1,
  1260. }
  1261. response = await async_client.post("/api/v1/queue/", json=data)
  1262. assert response.status_code == 200
  1263. result = response.json()
  1264. assert result["batch_id"] is None
  1265. assert result["batch_name"] is None
  1266. @pytest.mark.asyncio
  1267. @pytest.mark.integration
  1268. async def test_add_to_queue_quantity_creates_batch(
  1269. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1270. ):
  1271. """Verify quantity > 1 creates a batch and multiple queue items."""
  1272. printer = await printer_factory()
  1273. archive = await archive_factory()
  1274. data = {
  1275. "printer_id": printer.id,
  1276. "archive_id": archive.id,
  1277. "quantity": 3,
  1278. }
  1279. response = await async_client.post("/api/v1/queue/", json=data)
  1280. assert response.status_code == 200
  1281. result = response.json()
  1282. # First item is returned, linked to a batch
  1283. assert result["batch_id"] is not None
  1284. assert result["batch_name"] is not None
  1285. assert "×3" in result["batch_name"]
  1286. # Verify all 3 items were created
  1287. list_response = await async_client.get("/api/v1/queue/")
  1288. items = list_response.json()
  1289. batch_items = [i for i in items if i["batch_id"] == result["batch_id"]]
  1290. assert len(batch_items) == 3
  1291. # All items should have the same settings
  1292. for item in batch_items:
  1293. assert item["printer_id"] == printer.id
  1294. assert item["archive_id"] == archive.id
  1295. assert item["status"] == "pending"
  1296. @pytest.mark.asyncio
  1297. @pytest.mark.integration
  1298. async def test_add_to_queue_quantity_sequential_positions(
  1299. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1300. ):
  1301. """Verify batch items get sequential positions."""
  1302. printer = await printer_factory()
  1303. archive = await archive_factory()
  1304. data = {
  1305. "printer_id": printer.id,
  1306. "archive_id": archive.id,
  1307. "quantity": 3,
  1308. }
  1309. response = await async_client.post("/api/v1/queue/", json=data)
  1310. assert response.status_code == 200
  1311. batch_id = response.json()["batch_id"]
  1312. list_response = await async_client.get("/api/v1/queue/")
  1313. items = list_response.json()
  1314. batch_items = sorted(
  1315. [i for i in items if i["batch_id"] == batch_id],
  1316. key=lambda i: i["position"],
  1317. )
  1318. positions = [i["position"] for i in batch_items]
  1319. assert positions == [positions[0], positions[0] + 1, positions[0] + 2]
  1320. @pytest.mark.asyncio
  1321. @pytest.mark.integration
  1322. async def test_add_to_queue_quantity_with_print_options(
  1323. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1324. ):
  1325. """Verify print options are applied to all batch items."""
  1326. printer = await printer_factory()
  1327. archive = await archive_factory()
  1328. data = {
  1329. "printer_id": printer.id,
  1330. "archive_id": archive.id,
  1331. "quantity": 2,
  1332. "bed_levelling": False,
  1333. "timelapse": True,
  1334. }
  1335. response = await async_client.post("/api/v1/queue/", json=data)
  1336. assert response.status_code == 200
  1337. batch_id = response.json()["batch_id"]
  1338. list_response = await async_client.get("/api/v1/queue/")
  1339. batch_items = [i for i in list_response.json() if i["batch_id"] == batch_id]
  1340. assert len(batch_items) == 2
  1341. for item in batch_items:
  1342. assert item["bed_levelling"] is False
  1343. assert item["timelapse"] is True
  1344. @pytest.mark.asyncio
  1345. @pytest.mark.integration
  1346. async def test_get_batch(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  1347. """Verify batch can be retrieved with progress stats."""
  1348. printer = await printer_factory()
  1349. archive = await archive_factory()
  1350. # Create a batch of 3
  1351. data = {
  1352. "printer_id": printer.id,
  1353. "archive_id": archive.id,
  1354. "quantity": 3,
  1355. }
  1356. response = await async_client.post("/api/v1/queue/", json=data)
  1357. batch_id = response.json()["batch_id"]
  1358. # Get batch
  1359. response = await async_client.get(f"/api/v1/queue/batches/{batch_id}")
  1360. assert response.status_code == 200
  1361. result = response.json()
  1362. assert result["id"] == batch_id
  1363. assert result["quantity"] == 3
  1364. assert result["status"] == "active"
  1365. assert result["pending_count"] == 3
  1366. assert result["printing_count"] == 0
  1367. assert result["completed_count"] == 0
  1368. @pytest.mark.asyncio
  1369. @pytest.mark.integration
  1370. async def test_list_batches(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  1371. """Verify batches can be listed."""
  1372. printer = await printer_factory()
  1373. archive = await archive_factory()
  1374. # Create two batches
  1375. for qty in [2, 3]:
  1376. await async_client.post(
  1377. "/api/v1/queue/",
  1378. json={"printer_id": printer.id, "archive_id": archive.id, "quantity": qty},
  1379. )
  1380. response = await async_client.get("/api/v1/queue/batches")
  1381. assert response.status_code == 200
  1382. batches = response.json()
  1383. assert len(batches) >= 2
  1384. @pytest.mark.asyncio
  1385. @pytest.mark.integration
  1386. async def test_cancel_batch(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  1387. """Verify cancelling a batch cancels all pending items."""
  1388. printer = await printer_factory()
  1389. archive = await archive_factory()
  1390. data = {
  1391. "printer_id": printer.id,
  1392. "archive_id": archive.id,
  1393. "quantity": 3,
  1394. }
  1395. response = await async_client.post("/api/v1/queue/", json=data)
  1396. batch_id = response.json()["batch_id"]
  1397. # Cancel the batch
  1398. response = await async_client.delete(f"/api/v1/queue/batches/{batch_id}")
  1399. assert response.status_code == 200
  1400. # Verify all items are cancelled
  1401. list_response = await async_client.get("/api/v1/queue/")
  1402. batch_items = [i for i in list_response.json() if i["batch_id"] == batch_id]
  1403. for item in batch_items:
  1404. assert item["status"] == "cancelled"
  1405. # Verify batch status
  1406. batch_response = await async_client.get(f"/api/v1/queue/batches/{batch_id}")
  1407. assert batch_response.json()["status"] == "cancelled"
  1408. @pytest.mark.asyncio
  1409. @pytest.mark.integration
  1410. async def test_get_batch_not_found(self, async_client: AsyncClient):
  1411. """Verify 404 for non-existent batch."""
  1412. response = await async_client.get("/api/v1/queue/batches/9999")
  1413. assert response.status_code == 404