test_external_print_confirmation_1898.py 28 KB

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