Пример #1
0
    def test_callback_inspection(self):
        def x(a, b):
            pass

        def d(f):
            def w():
                return f()

            return w

        route = bottle.Route(bottle.Bottle(), None, None, d(x))
        self.assertEqual(route.get_undecorated_callback(), x)
        self.assertEqual(set(route.get_callback_args()), set(['a', 'b']))

        def d2(foo):
            def d(f):
                def w():
                    return f()

                return w

            return d

        route = bottle.Route(bottle.Bottle(), None, None, d2('foo')(x))
        self.assertEqual(route.get_undecorated_callback(), x)
        self.assertEqual(set(route.get_callback_args()), set(['a', 'b']))
Пример #2
0
 def test_expired_session(self):
     """Test that the session is invalid when it's expired."""
     self.mock_database.sessions.find_one.return_value = dict(
         session_expiration_datetime=datetime.min.replace(
             tzinfo=timezone.utc))
     route = bottle.Route(bottle.app(), "/", "POST", self.route)
     self.assertRaises(bottle.HTTPError, route.call)
Пример #3
0
 def test_valid_session(self):
     """Test that session ids are authenticated."""
     self.mock_database.sessions.find_one.return_value = dict(
         session_expiration_datetime=datetime.max.replace(
             tzinfo=timezone.utc))
     route = bottle.Route(bottle.app(), "/", "POST", self.route)
     self.assertEqual(self.success, route.call())
Пример #4
0
    def test_callback_inspection_multiple_args(self):
        # decorator with argument, modifying kwargs
        def d2(f="1"):
            def d(fn):
                def w(*args, **kwargs):
                    # modification of kwargs WITH the decorator argument
                    # is necessary requirement for the error
                    kwargs["a"] = f
                    return fn(*args, **kwargs)

                return w

            return d

        @d2(f='foo')
        def x(a, b):
            return

        route = bottle.Route(bottle.Bottle(), None, None, x)

        # triggers the "TypeError: 'foo' is not a Python function"
        self.assertEqual(set(route.get_callback_args()), set(['a', 'b']))

        def test_callback_inspection_newsig(self):
            env = {}
            eval(compile('def foo(a, *, b=5): pass', '<foo>', 'exec'), env,
                 env)
            route = bottle.Route(bottle.Bottle(), None, None, env['foo'])
            self.assertEqual(set(route.get_callback_args()), set(['a', 'b']))
    def test_apply_plugin_to_route_that_does_not_take_keyword(self):
        """Test that the plugin can be applied to a route."""
        def route():
            return "route"

        bottle.install(InjectionPlugin("value", "keyword"))
        route = bottle.Route(bottle.app(), "/", "GET", route)
        self.assertEqual("route", route.call())
    def test_apply_plugin(self):
        """Test that the plugin can be applied to a route."""
        def route(keyword):
            return keyword

        bottle.install(InjectionPlugin("value", "keyword"))
        route = bottle.Route(bottle.app(), "/", "GET", route)
        self.assertEqual("value", route.call())
Пример #7
0
 def test_apply_to_get_route(self):
     """Test that session ids are not authenticated with non-post routes."""
     database_mock = Mock()
     database_mock.sessions.find_one.return_value = None
     bottle.install(InjectionPlugin(database_mock, "database"))
     bottle.install(AuthenticationPlugin())
     route = bottle.Route(bottle.app(), "/", "GET", self.route)
     self.assertEqual("route called", route.call())
Пример #8
0
 def test_apply_invalid_session(self):
     """Test that session ids are authenticated."""
     database_mock = Mock()
     database_mock.sessions.find_one.return_value = None
     bottle.install(InjectionPlugin(database_mock, "database"))
     bottle.install(AuthenticationPlugin())
     route = bottle.Route(bottle.app(), "/", "POST", self.route)
     with patch("logging.warning", Mock()):  # Suppress logging
         self.assertEqual(dict(ok=False), route.call())
Пример #9
0
    def __register(self, app, method):
        rule = method.__route__
        elle.log.debug('%s: register route %s' % (app, rule))
        # Introspect method.
        if hasattr(method.__underlying_method__, '__fullargspec__'):
            spec = method.__underlying_method__.__fullargspec__
        else:
            spec = inspect.getfullargspec(method.__underlying_method__)
            del spec.args[0]  # remove self
        import itertools
        defaults = spec.defaults or []
        spec_args = dict(
            (name, default) for name, default in itertools.zip_longest(
                reversed(spec.args), reversed([True] * len(defaults))))
        for arg in re.findall('<(\\w*)(?::\\w*(?::[^>]*)?)?>', rule):
            if arg in spec_args:
                del spec_args[arg]
            elif spec.varkw is None:
                raise AssertionError(
                    'Rule %r yields %r but %r does not accept it' %
                    (rule, arg, method))
        # Callback.
        def callback(*args, **kwargs):
            arguments = dict(spec_args)

            def explode(d):
                if d is None:
                    return
                for key in dict(arguments):
                    if key in d:
                        kwargs[key] = d[key]
                        del d[key]
                        del arguments[key]
                if len(d) > 0:
                    if spec.varkw is not None:
                        kwargs.update(d)
                    else:
                        key = iter(d.keys()).__next__()
                        app.bad_request('unexpected JSON keys: %r' % key)

            try:
                explode(bottle.request.json)
            except ValueError:
                app.bad_request('invalid JSON')
            explode(bottle.request.query)
            for argument, default in arguments.items():
                if not default:
                    app.bad_request('missing argument: %r' % argument)
            return method(app, *args, **kwargs)

        # Add route.
        route = bottle.Route(app=app,
                             rule=rule,
                             method=method.__method__,
                             callback=callback)
        app.add_route(route)
Пример #10
0
 def test_unauthorized_sessions(self):
     """Test that an unauthorized session is invalid."""
     self.mock_database.reports_overviews.find_one.return_value = dict(
         _id="id", editors=["jodoe"])
     self.mock_database.sessions.find_one.return_value = dict(
         user="******",
         email="*****@*****.**",
         session_expiration_datetime=datetime.max)
     route = bottle.Route(bottle.app(), "/", "POST", self.route)
     self.assertRaises(bottle.HTTPError, route.call)
Пример #11
0
    def test_callback_inspection_multiple_args(self):
        # decorator with argument, modifying kwargs
        def d2(f="1"):
            def d(fn):
                def w(*args, **kwargs):
                    # modification of kwargs WITH the decorator argument
                    # is necessary requirement for the error
                    kwargs["a"] = f
                    return fn(*args, **kwargs)
                return w
            return d

        @d2(f='foo')
        def x(a, b):
            return

        route = bottle.Route(None, None, None, x)

        # triggers the "TypeError: 'foo' is not a Python function"
        self.assertEqual(set(route.get_callback_args()), set(['a', 'b']))
Пример #12
0
 def test_callback_inspection_newsig(self):
     env = {}
     eval(compile('def foo(a, *, b=5): pass', '<foo>', 'exec'), env, env)
     route = bottle.Route(None, None, None, env['foo'])
     self.assertEqual(set(route.get_callback_args()), set(['a', 'b']))
Пример #13
0
 def test_http_get_routes(self):
     """Test that session ids are not authenticated with non-post routes."""
     self.mock_database.sessions.find_one.return_value = None
     route = bottle.Route(bottle.app(), "/", "GET", self.route)
     self.assertEqual(self.success, route.call())
Пример #14
0
 def test_missing_session(self):
     """Test that the session is invalid when it's missing."""
     self.mock_database.sessions.find_one.return_value = None
     route = bottle.Route(bottle.app(), "/", "POST", self.route)
     self.assertRaises(bottle.HTTPError, route.call)
Пример #15
0
 def test_apply_valid_session(self):
     """Test that session ids are authenticated."""
     bottle.install(InjectionPlugin(Mock(), "database"))
     bottle.install(AuthenticationPlugin())
     route = bottle.Route(bottle.app(), "/", "POST", self.route)
     self.assertEqual("route called", route.call())