Skip to content

Commit

Permalink
Fix routing with multiple routes contain 'path' params (#49)
Browse files Browse the repository at this point in the history
  • Loading branch information
wochinge authored Nov 4, 2021
1 parent 0c6c860 commit 4df3d82
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
4 changes: 3 additions & 1 deletion sanic_routing/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -423,10 +423,11 @@ def _render(
"regex_routes" if group.regex else "dynamic_routes"
)
route_idx: t.Union[str, int] = 0
holder: t.List[Line] = []

if len(group.routes) > 1:
route_idx = "route_idx"
Node._inject_method_check(src, 1, group)
Node._inject_method_check(holder, 2, group)

src.extend(
[
Expand All @@ -438,6 +439,7 @@ def _render(
1,
),
Line("if match:", 1),
*holder,
Line("basket['__params__'] = match.groupdict()", 2),
Line(
(
Expand Down
31 changes: 31 additions & 0 deletions tests/test_routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -482,3 +482,34 @@ def handler2():
_, handler, params = router.get(f"/api/3/hello_world/{uri}", "GET")
assert handler() == "handler2"
assert params == {"version": "3", "foo": uri}


@pytest.mark.parametrize("uri", ("a-random-path", "a/random/path"))
def test_identical_path_routes_with_different_methods_similar_urls(uri):
def handler1():
return "handler1"

def handler2():
return "handler2"

def handler3():
return "handler3"

# test root level path with different methods
router = Router()
router.add("/constant/<foo:path>/story", handler1, methods=["GET", "OPTIONS"])
router.add("/constant/<foo:path>/tracker/events", handler2, methods=["PUT"])
router.add("/constant/<foo:path>/tracker/events", handler3, methods=["POST"])
router.finalize()

route, handler, params = router.get(f"/constant/{uri}/story", "GET")
assert params == {"foo": f"{uri}"}
assert handler() == "handler1"

_, handler, params = router.get(f"/constant/{uri}/tracker/events", "PUT")
assert params == {"foo": f"{uri}"}
assert handler() == "handler2"

_, handler, params = router.get(f"/constant/{uri}/tracker/events", "POST")
assert params == {"foo": f"{uri}"}
assert handler() == "handler3"

0 comments on commit 4df3d82

Please sign in to comment.