Coverage for tests/test_get_request_body.py: 100%

20 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-08-08 03:53 +0000

1from fastapi import FastAPI 1abcde

2from fastapi.testclient import TestClient 1abcde

3from pydantic import BaseModel 1abcde

4 

5app = FastAPI() 1abcde

6 

7 

8class Product(BaseModel): 1abcde

9 name: str 1abcde

10 description: str = None # type: ignore 1abcde

11 price: float 1abcde

12 

13 

14@app.get("/product") 1abcde

15async def create_item(product: Product): 1abcde

16 return product 1abcde

17 

18 

19client = TestClient(app) 1abcde

20 

21 

22def test_get_with_body(): 1abcde

23 body = {"name": "Foo", "description": "Some description", "price": 5.5} 1abcde

24 response = client.request("GET", "/product", json=body) 1abcde

25 assert response.json() == body 1abcde

26 

27 

28def test_openapi_schema(): 1abcde

29 response = client.get("/openapi.json") 1abcde

30 assert response.status_code == 200, response.text 1abcde

31 assert response.json() == { 1abcde

32 "openapi": "3.1.0", 

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

34 "paths": { 

35 "/product": { 

36 "get": { 

37 "summary": "Create Item", 

38 "operationId": "create_item_product_get", 

39 "requestBody": { 

40 "content": { 

41 "application/json": { 

42 "schema": {"$ref": "#/components/schemas/Product"} 

43 } 

44 }, 

45 "required": True, 

46 }, 

47 "responses": { 

48 "200": { 

49 "description": "Successful Response", 

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

51 }, 

52 "422": { 

53 "description": "Validation Error", 

54 "content": { 

55 "application/json": { 

56 "schema": { 

57 "$ref": "#/components/schemas/HTTPValidationError" 

58 } 

59 } 

60 }, 

61 }, 

62 }, 

63 } 

64 } 

65 }, 

66 "components": { 

67 "schemas": { 

68 "HTTPValidationError": { 

69 "title": "HTTPValidationError", 

70 "type": "object", 

71 "properties": { 

72 "detail": { 

73 "title": "Detail", 

74 "type": "array", 

75 "items": {"$ref": "#/components/schemas/ValidationError"}, 

76 } 

77 }, 

78 }, 

79 "Product": { 

80 "title": "Product", 

81 "required": ["name", "price"], 

82 "type": "object", 

83 "properties": { 

84 "name": {"title": "Name", "type": "string"}, 

85 "description": {"title": "Description", "type": "string"}, 

86 "price": {"title": "Price", "type": "number"}, 

87 }, 

88 }, 

89 "ValidationError": { 

90 "title": "ValidationError", 

91 "required": ["loc", "msg", "type"], 

92 "type": "object", 

93 "properties": { 

94 "loc": { 

95 "title": "Location", 

96 "type": "array", 

97 "items": { 

98 "anyOf": [{"type": "string"}, {"type": "integer"}] 

99 }, 

100 }, 

101 "msg": {"title": "Message", "type": "string"}, 

102 "type": {"title": "Error Type", "type": "string"}, 

103 }, 

104 }, 

105 } 

106 }, 

107 }