Andriy Kornatskyy avatar Andriy Kornatskyy committed 7f0a1ae

Refactoring route_name use.

Comments (0)

Files changed (7)

src/wheezy/routing/builders.py

 RE_PLAIN_ROUTE = re.compile(r'^[\w/-]+$')
 
 
-def try_build_plain_route(pattern, finishing, kwargs=None):
+def try_build_plain_route(pattern, finishing, kwargs=None, name=None):
     """ If the plain route regular expression match the pattern
         than create a PlainRoute instance.
 
     if isinstance(pattern, PlainRoute):
         return pattern
     if pattern == '' or RE_PLAIN_ROUTE.match(pattern):
-        return PlainRoute(pattern, finishing, kwargs)
+        return PlainRoute(pattern, finishing, kwargs, name)
     return None
 
 
-def try_build_curly_route(pattern, finishing, kwargs=None):
+def try_build_curly_route(pattern, finishing, kwargs=None, name=None):
     """ Convert pattern expression into regex with
         named groups and create regex route.
 
     if isinstance(pattern, RegexRoute):
         return pattern
     if RE_CURLY_ROUTE.search(pattern):
-        return RegexRoute(curly_convert(pattern), finishing, kwargs)
+        return RegexRoute(curly_convert(pattern), finishing, kwargs, name)
     return None
 
 
-def try_build_regex_route(pattern, finishing, kwargs=None):
+def try_build_regex_route(pattern, finishing, kwargs=None, name=None):
     """ There is no special tests to match regex selection
         strategy.
 
     """
     if isinstance(pattern, RegexRoute):
         return pattern
-    return RegexRoute(pattern, finishing, kwargs)
+    return RegexRoute(pattern, finishing, kwargs, name)
 
 
-def build_route(pattern, finishing, kwargs, route_builders):
+def build_route(pattern, finishing, kwargs, name, route_builders):
     """ Try to find suitable route builder to create a route.
 
         >>> from wheezy.routing.config import route_builders
-        >>> r = build_route(r'abc', False, {'a': 1}, route_builders)
+        >>> r = build_route(r'abc', False, {'a': 1}, None, route_builders)
         >>> assert isinstance(r, PlainRoute)
         >>> r.kwargs
         {'a': 1}
 
         Otherwise raise LookupError
 
-        >>> r = build_route(r'abc', None, False, [])
+        >>> r = build_route(r'abc', None, False, None, [])
         Traceback (most recent call last):
             ...
         LookupError: No matching route factory found
     """
+    if not finishing:
+        assert not name
     for try_build_route in route_builders:
-        route = try_build_route(pattern, finishing, kwargs)
+        route = try_build_route(pattern, finishing, kwargs, name)
         if route:
             return route
     else:

src/wheezy/routing/route.py

     """
     __slots__ = ('pattern', 'kwargs', 'matched', 'match', 'exact_matches')
 
-    def __init__(self, pattern, finishing, kwargs=None):
+    def __init__(self, pattern, finishing, kwargs=None, name=None):
         """ Initializes the route by given ``pattern``. If
             ``finishing`` is True than choose ``equals_math``
             strategy
             >>> r = PlainRoute(r'abc', True)
             >>> assert r.match == r.equals_match
             >>> r.exact_matches
-            (('abc', None),)
+            (('abc', {}),)
 
             Otherwise ``startswith_match`` strategy is selected.
 
             >>> assert r.match == r.startswith_match
         """
         self.pattern = pattern
-        self.kwargs = kwargs
+        self.kwargs = kwargs and kwargs.copy() or {}
         self.matched = len(pattern)
         # Choose match strategy
         if finishing:
+            if name:
+                self.kwargs['route_name'] = name
             self.match = self.equals_match
-            self.exact_matches = ((pattern, kwargs), )
+            self.exact_matches = ((pattern, self.kwargs), )
         else:
             self.match = self.startswith_match
             self.exact_matches = None
             >>> matched
             3
             >>> kwargs
+            {}
 
             Match returns ``self.kwargs``.
 
             >>> matched
             3
             >>> kwargs
+            {}
 
             Match returns ``self.kwargs``.
 
 class RegexRoute(object):
     """ Route based on regular expression matching.
     """
-    __slots__ = ('match', 'path', 'path_value',
+    __slots__ = ('match', 'path', 'path_value', 'name',
                  'path_format', 'kwargs', 'regex')
 
-    def __init__(self, pattern, finishing, kwargs=None):
+    def __init__(self, pattern, finishing, kwargs=None, name=None):
         pattern = pattern.lstrip('^').rstrip('$')
         # Choose match strategy
         self.path_format, default_values = parse_pattern(pattern)
-        self.kwargs = dict.fromkeys(default_values, '')
         if kwargs:
+            self.kwargs = dict.fromkeys(default_values, '')
+            self.kwargs.update(kwargs)
+            if finishing and name:
+                self.kwargs['route_name'] = name
             self.match = self.match_with_kwargs
             self.path = self.path_with_kwargs
-            self.kwargs.update(kwargs)
             self.path_value = self.path_format % self.kwargs
         else:
-            self.match = self.match_no_kwargs
+            if finishing and name:
+                self.name = name
+                self.match = self.match_no_kwargs_finishing
+            else:
+                self.match = self.match_no_kwargs
             self.path = self.path_no_kwargs
 
         pattern = '^' + pattern
             return m.end(), m.groupdict()
         return -1, None
 
+    def match_no_kwargs_finishing(self, path):
+        """ If the ``path`` match the regex pattern.
+
+            >>> r = RegexRoute(r'abc/(?P<id>\d+$)', True)
+            >>> matched, kwargs = r.match_no_kwargs('abc/1234')
+            >>> matched
+            8
+            >>> kwargs
+            {'id': '1234'}
+
+            Otherwise return ``(-1, None)``.
+
+            >>> matched, kwargs = r.match_no_kwargs('abc/x')
+            >>> matched
+            -1
+            >>> kwargs
+        """
+        m = self.regex.match(path)
+        if m:
+            kwargs = m.groupdict()
+            kwargs['route_name'] = self.name
+            return m.end(), kwargs
+        return -1, None
+
     def match_with_kwargs(self, path):
         """ If the ``path`` match the regex pattern.
 
             KeyError: 'day'
         """
         return self.path_format % values
+
+
+if __name__ == '__main__':
+    r = RegexRoute(r'abc/(?P<id>\d+$)', True, {
+        'lang': 'en'
+    })

src/wheezy/routing/router.py

         if name in self.route_map:
             warn('PathRouter: overriding route: %s.' % name)
         # build finishing route
-        kwargs = kwargs and kwargs.copy() or {}
-        route = build_route(pattern, True, kwargs, self.route_builders)
-        # allow build strategy specialize math/path cases
-        kwargs['route_name'] = name
+        route = build_route(pattern, True, kwargs, name, self.route_builders)
         self.route_map[name] = route.path
         if hasattr(route, 'exact_matches'):
             for pattern, kwargs in route.exact_matches:
             >>> warnings.simplefilter('default')
         """
         # try build intermediate route
-        route = build_route(pattern, False, kwargs, self.route_builders)
+        route = build_route(pattern, False, kwargs, None, self.route_builders)
         if isinstance(included, PathRouter):
             inner = included
         else:

src/wheezy/routing/tests/test_builders.py

         r = PlainRoute('', True)
 
         self.assertRaises(LookupError,
-                          lambda: build_route(r, False, None, []))
+                          lambda: build_route(r, False, None, None, []))
 
     def test_found(self):
         """ Sutable route strategy has been found.
         from wheezy.routing.builders import build_route
         from wheezy.routing import config
 
-        r = build_route(r'abc', False, {'a': 1}, config.route_builders)
+        r = build_route(r'abc', False, {'a': 1}, None, config.route_builders)
 
         assert r
         self.assertEqual({'a': 1}, r.kwargs)
         mock = m.mock
         builders = mock(), mock(), mock(), mock(), mock()
         b1, b2, b3, b4, b5 = builders
-        expect(b1(r'abc', False, None)).result(None)
-        expect(b2(r'abc', False, None)).result(None)
-        expect(b3(r'abc', False, None)).result('x')
+        expect(b1(r'abc', False, None, None)).result(None)
+        expect(b2(r'abc', False, None, None)).result(None)
+        expect(b3(r'abc', False, None, None)).result('x')
         m.replay()
 
-        r = build_route(r'abc', False, None, builders)
+        r = build_route(r'abc', False, None, None, builders)
 
         self.assertEqual('x', r)
         m.verify()
         mock = m.mock
         builders = mock(), mock()
         b1, b2 = builders
-        expect(b1(r'abc', False, None)).result(None)
-        expect(b2(r'abc', False, None)).result(None)
+        expect(b1(r'abc', False, None, None)).result(None)
+        expect(b2(r'abc', False, None, None)).result(None)
         m.replay()
 
-        self.assertRaises(LookupError,
-                          lambda: build_route(r'abc', False, None, builders))
+        self.assertRaises(LookupError, lambda: build_route(
+            r'abc', False, None, None, builders))
         m.verify()
 
 
         from wheezy.routing.builders import build_route
         from wheezy.routing.route import PlainRoute
 
-        r = build_route(r'abc', False, None, config.route_builders)
+        r = build_route(r'abc', False, None, None, config.route_builders)
 
         assert isinstance(r, PlainRoute)
 
             r'abc/{id}',
             False,
             None,
+            None,
             config.route_builders
         )
 
             r'abc/{id}',
             True,
             None,
+            None,
             config.route_builders
         )
 
             r'abc/(?P<id>\d+)',
             False,
             None,
+            None,
             config.route_builders
         )
 

src/wheezy/routing/tests/test_config.py

             assert callable(builder)
             args, varargs, keywords, defaults = \
                 inspect.getargspec(builder)
-            self.assertEqual(['pattern', 'finishing', 'kwargs'], args)
+            self.assertEqual(['pattern', 'finishing', 'kwargs', 'name'], args)
             self.assertEqual(None, varargs)
             self.assertEqual(None, keywords)
-            self.assertEqual((None,), defaults)
+            self.assertEqual((None, None), defaults)

src/wheezy/routing/tests/test_route.py

         self.assertEquals(r'abc', r.pattern)
         self.assertEquals(kw, r.kwargs)
         self.assertEquals(3, r.matched)
-        assert kw is r.kwargs
+        assert kw == r.kwargs
 
 
 class PlainRouteEqualsMatchTestCase(unittest.TestCase):
         matched, kwargs = r.equals_match(r'abc')
         self.assertEquals(3, matched)
         self.assertEquals({'a': 1}, r.kwargs)
-        assert kw is kwargs
+        assert kw == kwargs
 
     def test_no_kwargs(self):
         """ ``equals_match`` strategy when no kwargs supplied.
         r = PlainRoute(r'abc', True)
         matched, kwargs = r.equals_match(r'abc')
         self.assertEquals(3, matched)
-        self.assertEquals(None, r.kwargs)
+        self.assertEquals({}, r.kwargs)
 
     def test_no_match(self):
         """ ``equals_match`` strategy when there is no match.
         matched, kwargs = r.startswith_match(r'abc/de')
         self.assertEquals(4, matched)
         self.assertEquals(kw, kwargs)
-        assert kw is kwargs
+        assert kw == kwargs
 
     def test_no_kwargs(self):
         """ ``startswith_match`` strategy when no
         r = PlainRoute(r'abc/', False)
         matched, kwargs = r.startswith_match(r'abc/de')
         self.assertEquals(4, matched)
-        self.assertEquals(None, r.kwargs)
+        self.assertEquals({}, r.kwargs)
 
     def test_no_match(self):
         """ ``startswith_match`` strategy when there

src/wheezy/routing/tests/test_router.py

         expect(mock_route.path)
         mock_build_route = self.m.replace(builders.build_route)
         expect(
-            mock_build_route('abc', True, kw, self.r.route_builders)
+            mock_build_route('abc', True, kw, 'n', self.r.route_builders)
         ).result(mock_route)
         self.m.replay()
 
         expect(mock_route.path)
         mock_build_route = self.m.replace(builders.build_route)
         expect(
-            mock_build_route('abc', False, kw, self.r.route_builders)
+            mock_build_route('abc', False, kw, None, self.r.route_builders)
         ).result(mock_route)
         self.m.replay()
 
         expect(
             mock_build_route(
                 '', True,
-                {},
+                None, 'x',
                 self.r.route_builders
             )
         ).result(mock_route)
 
         self.assertEquals('h', handler)
         self.assertEquals(kw, kwargs)
-        assert kw is kwargs
+        assert kw == kwargs
 
     def test_kwargs_inner(self):
         """ there is a match is inner, kwargs is None
             mock_build_route(
                 'abc',
                 True,
-                {},
+                None,
+                'n',
                 self.r.route_builders)
         ).result(mock_route)
         expect(mock_route.path({'a': 1})).result('abc')
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.