Clearing cache of aiocache from unit test

480 Views Asked by At

In FastAPI I have an endpoint:

from aiocache import Cache, cached

@router.get("/id/{user_id}/permissions")
@cached(ttl=30, cache=Cache.MEMORY)
async def get_permissions(user_id: UUID4) -> list[Permissions]:

And then in my unit test, I want to clear the cache.

I have tried recreating the cache with a namespace, key. Currently I have:

from my_module import get_permissions

my_cache = get_permissions.cache
await my_cache.clear()

I have tried every imaginable combination. But I cannot get this asynchronous test to clear my cache. Any ideas? What am I doing wrong? Could it be there are in different processes?

2

There are 2 best solutions below

1
Vinícius OA On

Well, I've done the same as you, since your question is in an async context, perhaps is your test setup? Here is a sample that works using the pytest and pytest_asyncio plugins.

# conftest.py

@pytest.fixture(scope="session")
def event_loop():
    policy = asyncio.get_event_loop_policy()
    loop = policy.new_event_loop()
    yield loop
    loop.close()

# test_something.py

@pytest.mark.asyncio
async def test_something():
    from my_module import get_permissions
    my_cache = get_permissions.cache
    await my_cache.clear()
    
    # rest of the test.
0
Pithikos On

Use a fixture like this

@pytest.fixture(autouse=True)
def clear_redis():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(redis_cache.clear())
    yield