From dfe0eed7bd45fb8be80bc114a7783907ccd5ebee Mon Sep 17 00:00:00 2001 From: harish-berri Date: Sat, 9 May 2026 02:28:17 +0000 Subject: [PATCH] Add test for RedisCache async_increment fallback behavior when existing TTL is present This test verifies that when the expire(nx=True) argument is unsupported and the key already has a TTL, the async_increment method does not issue a second expire() call. It ensures the correct behavior of the fallback mechanism in the RedisCache implementation. --- .../test_litellm/caching/test_redis_cache.py | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/tests/test_litellm/caching/test_redis_cache.py b/tests/test_litellm/caching/test_redis_cache.py index 488e8ce0daa..7283d8307d4 100644 --- a/tests/test_litellm/caching/test_redis_cache.py +++ b/tests/test_litellm/caching/test_redis_cache.py @@ -133,6 +133,36 @@ async def test_redis_cache_async_increment_default_falls_back_when_expire_nx_uns mock_redis_instance.ttl.assert_awaited_once_with("rate_limit:window") +@pytest.mark.asyncio +async def test_redis_cache_async_increment_default_fallback_existing_ttl_skips_second_expire( + monkeypatch, redis_no_ping +): + """When expire(nx=True) is unsupported and key already has a TTL, fallback + should not issue a second expire() call.""" + monkeypatch.setenv("REDIS_HOST", "https://my-test-host") + redis_cache = RedisCache() + mock_redis_instance = AsyncMock() + mock_redis_instance.__aenter__.return_value = mock_redis_instance + mock_redis_instance.__aexit__.return_value = None + mock_redis_instance.expire.side_effect = [ + TypeError("unexpected keyword argument 'nx'"), + ] + mock_redis_instance.ttl.return_value = 42 + + with patch.object( + redis_cache, "init_async_client", return_value=mock_redis_instance + ): + await redis_cache.async_increment(key="rate_limit:window", value=1) + + assert mock_redis_instance.expire.await_count == 1 + assert mock_redis_instance.expire.await_args_list[0].args == ( + "rate_limit:window", + 60, + ) + assert mock_redis_instance.expire.await_args_list[0].kwargs == {"nx": True} + mock_redis_instance.ttl.assert_awaited_once_with("rate_limit:window") + + @pytest.mark.asyncio async def test_redis_client_init_with_socket_timeout(monkeypatch, redis_no_ping): monkeypatch.setenv("REDIS_HOST", "my-fake-host")