Coverage for tests / test_additional_responses_response_class.py: 100%

22 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-02-12 18:15 +0000

1from fastapi import FastAPI 1abcd

2from fastapi.responses import JSONResponse 1abcd

3from fastapi.testclient import TestClient 1abcd

4from inline_snapshot import snapshot 1abcd

5from pydantic import BaseModel 1abcd

6 

7app = FastAPI() 1abcd

8 

9 

10class JsonApiResponse(JSONResponse): 1abcd

11 media_type = "application/vnd.api+json" 1abcd

12 

13 

14class Error(BaseModel): 1abcd

15 status: str 1abcd

16 title: str 1abcd

17 

18 

19class JsonApiError(BaseModel): 1abcd

20 errors: list[Error] 1abcd

21 

22 

23@app.get( 1abcd

24 "/a", 

25 response_class=JsonApiResponse, 

26 responses={500: {"description": "Error", "model": JsonApiError}}, 

27) 

28async def a(): 1abcd

29 pass # pragma: no cover 

30 

31 

32@app.get("/b", responses={500: {"description": "Error", "model": Error}}) 1abcd

33async def b(): 1abcd

34 pass # pragma: no cover 

35 

36 

37client = TestClient(app) 1abcd

38 

39 

40def test_openapi_schema(): 1abcd

41 response = client.get("/openapi.json") 1efg

42 assert response.status_code == 200, response.text 1efg

43 assert response.json() == snapshot( 1efg

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 )