test_timelapse_scan_2704.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. """Timelapse scan reliability (#2704).
  2. A Bambu printer in LAN-only mode never reaches Bambu's NTP server, so the clock
  3. behind both the timelapse filename and the FTP mtime drifts freely — the P1S in
  4. the report was six and a half days out. That is why the automatic scan works by
  5. diffing the printer's ``/timelapse`` listing against a snapshot taken when the
  6. print started, and why nothing in that path may fall back to comparing times.
  7. These tests pin the parts that make the diff dependable:
  8. * the candidate is chosen by exclusion, never by ordering (ordering could only
  9. be done on the printer's clock);
  10. * a download that comes up short never attaches and never triggers a delete —
  11. deleting the printer's copy is only safe because the transfer was verified;
  12. * the baseline persisted at print start is what the manual Scan button uses,
  13. instead of the clock-based strategies that cannot work on a drifted printer.
  14. """
  15. import logging
  16. from unittest.mock import AsyncMock, MagicMock, patch
  17. import pytest
  18. from backend.app.core.printer_scope import ALL_PRINTERS
  19. logger = logging.getLogger(__name__)
  20. def _printer():
  21. p = MagicMock()
  22. p.id = 1
  23. p.name = "TestP1S"
  24. p.ip_address = "192.168.1.100"
  25. p.access_code = "12345678"
  26. p.model = "P1S"
  27. return p
  28. def _video(name: str, size: int = 1000):
  29. return {"name": name, "is_directory": False, "path": f"/timelapse/{name}", "size": size}
  30. def _session(archive=None):
  31. session = AsyncMock()
  32. session.__aenter__ = AsyncMock(return_value=session)
  33. session.__aexit__ = AsyncMock()
  34. if archive is not None:
  35. session.get = AsyncMock(return_value=archive)
  36. return session
  37. class TestCandidateSelection:
  38. """Which of the printer's videos belongs to this print."""
  39. @pytest.fixture
  40. def attach(self):
  41. from backend.app.main import _attach_first_unclaimed_timelapse
  42. return _attach_first_unclaimed_timelapse
  43. @pytest.mark.asyncio
  44. async def test_nothing_new_since_baseline_is_not_an_attach(self, attach):
  45. result = await attach(
  46. 42,
  47. _printer(),
  48. [_video("video_2026-07-21_09-17-37.avi")],
  49. {"video_2026-07-21_09-17-37.avi"},
  50. set(),
  51. 1,
  52. logger,
  53. )
  54. assert result is False
  55. @pytest.mark.asyncio
  56. async def test_attaches_the_one_new_file_and_deletes_it_from_the_printer(self, attach):
  57. download = AsyncMock(return_value=b"x" * 1000)
  58. delete = AsyncMock(return_value=True)
  59. service = MagicMock()
  60. service.attach_timelapse = AsyncMock(return_value=True)
  61. with (
  62. patch("backend.app.services.bambu_ftp.download_file_bytes_async", download),
  63. patch("backend.app.services.bambu_ftp.remote_file_settled", AsyncMock(return_value=True)),
  64. patch("backend.app.services.bambu_ftp.delete_archived_timelapse", delete),
  65. patch("backend.app.main.async_session", return_value=_session()),
  66. patch("backend.app.main.ArchiveService", return_value=service),
  67. patch("backend.app.main.ws_manager", MagicMock(send_archive_updated=AsyncMock())),
  68. ):
  69. result = await attach(
  70. 42,
  71. _printer(),
  72. [_video("old.avi"), _video("video_2026-07-22_06-18-39.avi")],
  73. {"old.avi"},
  74. set(),
  75. 1,
  76. logger,
  77. )
  78. assert result is True
  79. service.attach_timelapse.assert_awaited_once()
  80. assert service.attach_timelapse.await_args.args[2] == "video_2026-07-22_06-18-39.avi"
  81. delete.assert_awaited_once()
  82. assert delete.await_args.args[2] == "/timelapse/video_2026-07-22_06-18-39.avi"
  83. @pytest.mark.asyncio
  84. async def test_skips_a_previous_prints_late_landing_video(self, attach):
  85. """Two files are new since the baseline because the previous print's
  86. video only landed after this print started. It is already attached to
  87. another archive, so it is excluded by name — no timestamps involved."""
  88. download = AsyncMock(return_value=b"y" * 1000)
  89. service = MagicMock()
  90. service.attach_timelapse = AsyncMock(return_value=True)
  91. with (
  92. patch("backend.app.services.bambu_ftp.download_file_bytes_async", download),
  93. patch("backend.app.services.bambu_ftp.remote_file_settled", AsyncMock(return_value=True)),
  94. patch("backend.app.services.bambu_ftp.delete_archived_timelapse", AsyncMock()),
  95. patch("backend.app.main.async_session", return_value=_session()),
  96. patch("backend.app.main.ArchiveService", return_value=service),
  97. patch("backend.app.main.ws_manager", MagicMock(send_archive_updated=AsyncMock())),
  98. ):
  99. result = await attach(
  100. 42,
  101. _printer(),
  102. # Listing order puts the previous print's video first, so a
  103. # naive "take the first new one" would grab the wrong video.
  104. [_video("previous_print.avi"), _video("this_print.avi")],
  105. set(),
  106. {"previous_print"},
  107. 1,
  108. logger,
  109. )
  110. assert result is True
  111. assert service.attach_timelapse.await_args.args[2] == "this_print.avi"
  112. @pytest.mark.asyncio
  113. async def test_claimed_match_survives_the_mp4_conversion(self, attach):
  114. """Attached AVIs are converted to MP4 afterwards, which keeps the stem
  115. but changes the extension — so exclusion has to compare stems."""
  116. result = await attach(
  117. 42,
  118. _printer(),
  119. [_video("video_2026-07-22_06-18-39.avi")],
  120. set(),
  121. {"video_2026-07-22_06-18-39"}, # stored as .mp4 on the archive
  122. 1,
  123. logger,
  124. )
  125. assert result is False
  126. @pytest.mark.asyncio
  127. async def test_all_new_files_claimed_keeps_polling(self, attach):
  128. result = await attach(42, _printer(), [_video("a.avi"), _video("b.avi")], set(), {"a", "b"}, 1, logger)
  129. assert result is False
  130. class TestDownloadVerificationGatesTheDelete:
  131. """The printer's copy is the only other copy — it goes only after the
  132. transfer is verified against the size the listing reported."""
  133. @pytest.fixture
  134. def attach(self):
  135. from backend.app.main import _attach_first_unclaimed_timelapse
  136. return _attach_first_unclaimed_timelapse
  137. @pytest.mark.asyncio
  138. async def test_passes_the_listed_size_to_the_downloader(self, attach):
  139. download = AsyncMock(return_value=b"z" * 4096)
  140. service = MagicMock()
  141. service.attach_timelapse = AsyncMock(return_value=True)
  142. with (
  143. patch("backend.app.services.bambu_ftp.download_file_bytes_async", download),
  144. patch("backend.app.services.bambu_ftp.remote_file_settled", AsyncMock(return_value=True)),
  145. patch("backend.app.services.bambu_ftp.delete_archived_timelapse", AsyncMock()),
  146. patch("backend.app.main.async_session", return_value=_session()),
  147. patch("backend.app.main.ArchiveService", return_value=service),
  148. patch("backend.app.main.ws_manager", MagicMock(send_archive_updated=AsyncMock())),
  149. ):
  150. await attach(42, _printer(), [_video("new.avi", size=4096)], set(), set(), 1, logger)
  151. assert download.await_args.kwargs["expected_size"] == 4096
  152. @pytest.mark.asyncio
  153. async def test_short_download_does_not_attach_or_delete(self, attach):
  154. """download_file_bytes_async returns None on a size mismatch. The
  155. printer must keep its copy so the next poll round can retry."""
  156. delete = AsyncMock()
  157. service = MagicMock()
  158. service.attach_timelapse = AsyncMock(return_value=True)
  159. with (
  160. patch("backend.app.services.bambu_ftp.download_file_bytes_async", AsyncMock(return_value=None)),
  161. patch("backend.app.services.bambu_ftp.remote_file_settled", AsyncMock(return_value=True)),
  162. patch("backend.app.services.bambu_ftp.delete_archived_timelapse", delete),
  163. patch("backend.app.main.async_session", return_value=_session()),
  164. patch("backend.app.main.ArchiveService", return_value=service),
  165. ):
  166. result = await attach(42, _printer(), [_video("new.avi")], set(), set(), 1, logger)
  167. assert result is False
  168. service.attach_timelapse.assert_not_awaited()
  169. delete.assert_not_awaited()
  170. @pytest.mark.asyncio
  171. async def test_failed_attach_does_not_delete(self, attach):
  172. delete = AsyncMock()
  173. service = MagicMock()
  174. service.attach_timelapse = AsyncMock(return_value=False)
  175. with (
  176. patch("backend.app.services.bambu_ftp.download_file_bytes_async", AsyncMock(return_value=b"x" * 1000)),
  177. patch("backend.app.services.bambu_ftp.remote_file_settled", AsyncMock(return_value=True)),
  178. patch("backend.app.services.bambu_ftp.delete_archived_timelapse", delete),
  179. patch("backend.app.main.async_session", return_value=_session()),
  180. patch("backend.app.main.ArchiveService", return_value=service),
  181. ):
  182. result = await attach(42, _printer(), [_video("new.avi")], set(), set(), 1, logger)
  183. assert result is False
  184. delete.assert_not_awaited()
  185. class TestFtpDownloadSizeCheck:
  186. """`download_file` is where a truncated FTPS transfer used to pass for a
  187. complete one — a partial buffer is non-empty, so every caller downstream
  188. treated it as a good file."""
  189. def _client(self, payload: bytes):
  190. from backend.app.services.bambu_ftp import BambuFTPClient
  191. client = BambuFTPClient("192.168.1.100", "12345678")
  192. ftp = MagicMock()
  193. ftp.retrbinary = MagicMock(side_effect=lambda cmd, cb: cb(payload))
  194. client._ftp = ftp
  195. return client
  196. def test_exact_size_passes(self):
  197. assert self._client(b"a" * 500).download_file("/timelapse/v.avi", expected_size=500) == b"a" * 500
  198. def test_short_read_is_a_failure(self):
  199. assert self._client(b"a" * 499).download_file("/timelapse/v.avi", expected_size=500) is None
  200. def test_long_read_is_a_failure(self):
  201. """Not expected in practice, but a mismatch either way means we don't
  202. know what we have, and we're about to delete the original."""
  203. assert self._client(b"a" * 501).download_file("/timelapse/v.avi", expected_size=500) is None
  204. def test_zero_bytes_is_a_failure_even_without_an_expected_size(self):
  205. assert self._client(b"").download_file("/cache/whatever.3mf") is None
  206. def test_unverified_download_still_works_for_callers_that_do_not_pass_a_size(self):
  207. assert self._client(b"abc").download_file("/cache/whatever.3mf") == b"abc"
  208. class TestDeleteIsBestEffort:
  209. """A printer that refuses the delete must not break the flow — the video
  210. is already in the archive, and the diff excludes it by name from then on."""
  211. @pytest.mark.asyncio
  212. async def test_reports_success_on_delete(self):
  213. from backend.app.services.bambu_ftp import DeleteResult, delete_archived_timelapse
  214. with patch(
  215. "backend.app.services.bambu_ftp.delete_file_async", AsyncMock(return_value=DeleteResult.DELETED)
  216. ) as d:
  217. assert await delete_archived_timelapse("1.2.3.4", "code", "/timelapse/v.avi", verified=True) is True
  218. assert d.await_count == 1
  219. @pytest.mark.asyncio
  220. async def test_not_found_is_success_and_is_not_retried(self):
  221. """550 means the printer already cleaned up; waiting cannot change it."""
  222. from backend.app.services.bambu_ftp import DeleteResult, delete_archived_timelapse
  223. with patch(
  224. "backend.app.services.bambu_ftp.delete_file_async", AsyncMock(return_value=DeleteResult.NOT_FOUND)
  225. ) as d:
  226. assert await delete_archived_timelapse("1.2.3.4", "code", "/timelapse/v.avi", verified=True) is True
  227. assert d.await_count == 1
  228. @pytest.mark.asyncio
  229. async def test_failure_retries_then_gives_up_without_raising(self):
  230. from backend.app.services.bambu_ftp import DeleteResult, delete_archived_timelapse
  231. with (
  232. patch("backend.app.services.bambu_ftp.delete_file_async", AsyncMock(return_value=DeleteResult.FAILED)),
  233. patch("backend.app.services.bambu_ftp.asyncio.sleep", AsyncMock()),
  234. ):
  235. assert await delete_archived_timelapse("1.2.3.4", "code", "/timelapse/v.avi", verified=True) is False
  236. @pytest.mark.asyncio
  237. async def test_raising_transport_does_not_propagate(self):
  238. from backend.app.services.bambu_ftp import delete_archived_timelapse
  239. with (
  240. patch("backend.app.services.bambu_ftp.delete_file_async", AsyncMock(side_effect=OSError("boom"))),
  241. patch("backend.app.services.bambu_ftp.asyncio.sleep", AsyncMock()),
  242. ):
  243. assert await delete_archived_timelapse("1.2.3.4", "code", "/timelapse/v.avi", verified=True) is False
  244. class TestBaselineIsPersisted:
  245. """The baseline has to outlive the process: a restart mid-print used to
  246. lose it, and the manual scan never had access to it at all."""
  247. @pytest.mark.asyncio
  248. async def test_written_to_the_archive_row_at_print_start(self):
  249. from backend.app.main import _capture_timelapse_baseline_at_start
  250. archive = MagicMock()
  251. archive.timelapse_baseline = None
  252. session = _session(archive)
  253. with (
  254. patch("backend.app.main.async_session", return_value=session),
  255. patch(
  256. "backend.app.main._list_timelapse_videos",
  257. new=AsyncMock(return_value=([_video("a.avi"), _video("b.avi")], "/timelapse")),
  258. ),
  259. ):
  260. await _capture_timelapse_baseline_at_start(_printer(), 1, logger, archive_id=7)
  261. assert archive.timelapse_baseline == ["a.avi", "b.avi"]
  262. session.commit.assert_awaited()
  263. @pytest.mark.asyncio
  264. async def test_no_archive_id_keeps_it_in_memory_only(self):
  265. from backend.app.main import _capture_timelapse_baseline_at_start, _timelapse_baselines
  266. _timelapse_baselines.pop(1, None)
  267. session = _session(MagicMock())
  268. with (
  269. patch("backend.app.main.async_session", return_value=session),
  270. patch(
  271. "backend.app.main._list_timelapse_videos",
  272. new=AsyncMock(return_value=([_video("a.avi")], "/timelapse")),
  273. ),
  274. ):
  275. await _capture_timelapse_baseline_at_start(_printer(), 1, logger)
  276. assert _timelapse_baselines[1] == {"a.avi"}
  277. session.commit.assert_not_awaited()
  278. _timelapse_baselines.pop(1, None)
  279. @pytest.mark.asyncio
  280. async def test_listing_failure_stores_null_not_an_empty_baseline(self):
  281. """An empty list would make every video on the printer look new; NULL
  282. correctly means "no baseline" and falls back to a fresh snapshot."""
  283. from backend.app.main import _capture_timelapse_baseline_at_start
  284. archive = MagicMock()
  285. session = _session(archive)
  286. with (
  287. patch("backend.app.main.async_session", return_value=session),
  288. patch("backend.app.main._list_timelapse_videos", new=AsyncMock(side_effect=OSError("ftp down"))),
  289. ):
  290. await _capture_timelapse_baseline_at_start(_printer(), 1, logger, archive_id=7)
  291. assert archive.timelapse_baseline is None
  292. class TestManualScanUsesTheBaseline:
  293. """The reporter's second symptom: pressing "Scan for Timelapse" found
  294. nothing. Every strategy the endpoint had was clock-based, and their
  295. printer's clock was days out, so it could not match on any of them."""
  296. def _archive(self, baseline):
  297. from datetime import datetime, timezone
  298. a = MagicMock()
  299. a.id = 64
  300. a.printer_id = 1
  301. a.filename = "mops.3mf"
  302. a.timelapse_path = None
  303. a.timelapse_baseline = baseline
  304. a.started_at = datetime(2026, 7, 28, 20, 30, tzinfo=timezone.utc)
  305. a.completed_at = datetime(2026, 7, 28, 21, 19, tzinfo=timezone.utc)
  306. a.created_at = a.completed_at
  307. return a
  308. async def _scan(self, archive, listing, download=None, delete=None):
  309. from backend.app.api.routes import archives as archives_mod
  310. service = MagicMock()
  311. service.get_archive = AsyncMock(return_value=archive)
  312. service.attach_timelapse = AsyncMock(return_value=True)
  313. session = AsyncMock()
  314. session.__aenter__ = AsyncMock(return_value=session)
  315. session.__aexit__ = AsyncMock()
  316. session.execute = AsyncMock(
  317. return_value=MagicMock(
  318. scalar_one_or_none=MagicMock(return_value=_printer()),
  319. scalars=MagicMock(return_value=MagicMock(all=MagicMock(return_value=[]))),
  320. )
  321. )
  322. with (
  323. patch("backend.app.core.database.async_session", return_value=session),
  324. patch("backend.app.api.routes.archives.ArchiveService", return_value=service),
  325. patch("backend.app.services.bambu_ftp.list_files_async", AsyncMock(return_value=listing)),
  326. patch(
  327. "backend.app.services.bambu_ftp.get_ftp_retry_settings",
  328. AsyncMock(return_value=(False, 3, 2, 30)),
  329. ),
  330. patch(
  331. "backend.app.services.bambu_ftp.download_file_bytes_async",
  332. download or AsyncMock(return_value=b"x" * 1000),
  333. ),
  334. patch("backend.app.services.bambu_ftp.delete_archived_timelapse", delete or AsyncMock()),
  335. ):
  336. return await archives_mod.scan_timelapse(archive.id, None, ALL_PRINTERS)
  337. @pytest.mark.asyncio
  338. async def test_attaches_the_single_unclaimed_new_file(self):
  339. """The printer's clock is six days out here — exactly the reporter's
  340. case. Nothing in this path looks at a timestamp."""
  341. archive = self._archive(["video_2026-07-21_22-49-47.avi"])
  342. listing = [
  343. _video("video_2026-07-21_22-49-47.avi"),
  344. _video("video_2026-07-22_06-18-39.avi"),
  345. ]
  346. result = await self._scan(archive, listing)
  347. assert result["status"] == "attached"
  348. assert result["filename"] == "video_2026-07-22_06-18-39.avi"
  349. @pytest.mark.asyncio
  350. async def test_deletes_from_the_printer_after_attaching(self):
  351. delete = AsyncMock()
  352. archive = self._archive(["old.avi"])
  353. await self._scan(archive, [_video("old.avi"), _video("new.avi")], delete=delete)
  354. delete.assert_awaited_once()
  355. assert delete.await_args.args[2] == "/timelapse/new.avi"
  356. @pytest.mark.asyncio
  357. async def test_baseline_showing_nothing_new_does_not_guess(self):
  358. """With a baseline saying no new video exists, the clock strategies
  359. must not run — otherwise a coincidental timestamp match attaches
  360. someone else's video and calls it this print's."""
  361. archive = self._archive(["video_2026-07-28_20-30-00.avi"])
  362. # This file's embedded time is minutes from started_at, so the old
  363. # timestamp strategy would have matched it confidently.
  364. listing = [_video("video_2026-07-28_20-30-00.avi")]
  365. result = await self._scan(archive, listing)
  366. assert result["status"] == "not_found"
  367. @pytest.mark.asyncio
  368. async def test_ambiguous_baseline_offers_only_the_plausible_files(self):
  369. archive = self._archive(["old.avi"])
  370. listing = [_video("old.avi"), _video("candidate_a.avi"), _video("candidate_b.avi")]
  371. result = await self._scan(archive, listing)
  372. assert result["status"] == "not_found"
  373. assert {f["name"] for f in result["available_files"]} == {"candidate_a.avi", "candidate_b.avi"}
  374. @pytest.mark.asyncio
  375. async def test_archives_without_a_baseline_keep_the_old_strategies(self):
  376. """Rows predating the persisted baseline still get the best guess the
  377. endpoint can make, rather than nothing at all."""
  378. archive = self._archive(None)
  379. listing = [_video("mops_something.avi")] # matches by print name
  380. result = await self._scan(archive, listing)
  381. assert result["status"] == "attached"
  382. assert result["filename"] == "mops_something.avi"
  383. class TestPollBounds:
  384. """The poll is bounded twice on purpose."""
  385. def test_round_cap_tracks_the_wall_clock_budget(self):
  386. from backend.app.main import (
  387. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS,
  388. _TIMELAPSE_SCAN_TIMEOUT_SECONDS,
  389. _timelapse_scan_max_attempts,
  390. )
  391. assert (
  392. _timelapse_scan_max_attempts()
  393. == int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1
  394. )
  395. def test_zero_interval_does_not_divide_by_zero(self, monkeypatch):
  396. """The deadline alone can't bound the loop once sleeps are shortened to
  397. nothing, which is exactly what a test or a future tweak would do."""
  398. import backend.app.main as main_mod
  399. monkeypatch.setattr(main_mod, "_TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS", 0)
  400. assert main_mod._timelapse_scan_max_attempts() > 1
  401. def test_budget_is_much_longer_than_the_ladder_it_replaced(self):
  402. """The old [5, 10, 20, 30] ladder gave up after ~65 seconds, while the
  403. support bundles showed videos still arriving at the cutoff."""
  404. from backend.app.main import _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  405. assert _TIMELAPSE_SCAN_TIMEOUT_SECONDS >= 300
  406. class TestFinishPhotoUpgrade:
  407. """The print-complete notification waits ~60s for the timelapse, because
  408. holding it for minutes is worse than sending a live grab. On a P1S the
  409. video routinely lands later than that (p90 167s, worst observed 546s), so
  410. the archive kept the live grab — taken after the end G-code dropped the
  411. bed, which is the worse of the two photos. The upgrade runs afterwards."""
  412. @pytest.mark.asyncio
  413. async def test_puts_the_timelapse_frame_first_and_keeps_the_live_grab(self):
  414. """First, because the gallery opens at index 0. Kept, because the
  415. notification that already went out links to that exact file."""
  416. from backend.app.main import _upgrade_finish_photo_from_timelapse
  417. archive = MagicMock()
  418. archive.photos = ["finish_live_grab.jpg"]
  419. session = _session(archive)
  420. with (
  421. patch(
  422. "backend.app.main._capture_finish_photo_from_timelapse",
  423. AsyncMock(return_value=("finish_from_timelapse.jpg", False)),
  424. ),
  425. patch("backend.app.main.async_session", return_value=session),
  426. patch("backend.app.main.ws_manager", MagicMock(send_archive_updated=AsyncMock())) as ws,
  427. ):
  428. await _upgrade_finish_photo_from_timelapse(7, MagicMock())
  429. assert archive.photos == ["finish_from_timelapse.jpg", "finish_live_grab.jpg"]
  430. session.commit.assert_awaited()
  431. ws.send_archive_updated.assert_awaited_once()
  432. @pytest.mark.asyncio
  433. async def test_waits_far_longer_than_the_notification_can(self):
  434. from backend.app.main import (
  435. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS,
  436. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS,
  437. _upgrade_finish_photo_from_timelapse,
  438. )
  439. capture = AsyncMock(return_value=(None, True))
  440. with patch("backend.app.main._capture_finish_photo_from_timelapse", capture):
  441. await _upgrade_finish_photo_from_timelapse(7, MagicMock())
  442. assert capture.await_args.kwargs["timeout"] == _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS
  443. assert _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS > _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS
  444. # Covers the 546s worst case seen in the support bundles.
  445. assert _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS >= 600
  446. @pytest.mark.asyncio
  447. async def test_video_never_arrives_leaves_the_archive_alone(self):
  448. from backend.app.main import _upgrade_finish_photo_from_timelapse
  449. session = _session(MagicMock())
  450. with (
  451. patch("backend.app.main._capture_finish_photo_from_timelapse", AsyncMock(return_value=(None, True))),
  452. patch("backend.app.main.async_session", return_value=session),
  453. ):
  454. await _upgrade_finish_photo_from_timelapse(7, MagicMock())
  455. session.commit.assert_not_awaited()
  456. @pytest.mark.asyncio
  457. async def test_is_idempotent(self):
  458. """A second run must not list the same photo twice."""
  459. from backend.app.main import _upgrade_finish_photo_from_timelapse
  460. archive = MagicMock()
  461. archive.photos = ["finish_from_timelapse.jpg", "finish_live_grab.jpg"]
  462. session = _session(archive)
  463. with (
  464. patch(
  465. "backend.app.main._capture_finish_photo_from_timelapse",
  466. AsyncMock(return_value=("finish_from_timelapse.jpg", False)),
  467. ),
  468. patch("backend.app.main.async_session", return_value=session),
  469. ):
  470. await _upgrade_finish_photo_from_timelapse(7, MagicMock())
  471. assert archive.photos == ["finish_from_timelapse.jpg", "finish_live_grab.jpg"]
  472. session.commit.assert_not_awaited()
  473. @pytest.mark.asyncio
  474. async def test_missing_archive_does_not_raise(self):
  475. from backend.app.main import _upgrade_finish_photo_from_timelapse
  476. session = AsyncMock()
  477. session.__aenter__ = AsyncMock(return_value=session)
  478. session.__aexit__ = AsyncMock()
  479. session.get = AsyncMock(return_value=None)
  480. with (
  481. patch("backend.app.main._capture_finish_photo_from_timelapse", AsyncMock(return_value=("f.jpg", False))),
  482. patch("backend.app.main.async_session", return_value=session),
  483. ):
  484. await _upgrade_finish_photo_from_timelapse(7, MagicMock())
  485. session.commit.assert_not_awaited()
  486. @pytest.mark.asyncio
  487. async def test_refuses_to_delete_an_unverified_download(self):
  488. """The safety rule lives with the destructive call, not at the call
  489. sites — an unverified transfer may be a truncated file, and deleting
  490. the source would destroy the only complete copy."""
  491. from backend.app.services.bambu_ftp import delete_archived_timelapse
  492. with patch("backend.app.services.bambu_ftp.delete_file_async", AsyncMock()) as d:
  493. assert await delete_archived_timelapse("1.2.3.4", "code", "/timelapse/v.avi", verified=False) is False
  494. d.assert_not_awaited()
  495. @pytest.mark.asyncio
  496. async def test_verified_is_required_not_defaulted(self):
  497. """A future call site must not be able to silently skip the check."""
  498. import inspect
  499. from backend.app.services.bambu_ftp import delete_archived_timelapse
  500. param = inspect.signature(delete_archived_timelapse).parameters["verified"]
  501. assert param.default is inspect.Parameter.empty
  502. assert param.kind is inspect.Parameter.KEYWORD_ONLY
  503. class TestStaleBaselineCannotSurvive:
  504. """A reprint reuses the archive row, so a baseline left over from the
  505. previous run would have the scan diff this print against the printer's
  506. state before the *last* one — and unlike NULL, a stale list reads as
  507. authoritative and suppresses the fresh-snapshot fallback."""
  508. @pytest.mark.asyncio
  509. async def test_failed_capture_clears_rather_than_leaves_the_old_value(self):
  510. from backend.app.main import _capture_timelapse_baseline_at_start
  511. archive = MagicMock()
  512. archive.timelapse_baseline = ["from_the_previous_run.avi"]
  513. session = _session(archive)
  514. with (
  515. patch("backend.app.main.async_session", return_value=session),
  516. patch("backend.app.main._list_timelapse_videos", new=AsyncMock(side_effect=OSError("ftp down"))),
  517. ):
  518. await _capture_timelapse_baseline_at_start(_printer(), 1, logger, archive_id=7)
  519. assert archive.timelapse_baseline is None
  520. session.commit.assert_awaited()
  521. @pytest.mark.asyncio
  522. async def test_successful_capture_overwrites_the_old_value(self):
  523. from backend.app.main import _capture_timelapse_baseline_at_start
  524. archive = MagicMock()
  525. archive.timelapse_baseline = ["from_the_previous_run.avi"]
  526. session = _session(archive)
  527. with (
  528. patch("backend.app.main.async_session", return_value=session),
  529. patch(
  530. "backend.app.main._list_timelapse_videos",
  531. new=AsyncMock(return_value=([_video("now_on_the_printer.avi")], "/timelapse")),
  532. ),
  533. ):
  534. await _capture_timelapse_baseline_at_start(_printer(), 1, logger, archive_id=7)
  535. assert archive.timelapse_baseline == ["now_on_the_printer.avi"]
  536. class TestFileMustHaveStoppedGrowing:
  537. """Matching the listing's size proves we received what it said, not that
  538. the printer had finished writing. The scan's first look lands seconds after
  539. the print ends — exactly when the video is being written — so a growing
  540. file can be listed short, served short, and pass the length check. That was
  541. survivable while the printer kept its copy; it isn't now that a successful
  542. attach deletes it."""
  543. @pytest.mark.asyncio
  544. async def test_same_size_afterwards_is_settled(self):
  545. from backend.app.services.bambu_ftp import remote_file_settled
  546. with patch(
  547. "backend.app.services.bambu_ftp.list_files_async",
  548. AsyncMock(return_value=[_video("v.avi", size=4096)]),
  549. ):
  550. assert await remote_file_settled("1.2.3.4", "code", "/timelapse/v.avi", 4096) is True
  551. @pytest.mark.asyncio
  552. async def test_grown_since_download_is_not_settled(self):
  553. """We hold a prefix of the video, not the video."""
  554. from backend.app.services.bambu_ftp import remote_file_settled
  555. with patch(
  556. "backend.app.services.bambu_ftp.list_files_async",
  557. AsyncMock(return_value=[_video("v.avi", size=9000)]),
  558. ):
  559. assert await remote_file_settled("1.2.3.4", "code", "/timelapse/v.avi", 4096) is False
  560. @pytest.mark.asyncio
  561. async def test_vanished_counts_as_settled(self):
  562. """Nothing left that can grow, and nothing left to delete either."""
  563. from backend.app.services.bambu_ftp import remote_file_settled
  564. with patch(
  565. "backend.app.services.bambu_ftp.list_files_async",
  566. AsyncMock(return_value=[_video("something_else.avi")]),
  567. ):
  568. assert await remote_file_settled("1.2.3.4", "code", "/timelapse/v.avi", 4096) is True
  569. @pytest.mark.asyncio
  570. async def test_listing_failure_is_not_settled(self):
  571. """ "Could not check" must not read as "safe to delete"."""
  572. from backend.app.services.bambu_ftp import remote_file_settled
  573. with patch("backend.app.services.bambu_ftp.list_files_async", AsyncMock(return_value=[])):
  574. assert await remote_file_settled("1.2.3.4", "code", "/timelapse/v.avi", 4096) is False
  575. @pytest.mark.asyncio
  576. async def test_scan_discards_a_still_growing_video_without_deleting(self):
  577. from backend.app.main import _attach_first_unclaimed_timelapse
  578. delete = AsyncMock()
  579. service = MagicMock()
  580. service.attach_timelapse = AsyncMock(return_value=True)
  581. with (
  582. patch("backend.app.services.bambu_ftp.download_file_bytes_async", AsyncMock(return_value=b"x" * 1000)),
  583. patch("backend.app.services.bambu_ftp.remote_file_settled", AsyncMock(return_value=False)),
  584. patch("backend.app.services.bambu_ftp.delete_archived_timelapse", delete),
  585. patch("backend.app.main.async_session", return_value=_session()),
  586. patch("backend.app.main.ArchiveService", return_value=service),
  587. ):
  588. result = await _attach_first_unclaimed_timelapse(
  589. 42, _printer(), [_video("new.avi", size=1000)], set(), set(), 1, logger
  590. )
  591. assert result is False
  592. service.attach_timelapse.assert_not_awaited()
  593. delete.assert_not_awaited()
  594. @pytest.mark.asyncio
  595. async def test_scan_attaches_once_the_video_has_settled(self):
  596. from backend.app.main import _attach_first_unclaimed_timelapse
  597. settled = AsyncMock(return_value=True)
  598. service = MagicMock()
  599. service.attach_timelapse = AsyncMock(return_value=True)
  600. with (
  601. patch("backend.app.services.bambu_ftp.download_file_bytes_async", AsyncMock(return_value=b"x" * 1000)),
  602. patch("backend.app.services.bambu_ftp.remote_file_settled", settled),
  603. patch("backend.app.services.bambu_ftp.delete_archived_timelapse", AsyncMock()),
  604. patch("backend.app.main.async_session", return_value=_session()),
  605. patch("backend.app.main.ArchiveService", return_value=service),
  606. patch("backend.app.main.ws_manager", MagicMock(send_archive_updated=AsyncMock())),
  607. ):
  608. result = await _attach_first_unclaimed_timelapse(
  609. 42, _printer(), [_video("new.avi", size=1000)], set(), set(), 1, logger
  610. )
  611. assert result is True
  612. # Checked against what we actually received, not against the listing.
  613. assert settled.await_args.args[3] == 1000