Debian Codegraph @

tests/test_additional_responses_response_class.py

raw
1 from fastapi import FastAPI
2 from fastapi.responses import JSONResponse
3 from fastapi.testclient import TestClient
4 from inline_snapshot import snapshot
5 from pydantic import BaseModel
6
7 app = FastAPI()
8
9
10 class JsonApiResponse(JSONResponse):
11 media_type = "application/vnd.api+json"
12
13
14 class Error(BaseModel):
15 status: str
16 title: str
17
18
19 class JsonApiError(BaseModel):
20 errors: list[Error]
21
22
23 @app.get(
24 "/a",
25 response_class=JsonApiResponse,
26 responses={500: {"description": "Error", "model": JsonApiError}},
27 )
28 async def a():
29 pass # pragma: no cover
30
31
32 @app.get("/b", responses={500: {"description": "Error", "model": Error}})
33 async def b():
34 pass # pragma: no cover
35
36
37 client = TestClient(app)
38
39
40 def test_openapi_schema():
41 response = client.get("/openapi.json")
42 assert response.status_code == 200, response.text
43 assert response.json() == snapshot(
44 {
45 "openapi": "3.1.0",
46 "info": {"title": "FastAPI", "version": "0.1.0"},
47 "paths": {
48 "/a": {
49 "get": {
50 "responses": {
51 "500": {
52 "description": "Error",
53 "content": {
54 "application/vnd.api+json": {
55 "schema": {
56 "$ref": "#/components/schemas/JsonApiError"
57 }
58 }
59 },
60 },
61 "200": {
62 "description": "Successful Response",
63 "content": {"application/vnd.api+json": {"schema": {}}},
64 },
65 },
66 "summary": "A",
67 "operationId": "a_a_get",
68 }
69 },
70 "/b": {
71 "get": {
72 "responses": {
73 "500": {
74 "description": "Error",
75 "content": {
76 "application/json": {
77 "schema": {"$ref": "#/components/schemas/Error"}
78 }
79 },
80 },
81 "200": {
82 "description": "Successful Response",
83 "content": {"application/json": {"schema": {}}},
84 },
85 },
86 "summary": "B",
87 "operationId": "b_b_get",
88 }
89 },
90 },
91 "components": {
92 "schemas": {
93 "Error": {
94 "title": "Error",
95 "required": ["status", "title"],
96 "type": "object",
97 "properties": {
98 "status": {"title": "Status", "type": "string"},
99 "title": {"title": "Title", "type": "string"},
100 },
101 },
102 "JsonApiError": {
103 "title": "JsonApiError",
104 "required": ["errors"],
105 "type": "object",
106 "properties": {
107 "errors": {
108 "title": "Errors",
109 "type": "array",
110 "items": {"$ref": "#/components/schemas/Error"},
111 }
112 },
113 },
114 }
115 },
116 }
117 )