test_external_print_confirmation_1898.py 28 KB

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