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