test_background_dispatch_api.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. """Integration tests for background dispatch API behavior."""
  2. from unittest.mock import AsyncMock, patch
  3. import pytest
  4. from httpx import AsyncClient
  5. from backend.app.services.background_dispatch import DispatchEnqueueRejected
  6. class TestBackgroundDispatchArchivesAPI:
  7. """Tests for archive reprint dispatch endpoint."""
  8. @pytest.mark.asyncio
  9. @pytest.mark.integration
  10. async def test_reprint_returns_dispatched_payload(
  11. self, async_client: AsyncClient, archive_factory, printer_factory, db_session, tmp_path
  12. ):
  13. """Reprint endpoint returns background dispatch metadata."""
  14. printer = await printer_factory()
  15. archive = await archive_factory(
  16. printer.id,
  17. filename="widget.gcode.3mf",
  18. file_path="archives/test/widget.gcode.3mf",
  19. )
  20. archive_file = tmp_path / archive.file_path
  21. archive_file.parent.mkdir(parents=True, exist_ok=True)
  22. archive_file.write_bytes(b"3mf-data")
  23. with (
  24. patch("backend.app.api.routes.archives.settings.base_dir", tmp_path),
  25. patch("backend.app.services.printer_manager.printer_manager.is_connected", return_value=True),
  26. patch(
  27. "backend.app.services.background_dispatch.background_dispatch.dispatch_reprint_archive",
  28. new=AsyncMock(return_value={"dispatch_job_id": 15, "dispatch_position": 1}),
  29. ) as mock_dispatch,
  30. ):
  31. response = await async_client.post(
  32. f"/api/v1/archives/{archive.id}/reprint?printer_id={printer.id}",
  33. json={"plate_id": 2},
  34. )
  35. assert response.status_code == 200
  36. data = response.json()
  37. assert data["status"] == "dispatched"
  38. assert data["dispatch_job_id"] == 15
  39. assert data["dispatch_position"] == 1
  40. assert data["filename"] == "widget.gcode.3mf"
  41. mock_dispatch.assert_awaited_once()
  42. kwargs = mock_dispatch.await_args.kwargs
  43. assert kwargs["archive_name"].endswith("• Plate 2")
  44. assert kwargs["options"]["plate_id"] == 2
  45. @pytest.mark.asyncio
  46. @pytest.mark.integration
  47. async def test_reprint_returns_409_when_enqueue_rejected(
  48. self, async_client: AsyncClient, archive_factory, printer_factory, db_session, tmp_path
  49. ):
  50. """Reprint endpoint maps enqueue rejection to HTTP 409."""
  51. printer = await printer_factory()
  52. archive = await archive_factory(
  53. printer.id,
  54. filename="widget2.gcode.3mf",
  55. file_path="archives/test/widget2.gcode.3mf",
  56. )
  57. archive_file = tmp_path / archive.file_path
  58. archive_file.parent.mkdir(parents=True, exist_ok=True)
  59. archive_file.write_bytes(b"3mf-data")
  60. with (
  61. patch("backend.app.api.routes.archives.settings.base_dir", tmp_path),
  62. patch("backend.app.services.printer_manager.printer_manager.is_connected", return_value=True),
  63. patch(
  64. "backend.app.services.background_dispatch.background_dispatch.dispatch_reprint_archive",
  65. new=AsyncMock(side_effect=DispatchEnqueueRejected("already has a background dispatch")),
  66. ),
  67. ):
  68. response = await async_client.post(
  69. f"/api/v1/archives/{archive.id}/reprint?printer_id={printer.id}",
  70. json={"plate_id": 1},
  71. )
  72. assert response.status_code == 409
  73. assert "already has a background dispatch" in response.json()["detail"]
  74. class TestBackgroundDispatchLibraryAPI:
  75. """Tests for library print dispatch endpoint."""
  76. @pytest.fixture
  77. async def library_file_factory(self, db_session):
  78. """Factory to create library files."""
  79. async def _create_file(**kwargs):
  80. from backend.app.models.library import LibraryFile
  81. defaults = {
  82. "filename": "library_part.gcode.3mf",
  83. "file_path": "library/files/library_part.gcode.3mf",
  84. "file_type": "gcode",
  85. "file_size": 1024,
  86. }
  87. defaults.update(kwargs)
  88. lib_file = LibraryFile(**defaults)
  89. db_session.add(lib_file)
  90. await db_session.commit()
  91. await db_session.refresh(lib_file)
  92. return lib_file
  93. return _create_file
  94. @pytest.mark.asyncio
  95. @pytest.mark.integration
  96. async def test_library_print_returns_dispatched_payload(
  97. self, async_client: AsyncClient, library_file_factory, printer_factory, db_session, tmp_path
  98. ):
  99. """Library print endpoint returns dispatch job metadata."""
  100. printer = await printer_factory()
  101. lib_file = await library_file_factory()
  102. disk_path = tmp_path / lib_file.file_path
  103. disk_path.parent.mkdir(parents=True, exist_ok=True)
  104. disk_path.write_bytes(b"library data")
  105. with (
  106. patch("backend.app.api.routes.library.app_settings.base_dir", tmp_path),
  107. patch("backend.app.services.printer_manager.printer_manager.is_connected", return_value=True),
  108. patch(
  109. "backend.app.services.background_dispatch.background_dispatch.dispatch_print_library_file",
  110. new=AsyncMock(return_value={"dispatch_job_id": 21, "dispatch_position": 2}),
  111. ) as mock_dispatch,
  112. ):
  113. response = await async_client.post(
  114. f"/api/v1/library/files/{lib_file.id}/print?printer_id={printer.id}",
  115. json={"plate_id": 4},
  116. )
  117. assert response.status_code == 200
  118. data = response.json()
  119. assert data["status"] == "dispatched"
  120. assert data["dispatch_job_id"] == 21
  121. assert data["dispatch_position"] == 2
  122. assert data["archive_id"] is None
  123. mock_dispatch.assert_awaited_once()
  124. kwargs = mock_dispatch.await_args.kwargs
  125. assert kwargs["filename"].endswith("• Plate 4")
  126. assert kwargs["options"]["plate_id"] == 4
  127. @pytest.mark.asyncio
  128. @pytest.mark.integration
  129. async def test_library_print_returns_409_when_enqueue_rejected(
  130. self, async_client: AsyncClient, library_file_factory, printer_factory, db_session, tmp_path
  131. ):
  132. """Library print endpoint maps enqueue rejection to HTTP 409."""
  133. printer = await printer_factory()
  134. lib_file = await library_file_factory(filename="another_part.gcode")
  135. disk_path = tmp_path / lib_file.file_path
  136. disk_path.parent.mkdir(parents=True, exist_ok=True)
  137. disk_path.write_bytes(b"library data")
  138. with (
  139. patch("backend.app.api.routes.library.app_settings.base_dir", tmp_path),
  140. patch("backend.app.services.printer_manager.printer_manager.is_connected", return_value=True),
  141. patch(
  142. "backend.app.services.background_dispatch.background_dispatch.dispatch_print_library_file",
  143. new=AsyncMock(side_effect=DispatchEnqueueRejected("queue conflict")),
  144. ),
  145. ):
  146. response = await async_client.post(
  147. f"/api/v1/library/files/{lib_file.id}/print?printer_id={printer.id}",
  148. json={"plate_id": 1},
  149. )
  150. assert response.status_code == 409
  151. assert "queue conflict" in response.json()["detail"]
  152. @pytest.mark.asyncio
  153. @pytest.mark.integration
  154. async def test_library_print_cleanup_flag_defaults_false(
  155. self, async_client: AsyncClient, library_file_factory, printer_factory, db_session, tmp_path
  156. ):
  157. """Absent cleanup_library_after_dispatch in the request body ⇒ False reaches the dispatcher.
  158. Guards the File Manager / Project Detail paths from accidental deletion."""
  159. printer = await printer_factory()
  160. lib_file = await library_file_factory(filename="filemgr_part.gcode.3mf")
  161. disk_path = tmp_path / lib_file.file_path
  162. disk_path.parent.mkdir(parents=True, exist_ok=True)
  163. disk_path.write_bytes(b"library data")
  164. with (
  165. patch("backend.app.api.routes.library.app_settings.base_dir", tmp_path),
  166. patch("backend.app.services.printer_manager.printer_manager.is_connected", return_value=True),
  167. patch(
  168. "backend.app.services.background_dispatch.background_dispatch.dispatch_print_library_file",
  169. new=AsyncMock(return_value={"dispatch_job_id": 30, "dispatch_position": 1}),
  170. ) as mock_dispatch,
  171. ):
  172. response = await async_client.post(
  173. f"/api/v1/library/files/{lib_file.id}/print?printer_id={printer.id}",
  174. json={},
  175. )
  176. assert response.status_code == 200
  177. mock_dispatch.assert_awaited_once()
  178. assert mock_dispatch.await_args.kwargs["cleanup_library_after_dispatch"] is False
  179. # cleanup flag must never leak into the print-option dict forwarded to MQTT
  180. assert "cleanup_library_after_dispatch" not in mock_dispatch.await_args.kwargs["options"]
  181. @pytest.mark.asyncio
  182. @pytest.mark.integration
  183. async def test_library_print_forwards_cleanup_flag_true(
  184. self, async_client: AsyncClient, library_file_factory, printer_factory, db_session, tmp_path
  185. ):
  186. """Direct-Print flow sends cleanup_library_after_dispatch=True, which must reach the dispatcher."""
  187. printer = await printer_factory()
  188. lib_file = await library_file_factory(filename="transient_part.gcode.3mf")
  189. disk_path = tmp_path / lib_file.file_path
  190. disk_path.parent.mkdir(parents=True, exist_ok=True)
  191. disk_path.write_bytes(b"library data")
  192. with (
  193. patch("backend.app.api.routes.library.app_settings.base_dir", tmp_path),
  194. patch("backend.app.services.printer_manager.printer_manager.is_connected", return_value=True),
  195. patch(
  196. "backend.app.services.background_dispatch.background_dispatch.dispatch_print_library_file",
  197. new=AsyncMock(return_value={"dispatch_job_id": 31, "dispatch_position": 1}),
  198. ) as mock_dispatch,
  199. ):
  200. response = await async_client.post(
  201. f"/api/v1/library/files/{lib_file.id}/print?printer_id={printer.id}",
  202. json={"cleanup_library_after_dispatch": True},
  203. )
  204. assert response.status_code == 200
  205. mock_dispatch.assert_awaited_once()
  206. assert mock_dispatch.await_args.kwargs["cleanup_library_after_dispatch"] is True
  207. class TestBackgroundDispatchCancelAPI:
  208. """Tests for /background-dispatch cancel endpoint."""
  209. @pytest.mark.asyncio
  210. @pytest.mark.integration
  211. async def test_cancel_job_returns_cancelled(self, async_client: AsyncClient):
  212. """Cancel endpoint returns cancelled for queued job."""
  213. with patch(
  214. "backend.app.services.background_dispatch.background_dispatch.cancel_job",
  215. new=AsyncMock(
  216. return_value={
  217. "cancelled": True,
  218. "pending": False,
  219. "job_id": 9,
  220. "source_name": "cube.gcode.3mf",
  221. "printer_id": 1,
  222. "printer_name": "Printer A",
  223. }
  224. ),
  225. ):
  226. response = await async_client.delete("/api/v1/background-dispatch/9")
  227. assert response.status_code == 200
  228. data = response.json()
  229. assert data["status"] == "cancelled"
  230. assert data["job_id"] == 9
  231. @pytest.mark.asyncio
  232. @pytest.mark.integration
  233. async def test_cancel_job_returns_cancelling_for_active_job(self, async_client: AsyncClient):
  234. """Cancel endpoint returns cancelling while active upload is being interrupted."""
  235. with patch(
  236. "backend.app.services.background_dispatch.background_dispatch.cancel_job",
  237. new=AsyncMock(
  238. return_value={
  239. "cancelled": True,
  240. "pending": True,
  241. "job_id": 10,
  242. "source_name": "cube.gcode.3mf",
  243. "printer_id": 1,
  244. "printer_name": "Printer A",
  245. }
  246. ),
  247. ):
  248. response = await async_client.delete("/api/v1/background-dispatch/10")
  249. assert response.status_code == 200
  250. assert response.json()["status"] == "cancelling"
  251. @pytest.mark.asyncio
  252. @pytest.mark.integration
  253. async def test_cancel_job_returns_404_when_not_found(self, async_client: AsyncClient):
  254. """Cancel endpoint returns 404 for unknown job id."""
  255. with patch(
  256. "backend.app.services.background_dispatch.background_dispatch.cancel_job",
  257. new=AsyncMock(return_value={"cancelled": False, "reason": "not_found"}),
  258. ):
  259. response = await async_client.delete("/api/v1/background-dispatch/999")
  260. assert response.status_code == 404
  261. assert response.json()["detail"] == "Dispatch job not found"