如何在测试fastapi应用程序时触发寿命启动和关闭?

blpfk2vs  于 2021-06-09  发布在  Redis
关注(0)|答案(1)|浏览(626)

由于对fastapi非常陌生,我正在努力测试比我在教程中看到的稍微困难一些的代码。我用 fastapi_cache 模块和redis如下:

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\u main.py如下所示:

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")

当我跑的时候 pytest ,设置 cache 变量到 None 测试失败。我想我明白为什么代码不起作用了。但是如何修复它以正确测试缓存呢?

1hdlvixo

1hdlvixo1#

关键是 httpx 不实现寿命协议和触发器 startup 事件处理程序。为此,您需要使用 LifespanManager .
安装: pip install asgi_lifespan 代码如下:

import pytest
from asgi_lifespan import LifespanManager
from httpx import AsyncClient
from .main import app

@pytest.mark.asyncio
async def test_cache():
    async with LifespanManager(app):
        async with AsyncClient(app=app, base_url="http://localhost") as ac:
            response = await ac.get("/cache")

更多信息请点击此处:https://github.com/encode/httpx/issues/350

相关问题