from __future__ import annotations import threading import time import unittest from types import SimpleNamespace from scene_search.caption_jobs import CaptionJobManager, CaptionJobStopped class CaptionStopTests(unittest.TestCase): def test_stop_is_observed_at_next_safe_boundary(self) -> None: manager = CaptionJobManager(SimpleNamespace()) # type: ignore[arg-type] manager._state.update( { "running": True, "stage": "captioning", "frames_total": 10, "frames_completed": 3, } ) status = manager.stop() self.assertTrue(status["stop_requested"]) self.assertRaises( CaptionJobStopped, manager._wait_if_paused, "captioning", ) def test_stop_releases_a_paused_job(self) -> None: manager = CaptionJobManager(SimpleNamespace()) # type: ignore[arg-type] manager._state.update( { "running": True, "stage": "captioning", "frames_total": 10, "frames_completed": 3, } ) manager.pause() stopped = threading.Event() def worker() -> None: try: manager._wait_if_paused("captioning") except CaptionJobStopped: stopped.set() thread = threading.Thread(target=worker) thread.start() deadline = time.time() + 2 while time.time() < deadline and not manager.status().get("paused"): time.sleep(0.01) self.assertTrue(manager.status()["paused"]) status = manager.stop() self.assertTrue(status["stop_requested"]) thread.join(timeout=2) self.assertTrue(stopped.is_set()) def test_stop_is_refused_during_final_search_sync(self) -> None: manager = CaptionJobManager(SimpleNamespace()) # type: ignore[arg-type] manager._state.update({"running": True, "stage": "syncing"}) with self.assertRaisesRegex(RuntimeError, "search index is rebuilding"): manager.stop() if __name__ == "__main__": unittest.main()