55
66import time
77
8- import pytest
9- from aiocache import Cache
108from fastapi .security import HTTPBasicCredentials
119from models_library .api_schemas_api_server .api_keys import ApiKeyInDB
1210from pytest_mock import MockerFixture
@@ -43,7 +41,6 @@ async def test_cache_effectiveness_in_rest_authentication_dependencies(
4341 api_key_in_db : ApiKeyInDB ,
4442 api_key_repo : ApiKeysRepository ,
4543 users_repo : UsersRepository ,
46- monkeypatch : pytest .MonkeyPatch ,
4744 mocker : MockerFixture ,
4845):
4946 """Test that caching reduces database calls and improves performance.
@@ -118,15 +115,21 @@ async def test_cache_effectiveness_in_rest_authentication_dependencies(
118115 username = api_key_in_db .api_key , password = api_key_in_db .api_secret
119116 )
120117
121- # Test with cache enabled (default)
122- monkeypatch .delenv ("AIOCACHE_DISABLE" , raising = False )
123- await Cache ().clear () # Clear any existing cache
118+ # Get cache instances from repository methods
119+ # pylint: disable=no-member
120+ api_keys_cache = api_key_repo .get_user .cache
121+ users_cache = users_repo .get_active_user_email .cache
122+
123+ # Clear any existing cache
124+ await api_keys_cache .clear ()
125+ await users_cache .clear ()
124126
125127 # Spy on the connection's execute method by patching AsyncConnection.execute
126128 from sqlalchemy .ext .asyncio import AsyncConnection # noqa: PLC0415
127129
128130 execute_spy = mocker .spy (AsyncConnection , "execute" )
129131
132+ # Test with cache enabled (default behavior)
130133 # First call - should hit database
131134 start_time = time .time ()
132135 result1 = await get_current_identity (
@@ -148,8 +151,16 @@ async def test_cache_effectiveness_in_rest_authentication_dependencies(
148151 cached_db_calls = execute_spy .call_count
149152 execute_spy .reset_mock ()
150153
151- # Test with cache disabled
152- monkeypatch .setenv ("AIOCACHE_DISABLE" , "1" )
154+ # Verify cache was used
155+ api_key_cache_key = f"api_auth:{ api_key_in_db .api_key } "
156+ user_cache_key = f"user_email:{ api_key_in_db .user_id } "
157+
158+ assert await api_keys_cache .exists (api_key_cache_key ), "API key should be cached"
159+ assert await users_cache .exists (user_cache_key ), "User email should be cached"
160+
161+ # Test with cache disabled by clearing cache before each call
162+ await api_keys_cache .clear ()
163+ await users_cache .clear ()
153164
154165 # First call without cache
155166 start_time = time .time ()
@@ -160,6 +171,10 @@ async def test_cache_effectiveness_in_rest_authentication_dependencies(
160171 )
161172 no_cache_first_time = time .time () - start_time
162173
174+ # Clear cache again to simulate no caching
175+ await api_keys_cache .clear ()
176+ await users_cache .clear ()
177+
163178 # Second call without cache
164179 start_time = time .time ()
165180 result4 = await get_current_identity (
0 commit comments