test_external_print_confirmation_1898.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. """Ask for the outcome of prints Bambuddy did not start (#1898 follow-up).
  2. The ask-for-outcome flag rides from a queue item onto the archive at dispatch.
  3. On a farm where most jobs are started at the printer's screen, in Bambu Studio
  4. or in the Handy app there is no queue item to ride from, so every archive
  5. ``on_print_start`` created had ``confirm_requested`` false and the feature
  6. looked broken. ``confirm_outcome_external_prints`` is the missing source.
  7. Both archive-creating branches of ``on_print_start`` are driven here against a
  8. real database: the no-3MF fallback (what a P1S/A1 farm actually hits) and the
  9. normal path that archives a downloaded 3MF.
  10. """
  11. from contextlib import ExitStack
  12. from datetime import datetime, timezone
  13. from unittest.mock import AsyncMock, MagicMock, patch
  14. import pytest
  15. from sqlalchemy import select
  16. from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
  17. from backend.app.main import (
  18. _active_prints,
  19. _expected_print_creators,
  20. _expected_print_registered_at,
  21. _expected_prints,
  22. _print_ams_mappings,
  23. )
  24. from backend.app.models.archive import PrintArchive
  25. from backend.app.models.print_queue import PrintQueueItem
  26. from backend.app.models.settings import Settings
  27. DISPATCH = "/data/Metadata/plate_1.gcode"
  28. SUBTASK = "Bracket_plate_1"
  29. @pytest.fixture(autouse=True)
  30. def _clear_print_state():
  31. dicts = (
  32. _expected_prints,
  33. _expected_print_registered_at,
  34. _expected_print_creators,
  35. _print_ams_mappings,
  36. _active_prints,
  37. )
  38. for d in dicts:
  39. d.clear()
  40. yield
  41. for d in dicts:
  42. d.clear()
  43. class _StubArchiveService:
  44. """Stands in for ArchiveService on the downloaded-3MF branch.
  45. Writes the row the real service would write, without needing a parseable
  46. 3MF on disk. Everything this test asserts happens *after* the row exists.
  47. """
  48. def __init__(self, db):
  49. self.db = db
  50. async def archive_print(self, **kwargs):
  51. archive = PrintArchive(
  52. printer_id=kwargs.get("printer_id"),
  53. filename=f"{SUBTASK}.gcode.3mf",
  54. file_path=f"archives/test/{SUBTASK}.gcode.3mf",
  55. file_size=2048,
  56. print_name=SUBTASK,
  57. status="printing",
  58. started_at=datetime.now(timezone.utc),
  59. )
  60. self.db.add(archive)
  61. await self.db.commit()
  62. await self.db.refresh(archive)
  63. return archive
  64. async def _drive_print_start(
  65. test_engine, printer, *, download_ok: bool, extra_patches=(), state_fields=None, raw_data=None
  66. ) -> dict:
  67. """Run ``on_print_start`` against the test database.
  68. ``download_ok`` picks the branch: False leaves the 3MF unreachable and the
  69. no-3MF fallback archive is written inline; True takes the ArchiveService
  70. branch.
  71. """
  72. session_maker = async_sessionmaker(test_engine, class_=AsyncSession, expire_on_commit=False)
  73. state = MagicMock(
  74. current_project_url=f"ftp://{SUBTASK}.gcode.3mf",
  75. sdcard=True,
  76. sdcard_reported=True,
  77. subtask_id="", # a local print; a bare mock attribute would be stored as its repr
  78. )
  79. for name, value in (state_fields or {}).items():
  80. setattr(state, name, value)
  81. patches = [
  82. patch("backend.app.main.async_session", session_maker),
  83. patch("backend.app.core.database.async_session", session_maker),
  84. patch("backend.app.main.download_file_async", new=AsyncMock(return_value=download_ok)),
  85. patch("backend.app.main.download_file_try_paths_async", new=AsyncMock(return_value=None)),
  86. patch("backend.app.main.get_cached_3mf", return_value=None),
  87. patch("backend.app.main.cache_3mf_download"),
  88. patch("backend.app.main.peek_plate_index_in_3mf", return_value=None),
  89. patch("backend.app.main.ArchiveService", _StubArchiveService),
  90. # Imported inside the function, so patching it anywhere else lets the
  91. # directory walk open real sockets.
  92. patch("backend.app.services.bambu_ftp.list_files_async", new=AsyncMock(return_value=[])),
  93. patch("backend.app.main.ftps_handshake_blocked", return_value=False),
  94. patch("backend.app.main.get_ftp_retry_settings", new=AsyncMock(return_value=(False, 3, 2.0, 30))),
  95. patch("backend.app.main._record_energy_start", new_callable=AsyncMock),
  96. patch("backend.app.main._send_print_start_notification", new_callable=AsyncMock),
  97. patch("backend.app.main._maybe_start_layer_timelapse"),
  98. patch("backend.app.main._capture_timelapse_baseline_at_start", new_callable=AsyncMock),
  99. # Real, it would spawn a task that outlives the test by a minute.
  100. patch("backend.app.main._schedule_fallback_3mf_retry"),
  101. patch("backend.app.main._store_spoolman_print_data", new_callable=AsyncMock),
  102. # Imported inside on_print_start; it would try to persist the mocked
  103. # printer state's AMS trays and fail on the MagicMock values.
  104. patch("backend.app.services.usage_tracker.on_print_start", new_callable=AsyncMock),
  105. ]
  106. mocks: dict = {}
  107. with ExitStack() as stack:
  108. for p in [*patches, *extra_patches]:
  109. mocks[p.attribute] = stack.enter_context(p)
  110. notif = stack.enter_context(patch("backend.app.main.notification_service"))
  111. plug = stack.enter_context(patch("backend.app.main.smart_plug_manager"))
  112. ws = stack.enter_context(patch("backend.app.main.ws_manager"))
  113. relay = stack.enter_context(patch("backend.app.main.mqtt_relay"))
  114. pm = stack.enter_context(patch("backend.app.main.printer_manager"))
  115. notif.on_print_start = AsyncMock()
  116. plug.on_print_start = AsyncMock()
  117. ws.send_print_start = AsyncMock()
  118. ws.send_archive_created = AsyncMock()
  119. ws.send_archive_updated = AsyncMock()
  120. relay.on_print_start = AsyncMock()
  121. relay.on_archive_created = AsyncMock()
  122. pm.get_status = MagicMock(return_value=state)
  123. pm.get_printer = MagicMock(return_value=MagicMock(serial_number="TEST1898"))
  124. pm.get_client = MagicMock(return_value=None) # else its mock dispatch id is stored
  125. pm.get_current_print_user = MagicMock(return_value=None) # a print nobody started in Bambuddy
  126. mocks["ws_manager"] = ws
  127. mocks["mqtt_relay"] = relay
  128. from backend.app.main import on_print_start
  129. data = {"filename": DISPATCH, "subtask_name": SUBTASK}
  130. if raw_data is not None:
  131. data["raw_data"] = raw_data
  132. await on_print_start(printer.id, data)
  133. return mocks
  134. async def _set_setting(db_session, key: str, value: str) -> None:
  135. db_session.add(Settings(key=key, value=value))
  136. await db_session.commit()
  137. async def _created_archive(db_session, printer_id: int) -> PrintArchive:
  138. db_session.expire_all()
  139. archive = await db_session.scalar(
  140. select(PrintArchive).where(PrintArchive.printer_id == printer_id).order_by(PrintArchive.id.desc()).limit(1)
  141. )
  142. assert archive is not None, "on_print_start created no archive"
  143. return archive
  144. class TestExternalPrintGetsTheOutcomePrompt:
  145. @pytest.mark.asyncio
  146. @pytest.mark.integration
  147. async def test_no_3mf_fallback_asks_when_the_setting_is_on(self, test_engine, db_session, printer_factory):
  148. """The P1S/A1 case: the 3MF cannot be fetched, the archive is written
  149. inline — and that is the row the completion path reads the flag off."""
  150. printer = await printer_factory()
  151. await _set_setting(db_session, "confirm_outcome_external_prints", "true")
  152. await _drive_print_start(test_engine, printer, download_ok=False)
  153. archive = await _created_archive(db_session, printer.id)
  154. assert archive.extra_data.get("no_3mf_available") is True
  155. assert archive.confirm_requested is True
  156. # What the completion path gates the prompt on.
  157. assert archive.user_verdict is None
  158. @pytest.mark.asyncio
  159. @pytest.mark.integration
  160. async def test_the_archive_reaches_the_rest_of_the_1898_machinery(self, test_engine, db_session, printer_factory):
  161. """An externally started print is now a pending confirmation like any
  162. other: the prompt the completion path emits is gated on exactly these
  163. two fields, and the plate-release default resolves the same row."""
  164. from backend.app.services.print_confirmation import resolve_pending_confirmation_as_good
  165. printer = await printer_factory()
  166. printer_id = printer.id
  167. await _set_setting(db_session, "confirm_outcome_external_prints", "true")
  168. await _drive_print_start(test_engine, printer, download_ok=False)
  169. archive = await _created_archive(db_session, printer_id)
  170. archive.status = "completed"
  171. await db_session.commit()
  172. assert await resolve_pending_confirmation_as_good(db_session, printer_id) == archive.id
  173. @pytest.mark.asyncio
  174. @pytest.mark.integration
  175. async def test_downloaded_3mf_archive_asks_when_the_setting_is_on(self, test_engine, db_session, printer_factory):
  176. """The other creation branch: the 3MF arrived and ArchiveService wrote
  177. the row. The flag is set on the row afterwards rather than passed into
  178. archive_print, which also serves the queue dispatcher."""
  179. printer = await printer_factory()
  180. await _set_setting(db_session, "confirm_outcome_external_prints", "true")
  181. await _drive_print_start(test_engine, printer, download_ok=True)
  182. archive = await _created_archive(db_session, printer.id)
  183. assert archive.file_path.endswith(".3mf")
  184. assert archive.confirm_requested is True
  185. @pytest.mark.asyncio
  186. @pytest.mark.integration
  187. async def test_default_leaves_external_prints_alone(self, test_engine, db_session, printer_factory):
  188. """Default off: nothing about today's behaviour changes for an install
  189. that never touches the new setting — no row for it at all."""
  190. printer = await printer_factory()
  191. await _drive_print_start(test_engine, printer, download_ok=False)
  192. archive = await _created_archive(db_session, printer.id)
  193. assert archive.confirm_requested is False
  194. @pytest.mark.asyncio
  195. @pytest.mark.integration
  196. async def test_setting_off_does_not_ask(self, test_engine, db_session, printer_factory):
  197. printer = await printer_factory()
  198. await _set_setting(db_session, "confirm_outcome_external_prints", "false")
  199. await _drive_print_start(test_engine, printer, download_ok=False)
  200. assert (await _created_archive(db_session, printer.id)).confirm_requested is False
  201. @pytest.mark.asyncio
  202. @pytest.mark.integration
  203. async def test_an_odd_stored_value_counts_as_off(self, test_engine, db_session, printer_factory):
  204. """Settings live in a VARCHAR column and every other reader treats
  205. anything that is not "true" as off."""
  206. printer = await printer_factory()
  207. await _set_setting(db_session, "confirm_outcome_external_prints", "None")
  208. await _drive_print_start(test_engine, printer, download_ok=False)
  209. assert (await _created_archive(db_session, printer.id)).confirm_requested is False
  210. class TestAFailureHereCostsOnlyThePrompt:
  211. """The prompt is optional; the rest of print start is not.
  212. After a failed statement, a rollback of the whole transaction expires every
  213. object the session holds, and on an async session the next read of one
  214. raises instead of reloading. The print start below the check reads both
  215. the printer and the archive, so the check runs in a savepoint, and the flag
  216. write reloads what it used after its own rollback.
  217. """
  218. @staticmethod
  219. def _assert_print_start_finished(mocks, archive_id: int) -> None:
  220. assert archive_id in _active_prints.values()
  221. mocks["_record_energy_start"].assert_awaited()
  222. assert mocks["_record_energy_start"].await_args.args[0].id == archive_id
  223. mocks["_capture_timelapse_baseline_at_start"].assert_awaited()
  224. assert mocks["_capture_timelapse_baseline_at_start"].await_args.kwargs["archive_id"] == archive_id
  225. @pytest.mark.asyncio
  226. @pytest.mark.integration
  227. @pytest.mark.parametrize("download_ok", [True, False])
  228. async def test_a_failing_query_in_the_check(self, test_engine, db_session, printer_factory, download_ok):
  229. from sqlalchemy import text
  230. from backend.app.api.routes import settings as settings_routes
  231. real_get_setting = settings_routes.get_setting
  232. async def _broken_for_this_key(db, key):
  233. if key == "confirm_outcome_external_prints":
  234. # A real failed statement, not just an exception: this is what
  235. # leaves the transaction needing a rollback.
  236. await db.execute(text("SELECT no_such_column FROM settings"))
  237. return await real_get_setting(db, key)
  238. printer = await printer_factory()
  239. await _set_setting(db_session, "confirm_outcome_external_prints", "true")
  240. mocks = await _drive_print_start(
  241. test_engine,
  242. printer,
  243. download_ok=download_ok,
  244. extra_patches=[patch.object(settings_routes, "get_setting", _broken_for_this_key)],
  245. )
  246. archive = await _created_archive(db_session, printer.id)
  247. assert archive.confirm_requested is False
  248. self._assert_print_start_finished(mocks, archive.id)
  249. @pytest.mark.asyncio
  250. @pytest.mark.integration
  251. async def test_a_failing_flag_write(self, test_engine, db_session, printer_factory):
  252. async def _yes_but_poison_the_commit(db, printer_id, observed_name=None):
  253. # Two rows for one unique key: the commit that carries the flag fails.
  254. db.add(Settings(key="x_1898_duplicate", value="a"))
  255. db.add(Settings(key="x_1898_duplicate", value="b"))
  256. return True
  257. printer = await printer_factory()
  258. mocks = await _drive_print_start(
  259. test_engine,
  260. printer,
  261. download_ok=True,
  262. extra_patches=[patch("backend.app.main._ask_outcome_for_external_print", _yes_but_poison_the_commit)],
  263. )
  264. archive = await _created_archive(db_session, printer.id)
  265. # archive_print committed the row; only the flag is lost.
  266. assert archive.confirm_requested is False
  267. self._assert_print_start_finished(mocks, archive.id)
  268. class TestAQueuedPrintStillDecidesForItself:
  269. @pytest.mark.asyncio
  270. @pytest.mark.integration
  271. async def test_a_dispatched_job_is_not_overridden_by_the_setting(
  272. self, test_engine, db_session, printer_factory, archive_factory
  273. ):
  274. """A queue item that deliberately has the ask-for-outcome flag off must
  275. stay off. A restart mid-print empties the expected-print registry, so
  276. the queue row — which the scheduler commits to "printing" before the
  277. MQTT send — is the durable record that Bambuddy started this."""
  278. printer = await printer_factory()
  279. # Dispatched but not yet reported as started: the archive the scheduler
  280. # attached to the row only turns "printing" once on_print_start runs, so
  281. # the name-match resume above cannot find it and the queue row is the
  282. # only record that Bambuddy sent this print.
  283. source = await archive_factory(printer.id, filename=f"{SUBTASK}.gcode.3mf", status="pending", with_run=False)
  284. db_session.add(
  285. PrintQueueItem(
  286. printer_id=printer.id,
  287. archive_id=source.id,
  288. status="printing",
  289. confirm_outcome=False,
  290. )
  291. )
  292. await db_session.commit()
  293. await _set_setting(db_session, "confirm_outcome_external_prints", "true")
  294. await _drive_print_start(test_engine, printer, download_ok=False)
  295. archive = await _created_archive(db_session, printer.id)
  296. assert archive.confirm_requested is False
  297. @pytest.mark.asyncio
  298. @pytest.mark.integration
  299. async def test_a_queue_items_own_yes_survives_print_start(
  300. self, test_engine, db_session, printer_factory, archive_factory
  301. ):
  302. """The dispatcher copies ``confirm_outcome`` onto the archive before
  303. the print starts; the expected-print branch of ``on_print_start`` must
  304. leave that alone even while the external-print setting is off."""
  305. from backend.app.main import register_expected_print
  306. printer = await printer_factory()
  307. archive = await archive_factory(
  308. printer.id,
  309. filename=f"{SUBTASK}.gcode.3mf",
  310. status="pending",
  311. confirm_requested=True,
  312. with_run=False,
  313. )
  314. db_session.add(
  315. PrintQueueItem(
  316. printer_id=printer.id,
  317. archive_id=archive.id,
  318. status="printing",
  319. confirm_outcome=True,
  320. )
  321. )
  322. await db_session.commit()
  323. archive_id, printer_id = archive.id, printer.id
  324. register_expected_print(printer_id, f"{SUBTASK}.gcode.3mf", archive_id)
  325. await _drive_print_start(test_engine, printer, download_ok=False)
  326. db_session.expire_all()
  327. refreshed = await db_session.get(PrintArchive, archive_id)
  328. assert refreshed.status == "printing"
  329. assert refreshed.confirm_requested is True
  330. # No second row for the same print.
  331. rows = (await db_session.scalars(select(PrintArchive).where(PrintArchive.printer_id == printer_id))).all()
  332. assert len(rows) == 1
  333. class TestSettingsRoundTrip:
  334. @pytest.mark.asyncio
  335. @pytest.mark.integration
  336. async def test_defaults_to_off_and_round_trips(self, async_client):
  337. response = await async_client.get("/api/v1/settings/")
  338. assert response.status_code == 200
  339. assert response.json()["confirm_outcome_external_prints"] is False
  340. response = await async_client.put("/api/v1/settings/", json={"confirm_outcome_external_prints": True})
  341. assert response.status_code == 200
  342. assert response.json()["confirm_outcome_external_prints"] is True
  343. assert (await async_client.get("/api/v1/settings/")).json()["confirm_outcome_external_prints"] is True
  344. response = await async_client.put("/api/v1/settings/", json={"confirm_outcome_external_prints": False})
  345. assert response.status_code == 200
  346. assert (await async_client.get("/api/v1/settings/")).json()["confirm_outcome_external_prints"] is False
  347. @pytest.mark.asyncio
  348. @pytest.mark.integration
  349. async def test_updating_it_leaves_the_per_job_default_alone(self, async_client):
  350. """Two different questions: one seeds the per-job toggle in the print
  351. dialog, the other covers prints that never see that dialog."""
  352. await async_client.put("/api/v1/settings/", json={"default_confirm_outcome": True})
  353. body = (await async_client.put("/api/v1/settings/", json={"confirm_outcome_external_prints": True})).json()
  354. assert body["default_confirm_outcome"] is True
  355. assert body["confirm_outcome_external_prints"] is True
  356. class TestAStrandedQueueRowDoesNotMuteTheSetting:
  357. """A ``printing`` row is not proof that Bambuddy started what is printing now.
  358. ``_completion_belongs_to_queue_item`` deliberately leaves a row open when a
  359. completion's subtask name disagrees with the file it was dispatched with,
  360. and the scheduler's stranded sweep only takes it back once the printer has
  361. sat connected and terminal for minutes. Treating any such row as "we
  362. dispatched this" switched the setting off for every screen-started print in
  363. between -- the exact symptom the setting exists to cure.
  364. """
  365. @pytest.mark.asyncio
  366. @pytest.mark.integration
  367. async def test_a_row_left_open_for_another_file_still_asks(
  368. self, test_engine, db_session, printer_factory, archive_factory
  369. ):
  370. printer = await printer_factory()
  371. stranded_for = await archive_factory(
  372. printer.id, filename="SomeOtherJob.gcode.3mf", status="printing", with_run=False
  373. )
  374. db_session.add(
  375. PrintQueueItem(
  376. printer_id=printer.id,
  377. archive_id=stranded_for.id,
  378. status="printing",
  379. confirm_outcome=False,
  380. )
  381. )
  382. await db_session.commit()
  383. await _set_setting(db_session, "confirm_outcome_external_prints", "true")
  384. stranded_filename = stranded_for.filename
  385. await _drive_print_start(test_engine, printer, download_ok=False)
  386. archive = await _created_archive(db_session, printer.id)
  387. assert archive.filename != stranded_filename
  388. assert archive.confirm_requested is True
  389. class TestAReprintAsksAgain:
  390. """The reprint reuses the archive row, and the completion prompt is gated on
  391. ``user_verdict is None`` -- so without a reset the second run inherits the
  392. first run's answer and is never asked about."""
  393. @pytest.mark.asyncio
  394. @pytest.mark.integration
  395. async def test_the_previous_runs_verdict_does_not_carry_over(
  396. self, test_engine, db_session, printer_factory, archive_factory
  397. ):
  398. from backend.app.main import register_expected_print
  399. printer = await printer_factory()
  400. archive = await archive_factory(
  401. printer.id,
  402. filename=f"{SUBTASK}.gcode.3mf",
  403. status="completed",
  404. confirm_requested=True,
  405. user_verdict="good",
  406. confirm_token="token-from-the-first-run",
  407. with_run=False,
  408. )
  409. archive_id, printer_id = archive.id, printer.id
  410. register_expected_print(printer_id, f"{SUBTASK}.gcode.3mf", archive_id)
  411. await _drive_print_start(test_engine, printer, download_ok=False)
  412. db_session.expire_all()
  413. refreshed = await db_session.get(PrintArchive, archive_id)
  414. assert refreshed.status == "printing"
  415. assert refreshed.confirm_requested is True
  416. assert refreshed.user_verdict is None
  417. assert refreshed.confirm_token is None
  418. # And the completion really does ask again, which is the point.
  419. refreshed.status = "completed"
  420. await db_session.commit()
  421. sent, ws, notif = await _dispatch(db_session, printer_id, archive_id)
  422. assert sent is True
  423. ws.send_print_confirm_request.assert_awaited_once()
  424. notif.on_print_confirm_request.assert_awaited_once()
  425. @pytest.mark.asyncio
  426. @pytest.mark.integration
  427. async def test_an_archive_that_was_never_asked_about_keeps_its_verdict(
  428. self, test_engine, db_session, printer_factory, archive_factory
  429. ):
  430. """The reset is scoped to rows that ask. An archive answered once and
  431. later reprinted with the flag off must keep the answer it has."""
  432. from backend.app.main import register_expected_print
  433. printer = await printer_factory()
  434. archive = await archive_factory(
  435. printer.id,
  436. filename=f"{SUBTASK}.gcode.3mf",
  437. status="completed",
  438. confirm_requested=False,
  439. user_verdict="reject",
  440. with_run=False,
  441. )
  442. archive_id = archive.id
  443. register_expected_print(printer.id, f"{SUBTASK}.gcode.3mf", archive_id)
  444. await _drive_print_start(test_engine, printer, download_ok=False)
  445. db_session.expire_all()
  446. assert (await db_session.get(PrintArchive, archive_id)).user_verdict == "reject"
  447. async def _dispatch(db_session, printer_id: int, archive_id: int, **kwargs):
  448. """Run the completion path's outcome dispatch with the two emitters mocked."""
  449. from backend.app.main import dispatch_outcome_confirmation
  450. with (
  451. patch("backend.app.main.ws_manager") as ws,
  452. patch("backend.app.main.notification_service") as notif,
  453. ):
  454. ws.send_print_confirm_request = AsyncMock()
  455. notif.on_print_confirm_request = AsyncMock()
  456. sent = await dispatch_outcome_confirmation(
  457. db_session,
  458. printer_id,
  459. "Bench P1S",
  460. {"subtask_name": SUBTASK},
  461. archive_id,
  462. **kwargs,
  463. )
  464. return sent, ws, notif
  465. class TestTheCompletionEmitsThePrompt:
  466. """The half of the feature the user actually sees.
  467. Everything else here asserts a column value; this drives the block
  468. ``on_print_complete``'s notification task runs -- which is wrapped in a bare
  469. ``except Exception`` that only logs, so a regression in it is invisible
  470. unless something pins it.
  471. """
  472. @pytest.mark.asyncio
  473. @pytest.mark.integration
  474. async def test_an_external_print_gets_a_prompt_with_one_tap_links(self, test_engine, db_session, printer_factory):
  475. printer = await printer_factory()
  476. printer_id = printer.id
  477. await _set_setting(db_session, "confirm_outcome_external_prints", "true")
  478. await _set_setting(db_session, "external_url", "https://farm.example.com/")
  479. await _drive_print_start(test_engine, printer, download_ok=False)
  480. archive = await _created_archive(db_session, printer_id)
  481. archive_id = archive.id
  482. assert archive.confirm_requested is True
  483. archive.status = "completed"
  484. await db_session.commit()
  485. sent, ws, notif = await _dispatch(db_session, printer_id, archive_id)
  486. assert sent is True
  487. ws.send_print_confirm_request.assert_awaited_once()
  488. assert ws.send_print_confirm_request.await_args.args[1]["archive_id"] == archive_id
  489. # Nobody owns an external print: everyone on the printer is asked
  490. assert ws.send_print_confirm_request.await_args.kwargs["user_ids"] is None
  491. notif.on_print_confirm_request.assert_awaited_once()
  492. kwargs = notif.on_print_confirm_request.await_args.kwargs
  493. token = (await db_session.get(PrintArchive, archive_id)).confirm_token
  494. assert token, "the one-tap links need a minted capability token"
  495. assert kwargs["good_url"] == f"https://farm.example.com/api/v1/archives/confirm/{token}/good"
  496. assert kwargs["reject_url"] == f"https://farm.example.com/api/v1/archives/confirm/{token}/reject"
  497. assert kwargs["confirm_url"] == f"https://farm.example.com/archives?confirm={archive_id}"
  498. @pytest.mark.asyncio
  499. @pytest.mark.integration
  500. async def test_the_links_stay_absolute_without_an_external_url(self, test_engine, db_session, printer_factory):
  501. """Telegram's inline keyboard and ntfy's action buttons are both dropped
  502. for a relative URL, so an install that never set external_url used to
  503. get a message carrying two unusable paths and no buttons at all."""
  504. printer = await printer_factory()
  505. printer_id = printer.id
  506. await _set_setting(db_session, "confirm_outcome_external_prints", "true")
  507. await _drive_print_start(test_engine, printer, download_ok=False)
  508. archive = await _created_archive(db_session, printer_id)
  509. archive_id = archive.id
  510. archive.status = "completed"
  511. await db_session.commit()
  512. _, _, notif = await _dispatch(db_session, printer_id, archive_id)
  513. kwargs = notif.on_print_confirm_request.await_args.kwargs
  514. assert kwargs["good_url"].startswith("http")
  515. assert kwargs["reject_url"].startswith("http")
  516. assert kwargs["confirm_url"].startswith("http")
  517. @pytest.mark.asyncio
  518. @pytest.mark.integration
  519. async def test_a_failed_prompt_leaves_the_session_usable_for_the_email(self, db_session):
  520. """The completion task sends the per-user print email on the same
  521. session right after the prompt, so a prompt that dies mid-flush must
  522. not take the email with it."""
  523. from backend.app.main import _dispatch_outcome_confirmation_safely
  524. async def _dies_mid_flush(db, *args, **kwargs):
  525. db.add(Settings(key="x_1898_duplicate", value="a"))
  526. db.add(Settings(key="x_1898_duplicate", value="b"))
  527. await db.flush()
  528. with patch("backend.app.main.dispatch_outcome_confirmation", _dies_mid_flush):
  529. await _dispatch_outcome_confirmation_safely(db_session, 1, "X1C", {}, 1, {})
  530. # What _dispatch_user_print_email does next: read from the session.
  531. # Without the rollback this raises PendingRollbackError.
  532. await db_session.execute(select(Settings).limit(1))
  533. @pytest.mark.asyncio
  534. @pytest.mark.integration
  535. async def test_an_already_answered_archive_is_not_asked_again(self, db_session, printer_factory, archive_factory):
  536. printer = await printer_factory()
  537. archive = await archive_factory(
  538. printer.id, status="completed", confirm_requested=True, user_verdict="good", with_run=False
  539. )
  540. sent, ws, notif = await _dispatch(db_session, printer.id, archive.id)
  541. assert sent is False
  542. ws.send_print_confirm_request.assert_not_awaited()
  543. notif.on_print_confirm_request.assert_not_awaited()
  544. @pytest.mark.asyncio
  545. @pytest.mark.integration
  546. async def test_an_archive_that_never_opted_in_is_not_asked(self, db_session, printer_factory, archive_factory):
  547. printer = await printer_factory()
  548. archive = await archive_factory(printer.id, status="completed", confirm_requested=False, with_run=False)
  549. sent, _, notif = await _dispatch(db_session, printer.id, archive.id)
  550. assert sent is False
  551. notif.on_print_confirm_request.assert_not_awaited()
  552. @pytest.mark.asyncio
  553. @pytest.mark.integration
  554. @pytest.mark.parametrize("auth_on", [True, False])
  555. async def test_an_owned_print_asks_its_owner_and_who_may_answer_for_everyone(
  556. test_engine, db_session, printer_factory, archive_factory, auth_on
  557. ):
  558. from backend.app.models.group import Group
  559. from backend.app.models.user import User
  560. printer = await printer_factory()
  561. if auth_on:
  562. await _set_setting(db_session, "auth_enabled", "true")
  563. staff = Group(name="staff", permissions=["archives:update_all"])
  564. others = Group(name="others", permissions=["archives:update_own"])
  565. owner = User(username="prompted", password_hash="x", role="user", groups=[others])
  566. manager = User(username="manager", password_hash="x", role="user", groups=[staff])
  567. bystander = User(username="bystander", password_hash="x", role="user", groups=[others])
  568. gone = User(username="gone", password_hash="x", role="user", groups=[staff], is_active=False)
  569. db_session.add_all([staff, others, owner, manager, bystander, gone])
  570. await db_session.commit()
  571. archive = await archive_factory(printer.id, status="completed", created_by_id=owner.id, confirm_requested=True)
  572. sent, ws, _ = await _dispatch(db_session, printer.id, archive.id)
  573. assert sent is True
  574. asked = ws.send_print_confirm_request.await_args.kwargs["user_ids"]
  575. assert asked == ({owner.id, manager.id} if auth_on else None)