| 1 |
from typing import Any |
| 2 |
|
| 3 |
import pytest |
| 4 |
from fastapi import FastAPI |
| 5 |
from fastapi.testclient import TestClient |
| 6 |
from inline_snapshot import snapshot |
| 7 |
from pydantic import BaseModel, ConfigDict, Field |
| 8 |
|
| 9 |
|
| 10 |
@pytest.fixture(name="client") |
| 11 |
def get_client(): |
| 12 |
app = FastAPI() |
| 13 |
|
| 14 |
class ModelWithRef(BaseModel): |
| 15 |
ref: str = Field(validation_alias="$ref", serialization_alias="$ref") |
| 16 |
model_config = ConfigDict(validate_by_alias=True, serialize_by_alias=True) |
| 17 |
|
| 18 |
@app.get("/", response_model=ModelWithRef) |
| 19 |
async def read_root() -> Any: |
| 20 |
return {"$ref": "some-ref"} |
| 21 |
|
| 22 |
client = TestClient(app) |
| 23 |
return client |
| 24 |
|
| 25 |
|
| 26 |
def test_get(client: TestClient): |
| 27 |
response = client.get("/") |
| 28 |
assert response.json() == {"$ref": "some-ref"} |
| 29 |
|
| 30 |
|
| 31 |
def test_openapi_schema(client: TestClient): |
| 32 |
response = client.get("openapi.json") |
| 33 |
assert response.json() == snapshot( |
| 34 |
{ |
| 35 |
"openapi": "3.1.0", |
| 36 |
"info": {"title": "FastAPI", "version": "0.1.0"}, |
| 37 |
"paths": { |
| 38 |
"/": { |
| 39 |
"get": { |
| 40 |
"summary": "Read Root", |
| 41 |
"operationId": "read_root__get", |
| 42 |
"responses": { |
| 43 |
"200": { |
| 44 |
"description": "Successful Response", |
| 45 |
"content": { |
| 46 |
"application/json": { |
| 47 |
"schema": { |
| 48 |
"$ref": "#/components/schemas/ModelWithRef" |
| 49 |
} |
| 50 |
} |
| 51 |
}, |
| 52 |
} |
| 53 |
}, |
| 54 |
} |
| 55 |
} |
| 56 |
}, |
| 57 |
"components": { |
| 58 |
"schemas": { |
| 59 |
"ModelWithRef": { |
| 60 |
"properties": {"$ref": {"type": "string", "title": "$Ref"}}, |
| 61 |
"type": "object", |
| 62 |
"required": ["$ref"], |
| 63 |
"title": "ModelWithRef", |
| 64 |
} |
| 65 |
} |
| 66 |
}, |
| 67 |
} |
| 68 |
) |