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