def test_child_route_creation(self): router = Router({ 'home': { 'path': '/' }, 'parent': { 'path': '/parent', 'children': { 'child_one': { 'path': '/child_one', 'children': { 'sub_child': { 'path': '/test' } } }, 'child_two': { 'path': '/child_two' } } } }) assert len(router) == 5 request = create_request_from_environ(sample_environ(PATH_INFO='/child_one')) matches = router.matches(request) assert len(matches) == 0 request = create_request_from_environ(sample_environ(PATH_INFO='/parent/child_one')) matches = router.matches(request) assert len(matches) == 1 assert router.assemble('parent/child_one/sub_child') == '/parent/child_one/test'
def test_mandatory_segment_match(self): route = Route("search", path='/search/:keyword') invalid_request = create_request_from_environ(sample_environ(PATH_INFO='/searching')) valid_request_no_param = create_request_from_environ(sample_environ(PATH_INFO='/search')) valid_request_with_param = create_request_from_environ(sample_environ(PATH_INFO='/search/test')) assert not route.match(invalid_request).matched assert not route.match(valid_request_no_param).matched assert route.match(valid_request_with_param).matched
def test_accept_method_match(self): valid_request = create_request_from_environ( sample_environ(PATH_INFO='/test', REQUEST_METHOD='POST')) invalid_request = create_request_from_environ( sample_environ(PATH_INFO='/test', REQUEST_METHOD='GET')) route = Route(name='test', path='/test', accepts=('POST',)) assert route.match(valid_request) assert not route.match(invalid_request)
def test_static_match(self): route = Route(name='home', path='/') invalid_request = create_request_from_environ( sample_environ(PATH_INFO='/test')) valid_request = create_request_from_environ( sample_environ(PATH_INFO='/')) assert not route.match(invalid_request) assert route.match(valid_request)
def test_subdomain_match(self): valid_request = create_request_from_environ( sample_environ(PATH_INFO='/test', SERVER_NAME='clients.test.com')) invalid_request = create_request_from_environ( sample_environ(PATH_INFO='/test', SERVER_NAME='clients2.test.com')) route = Route(name='test', path='/test', subdomain='clients') assert route.match(valid_request) assert not route.match(invalid_request)
def test_format_match(self): valid_request = create_request_from_environ(sample_environ(PATH_INFO='/dump', HTTP_ACCEPT='application/json')) invalid_request = create_request_from_environ(sample_environ(PATH_INFO='/dump', HTTP_ACCEPT='application/xml')) valid_request_segment = create_request_from_environ(sample_environ(PATH_INFO='/dump.json')) route = Route(name='json', path='/dump', requires={'format': 'json'}) route_format = Route(name='json', path='/dump.:format', requires={'format': 'json'}) assert route.match(valid_request).matched assert not route.match(invalid_request).matched assert route_format.match(valid_request_segment).matched
def test_optional_segment_with_defaults(self): route = Route(name="search", path='/search[/:keyword]', defaults={'keyword': 'blah'}) invalid_request = create_request_from_environ(sample_environ(PATH_INFO='/searching')) valid_request = create_request_from_environ(sample_environ(PATH_INFO='/search')) valid_request_with_param = create_request_from_environ(sample_environ(PATH_INFO='/search/test')) valid_request_with_default = route.match(valid_request) assert not route.match(invalid_request).matched assert valid_request_with_default.matched assert valid_request_with_default.params == {'keyword': 'blah'} assert route.match(valid_request_with_param).matched
def test_optional_segment_match(self): route = Route(name="search", path='/search[/:keyword]') invalid_request = create_request_from_environ( sample_environ(PATH_INFO='/searching')) valid_request = create_request_from_environ( sample_environ(PATH_INFO='/search')) valid_request_with_param = create_request_from_environ( sample_environ(PATH_INFO='/search/test')) assert not route.match(invalid_request) assert route.match(valid_request) assert route.match(valid_request_with_param)
def test_optional_segment_with_required(self): route = Route( name="search", path='/search[/:keyword]', requires={'keyword': 'blah'}) valid_request = create_request_from_environ( sample_environ(PATH_INFO='/search/blah')) invalid_request = create_request_from_environ( sample_environ(PATH_INFO='/search/test')) assert not route.match(invalid_request) assert route.match(valid_request)
def test_requires_get_variables(self): route = Route(name='test', path='/', requires={'test': '.*'}) request = create_request_from_environ(sample_environ( PATH_INFO='/', QUERY_STRING='test=blah&something=test')) match = route.match(request) assert match request = create_request_from_environ(sample_environ( PATH_INFO='/', QUERY_STRING='tesst=blah')) match = route.match(request) assert not match
def test_is_secure(self): environ = sample_environ(HTTPS='HTTPS') environ['wsgi.url_scheme'] = 'https' request = create_request_from_environ(environ) assert str( request) == 'GET https://127.0.0.1:80/ HTTP/1.1\r\nHost: 127.0.0.1\r\nHttps: HTTPS\r\n\r\n' assert request.is_secure()
def run(self, environ, start_response): request = create_request_from_environ(environ, self.config['session']['class'], self.config['session'].get('options')) try: route_result = self.dispatcher.trigger(Event(events.ROUTE_MATCH, target=self, params={ 'request': request, 'router': self.container.get('router') })) route_match = route_result.first() except ApplicationError as exc: route_match = None response, view_model = self.__raise_exception_event(exception=exc, request=request) if route_match: try: dispatch_event = Event(events.DISPATCH_EXECUTE, target=self, params={ 'route_match': route_match, 'request': request, 'container': self.container }) dispatch_result = self.dispatcher.trigger(dispatch_event) response = dispatch_event.params['controller_class'].response view_model = dispatch_result.first() except ApplicationError as exc: response, view_model = self.__raise_exception_event(exception=exc, request=request, route_match=route_match) if not isinstance(view_model, Response): try: self.__render(request=request, response=response, view_model=view_model) except ApplicationError as exc: response, view_model = self.__raise_exception_event(exception=exc, request=request, route_match=route_match) self.__render(request=request, response=response, view_model=view_model) start_response(*response.start()) return [response()]
def execute(self): try: router = self.container.get('router') if not router.routes: raise ConsoleError('There are no routes associated with the application.') if self.parsed_args.url: environ = {} util.setup_testing_defaults(environ) environ.update({ 'REQUEST_METHOD': self.parsed_args.method or 'GET', 'HTTP_ACCEPT': self.parsed_args.format or 'text/html', 'PATH_INFO': self.parsed_args.url, 'SERVER_NAME': self.parsed_args.server or '127.0.0.1' }) request = create_request_from_environ(environ) matches = router.matches(request) if matches: sys.stdout.write(colors.header('Displaying {0} matching routes for the application:\n'.format(len(matches)))) for match in matches: sys.stdout.write('{0}\t\t\{1}\t\t{2}\n'.format(colors.ok_green(match.route.name), match.route.path, match.route.regex.pattern)) else: raise ConsoleError('There are no matching routes.') else: sys.stdout.write(colors.header('Displaying {0} routes for the application:\n'.format(len(router)))) for name, route in router: sys.stdout.write('{0}\t\t{1}\n'.format(name, route.path)) except ConsoleError: raise except: _no_application_error()
def setup(self): environ = sample_environ(HTTP_COOKIE='watson.session=123456;', REQUEST_METHOD='POST') environ['wsgi.input'] = BufferedReader( BytesIO(b'form_csrf_token=123456&test=blah')) self.request = create_request_from_environ( environ, 'watson.http.sessions.Memory')
def test_create_put_from_environ(self): environ = sample_environ(REQUEST_METHOD='POST') environ['wsgi.input'] = BufferedReader( BytesIO(b'HTTP_REQUEST_METHOD=PUT')) request = create_request_from_environ(environ) assert request.post['HTTP_REQUEST_METHOD'] == 'PUT' assert request.is_method('PUT')
def create_event(self, **kwargs): router = Router({"home": {"path": "/"}}) environ = {} util.setup_testing_defaults(environ) environ.update(**kwargs) event = Event("TestEvent", params={"router": router, "request": create_request_from_environ(environ)}) return event
def test_create_mutable(self): environ = sample_environ() environ['REQUEST_METHOD'] = 'POST' environ['wsgi.input'] = BufferedReader(BytesIO(b'HTTP_REQUEST_METHOD=PUT')) request = create_request_from_environ(environ) new_request = copy(request) assert isinstance(request.post, ImmutableMultiDict) assert isinstance(new_request.post, MultiDict)
def simple_request_response(environ, start_response): setup_testing_defaults(environ) request = create_request_from_environ(environ) response = Response(200, body='Hello World!') start_response(*response.start()) return [response()]
def setup(self): environ = sample_environ( HTTP_COOKIE='watson.session=123456;', REQUEST_METHOD='POST') environ['wsgi.input'] = BufferedReader( BytesIO(b'form_csrf_token=123456&test=blah')) self.request = create_request_from_environ( environ, 'watson.http.sessions.Memory')
def simple_request_response(environ, start_response): setup_testing_defaults(environ) request = create_request_from_environ(environ) response = Response(200, body="Hello World!") start_response(*response.start()) return [response()]
def test_session_from_https_request(self): environ = sample_environ(HTTPS='HTTPS') request = create_request_from_environ(environ) assert request.is_secure() request.session_to_cookie() cookie = request.cookies[sessions.COOKIE_KEY] assert cookie['httponly'] assert cookie['secure']
def test_create_mutable(self): environ = sample_environ() environ['REQUEST_METHOD'] = 'POST' environ['wsgi.input'] = BufferedReader( BytesIO(b'HTTP_REQUEST_METHOD=PUT')) request = create_request_from_environ(environ) new_request = copy(request) assert isinstance(request.post, ImmutableMultiDict) assert isinstance(new_request.post, MultiDict)
def create_event(self, **kwargs): router = Router({'home': {'path': '/'}}) environ = {} util.setup_testing_defaults(environ) environ.update(**kwargs) event = Event( 'TestEvent', params={'router': router, 'request': create_request_from_environ(environ)}) return event
def test_short_circuit(self): environ = sample_environ() route = Route("test", path="/", defaults={"controller": "tests.watson.mvc.support.ShortCircuitedController"}) match = RouteMatch(route, {"controller": "tests.watson.mvc.support.ShortCircuitedController"}, True) event = Event( "something", params={"route_match": match, "container": IocContainer(), "request": create_request_from_environ(environ)}, ) listener = listeners.DispatchExecute({"404": "page/404"}) response = listener(event) assert isinstance(response, Response)
def create_event(self, **kwargs): router = Router({'home': {'path': '/'}}) environ = {} util.setup_testing_defaults(environ) environ.update(**kwargs) event = Event('TestEvent', params={ 'router': router, 'request': create_request_from_environ(environ) }) return event
def run(self, environ, start_response): request = create_request_from_environ( environ, self.config['session']['class'], self.config['session'].get('options')) try: route_result = self.dispatcher.trigger( Event(events.ROUTE_MATCH, target=self, params={ 'request': request, 'router': self.container.get('router') })) route_match = route_result.first() except ApplicationError as exc: route_match = None response, view_model = self.__raise_exception_event( exception=exc, request=request) if route_match: try: dispatch_event = Event(events.DISPATCH_EXECUTE, target=self, params={ 'route_match': route_match, 'request': request, 'container': self.container }) dispatch_result = self.dispatcher.trigger(dispatch_event) response = dispatch_event.params['controller_class'].response view_model = dispatch_result.first() except ApplicationError as exc: response, view_model = self.__raise_exception_event( exception=exc, request=request, route_match=route_match) if not isinstance(view_model, Response): try: self.__render(request=request, response=response, view_model=view_model) except ApplicationError as exc: response, view_model = self.__raise_exception_event( exception=exc, request=request, route_match=route_match) self.__render(request=request, response=response, view_model=view_model) start_response(*response.start()) self.dispatcher.trigger( Event(events.COMPLETE, target=self, params={'container': self.container})) return [response()]
def test_post_redirect_get(self): base = controllers.HttpMixin() router = Router({'test': {'path': '/test'}}) environ = sample_environ(PATH_INFO='/', REQUEST_METHOD='POST') environ['wsgi.input'] = BufferedReader(BytesIO(b'post_var_one=test&post_var_two=blah')) base.request = create_request_from_environ(environ, 'watson.http.sessions.Memory') base.container = Mock() base.container.get.return_value = router response = base.redirect('test') assert response.status_code == 303 assert base.redirect_vars == base.request.session['post_redirect_get'] base.clear_redirect_vars() assert not base.redirect_vars base.redirect('test', clear=True) assert not base.redirect_vars
def test_short_circuit(self): environ = sample_environ() route = Route( 'test', path='/', options={'controller': 'tests.watson.mvc.support.ShortCircuitedController'}) match = RouteMatch( route, {'controller': 'tests.watson.mvc.support.ShortCircuitedController'}) event = Event( 'something', params={'route_match': match, 'container': IocContainer(), 'request': create_request_from_environ(environ)}) listener = listeners.DispatchExecute({'404': 'page/404'}) response = listener(event) assert isinstance(response, Response)
def execute(self): try: router = self.container.get('router') if not router.routes: raise ConsoleError( 'There are no routes associated with the application.') if self.parsed_args.url: environ = {} util.setup_testing_defaults(environ) environ.update({ 'REQUEST_METHOD': self.parsed_args.method or 'GET', 'HTTP_ACCEPT': self.parsed_args.format or 'text/html', 'PATH_INFO': self.parsed_args.url, 'SERVER_NAME': self.parsed_args.server or '127.0.0.1' }) request = create_request_from_environ(environ) matches = router.matches(request) if matches: sys.stdout.write( colors.header( 'Displaying {0} matching routes for the application:\n' .format(len(matches)))) for match in matches: sys.stdout.write('{0}\t\t\{1}\t\t{2}\n'.format( colors.ok_green(match.route.name), match.route.path, match.route.regex.pattern)) else: raise ConsoleError('There are no matching routes.') else: sys.stdout.write( colors.header( 'Displaying {0} routes for the application:\n'.format( len(router)))) for name, route in router: sys.stdout.write('{0}\t\t{1}\n'.format(name, route.path)) except ConsoleError: raise except: _no_application_error()
def test_redirect(self): base = controllers.HttpMixin() router = Router({ 'test': { 'path': '/test', }, 'segment': { 'path': '/segment[/:part]', 'type': 'segment', 'defaults': {'part': 'test'} } }) base.request = create_request_from_environ(sample_environ()) base.container = Mock() base.container.get.return_value = router response = base.redirect('/test') assert response.headers['location'] == '/test' response = base.redirect('segment') assert response.headers['location'] == '/segment/test' assert response.status_code == 302
def test_short_circuit(self): environ = sample_environ() route = Route('test', path='/', options={ 'controller': 'tests.watson.mvc.support.ShortCircuitedController' }) match = RouteMatch(route, { 'controller': 'tests.watson.mvc.support.ShortCircuitedController' }) event = Event('something', params={ 'route_match': match, 'container': IocContainer(), 'request': create_request_from_environ(environ) }) listener = listeners.DispatchExecute({'404': 'page/404'}) response = listener(event) assert isinstance(response, Response)
def test_sort_routes(self): router = Router({ 'home': { 'path': '/' }, 'test': { 'path': '/' }, 'highest': { 'path': '/', 'priority': 1000 }, 'lowest': { 'path': '/', 'priority': -1 } }) request = create_request_from_environ(sample_environ(PATH_INFO='/')) matches = router.matches(request) assert matches[0].route.name == 'highest' assert matches[3].route.name == 'lowest'
def setup(self): self.protected_form = has_csrf(UnprotectedForm) environ = sample_environ(REQUEST_METHOD='POST') environ['wsgi.input'] = BufferedReader(BytesIO(b'test=blah')) self.request = create_request_from_environ( environ, 'watson.http.sessions.Memory')
def test_cookies(self): environ = sample_environ(HTTP_COOKIE='test=something;') request = create_request_from_environ(environ) assert request.cookies['test'].value == 'something'
def test_session(self): environ = sample_environ(HTTP_COOKIE='watson.session=123456;') request = create_request_from_environ( environ, 'watson.http.sessions.Memory') assert request.session.id == '123456' assert isinstance(request.session, sessions.Memory)
def test_repr(self): environ = sample_environ() assert repr(create_request_from_environ(environ) ) == '<watson.http.messages.Request method:GET url:http://127.0.0.1/>'
def test_session_from_request(self): environ = sample_environ(HTTP_COOKIE='watson.session=12345') request = create_request_from_environ(environ) assert isinstance(request.session, sessions.File) assert isinstance(request, sessions.SessionMixin)
def setup(self): self.protected_form = has_csrf(UnprotectedForm) environ = sample_environ(REQUEST_METHOD='POST') environ['wsgi.input'] = BufferedReader(BytesIO(b'test=blah')) self.request = create_request_from_environ(environ, 'watson.http.sessions.Memory')
def test_create_from_environ(self): environ = sample_environ() request = create_request_from_environ(environ) assert request.method == 'GET' assert request.is_method('GET')
def test_repr(self): environ = sample_environ() assert repr( create_request_from_environ(environ) ) == '<watson.http.messages.Request method:GET url:http://127.0.0.1/>'
def test_get_vars(self): environ = sample_environ( QUERY_STRING='blah=something&someget=test&arr[]=a&arr[]=b') request = create_request_from_environ(environ) assert request.get['blah'] == 'something'
def test_is_xml_http_request(self): environ = sample_environ(HTTP_X_REQUESTED_WITH='XmlHttpRequest') request = create_request_from_environ(environ) assert request.is_xml_http_request()
def test_session(self): environ = sample_environ(HTTP_COOKIE='watson.session=123456;') request = create_request_from_environ(environ, 'watson.http.sessions.Memory') assert request.session.id == '123456' assert isinstance(request.session, sessions.Memory)
def test_server(self): environ = sample_environ() request = create_request_from_environ(environ) assert request.server['PATH_INFO'] == '/'
def test_host(self): environ = sample_environ(HTTP_X_FORWARDED_FOR='10.11.12.13') request = create_request_from_environ(environ) assert request.host() == '10.11.12.13'