from unittest.mock import MagicMock, patch import ai_cache import cache class TestCacheResilience: def test_redis_negative_caching_cooldown(self): # Reset cache state cache._redis_client = None cache._last_redis_failure = 0.0 with patch("redis.Redis.from_url") as mock_from_url: mock_from_url.side_effect = Exception("Connection refused") # First call attempts connection and fails client1 = cache.get_redis_client() assert client1 is None assert mock_from_url.call_count == 1 # Second call within cooldown fails immediately without calling from_url client2 = cache.get_redis_client() assert client2 is None assert mock_from_url.call_count == 1 # Socket timeouts were passed mock_from_url.assert_called_with( cache.REDIS_URL, decode_responses=True, socket_connect_timeout=0.2, socket_timeout=0.2, ) def test_redis_get_cache_sets_cooldown_on_error(self): cache._redis_client = MagicMock() cache._redis_client.get.side_effect = Exception("Socket closed") cache._last_redis_failure = 0.0 val = cache.get_cache("some_key") assert val is None assert cache._redis_client is None assert cache._last_redis_failure > 0 class TestAiCacheLocalMode: def test_ai_cache_skips_firestore_in_sandbox_mode(self): with patch.dict("os.environ", {"SANDBOX_MODE": "true"}): with patch("db.init_firebase") as mock_init_fb: item = ai_cache.get_cached_item("non_existent_key") assert item is None mock_init_fb.assert_not_called() def test_ai_cache_firestore_timeout_parameter(self): mock_doc = MagicMock() mock_doc_ref = MagicMock() mock_doc_ref.get.return_value = mock_doc mock_doc.exists = True mock_doc.to_dict.return_value = {"payload": "test_data"} mock_firestore_client = MagicMock() mock_firestore_client.collection.return_value.document.return_value = mock_doc_ref with ( patch("ai_cache.is_local_or_sandbox_mode", return_value=False), patch("ai_cache._can_attempt_firestore", return_value=True), patch("db.init_firebase", return_value=mock_firestore_client), ): res = ai_cache.get_cached_item("my_key") assert res == "test_data" mock_doc_ref.get.assert_called_with(timeout=0.5) def test_ai_cache_records_failure_when_init_firebase_returns_none(self): ai_cache._last_firestore_failure = 0.0 with ( patch("ai_cache.is_local_or_sandbox_mode", return_value=False), patch("ai_cache._can_attempt_firestore", return_value=True), patch("db.init_firebase", return_value=None), ): res = ai_cache.get_cached_item("missing_key") assert res is None assert ai_cache._last_firestore_failure > 0.0 def test_redis_disabled_or_empty_url_returns_none(self): cache._redis_client = None with patch.object(cache, "REDIS_URL", ""): assert cache.get_redis_client() is None with patch.object(cache, "REDIS_URL", "disabled"): assert cache.get_redis_client() is None