test_layer_timelapse.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. """
  2. Tests for the layer timelapse service.
  3. These tests cover session management and pure logic functions.
  4. """
  5. import time
  6. from datetime import datetime
  7. from pathlib import Path
  8. from unittest.mock import ANY, AsyncMock, MagicMock, patch
  9. import pytest
  10. class TestTimelapseSessionManagement:
  11. """Tests for timelapse session lifecycle."""
  12. def test_start_session_creates_new_session(self):
  13. """Verify start_session creates and registers a new session."""
  14. from backend.app.services.layer_timelapse import (
  15. _active_sessions,
  16. cancel_session,
  17. get_session,
  18. start_session,
  19. )
  20. # Clear any existing sessions
  21. _active_sessions.clear()
  22. with patch("backend.app.services.layer_timelapse.settings") as mock_settings:
  23. mock_settings.base_dir = Path("/tmp/test_bambuddy")
  24. session = start_session(
  25. printer_id=1,
  26. archive_id=100,
  27. url="http://camera.local/mjpeg",
  28. cam_type="mjpeg",
  29. )
  30. assert session is not None
  31. assert session.printer_id == 1
  32. assert session.archive_id == 100
  33. assert session.camera_url == "http://camera.local/mjpeg"
  34. assert session.camera_type == "mjpeg"
  35. assert session.last_layer == -1
  36. assert session.frame_count == 0
  37. # Session should be retrievable
  38. retrieved = get_session(1)
  39. assert retrieved is session
  40. # Cleanup
  41. cancel_session(1)
  42. def test_start_session_cancels_existing(self):
  43. """Verify starting a new session cancels any existing session."""
  44. from backend.app.services.layer_timelapse import (
  45. _active_sessions,
  46. cancel_session,
  47. get_session,
  48. start_session,
  49. )
  50. _active_sessions.clear()
  51. with patch("backend.app.services.layer_timelapse.settings") as mock_settings:
  52. mock_settings.base_dir = Path("/tmp/test_bambuddy")
  53. # Start first session
  54. session1 = start_session(1, 100, "http://cam1/", "mjpeg")
  55. # Mock cleanup to track if it was called
  56. session1.cleanup = MagicMock()
  57. # Start second session for same printer
  58. session2 = start_session(1, 101, "http://cam2/", "rtsp")
  59. # First session should be replaced
  60. current = get_session(1)
  61. assert current is session2
  62. assert current.archive_id == 101 # Verify it's the new session
  63. assert current.camera_url == "http://cam2/"
  64. # First session's cleanup should have been called
  65. session1.cleanup.assert_called_once()
  66. # Cleanup
  67. cancel_session(1)
  68. def test_get_session_returns_none_for_unknown(self):
  69. """Verify get_session returns None for unknown printer."""
  70. from backend.app.services.layer_timelapse import _active_sessions, get_session
  71. _active_sessions.clear()
  72. result = get_session(999)
  73. assert result is None
  74. def test_cancel_session_removes_and_cleans_up(self):
  75. """Verify cancel_session removes session and cleans up."""
  76. from backend.app.services.layer_timelapse import (
  77. _active_sessions,
  78. cancel_session,
  79. get_session,
  80. start_session,
  81. )
  82. _active_sessions.clear()
  83. with patch("backend.app.services.layer_timelapse.settings") as mock_settings:
  84. mock_settings.base_dir = Path("/tmp/test_bambuddy")
  85. session = start_session(1, 100, "http://cam/", "mjpeg")
  86. # Mock cleanup to avoid filesystem operations
  87. session.cleanup = MagicMock()
  88. cancel_session(1)
  89. # Session should be removed
  90. assert get_session(1) is None
  91. # Cleanup should have been called
  92. session.cleanup.assert_called_once()
  93. def test_cancel_nonexistent_session_is_safe(self):
  94. """Verify canceling a non-existent session doesn't error."""
  95. from backend.app.services.layer_timelapse import _active_sessions, cancel_session
  96. _active_sessions.clear()
  97. # Should not raise
  98. cancel_session(999)
  99. class TestTimelapseSession:
  100. """Tests for TimelapseSession class."""
  101. def test_session_id_format(self):
  102. """Verify session ID follows expected datetime format."""
  103. from backend.app.services.layer_timelapse import TimelapseSession, _active_sessions
  104. _active_sessions.clear()
  105. with patch("backend.app.services.layer_timelapse.settings") as mock_settings:
  106. mock_settings.base_dir = Path("/tmp/test_bambuddy")
  107. session = TimelapseSession(
  108. printer_id=1,
  109. archive_id=100,
  110. camera_url="http://test/",
  111. camera_type="mjpeg",
  112. )
  113. # Session ID should be timestamp format YYYYMMDD_HHMMSS
  114. assert len(session.session_id) == 15
  115. assert session.session_id[8] == "_"
  116. # Should be parseable as datetime
  117. try:
  118. datetime.strptime(session.session_id, "%Y%m%d_%H%M%S")
  119. except ValueError:
  120. pytest.fail("Session ID is not valid datetime format")
  121. def test_frames_dir_path_structure(self):
  122. """Verify frames directory path is structured correctly."""
  123. from backend.app.services.layer_timelapse import TimelapseSession
  124. with patch("backend.app.services.layer_timelapse.settings") as mock_settings:
  125. mock_settings.base_dir = Path("/data/bambuddy")
  126. with patch.object(Path, "mkdir"): # Avoid creating real directories
  127. session = TimelapseSession(
  128. printer_id=42,
  129. archive_id=100,
  130. camera_url="http://test/",
  131. camera_type="mjpeg",
  132. )
  133. expected_path = Path("/data/bambuddy/timelapse_frames/42") / session.session_id
  134. assert session.frames_dir == expected_path
  135. class TestLayerChangeLogic:
  136. """Tests for layer change capture logic."""
  137. @pytest.mark.asyncio
  138. async def test_capture_layer_only_on_increase(self):
  139. """Verify frames are only captured when layer increases."""
  140. from backend.app.services.layer_timelapse import TimelapseSession
  141. with patch("backend.app.services.layer_timelapse.settings") as mock_settings:
  142. mock_settings.base_dir = Path("/tmp/test")
  143. with patch.object(Path, "mkdir"):
  144. session = TimelapseSession(1, 100, "http://test/", "mjpeg")
  145. # Mock capture_frame to return data
  146. with patch(
  147. "backend.app.services.layer_timelapse.capture_frame", new_callable=AsyncMock
  148. ) as mock_capture:
  149. mock_capture.return_value = b"\xff\xd8test\xff\xd9"
  150. with patch.object(Path, "write_bytes"):
  151. # First layer should capture
  152. result = await session.capture_layer(1)
  153. assert result is True
  154. assert session.last_layer == 1
  155. assert session.frame_count == 1
  156. # Same layer should NOT capture
  157. result = await session.capture_layer(1)
  158. assert result is False
  159. assert session.frame_count == 1
  160. # Lower layer should NOT capture
  161. result = await session.capture_layer(0)
  162. assert result is False
  163. assert session.frame_count == 1
  164. # Higher layer should capture
  165. result = await session.capture_layer(5)
  166. assert result is True
  167. assert session.last_layer == 5
  168. assert session.frame_count == 2
  169. @pytest.mark.asyncio
  170. async def test_capture_layer_handles_failed_capture(self):
  171. """Verify failed capture returns False but updates layer."""
  172. from backend.app.services.layer_timelapse import TimelapseSession
  173. with patch("backend.app.services.layer_timelapse.settings") as mock_settings:
  174. mock_settings.base_dir = Path("/tmp/test")
  175. with patch.object(Path, "mkdir"):
  176. session = TimelapseSession(1, 100, "http://test/", "mjpeg")
  177. # Mock capture_frame to return None (failure)
  178. with patch(
  179. "backend.app.services.layer_timelapse.capture_frame", new_callable=AsyncMock
  180. ) as mock_capture:
  181. mock_capture.return_value = None
  182. result = await session.capture_layer(1)
  183. assert result is False
  184. assert session.last_layer == 1 # Layer is still updated
  185. assert session.frame_count == 0 # But frame count not incremented
  186. class TestCaptureLayerAppliesRotation:
  187. """camera_rotation was previously only wired into the notification-
  188. snapshot path, so a layer-timelapse video came out upside-down whenever
  189. the printer had a rotation configured. capture_layer now applies it to
  190. every captured frame, whether fresh or reused from the live view's
  191. buffer, before writing to disk."""
  192. @pytest.mark.asyncio
  193. async def test_rotates_fresh_capture_when_configured(self, tmp_path):
  194. from backend.app.services.layer_timelapse import TimelapseSession
  195. with patch("backend.app.services.layer_timelapse.settings") as mock_settings:
  196. mock_settings.base_dir = tmp_path
  197. with patch.object(Path, "mkdir"):
  198. session = TimelapseSession(1, 100, "/dev/video1", "usb", rotation=180)
  199. with (
  200. patch("backend.app.api.routes.camera.live_frame_for_capture", return_value=(False, None)),
  201. patch(
  202. "backend.app.services.layer_timelapse.capture_frame",
  203. new_callable=AsyncMock,
  204. return_value=b"\xff\xd8unrotated\xff\xd9",
  205. ),
  206. patch(
  207. "backend.app.services.layer_timelapse.apply_camera_rotation",
  208. return_value=b"\xff\xd8rotated\xff\xd9",
  209. ) as mock_rotate,
  210. patch.object(Path, "write_bytes") as mock_write,
  211. ):
  212. result = await session.capture_layer(1)
  213. assert result is True
  214. mock_rotate.assert_called_once_with(b"\xff\xd8unrotated\xff\xd9", 180, ANY)
  215. mock_write.assert_called_once_with(b"\xff\xd8rotated\xff\xd9")
  216. @pytest.mark.asyncio
  217. async def test_rotates_buffered_frame_when_configured(self, tmp_path):
  218. from backend.app.services.layer_timelapse import TimelapseSession
  219. with patch("backend.app.services.layer_timelapse.settings") as mock_settings:
  220. mock_settings.base_dir = tmp_path
  221. with patch.object(Path, "mkdir"):
  222. session = TimelapseSession(1, 100, "/dev/video1", "usb", rotation=90)
  223. with (
  224. patch(
  225. "backend.app.api.routes.camera.live_frame_for_capture",
  226. return_value=(True, b"\xff\xd8buffered\xff\xd9"),
  227. ),
  228. patch(
  229. "backend.app.services.layer_timelapse.apply_camera_rotation",
  230. return_value=b"\xff\xd8rotated\xff\xd9",
  231. ) as mock_rotate,
  232. patch.object(Path, "write_bytes") as mock_write,
  233. ):
  234. result = await session.capture_layer(1)
  235. assert result is True
  236. mock_rotate.assert_called_once_with(b"\xff\xd8buffered\xff\xd9", 90, ANY)
  237. mock_write.assert_called_once_with(b"\xff\xd8rotated\xff\xd9")
  238. @pytest.mark.asyncio
  239. async def test_skips_rotation_when_not_configured(self, tmp_path):
  240. """Default rotation=0 - no-op, and must not even call apply_camera_rotation
  241. (avoids the PIL decode/re-encode round trip for the common case)."""
  242. from backend.app.services.layer_timelapse import TimelapseSession
  243. with patch("backend.app.services.layer_timelapse.settings") as mock_settings:
  244. mock_settings.base_dir = tmp_path
  245. with patch.object(Path, "mkdir"):
  246. session = TimelapseSession(1, 100, "/dev/video1", "usb")
  247. assert session.rotation == 0
  248. with (
  249. patch("backend.app.api.routes.camera.live_frame_for_capture", return_value=(False, None)),
  250. patch(
  251. "backend.app.services.layer_timelapse.capture_frame",
  252. new_callable=AsyncMock,
  253. return_value=b"\xff\xd8unrotated\xff\xd9",
  254. ),
  255. patch("backend.app.services.layer_timelapse.apply_camera_rotation") as mock_rotate,
  256. patch.object(Path, "write_bytes") as mock_write,
  257. ):
  258. result = await session.capture_layer(1)
  259. assert result is True
  260. mock_rotate.assert_not_called()
  261. mock_write.assert_called_once_with(b"\xff\xd8unrotated\xff\xd9")
  262. class TestOnLayerChange:
  263. """Tests for the on_layer_change callback."""
  264. @pytest.mark.asyncio
  265. async def test_on_layer_change_captures_when_session_exists(self):
  266. """Verify on_layer_change triggers capture when session exists."""
  267. from backend.app.services.layer_timelapse import (
  268. _active_sessions,
  269. cancel_session,
  270. on_layer_change,
  271. start_session,
  272. )
  273. _active_sessions.clear()
  274. with patch("backend.app.services.layer_timelapse.settings") as mock_settings:
  275. mock_settings.base_dir = Path("/tmp/test")
  276. with patch.object(Path, "mkdir"):
  277. session = start_session(1, 100, "http://test/", "mjpeg")
  278. with patch.object(session, "capture_layer", new_callable=AsyncMock) as mock_capture:
  279. mock_capture.return_value = True
  280. await on_layer_change(1, 5)
  281. mock_capture.assert_called_once_with(5)
  282. cancel_session(1)
  283. @pytest.mark.asyncio
  284. async def test_on_layer_change_does_nothing_without_session(self):
  285. """Verify on_layer_change is safe when no session exists."""
  286. from backend.app.services.layer_timelapse import _active_sessions, on_layer_change
  287. _active_sessions.clear()
  288. # Should not raise
  289. await on_layer_change(999, 10)
  290. class TestGetActiveSessions:
  291. """Tests for get_active_sessions."""
  292. def test_get_active_sessions_returns_copy(self):
  293. """Verify get_active_sessions returns a copy, not the original dict."""
  294. from backend.app.services.layer_timelapse import (
  295. _active_sessions,
  296. cancel_session,
  297. get_active_sessions,
  298. start_session,
  299. )
  300. _active_sessions.clear()
  301. with patch("backend.app.services.layer_timelapse.settings") as mock_settings:
  302. mock_settings.base_dir = Path("/tmp/test")
  303. with patch.object(Path, "mkdir"):
  304. start_session(1, 100, "http://test/", "mjpeg")
  305. sessions = get_active_sessions()
  306. # Should be a copy
  307. assert sessions is not _active_sessions
  308. assert 1 in sessions
  309. # Modifying copy shouldn't affect original
  310. sessions.clear()
  311. assert 1 in _active_sessions
  312. cancel_session(1)
  313. class TestCleanupOrphanedTimelapseSessions:
  314. """_active_sessions is in-memory only, so a process restart mid-print
  315. loses track of an active session without ever cleaning up its frames
  316. directory (or a stitched-but-not-attached output .mp4). Confirmed live:
  317. 38MB of exactly this leftover on Carl's OrangePi after several restarts
  318. during testing. cleanup_orphaned_timelapse_sessions() sweeps for it."""
  319. def _touch_old(self, path, age_seconds=600):
  320. import os
  321. path.touch()
  322. old = time.time() - age_seconds
  323. os.utime(path, (old, old))
  324. def _mkdir_old(self, path, age_seconds=600):
  325. import os
  326. path.mkdir(parents=True)
  327. old = time.time() - age_seconds
  328. os.utime(path, (old, old))
  329. def test_removes_orphaned_frame_dir_and_stray_output(self, tmp_path):
  330. from backend.app.services.layer_timelapse import (
  331. _active_sessions,
  332. cleanup_orphaned_timelapse_sessions,
  333. )
  334. _active_sessions.clear()
  335. printer_dir = tmp_path / "timelapse_frames" / "1"
  336. self._mkdir_old(printer_dir / "20260101_000000")
  337. self._touch_old(printer_dir / "timelapse_20260101_000000.mp4")
  338. with patch("backend.app.services.layer_timelapse.settings") as mock_settings:
  339. mock_settings.base_dir = tmp_path
  340. removed = cleanup_orphaned_timelapse_sessions(min_age_seconds=300)
  341. assert removed == 2
  342. assert not (printer_dir / "20260101_000000").exists()
  343. assert not (printer_dir / "timelapse_20260101_000000.mp4").exists()
  344. def test_spares_the_currently_active_session(self, tmp_path):
  345. from backend.app.services.layer_timelapse import (
  346. TimelapseSession,
  347. _active_sessions,
  348. cleanup_orphaned_timelapse_sessions,
  349. )
  350. _active_sessions.clear()
  351. with patch("backend.app.services.layer_timelapse.settings") as mock_settings:
  352. mock_settings.base_dir = tmp_path
  353. session = TimelapseSession(1, 100, "/dev/video1", "usb")
  354. _active_sessions[1] = session
  355. import os
  356. old = time.time() - 600
  357. os.utime(session.frames_dir, (old, old))
  358. removed = cleanup_orphaned_timelapse_sessions(min_age_seconds=300)
  359. assert removed == 0
  360. assert session.frames_dir.exists()
  361. _active_sessions.clear()
  362. def test_spares_recently_modified_entries(self, tmp_path):
  363. """Defensive margin: something modified within min_age_seconds is
  364. left alone even if it doesn't match an active session, in case this
  365. is ever invoked while a session is mid-creation."""
  366. from backend.app.services.layer_timelapse import (
  367. _active_sessions,
  368. cleanup_orphaned_timelapse_sessions,
  369. )
  370. _active_sessions.clear()
  371. printer_dir = tmp_path / "timelapse_frames" / "1"
  372. printer_dir.mkdir(parents=True)
  373. (printer_dir / "20260101_000000").mkdir()
  374. with patch("backend.app.services.layer_timelapse.settings") as mock_settings:
  375. mock_settings.base_dir = tmp_path
  376. removed = cleanup_orphaned_timelapse_sessions(min_age_seconds=300)
  377. assert removed == 0
  378. assert (printer_dir / "20260101_000000").exists()
  379. def test_no_base_dir_is_a_no_op(self, tmp_path):
  380. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  381. with patch("backend.app.services.layer_timelapse.settings") as mock_settings:
  382. mock_settings.base_dir = tmp_path / "does-not-exist"
  383. removed = cleanup_orphaned_timelapse_sessions()
  384. assert removed == 0
  385. def test_ignores_non_numeric_printer_dirs(self, tmp_path):
  386. """Defensive: unrelated directories under timelapse_frames/ (there
  387. shouldn't be any, but printer_id is parsed from the dir name) must
  388. not raise."""
  389. from backend.app.services.layer_timelapse import (
  390. _active_sessions,
  391. cleanup_orphaned_timelapse_sessions,
  392. )
  393. _active_sessions.clear()
  394. (tmp_path / "timelapse_frames" / "not-a-printer-id").mkdir(parents=True)
  395. with patch("backend.app.services.layer_timelapse.settings") as mock_settings:
  396. mock_settings.base_dir = tmp_path
  397. removed = cleanup_orphaned_timelapse_sessions()
  398. assert removed == 0
  399. def test_spares_a_session_that_is_mid_stitch(self, tmp_path):
  400. """on_print_complete drops the session from _active_sessions before it
  401. hands frames_dir to ffmpeg, so for the length of a stitch (up to 300s)
  402. the directory matches no active session. Its mtime is the last layer's
  403. frame write, which on a tall print's final layer is easily older than
  404. the age margin — and the margin's default IS the stitch timeout, so it
  405. offers no headroom here. _finalizing_sessions covers that window."""
  406. import os
  407. from backend.app.services.layer_timelapse import (
  408. TimelapseSession,
  409. _active_sessions,
  410. _finalizing_sessions,
  411. cleanup_orphaned_timelapse_sessions,
  412. )
  413. _active_sessions.clear()
  414. _finalizing_sessions.clear()
  415. with patch("backend.app.services.layer_timelapse.settings") as mock_settings:
  416. mock_settings.base_dir = tmp_path
  417. session = TimelapseSession(1, 100, "/dev/video1", "usb")
  418. (session.frames_dir / "layer_00001.jpg").write_bytes(b"x")
  419. old = time.time() - 600
  420. os.utime(session.frames_dir, (old, old))
  421. # Exactly the state on_print_complete is in while ffmpeg runs.
  422. _active_sessions.pop(1, None)
  423. _finalizing_sessions[1] = session.session_id
  424. removed = cleanup_orphaned_timelapse_sessions(min_age_seconds=300)
  425. assert removed == 0
  426. assert session.frames_dir.exists(), "ffmpeg's input was deleted mid-stitch"
  427. _finalizing_sessions.clear()
  428. @pytest.mark.asyncio
  429. async def test_on_print_complete_clears_the_finalizing_marker(self, tmp_path):
  430. """Including when the stitch fails — a leaked marker would make the
  431. sweep skip that printer's leftovers forever."""
  432. from backend.app.services.layer_timelapse import (
  433. TimelapseSession,
  434. _active_sessions,
  435. _finalizing_sessions,
  436. on_print_complete,
  437. )
  438. _active_sessions.clear()
  439. _finalizing_sessions.clear()
  440. with patch("backend.app.services.layer_timelapse.settings") as mock_settings:
  441. mock_settings.base_dir = tmp_path
  442. session = TimelapseSession(1, 100, "/dev/video1", "usb")
  443. session.frame_count = 3
  444. _active_sessions[1] = session
  445. with patch.object(TimelapseSession, "stitch", AsyncMock(side_effect=RuntimeError("ffmpeg died"))):
  446. result = await on_print_complete(1)
  447. assert result is None
  448. assert 1 not in _finalizing_sessions
  449. def test_leaves_unrelated_files_alone(self, tmp_path):
  450. """Only this module's own artifacts are swept. A file that is neither a
  451. session directory nor timelapse_<id>.mp4 was put there by something
  452. else, and age is not a reason to delete it."""
  453. from backend.app.services.layer_timelapse import (
  454. _active_sessions,
  455. cleanup_orphaned_timelapse_sessions,
  456. )
  457. _active_sessions.clear()
  458. printer_dir = tmp_path / "timelapse_frames" / "1"
  459. printer_dir.mkdir(parents=True)
  460. stranger = printer_dir / "notes.txt"
  461. self._touch_old(stranger)
  462. self._touch_old(printer_dir / "timelapse_20260101_000000.mp4")
  463. with patch("backend.app.services.layer_timelapse.settings") as mock_settings:
  464. mock_settings.base_dir = tmp_path
  465. removed = cleanup_orphaned_timelapse_sessions(min_age_seconds=300)
  466. assert removed == 1
  467. assert stranger.exists()
  468. assert not (printer_dir / "timelapse_20260101_000000.mp4").exists()
  469. def test_a_removal_that_fails_is_not_counted_as_removed(self, tmp_path):
  470. """The count and the log line are the only evidence an operator has of
  471. what was deleted, so a failed rmtree must not be reported as a success.
  472. The stub honours rmtree's real contract — ignore_errors=True swallows
  473. the failure and returns normally — because that is the whole point: a
  474. caller passing it gets a silent no-op that the surrounding
  475. ``except OSError`` can never see, and would still count and log the
  476. directory as removed. A stub that raised unconditionally would pass
  477. either way and prove nothing.
  478. """
  479. from backend.app.services.layer_timelapse import (
  480. _active_sessions,
  481. cleanup_orphaned_timelapse_sessions,
  482. )
  483. _active_sessions.clear()
  484. printer_dir = tmp_path / "timelapse_frames" / "1"
  485. self._mkdir_old(printer_dir / "20260101_000000")
  486. def rmtree_on_read_only_fs(path, ignore_errors=False, **kwargs):
  487. if ignore_errors:
  488. return # silently does nothing, exactly like the real thing
  489. raise OSError("read-only fs")
  490. with patch("backend.app.services.layer_timelapse.settings") as mock_settings:
  491. mock_settings.base_dir = tmp_path
  492. with patch("backend.app.services.layer_timelapse.shutil.rmtree", rmtree_on_read_only_fs):
  493. removed = cleanup_orphaned_timelapse_sessions(min_age_seconds=300)
  494. assert removed == 0, "a directory that is still on disk was reported as removed"
  495. assert (printer_dir / "20260101_000000").exists()