test_timelapse_scan_2704.py 33 KB

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