Coverage for tests/test_computed_fields.py: 100%
34 statements
« prev ^ index » next coverage.py v7.6.1, created at 2025-01-13 13:38 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2025-01-13 13:38 +0000
1import pytest 1abcde
2from fastapi import FastAPI 1abcde
3from fastapi.testclient import TestClient 1abcde
5from .utils import needs_pydanticv2 1abcde
8@pytest.fixture(name="client") 1abcde
9def get_client(): 1abcde
10 app = FastAPI() 1abcde
12 from pydantic import BaseModel, computed_field 1abcde
14 class Rectangle(BaseModel): 1abcde
15 width: int 1abcde
16 length: int 1abcde
18 @computed_field 1abcde
19 @property 1abcde
20 def area(self) -> int: 1abcde
21 return self.width * self.length 1fghij
23 @app.get("/") 1abcde
24 def read_root() -> Rectangle: 1abcde
25 return Rectangle(width=3, length=4) 1fghij
27 @app.get("/responses", responses={200: {"model": Rectangle}}) 1abcde
28 def read_responses() -> Rectangle: 1abcde
29 return Rectangle(width=3, length=4) 1fghij
31 client = TestClient(app) 1abcde
32 return client 1abcde
35@pytest.mark.parametrize("path", ["/", "/responses"]) 1abcde
36@needs_pydanticv2 1abcde
37def test_get(client: TestClient, path: str): 1abcde
38 response = client.get(path) 1fghij
39 assert response.status_code == 200, response.text 1fghij
40 assert response.json() == {"width": 3, "length": 4, "area": 12} 1fghij
43@needs_pydanticv2 1abcde
44def test_openapi_schema(client: TestClient): 1abcde
45 response = client.get("/openapi.json") 1klmno
46 assert response.status_code == 200, response.text 1klmno
47 assert response.json() == { 1klmno
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 }