简体   繁体   English

测试 FastAPI 应用程序时如何触发生命周期启动和关闭?

[英]How to trigger lifespan startup and shutdown while testing FastAPI app?

Being very new to FastAPI I am strugling to test slightly more difficult code than I saw in the tutorial.作为 FastAPI 的新手,我正在努力测试比我在教程中看到的稍微困难的代码。 I use fastapi_cache module and Redis like this:我像这样使用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_main.py looks like this: test_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")

When I run pytest , it sets cache variable to None and test fails.当我运行pytest时,它将cache变量设置为None并且测试失败。 I think I understand why the code is not working.我想我明白为什么代码不起作用。 But how do I fix it to test my caching properly?但是如何修复它以正确测试我的缓存?

The point is that httpx does not implement lifespan protocol and trigger startup event handlers.关键是httpx没有实现生命周期协议并触发startup事件处理程序。 For this, you need to use LifespanManager .为此,您需要使用LifespanManager

Install: pip install asgi_lifespan安装: pip install asgi_lifespan

The code would be like so:代码将是这样的:

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

More info here: https://github.com/encode/httpx/issues/350更多信息在这里: https://github.com/encode/httpx/issues/350

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM