Coverage for tests/test_computed_fields.py: 100%
30 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-08-08 03:53 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2024-08-08 03:53 +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 1abcde
23 @app.get("/") 1abcde
24 def read_root() -> Rectangle: 1abcde
25 return Rectangle(width=3, length=4) 1abcde
27 client = TestClient(app) 1abcde
28 return client 1abcde
31@needs_pydanticv2 1abcde
32def test_get(client: TestClient): 1abcde
33 response = client.get("/") 1abcde
34 assert response.status_code == 200, response.text 1abcde
35 assert response.json() == {"width": 3, "length": 4, "area": 12} 1abcde
38@needs_pydanticv2 1abcde
39def test_openapi_schema(client: TestClient): 1abcde
40 response = client.get("/openapi.json") 1abcde
41 assert response.status_code == 200, response.text 1abcde
42 assert response.json() == { 1abcde
43 "openapi": "3.1.0",
44 "info": {"title": "FastAPI", "version": "0.1.0"},
45 "paths": {
46 "/": {
47 "get": {
48 "summary": "Read Root",
49 "operationId": "read_root__get",
50 "responses": {
51 "200": {
52 "description": "Successful Response",
53 "content": {
54 "application/json": {
55 "schema": {"$ref": "#/components/schemas/Rectangle"}
56 }
57 },
58 }
59 },
60 }
61 }
62 },
63 "components": {
64 "schemas": {
65 "Rectangle": {
66 "properties": {
67 "width": {"type": "integer", "title": "Width"},
68 "length": {"type": "integer", "title": "Length"},
69 "area": {"type": "integer", "title": "Area", "readOnly": True},
70 },
71 "type": "object",
72 "required": ["width", "length", "area"],
73 "title": "Rectangle",
74 }
75 }
76 },
77 }