import os import json import tempfile import unittest from unittest.mock import patch, MagicMock from utils.cloud_config import ( compute_config_hash, fetch_cloud_config, save_local_cache, load_local_config, load_remote_or_cache, ) class TestCloudConfig(unittest.TestCase): def test_compute_config_hash(self): data1 = {"b": 2, "a": 1} data2 = {"a": 1, "b": 2} data3 = {"a": 1, "b": 3} self.assertEqual(compute_config_hash(data1), compute_config_hash(data2)) self.assertNotEqual(compute_config_hash(data1), compute_config_hash(data3)) def test_fetch_cloud_config_success(self): with patch("toolkit.vs_cloud_api.VSCloudApi.Instance") as mock_api_inst: mock_inst = MagicMock() mock_inst.get_node_configurations.return_value = { "items": [{"identifier": "group_a", "enable": True}] } mock_api_inst.return_value = mock_inst data = fetch_cloud_config(role="sentinel", node_id="node-1") self.assertEqual(data, [{"identifier": "group_a", "enable": True}]) def test_fetch_cloud_config_failure(self): with patch("toolkit.vs_cloud_api.VSCloudApi.Instance") as mock_api_inst: mock_inst = MagicMock() mock_inst.get_node_configurations.side_effect = Exception("API down") mock_api_inst.return_value = mock_inst data = fetch_cloud_config(role="sentinel", node_id="node-1") self.assertIsNone(data) def test_load_cloud_or_cache_success_and_save(self): with patch("toolkit.vs_cloud_api.VSCloudApi.Instance") as mock_api_inst: mock_inst = MagicMock() mock_inst.get_node_configurations.return_value = { "items": [{"identifier": "group_remote", "enable": True}] } mock_api_inst.return_value = mock_inst with tempfile.TemporaryDirectory() as tmp_dir: cache_path = os.path.join(tmp_dir, "cache.json") data, hash_val, loaded_cloud = load_remote_or_cache( role="sentinel", node_id="node-1", local_cache_path=cache_path ) self.assertTrue(loaded_cloud) self.assertEqual(data, [{"identifier": "group_remote", "enable": True}]) self.assertTrue(os.path.exists(cache_path)) # 验证本地缓存是否被写入 cached_data = load_local_config(cache_path) self.assertEqual(cached_data, [{"identifier": "group_remote", "enable": True}]) def test_load_cloud_or_cache_fallback_to_local(self): with patch("toolkit.vs_cloud_api.VSCloudApi.Instance") as mock_api_inst: mock_inst = MagicMock() mock_inst.get_node_configurations.side_effect = Exception("API down") mock_api_inst.return_value = mock_inst with tempfile.TemporaryDirectory() as tmp_dir: cache_path = os.path.join(tmp_dir, "cache.json") save_local_cache(cache_path, [{"identifier": "group_cached", "enable": True}]) data, hash_val, loaded_cloud = load_remote_or_cache( role="sentinel", node_id="node-1", local_cache_path=cache_path ) self.assertFalse(loaded_cloud) self.assertEqual(data, [{"identifier": "group_cached", "enable": True}]) if __name__ == "__main__": unittest.main()