diff --git a/tests/test_schema_ref_pydantic_v2.py b/tests/test_schema_ref_pydantic_v2.py new file mode 100644 index 000000000..443744e27 --- /dev/null +++ b/tests/test_schema_ref_pydantic_v2.py @@ -0,0 +1,72 @@ +import sys + +from fastapi import FastAPI +from fastapi.testclient import TestClient +from inline_snapshot import snapshot + +from tests.utils import skip_module_if_py_gte_314 + +if sys.version_info >= (3, 14): + skip_module_if_py_gte_314() + +from pydantic import BaseModel, ConfigDict, Field + +app = FastAPI() + + +class ModelWithRef(BaseModel): + ref: str = Field(validation_alias="$ref", serialization_alias="$ref") + model_config = ConfigDict(validate_by_alias=True, serialize_by_alias=True) + + +@app.get("/") +async def read_root() -> ModelWithRef: + return ModelWithRef(ref="some-ref") + + +client = TestClient(app) + + +def test_get(): + response = client.get("/") + assert response.json() == {"$ref": "some-ref"} + + +def test_openapi_schema(): + response = client.get("openapi.json") + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/": { + "get": { + "summary": "Read Root", + "operationId": "read_root__get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ModelWithRef" + } + } + }, + } + }, + } + } + }, + "components": { + "schemas": { + "ModelWithRef": { + "properties": {"$ref": {"type": "string", "title": "$Ref"}}, + "type": "object", + "required": ["$ref"], + "title": "ModelWithRef", + } + } + }, + } + )