Debian Codegraph @

tests/test_router_path_params.py

raw symbols SCIP
1 import pytest
2
3 from ninja import NinjaAPI, Path, Router
4 from ninja.testing import TestClient
5
6 api = NinjaAPI()
7 router_with_path_type = Router()
8 router_without_path_type = Router()
9 router_with_multiple = Router()
10
11
12 @router_with_path_type.get("/metadata")
13 def get_item_metadata(request, item_id: int = Path(None)) -> int:
14 return item_id
15
16
17 @router_without_path_type.get("/")
18 def get_item_metadata_2(request, item_id: str = Path(None)) -> str:
19 return item_id
20
21
22 @router_without_path_type.get("/metadata")
23 def get_item_metadata_3(request, item_id: str = Path(None)) -> str:
24 return item_id
25
26
27 @router_without_path_type.get("/")
28 def get_item_metadata_4(request, item_id: str = Path(None)) -> str:
29 return item_id
30
31
32 @router_with_multiple.get("/metadata/{kind}")
33 def get_item_metadata_5(
34 request, item_id: int = Path(None), name: str = Path(None), kind: str = Path(None)
35 ) -> str:
36 return f"{item_id} {name} {kind}"
37
38
39 api.add_router("/with_type/{int:item_id}", router_with_path_type)
40 api.add_router("/without_type/{item_id}", router_without_path_type)
41 api.add_router("/with_multiple/{int:item_id}/name/{name}", router_with_multiple)
42
43 client = TestClient(api)
44
45
46 @pytest.mark.parametrize(
47 "path,expected_status,expected_response",
48 [
49 ("/with_type/1/metadata", 200, 1),
50 ("/without_type/1/metadata", 200, "1"),
51 ("/without_type/abc/metadata", 200, "abc"),
52 ("/with_multiple/99/name/foo/metadata/timestamp", 200, "99 foo timestamp"),
53 ],
54 )
55 def test_router_with_path_params(path, expected_status, expected_response):
56 response = client.get(path)
57 assert response.status_code == expected_status
58 assert response.json() == expected_response
59
60
61 @pytest.mark.parametrize(
62 "path,expected_exception,expect_exception_contains",
63 [
64 ("/with_type/abc/metadata", Exception, "Cannot resolve"),
65 ("/with_type//metadata", Exception, "Cannot resolve"),
66 ("/with_type/null/metadata", Exception, "Cannot resolve"),
67 ("/with_type", Exception, "Cannot resolve"),
68 ("/with_type/", Exception, "Cannot resolve"),
69 ("/with_type//", Exception, "Cannot resolve"),
70 ("/with_type/null", Exception, "Cannot resolve"),
71 ("/with_type/null/", Exception, "Cannot resolve"),
72 ("/without_type", Exception, "Cannot resolve"),
73 ("/without_type/", Exception, "Cannot resolve"),
74 ("/without_type//", Exception, "Cannot resolve"),
75 ("/with_multiple/abc/name/foo/metadata/timestamp", Exception, "Cannot resolve"),
76 ("/with_multiple/99", Exception, "Cannot resolve"),
77 ],
78 )
79 def test_router_with_path_params_nomatch(
80 path, expected_exception, expect_exception_contains
81 ):
82 with pytest.raises(expected_exception, match=expect_exception_contains):
83 client.get(path)