Coverage for tests / test_response_code_no_body.py: 100%

28 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-04-06 01:24 +0000

1from fastapi import FastAPI 1adbc

2from fastapi.responses import JSONResponse 1adbc

3from fastapi.testclient import TestClient 1adbc

4from inline_snapshot import snapshot 1adbc

5from pydantic import BaseModel 1adbc

6 

7app = FastAPI() 1adbc

8 

9 

10class JsonApiResponse(JSONResponse): 1adbc

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

12 

13 

14class Error(BaseModel): 1adbc

15 status: str 1abc

16 title: str 1abc

17 

18 

19class JsonApiError(BaseModel): 1adbc

20 errors: list[Error] 1abc

21 

22 

23@app.get( 1adbc

24 "/a", 

25 status_code=204, 

26 response_class=JsonApiResponse, 

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

28) 

29async def a(): 1adbc

30 pass 1efgh

31 

32 

33@app.get("/b", responses={204: {"description": "No Content"}}) 1adbc

34async def b(): 1adbc

35 pass # pragma: no cover 

36 

37 

38client = TestClient(app) 1adbc

39 

40 

41def test_get_response(): 1adbc

42 response = client.get("/a") 1efgh

43 assert response.status_code == 204, response.text 1efgh

44 assert "content-length" not in response.headers 1efgh

45 assert response.content == b"" 1efgh

46 

47 

48def test_openapi_schema(): 1adbc

49 response = client.get("/openapi.json") 1ijkl

50 assert response.status_code == 200, response.text 1ijkl

51 assert response.json() == snapshot( 1ijkl

52 { 

53 "openapi": "3.1.0", 

54 "info": {"title": "FastAPI", "version": "0.1.0"}, 

55 "paths": { 

56 "/a": { 

57 "get": { 

58 "responses": { 

59 "500": { 

60 "description": "Error", 

61 "content": { 

62 "application/vnd.api+json": { 

63 "schema": { 

64 "$ref": "#/components/schemas/JsonApiError" 

65 } 

66 } 

67 }, 

68 }, 

69 "204": {"description": "Successful Response"}, 

70 }, 

71 "summary": "A", 

72 "operationId": "a_a_get", 

73 } 

74 }, 

75 "/b": { 

76 "get": { 

77 "responses": { 

78 "204": {"description": "No Content"}, 

79 "200": { 

80 "description": "Successful Response", 

81 "content": {"application/json": {"schema": {}}}, 

82 }, 

83 }, 

84 "summary": "B", 

85 "operationId": "b_b_get", 

86 } 

87 }, 

88 }, 

89 "components": { 

90 "schemas": { 

91 "Error": { 

92 "title": "Error", 

93 "required": ["status", "title"], 

94 "type": "object", 

95 "properties": { 

96 "status": {"title": "Status", "type": "string"}, 

97 "title": {"title": "Title", "type": "string"}, 

98 }, 

99 }, 

100 "JsonApiError": { 

101 "title": "JsonApiError", 

102 "required": ["errors"], 

103 "type": "object", 

104 "properties": { 

105 "errors": { 

106 "title": "Errors", 

107 "type": "array", 

108 "items": {"$ref": "#/components/schemas/Error"}, 

109 } 

110 }, 

111 }, 

112 } 

113 }, 

114 } 

115 )