def test_server_name_casing(self): m = r.Map([r.Rule('/', endpoint='index', subdomain='foo')]) env = create_environ() env['SERVER_NAME'] = env['HTTP_HOST'] = 'FOO.EXAMPLE.COM' a = m.bind_to_environ(env, server_name='example.com') assert a.match('/') == ('index', {}) env = create_environ() env['SERVER_NAME'] = '127.0.0.1' env['SERVER_PORT'] = '5000' del env['HTTP_HOST'] a = m.bind_to_environ(env, server_name='example.com') try: a.match() except r.NotFound: pass else: assert False, 'Expected not found exception'
def test_http_host_before_server_name(self): env = { 'HTTP_HOST': 'wiki.example.com', 'SERVER_NAME': 'web0.example.com', 'SERVER_PORT': '80', 'SCRIPT_NAME': '', 'PATH_INFO': '', 'REQUEST_METHOD': 'GET', 'wsgi.url_scheme': 'http' } map = r.Map([r.Rule('/', endpoint='index', subdomain='wiki')]) adapter = map.bind_to_environ(env, server_name='example.com') assert adapter.match('/') == ('index', {}) assert adapter.build('index', force_external=True) == 'http://wiki.example.com/' assert adapter.build('index') == '/' env['HTTP_HOST'] = 'admin.example.com' adapter = map.bind_to_environ(env, server_name='example.com') assert adapter.build('index') == 'http://wiki.example.com/'
def test_host_matching(self): m = r.Map([ r.Rule('/', endpoint='index', host='www.<domain>'), r.Rule('/', endpoint='files', host='files.<domain>'), r.Rule('/foo/', defaults={'page': 1}, host='www.<domain>', endpoint='x'), r.Rule('/<int:page>', host='files.<domain>', endpoint='x') ], host_matching=True) a = m.bind('www.example.com') assert a.match('/') == ('index', {'domain': 'example.com'}) assert a.match('/foo/') == ('x', {'domain': 'example.com', 'page': 1}) try: a.match('/foo') except r.RequestRedirect, e: assert e.new_url == 'http://www.example.com/foo/'
def test_method_fallback(): map = r.Map( [ r.Rule("/", endpoint="index", methods=["GET"]), r.Rule("/<name>", endpoint="hello_name", methods=["GET"]), r.Rule("/select", endpoint="hello_select", methods=["POST"]), r.Rule("/search_get", endpoint="search", methods=["GET"]), r.Rule("/search_post", endpoint="search", methods=["POST"]), ] ) adapter = map.bind("example.com") assert adapter.build("index") == "/" assert adapter.build("index", method="GET") == "/" assert adapter.build("hello_name", {"name": "foo"}) == "/foo" assert adapter.build("hello_select") == "/select" assert adapter.build("hello_select", method="POST") == "/select" assert adapter.build("search") == "/search_get" assert adapter.build("search", method="GET") == "/search_get" assert adapter.build("search", method="POST") == "/search_post"
def _FetchRoutingMap(self): headers = { "x-csrftoken": self.csrf_token, "x-requested-with": "XMLHttpRequest" } cookies = {"csrftoken": self.csrf_token} url = "%s/%s" % (self.api_endpoint.strip("/"), "api/v2/reflection/api-methods") response = requests.get(url, headers=headers, cookies=cookies, auth=self.auth) self._CheckResponseStatus(response) json_str = response.content[len(self.JSON_PREFIX):] # Register descriptors in the database, so that all API-related # protos are recognized when Any messages are unpacked. utils.RegisterProtoDescriptors(symbol_database.Default()) proto = reflection_pb2.ApiListApiMethodsResult() json_format.Parse(json_str, proto, ignore_unknown_fields=True) routing_rules = [] self.api_methods = {} for method in proto.items: if not method.http_route.startswith("/api/v2/"): method.http_route = method.http_route.replace( "/api/", "/api/v2/", 1) self.api_methods[method.name] = method routing_rules.append( routing.Rule(method.http_route, methods=method.http_methods, endpoint=method.name)) self.handlers_map = routing.Map(routing_rules) parsed_endpoint_url = urlparse.urlparse(self.api_endpoint) self.urls = self.handlers_map.bind( parsed_endpoint_url.netloc, url_scheme=parsed_endpoint_url.scheme)
def test_http_host_before_server_name(): env = { "HTTP_HOST": "wiki.example.com", "SERVER_NAME": "web0.example.com", "SERVER_PORT": "80", "SCRIPT_NAME": "", "PATH_INFO": "", "REQUEST_METHOD": "GET", "wsgi.url_scheme": "http", } map = r.Map([r.Rule("/", endpoint="index", subdomain="wiki")]) adapter = map.bind_to_environ(env, server_name="example.com") assert adapter.match("/") == ("index", {}) assert adapter.build("index", force_external=True) == "http://wiki.example.com/" assert adapter.build("index") == "/" env["HTTP_HOST"] = "admin.example.com" adapter = map.bind_to_environ(env, server_name="example.com") assert adapter.build("index") == "http://wiki.example.com/"
def test_server_name_interpolation(): server_name = "example.invalid" map = r.Map( [r.Rule("/", endpoint="index"), r.Rule("/", endpoint="alt", subdomain="alt")] ) env = create_environ("/", f"http://{server_name}/") adapter = map.bind_to_environ(env, server_name=server_name) assert adapter.match() == ("index", {}) env = create_environ("/", f"http://alt.{server_name}/") adapter = map.bind_to_environ(env, server_name=server_name) assert adapter.match() == ("alt", {}) env = create_environ("/", f"http://{server_name}/") with pytest.warns(UserWarning): adapter = map.bind_to_environ(env, server_name="foo") assert adapter.subdomain == "<invalid>"
def test_error_message_without_suggested_rule(): m = r.Map([r.Rule("/foo/", endpoint="world", methods=["GET"])]) adapter = m.bind("example.com") with pytest.raises(r.BuildError) as excinfo: adapter.build("urks") assert str(excinfo.value).startswith("Could not build url for endpoint 'urks'.") with pytest.raises(r.BuildError) as excinfo: adapter.build("world", method="POST") assert str(excinfo.value).startswith( "Could not build url for endpoint 'world' ('POST')." ) with pytest.raises(r.BuildError) as excinfo: adapter.build("urks", values={"user_id": 5}) assert str(excinfo.value).startswith( "Could not build url for endpoint 'urks' with values ['user_id']." )
def test_negative(): map = r.Map([ r.Rule('/foos/<int(signed=True):page>', endpoint='foos'), r.Rule('/bars/<float(signed=True):page>', endpoint='bars'), r.Rule('/foo/<int:page>', endpoint='foo'), r.Rule('/bar/<float:page>', endpoint='bar') ]) adapter = map.bind('example.org', '/') assert adapter.match('/foos/-2') == ('foos', {'page': -2}) assert adapter.match('/foos/-50') == ('foos', {'page': -50}) assert adapter.match('/bars/-2.0') == ('bars', {'page': -2.0}) assert adapter.match('/bars/-0.185') == ('bars', {'page': -0.185}) # Make sure signed values are rejected in unsigned mode pytest.raises(r.NotFound, lambda: adapter.match('/foo/-2')) pytest.raises(r.NotFound, lambda: adapter.match('/foo/-50')) pytest.raises(r.NotFound, lambda: adapter.match('/bar/-0.185')) pytest.raises(r.NotFound, lambda: adapter.match('/bar/-2.0'))
def test_negative(): map = r.Map([ r.Rule("/foos/<int(signed=True):page>", endpoint="foos"), r.Rule("/bars/<float(signed=True):page>", endpoint="bars"), r.Rule("/foo/<int:page>", endpoint="foo"), r.Rule("/bar/<float:page>", endpoint="bar"), ]) adapter = map.bind("example.org", "/") assert adapter.match("/foos/-2") == ("foos", {"page": -2}) assert adapter.match("/foos/-50") == ("foos", {"page": -50}) assert adapter.match("/bars/-2.0") == ("bars", {"page": -2.0}) assert adapter.match("/bars/-0.185") == ("bars", {"page": -0.185}) # Make sure signed values are rejected in unsigned mode pytest.raises(r.NotFound, lambda: adapter.match("/foo/-2")) pytest.raises(r.NotFound, lambda: adapter.match("/foo/-50")) pytest.raises(r.NotFound, lambda: adapter.match("/bar/-0.185")) pytest.raises(r.NotFound, lambda: adapter.match("/bar/-2.0"))
def _BuildHttpRoutingMap(self, router_cls): """Builds a werkzeug routing map out of a given router class.""" if not issubclass(router_cls, api_call_router.ApiCallRouter): raise ValueError("Router has to be an instance of ApiCallRouter.") routing_map = routing.Map() # Note: we traverse methods of the base class (ApiCallRouter) to avoid # potential problems caused by child router classes using the @Http # annotation (thus adding additional unforeseen HTTP paths/methods). We # don't want the HTTP API to depend on a particular router implementation. for _, metadata in router_cls.GetAnnotatedMethods().items(): for http_method, path in metadata.http_methods: routing_map.add( routing.Rule(path, methods=[http_method], endpoint=metadata)) return routing_map
def __init__(self, pod, debug=False): rule = routing.Rule self.pod = pod self.debug = debug self.url_map = routing.Map([ rule('/', endpoint=serve_pod), rule('/_grow/ui/tools/<path:tool>', endpoint=serve_ui_tool), rule('/_grow/preprocessors/run/<path:name>', endpoint=serve_run_preprocessor), rule('/_grow/<any("translations"):page>/<path:locale>', endpoint=serve_console), rule('/_grow/<path:page>', endpoint=serve_console), rule('/_grow', endpoint=serve_console), rule('/<path:path>', endpoint=serve_pod), ], strict_slashes=False) # Start off the server with a clean dependency graph. self.pod.podcache.dependency_graph.mark_clean()
def test_path(self): map = r.Map([ r.Rule('/', defaults={'name': 'FrontPage'}, endpoint='page'), r.Rule('/Special', endpoint='special'), r.Rule('/<int:year>', endpoint='year'), r.Rule('/<path:name>', endpoint='page'), r.Rule('/<path:name>/edit', endpoint='editpage'), r.Rule('/<path:name>/silly/<path:name2>', endpoint='sillypage'), r.Rule('/<path:name>/silly/<path:name2>/edit', endpoint='editsillypage'), r.Rule('/Talk:<path:name>', endpoint='talk'), r.Rule('/User:<username>', endpoint='user'), r.Rule('/User:<username>/<path:name>', endpoint='userpage'), r.Rule('/Files/<path:file>', endpoint='files'), ]) adapter = map.bind('example.org', '/') assert adapter.match('/') == ('page', {'name': 'FrontPage'}) self.assert_raises(r.RequestRedirect, lambda: adapter.match('/FrontPage')) assert adapter.match('/Special') == ('special', {}) assert adapter.match('/2007') == ('year', {'year': 2007}) assert adapter.match('/Some/Page') == ('page', {'name': 'Some/Page'}) assert adapter.match('/Some/Page/edit') == ('editpage', { 'name': 'Some/Page' }) assert adapter.match('/Foo/silly/bar') == ('sillypage', { 'name': 'Foo', 'name2': 'bar' }) assert adapter.match('/Foo/silly/bar/edit') == ('editsillypage', { 'name': 'Foo', 'name2': 'bar' }) assert adapter.match('/Talk:Foo/Bar') == ('talk', {'name': 'Foo/Bar'}) assert adapter.match('/User:thomas') == ('user', { 'username': '******' }) assert adapter.match('/User:thomas/projects/werkzeug') == \ ('userpage', {'username':'******', 'name':'projects/werkzeug'}) assert adapter.match('/Files/downloads/werkzeug/0.2.zip') == \ ('files', {'file':'downloads/werkzeug/0.2.zip'})
def test_basic_building(): map = r.Map([ r.Rule('/', endpoint='index'), r.Rule('/foo', endpoint='foo'), r.Rule('/bar/<baz>', endpoint='bar'), r.Rule('/bar/<int:bazi>', endpoint='bari'), r.Rule('/bar/<float:bazf>', endpoint='barf'), r.Rule('/bar/<path:bazp>', endpoint='barp'), r.Rule('/hehe', endpoint='blah', subdomain='blah') ]) adapter = map.bind('example.org', '/', subdomain='blah') assert adapter.build('index', {}) == 'http://example.org/' assert adapter.build('foo', {}) == 'http://example.org/foo' assert adapter.build('bar', {'baz': 'blub'}) == \ 'http://example.org/bar/blub' assert adapter.build('bari', {'bazi': 50}) == 'http://example.org/bar/50' multivalues = MultiDict([('bazi', 50), ('bazi', None)]) assert adapter.build('bari', multivalues) == 'http://example.org/bar/50' assert adapter.build('barf', {'bazf': 0.815}) == \ 'http://example.org/bar/0.815' assert adapter.build('barp', {'bazp': 'la/di'}) == \ 'http://example.org/bar/la/di' assert adapter.build('blah', {}) == '/hehe' pytest.raises(r.BuildError, lambda: adapter.build('urks')) adapter = map.bind('example.org', '/test', subdomain='blah') assert adapter.build('index', {}) == 'http://example.org/test/' assert adapter.build('foo', {}) == 'http://example.org/test/foo' assert adapter.build('bar', {'baz': 'blub'}) == \ 'http://example.org/test/bar/blub' assert adapter.build('bari', {'bazi': 50}) == 'http://example.org/test/bar/50' assert adapter.build('barf', {'bazf': 0.815}) == 'http://example.org/test/bar/0.815' assert adapter.build('barp', {'bazp': 'la/di'}) == 'http://example.org/test/bar/la/di' assert adapter.build('blah', {}) == '/test/hehe' adapter = map.bind('example.org') assert adapter.build('foo', {}) == '/foo' assert adapter.build('foo', {}, force_external=True) == 'http://example.org/foo' adapter = map.bind('example.org', url_scheme='') assert adapter.build('foo', {}) == '/foo' assert adapter.build('foo', {}, force_external=True) == '//example.org/foo'
def test_double_defaults(prefix): m = r.Map([ r.Rule(prefix + '/', defaults={'foo': 1, 'bar': False}, endpoint='x'), r.Rule(prefix + '/<int:foo>', defaults={'bar': False}, endpoint='x'), r.Rule(prefix + '/bar/', defaults={'foo': 1, 'bar': True}, endpoint='x'), r.Rule(prefix + '/bar/<int:foo>', defaults={'bar': True}, endpoint='x') ]) a = m.bind('example.com') assert a.match(prefix + '/') == ('x', {'foo': 1, 'bar': False}) assert a.match(prefix + '/2') == ('x', {'foo': 2, 'bar': False}) assert a.match(prefix + '/bar/') == ('x', {'foo': 1, 'bar': True}) assert a.match(prefix + '/bar/2') == ('x', {'foo': 2, 'bar': True}) assert a.build('x', {'foo': 1, 'bar': False}) == prefix + '/' assert a.build('x', {'foo': 2, 'bar': False}) == prefix + '/2' assert a.build('x', {'bar': False}) == prefix + '/' assert a.build('x', {'foo': 1, 'bar': True}) == prefix + '/bar/' assert a.build('x', {'foo': 2, 'bar': True}) == prefix + '/bar/2' assert a.build('x', {'bar': True}) == prefix + '/bar/'
def test_error_message_without_suggested_rule(): m = r.Map([ r.Rule(u'/foo/', endpoint='world', methods=['GET']), ]) adapter = m.bind('example.com') with pytest.raises(r.BuildError) as excinfo: adapter.build('urks') assert str( excinfo.value).startswith("Could not build url for endpoint 'urks'.") with pytest.raises(r.BuildError) as excinfo: adapter.build('world', method='POST') assert str(excinfo.value).startswith( "Could not build url for endpoint 'world' ('POST').") with pytest.raises(r.BuildError) as excinfo: adapter.build('urks', values={'user_id': 5}) assert str(excinfo.value).startswith( "Could not build url for endpoint 'urks' with values ['user_id'].")
def test_complex_routing_rules(): m = r.Map( [ r.Rule("/", endpoint="index"), r.Rule("/<int:blub>", endpoint="an_int"), r.Rule("/<blub>", endpoint="a_string"), r.Rule("/foo/", endpoint="nested"), r.Rule("/foobar/", endpoint="nestedbar"), r.Rule("/foo/<path:testing>/", endpoint="nested_show"), r.Rule("/foo/<path:testing>/edit", endpoint="nested_edit"), r.Rule("/users/", endpoint="users", defaults={"page": 1}), r.Rule("/users/page/<int:page>", endpoint="users"), r.Rule("/foox", endpoint="foox"), r.Rule("/<path:bar>/<path:blub>", endpoint="barx_path_path"), ] ) a = m.bind("example.com") assert a.match("/") == ("index", {}) assert a.match("/42") == ("an_int", {"blub": 42}) assert a.match("/blub") == ("a_string", {"blub": "blub"}) assert a.match("/foo/") == ("nested", {}) assert a.match("/foobar/") == ("nestedbar", {}) assert a.match("/foo/1/2/3/") == ("nested_show", {"testing": "1/2/3"}) assert a.match("/foo/1/2/3/edit") == ("nested_edit", {"testing": "1/2/3"}) assert a.match("/users/") == ("users", {"page": 1}) assert a.match("/users/page/2") == ("users", {"page": 2}) assert a.match("/foox") == ("foox", {}) assert a.match("/1/2/3") == ("barx_path_path", {"bar": "1", "blub": "2/3"}) assert a.build("index") == "/" assert a.build("an_int", {"blub": 42}) == "/42" assert a.build("a_string", {"blub": "test"}) == "/test" assert a.build("nested") == "/foo/" assert a.build("nestedbar") == "/foobar/" assert a.build("nested_show", {"testing": "1/2/3"}) == "/foo/1/2/3/" assert a.build("nested_edit", {"testing": "1/2/3"}) == "/foo/1/2/3/edit" assert a.build("users", {"page": 1}) == "/users/" assert a.build("users", {"page": 2}) == "/users/page/2" assert a.build("foox") == "/foox" assert a.build("barx_path_path", {"bar": "1", "blub": "2/3"}) == "/1/2/3"
def test_path(): map = r.Map([ r.Rule('/', defaults={'name': 'FrontPage'}, endpoint='page'), r.Rule('/Special', endpoint='special'), r.Rule('/<int:year>', endpoint='year'), r.Rule('/<path:name>:foo', endpoint='foopage'), r.Rule('/<path:name>:<path:name2>', endpoint='twopage'), r.Rule('/<path:name>', endpoint='page'), r.Rule('/<path:name>/edit', endpoint='editpage'), r.Rule('/<path:name>/silly/<path:name2>', endpoint='sillypage'), r.Rule('/<path:name>/silly/<path:name2>/edit', endpoint='editsillypage'), r.Rule('/Talk:<path:name>', endpoint='talk'), r.Rule('/User:<username>', endpoint='user'), r.Rule('/User:<username>/<path:name>', endpoint='userpage'), r.Rule('/User:<username>/comment/<int:id>-<int:replyId>', endpoint='usercomment'), r.Rule('/Files/<path:file>', endpoint='files'), r.Rule('/<admin>/<manage>/<things>', endpoint='admin'), ]) adapter = map.bind('example.org', '/') assert adapter.match('/') == ('page', {'name': 'FrontPage'}) pytest.raises(r.RequestRedirect, lambda: adapter.match('/FrontPage')) assert adapter.match('/Special') == ('special', {}) assert adapter.match('/2007') == ('year', {'year': 2007}) assert adapter.match('/Some:foo') == ('foopage', {'name': 'Some'}) assert adapter.match('/Some:bar') == ('twopage', {'name': 'Some', 'name2': 'bar'}) assert adapter.match('/Some/Page') == ('page', {'name': 'Some/Page'}) assert adapter.match('/Some/Page/edit') == ('editpage', {'name': 'Some/Page'}) assert adapter.match('/Foo/silly/bar') == ('sillypage', {'name': 'Foo', 'name2': 'bar'}) assert adapter.match( '/Foo/silly/bar/edit') == ('editsillypage', {'name': 'Foo', 'name2': 'bar'}) assert adapter.match('/Talk:Foo/Bar') == ('talk', {'name': 'Foo/Bar'}) assert adapter.match('/User:thomas') == ('user', {'username': '******'}) assert adapter.match('/User:thomas/projects/werkzeug') == \ ('userpage', {'username': '******', 'name': 'projects/werkzeug'}) assert adapter.match('/User:thomas/comment/123-456') == \ ('usercomment', {'username': '******', 'id': 123, 'replyId': 456}) assert adapter.match('/Files/downloads/werkzeug/0.2.zip') == \ ('files', {'file': 'downloads/werkzeug/0.2.zip'}) assert adapter.match('/Jerry/eats/cheese') == \ ('admin', {'admin': 'Jerry', 'manage': 'eats', 'things': 'cheese'})
def test_converter_with_tuples(): ''' Regression test for https://github.com/mitsuhiko/werkzeug/issues/709 ''' class TwoValueConverter(r.BaseConverter): def __init__(self, *args, **kwargs): super(TwoValueConverter, self).__init__(*args, **kwargs) self.regex = r'(\w\w+)/(\w\w+)' def to_python(self, two_values): one, two = two_values.split('/') return one, two def to_url(self, values): return "%s/%s" % (values[0], values[1]) map = r.Map([r.Rule('/<two:foo>/', endpoint='handler')], converters={'two': TwoValueConverter}) a = map.bind('example.org', '/') route, kwargs = a.match('/qwert/yuiop/') assert kwargs['foo'] == ('qwert', 'yuiop')
def test_dispatch(self): env = create_environ('/') map = r.Map([ r.Rule('/', endpoint='root'), r.Rule('/foo/', endpoint='foo') ]) adapter = map.bind_to_environ(env) raise_this = None def view_func(endpoint, values): if raise_this is not None: raise raise_this return Response(repr((endpoint, values))) dispatch = lambda p, q=False: Response.force_type(adapter.dispatch(view_func, p, catch_http_exceptions=q), env) assert dispatch('/').data == b"('root', {})" assert dispatch('/foo').status_code == 301 raise_this = r.NotFound() self.assert_raises(r.NotFound, lambda: dispatch('/bar')) assert dispatch('/bar', True).status_code == 404
def test_alias_redirects(self): m = r.Map([ r.Rule('/', endpoint='index'), r.Rule('/index.html', endpoint='index', alias=True), r.Rule('/users/', defaults={'page': 1}, endpoint='users'), r.Rule('/users/index.html', defaults={'page': 1}, alias=True, endpoint='users'), r.Rule('/users/page/<int:page>', endpoint='users'), r.Rule('/users/page-<int:page>.html', alias=True, endpoint='users'), ]) a = m.bind('example.com') def ensure_redirect(path, new_url, args=None): try: a.match(path, query_args=args) except r.RequestRedirect, e: assert e.new_url == 'http://example.com' + new_url else:
def test_basic_building(): map = r.Map( [ r.Rule("/", endpoint="index"), r.Rule("/foo", endpoint="foo"), r.Rule("/bar/<baz>", endpoint="bar"), r.Rule("/bar/<int:bazi>", endpoint="bari"), r.Rule("/bar/<float:bazf>", endpoint="barf"), r.Rule("/bar/<path:bazp>", endpoint="barp"), r.Rule("/hehe", endpoint="blah", subdomain="blah"), ] ) adapter = map.bind("example.org", "/", subdomain="blah") assert adapter.build("index", {}) == "http://example.org/" assert adapter.build("foo", {}) == "http://example.org/foo" assert adapter.build("bar", {"baz": "blub"}) == "http://example.org/bar/blub" assert adapter.build("bari", {"bazi": 50}) == "http://example.org/bar/50" assert adapter.build("barf", {"bazf": 0.815}) == "http://example.org/bar/0.815" assert adapter.build("barp", {"bazp": "la/di"}) == "http://example.org/bar/la/di" assert adapter.build("blah", {}) == "/hehe" pytest.raises(r.BuildError, lambda: adapter.build("urks")) adapter = map.bind("example.org", "/test", subdomain="blah") assert adapter.build("index", {}) == "http://example.org/test/" assert adapter.build("foo", {}) == "http://example.org/test/foo" assert adapter.build("bar", {"baz": "blub"}) == "http://example.org/test/bar/blub" assert adapter.build("bari", {"bazi": 50}) == "http://example.org/test/bar/50" assert adapter.build("barf", {"bazf": 0.815}) == "http://example.org/test/bar/0.815" assert ( adapter.build("barp", {"bazp": "la/di"}) == "http://example.org/test/bar/la/di" ) assert adapter.build("blah", {}) == "/test/hehe" adapter = map.bind("example.org") assert adapter.build("foo", {}) == "/foo" assert adapter.build("foo", {}, force_external=True) == "http://example.org/foo" adapter = map.bind("example.org", url_scheme="") assert adapter.build("foo", {}) == "/foo" assert adapter.build("foo", {}, force_external=True) == "//example.org/foo"
def test_double_defaults(prefix): m = r.Map( [ r.Rule(f"{prefix}/", defaults={"foo": 1, "bar": False}, endpoint="x"), r.Rule(f"{prefix}/<int:foo>", defaults={"bar": False}, endpoint="x"), r.Rule(f"{prefix}/bar/", defaults={"foo": 1, "bar": True}, endpoint="x"), r.Rule(f"{prefix}/bar/<int:foo>", defaults={"bar": True}, endpoint="x"), ] ) a = m.bind("example.com") assert a.match(f"{prefix}/") == ("x", {"foo": 1, "bar": False}) assert a.match(f"{prefix}/2") == ("x", {"foo": 2, "bar": False}) assert a.match(f"{prefix}/bar/") == ("x", {"foo": 1, "bar": True}) assert a.match(f"{prefix}/bar/2") == ("x", {"foo": 2, "bar": True}) assert a.build("x", {"foo": 1, "bar": False}) == f"{prefix}/" assert a.build("x", {"foo": 2, "bar": False}) == f"{prefix}/2" assert a.build("x", {"bar": False}) == f"{prefix}/" assert a.build("x", {"foo": 1, "bar": True}) == f"{prefix}/bar/" assert a.build("x", {"foo": 2, "bar": True}) == f"{prefix}/bar/2" assert a.build("x", {"bar": True}) == f"{prefix}/bar/"
def test_dispatch(): env = create_environ("/") map = r.Map([r.Rule("/", endpoint="root"), r.Rule("/foo/", endpoint="foo")]) adapter = map.bind_to_environ(env) raise_this = None def view_func(endpoint, values): if raise_this is not None: raise raise_this return Response(repr((endpoint, values))) def dispatch(path, quiet=False): return Response.force_type( adapter.dispatch(view_func, path, catch_http_exceptions=quiet), env ) assert dispatch("/").data == b"('root', {})" assert dispatch("/foo").status_code == 308 raise_this = r.NotFound() pytest.raises(r.NotFound, lambda: dispatch("/bar")) assert dispatch("/bar", True).status_code == 404
def test_basic_routing(): map = r.Map( [ r.Rule("/", endpoint="index"), r.Rule("/foo", endpoint="foo"), r.Rule("/bar/", endpoint="bar"), ] ) adapter = map.bind("example.org", "/") assert adapter.match("/") == ("index", {}) assert adapter.match("/foo") == ("foo", {}) assert adapter.match("/bar/") == ("bar", {}) pytest.raises(r.RequestRedirect, lambda: adapter.match("/bar")) pytest.raises(r.NotFound, lambda: adapter.match("/blub")) adapter = map.bind("example.org", "/test") with pytest.raises(r.RequestRedirect) as excinfo: adapter.match("/bar") assert excinfo.value.new_url == "http://example.org/test/bar/" adapter = map.bind("example.org", "/") with pytest.raises(r.RequestRedirect) as excinfo: adapter.match("/bar") assert excinfo.value.new_url == "http://example.org/bar/" adapter = map.bind("example.org", "/") with pytest.raises(r.RequestRedirect) as excinfo: adapter.match("/bar", query_args={"aha": "muhaha"}) assert excinfo.value.new_url == "http://example.org/bar/?aha=muhaha" adapter = map.bind("example.org", "/") with pytest.raises(r.RequestRedirect) as excinfo: adapter.match("/bar", query_args="aha=muhaha") assert excinfo.value.new_url == "http://example.org/bar/?aha=muhaha" adapter = map.bind_to_environ(create_environ("/bar?foo=bar", "http://example.org/")) with pytest.raises(r.RequestRedirect) as excinfo: adapter.match() assert excinfo.value.new_url == "http://example.org/bar/?foo=bar"
def test_complex_routing_rules(): m = r.Map([ r.Rule('/', endpoint='index'), r.Rule('/<int:blub>', endpoint='an_int'), r.Rule('/<blub>', endpoint='a_string'), r.Rule('/foo/', endpoint='nested'), r.Rule('/foobar/', endpoint='nestedbar'), r.Rule('/foo/<path:testing>/', endpoint='nested_show'), r.Rule('/foo/<path:testing>/edit', endpoint='nested_edit'), r.Rule('/users/', endpoint='users', defaults={'page': 1}), r.Rule('/users/page/<int:page>', endpoint='users'), r.Rule('/foox', endpoint='foox'), r.Rule('/<path:bar>/<path:blub>', endpoint='barx_path_path') ]) a = m.bind('example.com') assert a.match('/') == ('index', {}) assert a.match('/42') == ('an_int', {'blub': 42}) assert a.match('/blub') == ('a_string', {'blub': 'blub'}) assert a.match('/foo/') == ('nested', {}) assert a.match('/foobar/') == ('nestedbar', {}) assert a.match('/foo/1/2/3/') == ('nested_show', {'testing': '1/2/3'}) assert a.match('/foo/1/2/3/edit') == ('nested_edit', {'testing': '1/2/3'}) assert a.match('/users/') == ('users', {'page': 1}) assert a.match('/users/page/2') == ('users', {'page': 2}) assert a.match('/foox') == ('foox', {}) assert a.match('/1/2/3') == ('barx_path_path', {'bar': '1', 'blub': '2/3'}) assert a.build('index') == '/' assert a.build('an_int', {'blub': 42}) == '/42' assert a.build('a_string', {'blub': 'test'}) == '/test' assert a.build('nested') == '/foo/' assert a.build('nestedbar') == '/foobar/' assert a.build('nested_show', {'testing': '1/2/3'}) == '/foo/1/2/3/' assert a.build('nested_edit', {'testing': '1/2/3'}) == '/foo/1/2/3/edit' assert a.build('users', {'page': 1}) == '/users/' assert a.build('users', {'page': 2}) == '/users/page/2' assert a.build('foox') == '/foox' assert a.build('barx_path_path', {'bar': '1', 'blub': '2/3'}) == '/1/2/3'
def __init__(self, cert_db, crtsh_checker): self.cert_db = cert_db self.crtsh_checker = crtsh_checker self.jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader( str(Path(__file__).parent.joinpath("templates"))), autoescape=True) self.url_map = routing.Map([ routing.Rule("/", methods=["GET"], endpoint=self.home), routing.Rule("/add-certificate/", methods=["POST"], endpoint=self.add_certificate), routing.Rule( "/create-batch/", methods=["GET", "POST"], endpoint=self.create_batch, ), routing.Rule( "/batches/", methods=["GET"], endpoint=self.list_batches, ), routing.Rule( "/batch/<batch_id>/", methods=["GET"], endpoint=self.batch, ), routing.Rule( "/cablint/", methods=["GET"], endpoint=self.cablint, ), routing.Rule( "/zlint/", methods=["GET"], endpoint=self.zlint, ), ])
def __init__(self, session_factory, jinja_environment): self._session_factory = session_factory self._jinja_environment = jinja_environment self._url_map = routing.Map([ routing.Rule('/', endpoint='list days', methods=['GET']), routing.Rule('/<date>/', endpoint='list times on day', methods=['GET']), routing.Rule('/<date>/<time>/', endpoint='list snapshots at time', methods=['GET']), routing.Rule('/<date>/<time>/<hostname>/<title>/', endpoint='snapshot', methods=['GET', 'PUT']), ]) self._endpoints = { 'list days': RequestHandler.list_days, 'list times on day': RequestHandler.list_times, 'list snapshots at time': RequestHandler.list_snapshots, 'snapshot': RequestHandler.view_or_add_snapshot, }
def test_basic_routing(): map = r.Map([ r.Rule('/', endpoint='index'), r.Rule('/foo', endpoint='foo'), r.Rule('/bar/', endpoint='bar') ]) adapter = map.bind('example.org', '/') assert adapter.match('/') == ('index', {}) assert adapter.match('/foo') == ('foo', {}) assert adapter.match('/bar/') == ('bar', {}) pytest.raises(r.RequestRedirect, lambda: adapter.match('/bar')) pytest.raises(r.NotFound, lambda: adapter.match('/blub')) adapter = map.bind('example.org', '/test') with pytest.raises(r.RequestRedirect) as excinfo: adapter.match('/bar') assert excinfo.value.new_url == 'http://example.org/test/bar/' adapter = map.bind('example.org', '/') with pytest.raises(r.RequestRedirect) as excinfo: adapter.match('/bar') assert excinfo.value.new_url == 'http://example.org/bar/' adapter = map.bind('example.org', '/') with pytest.raises(r.RequestRedirect) as excinfo: adapter.match('/bar', query_args={'aha': 'muhaha'}) assert excinfo.value.new_url == 'http://example.org/bar/?aha=muhaha' adapter = map.bind('example.org', '/') with pytest.raises(r.RequestRedirect) as excinfo: adapter.match('/bar', query_args='aha=muhaha') assert excinfo.value.new_url == 'http://example.org/bar/?aha=muhaha' adapter = map.bind_to_environ( create_environ('/bar?foo=bar', 'http://example.org/')) with pytest.raises(r.RequestRedirect) as excinfo: adapter.match() assert excinfo.value.new_url == 'http://example.org/bar/?foo=bar'
def __init__(self): self.routing_map = werkzeug_routing.Map() self.routing_map.add( werkzeug_routing.Rule("/", methods=["HEAD", "GET"], endpoint=EndpointWrapper( self._HandleHomepage))) self.routing_map.add( werkzeug_routing.Rule( "/api/<path:path>", methods=["HEAD", "GET", "POST", "PUT", "PATCH", "DELETE"], endpoint=EndpointWrapper(self._HandleApi))) self.routing_map.add( werkzeug_routing.Rule("/help/<path:path>", methods=["HEAD", "GET"], endpoint=EndpointWrapper(self._HandleHelp))) for v2_route in ["/v2", "/v2/", "/v2/<path:path>"]: self.routing_map.add( werkzeug_routing.Rule(v2_route, methods=["HEAD", "GET"], endpoint=EndpointWrapper( self._HandleHomepageV2)))