| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from typing import TYPE_CHECKING, Annotated |
| 4 |
|
| 5 |
import pytest |
| 6 |
from fastapi import Depends, FastAPI |
| 7 |
from fastapi.testclient import TestClient |
| 8 |
from inline_snapshot import snapshot |
| 9 |
|
| 10 |
if TYPE_CHECKING: # pragma: no cover |
| 11 |
from collections.abc import AsyncGenerator |
| 12 |
|
| 13 |
|
| 14 |
class DummyClient: |
| 15 |
async def get_people(self) -> list: |
| 16 |
return ["John Doe", "Jane Doe"] |
| 17 |
|
| 18 |
async def close(self) -> None: |
| 19 |
pass |
| 20 |
|
| 21 |
|
| 22 |
async def get_client() -> AsyncGenerator[DummyClient, None]: |
| 23 |
client = DummyClient() |
| 24 |
yield client |
| 25 |
await client.close() |
| 26 |
|
| 27 |
|
| 28 |
Client = Annotated[DummyClient, Depends(get_client)] |
| 29 |
|
| 30 |
|
| 31 |
@pytest.fixture(name="client") |
| 32 |
def client_fixture() -> TestClient: |
| 33 |
app = FastAPI() |
| 34 |
|
| 35 |
@app.get("/") |
| 36 |
async def get_people(client: Client) -> list: |
| 37 |
return await client.get_people() |
| 38 |
|
| 39 |
client = TestClient(app) |
| 40 |
return client |
| 41 |
|
| 42 |
|
| 43 |
def test_get(client: TestClient): |
| 44 |
response = client.get("/") |
| 45 |
assert response.status_code == 200, response.text |
| 46 |
assert response.json() == ["John Doe", "Jane Doe"] |
| 47 |
|
| 48 |
|
| 49 |
def test_openapi_schema(client: TestClient): |
| 50 |
response = client.get("/openapi.json") |
| 51 |
assert response.status_code == 200, response.text |
| 52 |
assert response.json() == snapshot( |
| 53 |
{ |
| 54 |
"openapi": "3.1.0", |
| 55 |
"info": {"title": "FastAPI", "version": "0.1.0"}, |
| 56 |
"paths": { |
| 57 |
"/": { |
| 58 |
"get": { |
| 59 |
"summary": "Get People", |
| 60 |
"operationId": "get_people__get", |
| 61 |
"responses": { |
| 62 |
"200": { |
| 63 |
"description": "Successful Response", |
| 64 |
"content": { |
| 65 |
"application/json": { |
| 66 |
"schema": { |
| 67 |
"items": {}, |
| 68 |
"type": "array", |
| 69 |
"title": "Response Get People Get", |
| 70 |
} |
| 71 |
} |
| 72 |
}, |
| 73 |
} |
| 74 |
}, |
| 75 |
} |
| 76 |
} |
| 77 |
}, |
| 78 |
} |
| 79 |
) |