forked from fastapiutils/fastapi-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_cbv_base.py
More file actions
88 lines (62 loc) · 2.25 KB
/
test_cbv_base.py
File metadata and controls
88 lines (62 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
from typing import Any, Dict, List, Optional, Union
from fastapi import FastAPI
from fastapi.responses import PlainTextResponse
from starlette.testclient import TestClient
from fastapi_utils.cbv_base import Api, Resource, set_responses
def test_cbv() -> None:
class CBV(Resource):
def __init__(self, z: int = 1):
super().__init__()
self.y = 1
self.z = z
@set_responses(int)
def post(self, x: int) -> int:
print(x)
return x + self.y + self.z
@set_responses(bool)
def get(self) -> bool:
return hasattr(self, "cy")
app = FastAPI()
api = Api(app)
cbv = CBV(2)
api.add_resource(cbv, "/", "/classvar")
client = TestClient(app)
response_1 = client.post("/", params={"x": 1}, json={})
assert response_1.status_code == 200
assert response_1.content == b"4"
response_2 = client.get("/classvar")
assert response_2.status_code == 200
assert response_2.content == b"false"
def test_arg_in_path() -> None:
class TestCBV(Resource):
@set_responses(str)
def get(self, item_id: str) -> str:
return item_id
app = FastAPI()
api = Api(app)
test_cbv_resource = TestCBV()
api.add_resource(test_cbv_resource, "/{item_id}")
assert TestClient(app).get("/test").json() == "test"
def test_multiple_routes() -> None:
class RootHandler(Resource):
def get(self, item_path: Optional[str] = None) -> Union[List[Any], Dict[str, str]]:
if item_path:
return {"item_path": item_path}
return []
app = FastAPI()
api = Api(app)
root_handler_resource = RootHandler()
api.add_resource(root_handler_resource, "/items/?", "/items/{item_path:path}")
client = TestClient(app)
assert client.get("/items/1").json() == {"item_path": "1"}
assert client.get("/items").json() == []
def test_different_response_model() -> None:
class RootHandler(Resource):
@set_responses({}, response_class=PlainTextResponse)
def get(self) -> str:
return "Done!"
app = FastAPI()
api = Api(app)
api.add_resource(RootHandler(), "/check")
client = TestClient(app)
assert client.get("/check").text == "Done!"