簡體   English   中英

測試 FastAPI 應用程序時如何觸發生命周期啟動和關閉?

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

作為 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_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並且測試失敗。 我想我明白為什么代碼不起作用。 但是如何修復它以正確測試我的緩存?

關鍵是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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM