Coverage for tests/test_computed_fields.py: 100%
34 statements
« prev ^ index » next coverage.py v7.6.1, created at 2025-05-05 00:03 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2025-05-05 00:03 +0000
1import pytest 1abcdef
2from fastapi import FastAPI 1abcdef
3from fastapi.testclient import TestClient 1abcdef
5from .utils import needs_pydanticv2 1abcdef
8@pytest.fixture(name="client") 1abcdef
9def get_client(): 1abcdef
10 app = FastAPI() 1abcdef
12 from pydantic import BaseModel, computed_field 1abcdef
14 class Rectangle(BaseModel): 1abcdef
15 width: int 1abcdef
16 length: int 1abcdef
18 @computed_field 1abcdef
19 @property 1abcdef
20 def area(self) -> int: 1abcdef
21 return self.width * self.length 1ghijkl
23 @app.get("/") 1abcdef
24 def read_root() -> Rectangle: 1abcdef
25 return Rectangle(width=3, length=4) 1ghijkl
27 @app.get("/responses", responses={200: {"model": Rectangle}}) 1abcdef
28 def read_responses() -> Rectangle: 1abcdef
29 return Rectangle(width=3, length=4) 1ghijkl
31 client = TestClient(app) 1abcdef
32 return client 1abcdef
35@pytest.mark.parametrize("path", ["/", "/responses"]) 1abcdef
36@needs_pydanticv2 1abcdef
37def test_get(client: TestClient, path: str): 1abcdef
38 response = client.get(path) 1ghijkl
39 assert response.status_code == 200, response.text 1ghijkl
40 assert response.json() == {"width": 3, "length": 4, "area": 12} 1ghijkl
43@needs_pydanticv2 1abcdef
44def test_openapi_schema(client: TestClient): 1abcdef
45 response = client.get("/openapi.json") 1mnopqr
46 assert response.status_code == 200, response.text 1mnopqr
47 assert response.json() == { 1mnopqr
48 "openapi": "3.1.0",
49 "info": {"title": "FastAPI", "version": "0.1.0"},
50 "paths": {
51 "/": {
52 "get": {
53 "summary": "Read Root",
54 "operationId": "read_root__get",
55 "responses": {
56 "200": {
57 "description": "Successful Response",
58 "content": {
59 "application/json": {
60 "schema": {"$ref": "#/components/schemas/Rectangle"}
61 }
62 },
63 }
64 },
65 }
66 },
67 "/responses": {
68 "get": {
69 "summary": "Read Responses",
70 "operationId": "read_responses_responses_get",
71 "responses": {
72 "200": {
73 "description": "Successful Response",
74 "content": {
75 "application/json": {
76 "schema": {"$ref": "#/components/schemas/Rectangle"}
77 }
78 },
79 }
80 },
81 }
82 },
83 },
84 "components": {
85 "schemas": {
86 "Rectangle": {
87 "properties": {
88 "width": {"type": "integer", "title": "Width"},
89 "length": {"type": "integer", "title": "Length"},
90 "area": {"type": "integer", "title": "Area", "readOnly": True},
91 },
92 "type": "object",
93 "required": ["width", "length", "area"],
94 "title": "Rectangle",
95 }
96 }
97 },
98 }