Я получаю сообщение об ошибке. Объект «Состояние» не имеет атрибута «реализация» с тестовым кодом FastAPI.
Вот весь соответствующий код. Вы можете скопировать и вставить содержимое каждого из этих файлов, чтобы запустить MWE.
# tests/example_test.py
import pytest
from httpx import AsyncClient
from webserver import app
@pytest.mark.anyio
async def test_get_value():
async with AsyncClient(app=app) as client:
response = await client.get('/api/get_value')
assert response.status_code == 200
assert response.json() == {
'value': 0,
}
# webserver.py
from fastapi import FastAPI
from fastapi import Request
from httpx import AsyncClient
from contextlib import asynccontextmanager
from implementation import Implementation
@asynccontextmanager
async def lifespan(app: FastAPI):
async with AsyncClient(app=app) as client:
implementation = Implementation()
yield {'implementation': implementation}
implementation.shutdown()
app = FastAPI(lifespan=lifespan)
@app.post('/api/increment')
async def api_increment(
request: Request,
):
implementation: Implementation = request.state.implementation
implementation.increment()
return {}
@app.get('/api/get_value')
async def api_get_value(
request: Request,
):
implementation: Implementation = request.state.implementation
value = implementation.get_value()
return {
'value': value,
}
# implementation.py
class Implementation():
def __init__(self) -> None:
self.current_value = 0
self._initialized = True
print(f'Implementation starts')
def shutdown(self) -> None:
'''
A function which must be called to cleanup resources before exit
'''
self._initialized = False
print(f'Implementation stops')
def increment(self) -> None:
'''
In reality this would do something like read/write to a file, db etc
'''
self.current_value += 1
def get_value(self) -> None:
return self.current_value
К вашему сведению: этот синхронный тест работает:
from fastapi.testclient import TestClient
def test_get_value_synchronous():
with TestClient(app) as client:
response = client.get('/api/get_value')
assert response.status_code == 200
assert response.json() == {
'value': 0,
}
Подробнее здесь: https://stackoverflow.com/questions/787 ... ementation