Coverage for tests / test_schema_compat_pydantic_v2.py: 100%
30 statements
« prev ^ index » next coverage.py v7.13.3, created at 2026-04-06 01:24 +0000
« prev ^ index » next coverage.py v7.13.3, created at 2026-04-06 01:24 +0000
1import pytest 1ghij
2from fastapi import FastAPI 1ghij
3from fastapi.testclient import TestClient 1ghij
4from inline_snapshot import snapshot 1ghij
5from pydantic import BaseModel 1ghij
7from tests.utils import needs_py310 1ghij
10@pytest.fixture(name="client") 1ghij
11def get_client(): 1ghij
12 from enum import Enum 1abklcdef
14 app = FastAPI() 1abklcdef
16 class PlatformRole(str, Enum): 1abklcdef
17 admin = "admin" 1abklcdef
18 user = "user" 1abklcdef
20 class OtherRole(str, Enum): ... 1abklcdef
22 class User(BaseModel): 1abklcdef
23 username: str 1abcdef
24 role: PlatformRole | OtherRole 1abcdef
26 @app.get("/users") 1abklcdef
27 async def get_user() -> User: 1abklcdef
28 return {"username": "alice", "role": "admin"} 1mnop
30 client = TestClient(app) 1abklcdef
31 return client 1abklcdef
34@needs_py310 1ghij
35def test_get(client: TestClient): 1ghij
36 response = client.get("/users") 1mnop
37 assert response.json() == {"username": "alice", "role": "admin"} 1mnop
40@needs_py310 1ghij
41def test_openapi_schema(client: TestClient): 1ghij
42 response = client.get("openapi.json") 1qrst
43 assert response.json() == snapshot( 1qrst
44 {
45 "openapi": "3.1.0",
46 "info": {"title": "FastAPI", "version": "0.1.0"},
47 "paths": {
48 "/users": {
49 "get": {
50 "summary": "Get User",
51 "operationId": "get_user_users_get",
52 "responses": {
53 "200": {
54 "description": "Successful Response",
55 "content": {
56 "application/json": {
57 "schema": {"$ref": "#/components/schemas/User"}
58 }
59 },
60 }
61 },
62 }
63 }
64 },
65 "components": {
66 "schemas": {
67 "PlatformRole": {
68 "type": "string",
69 "enum": ["admin", "user"],
70 "title": "PlatformRole",
71 },
72 "User": {
73 "properties": {
74 "username": {"type": "string", "title": "Username"},
75 "role": {
76 "anyOf": [
77 {"$ref": "#/components/schemas/PlatformRole"},
78 {"enum": [], "title": "OtherRole"},
79 ],
80 "title": "Role",
81 },
82 },
83 "type": "object",
84 "required": ["username", "role"],
85 "title": "User",
86 },
87 }
88 },
89 }
90 )