Skip to content

Commit

Permalink
fix MatchResult type
Browse files Browse the repository at this point in the history
  • Loading branch information
aodag committed Jan 28, 2018
1 parent dfd3c42 commit a732e07
Show file tree
Hide file tree
Showing 5 changed files with 43 additions and 32 deletions.
4 changes: 1 addition & 3 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,7 @@ def _read(name):
long_description=readme + "\n" + changes,
test_suite="webdispatch",
license="MIT",
install_requires=[
"mypy_extensions",
],
install_requires=[],
tests_require=tests_require,
extras_require={
"testing": tests_require,
Expand Down
20 changes: 10 additions & 10 deletions webdispatch/tests/test_uritemplate.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,17 +127,17 @@ def test_match_empty(self):

result = target.match(path)

compare(result["matchdict"], dict())
compare(result["matchlength"], 0)
compare(result.matchdict, dict())
compare(result.matchlength, 0)

def test_wildcard(self):
""" test matching pattern including wildcard"""
path = "hoge/{var1}/*"
target = self._make_one(path)
result = target.match("hoge/egg/bacon")

compare(result["matchdict"], dict(var1="egg"))
compare(result["matchlength"], 9)
compare(result.matchdict, dict(var1="egg"))
compare(result.matchlength, 9)

def test_match_no_match(self):
""" test no mathing"""
Expand All @@ -153,32 +153,32 @@ def test_match_match_one(self):
target = self._make_one(path)
result = target.match("a")

compare(result["matchdict"], dict(var1="a"))
compare(result["matchlength"], 1)
compare(result.matchdict, dict(var1="a"))
compare(result.matchlength, 1)

def test_match_match_complex_word(self):
""" test matching a string"""
path = "{var1}"
target = self._make_one(path)
result = target.match("abc")

compare(result["matchdict"], dict(var1="abc"))
compare(result.matchdict, dict(var1="abc"))

def test_match_match_many(self):
""" test matching pattern including two vars """
path = "{var1}/users/{var2}"
target = self._make_one(path)
result = target.match("a/users/egg")

compare(result["matchdict"], dict(var1="a", var2="egg"))
compare(result.matchdict, dict(var1="a", var2="egg"))

def test_match_conveter(self):
""" test matching pattern including specified converter """
path = "{var1:int}/users/{var2}"
target = self._make_one(path)
result = target.match("1/users/egg")

compare(result["matchdict"], dict(var1=1, var2="egg"))
compare(result.matchdict, dict(var1=1, var2="egg"))

def test_match_conveter_error(self):
""" test matching pattern including specified converter """
Expand All @@ -198,7 +198,7 @@ def test_match_custom_conveter(self):
target = self._make_one(path, converters=converters)
result = target.match("1/users/20140420")

compare(result["matchdict"],
compare(result.matchdict,
dict(var1="1", var2=datetime(2014, 4, 20)))

def test_substitue(self):
Expand Down
8 changes: 5 additions & 3 deletions webdispatch/tests/test_urldispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,14 @@ def test_lookup_none(self):

def test_lookup(self):
""" test looking up basic usage """
from webdispatch.uritemplate import MatchResult
target = self._make_one()
target.add('testing-route', 'a')
result = target.lookup('a')
compare(result, {'name': 'testing-route',
'matchdict': {},
'matchlength': 1})
compare(result, C(MatchResult,
name='testing-route',
matchdict={},
matchlength=1))

def test_generate(self):
""" test generating url """
Expand Down
26 changes: 19 additions & 7 deletions webdispatch/uritemplate.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
Callable,
Tuple,
)
from mypy_extensions import TypedDict

VARS_PT = re.compile(r"{(?P<varname>[a-zA-Z0-9_]+)"
r"(:(?P<converter>[a-zA-Z0-9_]+))?}",
Expand Down Expand Up @@ -84,9 +83,22 @@ class URITemplateFormatException(Exception):
""" raised when uri template format error duaring"""


MATCH_RESULT_TYPE = TypedDict(
"MATCH_RESULT_TYPE",
{"matchdict": Dict[str, Any], "matchlength": int})
class MatchResult:
""" result of parsing url """
def __init__(self, matchdict: Dict[str, Any], matchlength: int) -> None:
self.name = None # type: str
self.matchdict = matchdict
self.matchlength = matchlength

def new_named_args(self, cur_named_args: Dict[str, Any]) -> Dict[str, Any]:
""" create new named args updating current name args"""
named_args = cur_named_args.copy()
named_args.update(self.matchdict)
return named_args

def split_path_info(self, path_info: str) -> Tuple[str, str]:
""" split path_info to new script_name and new path_info"""
return path_info[:self.matchlength], path_info[self.matchlength:]


class URITemplate(object):
Expand All @@ -105,7 +117,7 @@ def __init__(self, tmpl_pattern: str,
self.converters = detect_converters(
tmpl_pattern, converters)

def match(self, path_info: str) -> MATCH_RESULT_TYPE:
def match(self, path_info: str) -> MatchResult:
""" parse path_info and detect urlvars of url pattern """
matched = self.regex.match(path_info)
if matched is None:
Expand All @@ -118,8 +130,8 @@ def match(self, path_info: str) -> MATCH_RESULT_TYPE:
except ValueError:
return None

return {"matchdict": matchdict,
"matchlength": matchlength}
return MatchResult(matchdict,
matchlength)

def convert_values(self, matchdict: Dict[str, str]) -> Dict[str, Any]:
""" convert values of ``matchdict``
Expand Down
17 changes: 8 additions & 9 deletions webdispatch/urldispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
Tuple,
Iterable,
)
from .uritemplate import URITemplate
from .uritemplate import URITemplate, MatchResult
from .base import DispatchBase


Expand All @@ -29,14 +29,14 @@ def add(self, name: str, pattern: str) -> None:
self.patterns[name] = URITemplate(
pattern, converters=self.converters)

def lookup(self, path_info: str) -> Dict[str, Any]:
def lookup(self, path_info: str) -> MatchResult:
""" lookup url match for path_info
"""
for name, pattern in self.patterns.items():
match = pattern.match(path_info)
if match is None:
continue
match["name"] = name
match.name = name
return match
return None

Expand Down Expand Up @@ -106,23 +106,22 @@ def detect_view_name(self, environ: Dict[str, Any]) -> str:
if match is None:
return None

extra_path_info = path_info[match["matchlength"]:]
splited = match.split_path_info(path_info)
extra_path_info = splited[1]
pos_args = [] # type: List[str]
named_args = match["matchdict"]

routing_args = environ.get('wsgiorg.routing_args', ((), {}))
(cur_pos, cur_named) = routing_args
new_pos = list(cur_pos) + list(pos_args)
new_named = cur_named.copy()
new_named.update(named_args)
new_named = match.new_named_args(cur_named)
environ['wsgiorg.routing_args'] = (new_pos, new_named)
environ['webdispatch.urlmapper'] = self.urlmapper
urlgenerator = URLGenerator(environ, self.urlmapper)
environ['webdispatch.urlgenerator'] = urlgenerator
environ['SCRIPT_NAME'] = script_name + path_info[:match["matchlength"]]
environ['SCRIPT_NAME'] = script_name + splited[0]
environ['PATH_INFO'] = extra_path_info

return match["name"]
return match.name

def on_view_not_found(
self,
Expand Down

0 comments on commit a732e07

Please sign in to comment.