Coverage for tests/test_schema_ref_pydantic_v2.py: 100%

26 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-12-04 08:29 +0000

1from typing import Any 1abcdefg

2 

3import pytest 1abcdefg

4from fastapi import FastAPI 1abcdefg

5from fastapi.testclient import TestClient 1abcdefg

6from inline_snapshot import snapshot 1abcdefg

7from pydantic import BaseModel, ConfigDict, Field 1abcdefg

8 

9from tests.utils import needs_pydanticv2 1abcdefg

10 

11 

12@pytest.fixture(name="client") 1abcdefg

13def get_client(): 1abcdefg

14 app = FastAPI() 1abcdefg

15 

16 class ModelWithRef(BaseModel): 1abcdefg

17 ref: str = Field(validation_alias="$ref", serialization_alias="$ref") 1abcdefg

18 model_config = ConfigDict(validate_by_alias=True, serialize_by_alias=True) 1abcdefg

19 

20 @app.get("/", response_model=ModelWithRef) 1abcdefg

21 async def read_root() -> Any: 1abcdefg

22 return {"$ref": "some-ref"} 1hijklmn

23 

24 client = TestClient(app) 1abcdefg

25 return client 1abcdefg

26 

27 

28@needs_pydanticv2 1abcdefg

29def test_get(client: TestClient): 1abcdefg

30 response = client.get("/") 1hijklmn

31 assert response.json() == {"$ref": "some-ref"} 1hijklmn

32 

33 

34@needs_pydanticv2 1abcdefg

35def test_openapi_schema(client: TestClient): 1abcdefg

36 response = client.get("openapi.json") 1opqrstu

37 assert response.json() == snapshot( 1opqrstu

38 { 

39 "openapi": "3.1.0", 

40 "info": {"title": "FastAPI", "version": "0.1.0"}, 

41 "paths": { 

42 "/": { 

43 "get": { 

44 "summary": "Read Root", 

45 "operationId": "read_root__get", 

46 "responses": { 

47 "200": { 

48 "description": "Successful Response", 

49 "content": { 

50 "application/json": { 

51 "schema": { 

52 "$ref": "#/components/schemas/ModelWithRef" 

53 } 

54 } 

55 }, 

56 } 

57 }, 

58 } 

59 } 

60 }, 

61 "components": { 

62 "schemas": { 

63 "ModelWithRef": { 

64 "properties": {"$ref": {"type": "string", "title": "$Ref"}}, 

65 "type": "object", 

66 "required": ["$ref"], 

67 "title": "ModelWithRef", 

68 } 

69 } 

70 }, 

71 } 

72 )