from __future__ import annotations import unittest from unittest.mock import MagicMock, patch from app.services import cluster_runtime_service class RuntimeSchemaGuardTests(unittest.TestCase): def test_ensure_runtime_schema_executes_only_once_per_process(self) -> None: conn = MagicMock() cursor_cm = MagicMock() cursor = MagicMock() conn.cursor.return_value = cursor_cm cursor_cm.__enter__.return_value = cursor db_cm = MagicMock() db_cm.__enter__.return_value = conn with patch.object(cluster_runtime_service, "_RUNTIME_SCHEMA_READY", False): with patch.object(cluster_runtime_service, "get_db", return_value=db_cm) as mocked_get_db: cluster_runtime_service.ensure_runtime_schema() cluster_runtime_service.ensure_runtime_schema() mocked_get_db.assert_called_once() self.assertEqual(cursor.execute.call_count, 2) cursor.execute.assert_any_call( "SELECT pg_advisory_xact_lock(%s)", (cluster_runtime_service._RUNTIME_SCHEMA_ADVISORY_LOCK_ID,), ) cursor.execute.assert_any_call(cluster_runtime_service._RUNTIME_SCHEMA_SQL) conn.commit.assert_called_once() def test_control_node_supports_worker_only_on_mainland_with_worker_signals(self) -> None: self.assertFalse( cluster_runtime_service._control_node_supports_worker( region="overseas", metadata={ "worker_online": False, "detect_participating": True, "active_threads": 0, "max_threads": 0, }, ) ) self.assertTrue( cluster_runtime_service._control_node_supports_worker( region="mainland", metadata={ "worker_online": True, "detect_participating": False, "active_threads": 0, "max_threads": 0, }, ) ) def test_metadata_idle_without_runtime_work_detects_stale_idle_heartbeat(self) -> None: self.assertTrue( cluster_runtime_service._metadata_idle_without_runtime_work( { "phase_label": "idle", "phase_detail": "Worker 已启动,等待检测指令", "active_threads": 323, "max_threads": 4, "active_job_code": "", "job_items_total": 0, "job_items_claimed": 0, "job_items_running": 0, "job_items_completed": 0, "job_items_failed": 0, } ) ) self.assertFalse( cluster_runtime_service._metadata_idle_without_runtime_work( { "phase_label": "running", "active_threads": 12, } ) ) self.assertFalse( cluster_runtime_service._metadata_idle_without_runtime_work( { "phase_label": "idle", "active_job_code": "sync-overseas-1", } ) ) if __name__ == "__main__": unittest.main()