Being very new to FastAPI I am strugling to test slightly more difficult code than I saw in the tutorial. I use fastapi_cache
module and Redis like this:
from fastapi import Depends, FastAPI, Query, Request
from fastapi_cache.backends.redis import CACHE_KEY, RedisCacheBackend
from fastapi_cache import caches, close_caches
app = FastAPI()
def redis_cache():
return caches.get(CACHE_KEY)
@app.get('/cache')
async def test(
cache: RedisCacheBackend = Depends(redis_cache),
n: int = Query(
...,
gt=-1
)
):
# code that uses redis cache
@app.on_event('startup')
async def on_startup() -> None:
rc = RedisCacheBackend('redis://redis')
caches.set(CACHE_KEY, rc)
@app.on_event('shutdown')
async def on_shutdown() -> None:
await close_caches()
test_main.py looks like this:
import pytest
from httpx import AsyncClient
from .main import app
@pytest.mark.asyncio
async def test_cache():
async with AsyncClient(app=app, base_url="http://test") as ac:
response = await ac.get("/cache?n=150")
When I run pytest
, it sets cache
variable to None
and test fails. I think I understand why the code is not working. But how do I fix it to test my caching properly?
2
Answers
The point is that
httpx
does not implement lifespan protocol and triggerstartup
event handlers. For this, you need to useLifespanManager
.Install:
pip install asgi_lifespan
The code would be like so:
More info here: https://github.com/encode/httpx/issues/350
In case if you don’t want to add dependency just for a tests, here is the simple implementation for
asyncio
:I use it like this: