Coverage for tests / test_schema_compat_pydantic_v2.py: 100%

30 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-02-12 18:15 +0000

1import pytest 1abdc

2from fastapi import FastAPI 1abdc

3from fastapi.testclient import TestClient 1abdc

4from inline_snapshot import snapshot 1abdc

5from pydantic import BaseModel 1abdc

6 

7from tests.utils import needs_py310 1abdc

8 

9 

10@pytest.fixture(name="client") 1abdc

11def get_client(): 1abdc

12 from enum import Enum 1abc

13 

14 app = FastAPI() 1abc

15 

16 class PlatformRole(str, Enum): 1abc

17 admin = "admin" 1abc

18 user = "user" 1abc

19 

20 class OtherRole(str, Enum): ... 1abc

21 

22 class User(BaseModel): 1abc

23 username: str 1abc

24 role: PlatformRole | OtherRole 1abc

25 

26 @app.get("/users") 1abc

27 async def get_user() -> User: 1abc

28 return {"username": "alice", "role": "admin"} 1efg

29 

30 client = TestClient(app) 1abc

31 return client 1abc

32 

33 

34@needs_py310 1abdc

35def test_get(client: TestClient): 1abdc

36 response = client.get("/users") 1efg

37 assert response.json() == {"username": "alice", "role": "admin"} 1efg

38 

39 

40@needs_py310 1abdc

41def test_openapi_schema(client: TestClient): 1abdc

42 response = client.get("openapi.json") 1hij

43 assert response.json() == snapshot( 1hij

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 )