Example #1
0
def test_validate_arguments():
    take_none = lambda: None
    take_two = lambda a, b: None
    take_two_one_default = lambda a, b=0: None

    assert utils.validate_arguments(take_two, (
        1,
        2,
    ), {}) == ((1, 2), {})
    assert utils.validate_arguments(take_two, (1, ), {'b': 2}) == ((1, 2), {})
    assert utils.validate_arguments(take_two_one_default, (1, ),
                                    {}) == ((1, 0), {})
    assert utils.validate_arguments(take_two_one_default, (1, 2),
                                    {}) == ((1, 2), {})

    pytest.raises(utils.ArgumentValidationError, utils.validate_arguments,
                  take_two, (), {})

    assert utils.validate_arguments(take_none, (
        1,
        2,
    ), {'c': 3}) == ((), {})
    pytest.raises(utils.ArgumentValidationError,
                  utils.validate_arguments,
                  take_none, (1, ), {},
                  drop_extra=False)
    pytest.raises(utils.ArgumentValidationError,
                  utils.validate_arguments,
                  take_none, (), {'a': 1},
                  drop_extra=False)
Example #2
0
    def test_validate_arguments(self):
        take_none = lambda: None
        take_two = lambda a, b: None
        take_two_one_default = lambda a, b=0: None

        self.assert_equal(utils.validate_arguments(take_two, (
            1,
            2,
        ), {}), ((1, 2), {}))
        self.assert_equal(utils.validate_arguments(take_two, (1, ), {'b': 2}),
                          ((1, 2), {}))
        self.assert_equal(
            utils.validate_arguments(take_two_one_default, (1, ), {}),
            ((1, 0), {}))
        self.assert_equal(
            utils.validate_arguments(take_two_one_default, (1, 2), {}),
            ((1, 2), {}))

        self.assert_raises(utils.ArgumentValidationError,
                           utils.validate_arguments, take_two, (), {})

        self.assert_equal(
            utils.validate_arguments(take_none, (
                1,
                2,
            ), {'c': 3}), ((), {}))
        self.assert_raises(utils.ArgumentValidationError,
                           utils.validate_arguments,
                           take_none, (1, ), {},
                           drop_extra=False)
        self.assert_raises(utils.ArgumentValidationError,
                           utils.validate_arguments,
                           take_none, (), {'a': 1},
                           drop_extra=False)
Example #3
0
def test_validate_arguments():
    take_none = lambda: None
    take_two = lambda a, b: None
    take_two_one_default = lambda a, b=0: None

    assert utils.validate_arguments(take_two, (1, 2), {}) == ((1, 2), {})
    assert utils.validate_arguments(take_two, (1,), {"b": 2}) == ((1, 2), {})
    assert utils.validate_arguments(take_two_one_default, (1,), {}) == ((1, 0), {})
    assert utils.validate_arguments(take_two_one_default, (1, 2), {}) == ((1, 2), {})

    pytest.raises(utils.ArgumentValidationError, utils.validate_arguments, take_two, (), {})

    assert utils.validate_arguments(take_none, (1, 2), {"c": 3}) == ((), {})
    pytest.raises(utils.ArgumentValidationError, utils.validate_arguments, take_none, (1,), {}, drop_extra=False)
    pytest.raises(utils.ArgumentValidationError, utils.validate_arguments, take_none, (), {"a": 1}, drop_extra=False)
Example #4
0
File: web.py Project: sacherjj/keg
def _call_with_expected_args(view, calling_args, method, method_is_bound=True):
    """ handle argument conversion to what the method accepts """
    if isinstance(method, six.string_types):
        if not hasattr(view, method):
            return
        method = getattr(view, method)

    try:
        # validate_arguments is made for a function, not a class method
        # so we need to "trick" it by sending self here, but then
        # removing it before the bound method is called below
        pos_args = (view, ) if method_is_bound else tuple()
        args, kwargs = validate_arguments(method, pos_args,
                                          calling_args.copy())
    except ArgumentValidationError as e:
        msg = 'Argument mismatch occured: method=%s, missing=%s, extra_keys=%s, extra_pos=%s.' \
              '  Arguments available: %s' % (method, e.missing, e.extra, e.extra_positional,
                                             calling_args)
        raise ViewArgumentError(msg)
        # used to raise a BadRequest here, but after deliberation, it seems likely this is only
        # going to happen b/c of programmer error.  Therefore, just propogate the exception.
        raise
    if method_is_bound:
        # remove "self" from args since its a bound method
        args = args[1:]
    return method(*args, **kwargs)
Example #5
0
def configurator(scanner, name, ob):
    """Generic decorator for configuring the scanning application. The
    decorated function is called with the scan parameters listed in the
    signature (which can include the implicit `application`)."""
    params = vars(scanner).copy()
    args, kwargs = validate_arguments(ob, (), params)
    ob(*args, **kwargs)
Example #6
0
def _call_with_expected_args(view, calling_args, method, method_is_bound=True):
    """ handle argument conversion to what the method accepts """
    if isinstance(method, six.string_types):
        if not hasattr(view, method):
            return
        method = getattr(view, method)

    try:
        # validate_arguments is made for a function, not a class method
        # so we need to "trick" it by sending self here, but then
        # removing it before the bound method is called below
        pos_args = (view,) if method_is_bound else tuple()
        args, kwargs = validate_arguments(method, pos_args, calling_args.copy())
    except ArgumentValidationError as e:
        msg = 'Argument mismatch occured: method=%s, missing=%s, extra_keys=%s, extra_pos=%s.' \
              '  Arguments available: %s' % (method, e.missing, e.extra, e.extra_positional,
                                             calling_args)
        raise ViewArgumentError(msg)
        # used to raise a BadRequest here, but after deliberation, it seems likely this is only
        # going to happen b/c of programmer error.  Therefore, just propogate the exception.
        raise
    if method_is_bound:
        # remove "self" from args since its a bound method
        args = args[1:]
    return method(*args, **kwargs)
Example #7
0
    def test_validate_arguments(self):
        take_none = lambda: None
        take_two = lambda a, b: None
        take_two_one_default = lambda a, b=0: None

        assert utils.validate_arguments(take_two, (1, 2,), {}) == ((1, 2), {})
        assert utils.validate_arguments(take_two, (1,), {'b': 2}) == ((1, 2), {})
        assert utils.validate_arguments(take_two_one_default, (1,), {}) == ((1, 0), {})
        assert utils.validate_arguments(take_two_one_default, (1, 2), {}) == ((1, 2), {})

        self.assert_raises(utils.ArgumentValidationError,
                           utils.validate_arguments, take_two, (), {})

        assert utils.validate_arguments(take_none, (1, 2,), {'c': 3}) == ((), {})
        self.assert_raises(utils.ArgumentValidationError,
                           utils.validate_arguments, take_none, (1,), {}, drop_extra=False)
        self.assert_raises(utils.ArgumentValidationError,
                           utils.validate_arguments, take_none, (), {'a': 1}, drop_extra=False)
Example #8
0
def adv_validate_arguments(callback, args, kwargs):
    """
    "Advanced version" of Werkzeug's "validate_arguments" which doesn't modify
    passed args and kwargs

    :return: (args, kwargs) to pass to original function
    """
    bind_args = list(args)
    bind_kwargs = {ensure_unicode(k): v for k, v in kwargs.items()}
    arguments, keyword_arguments = validate_arguments(callback, bind_args, bind_kwargs)
    return arguments, keyword_arguments
Example #9
0
def test_validate_arguments():
    def take_none():
        pass

    def take_two(a, b):
        pass

    def take_two_one_default(a, b=0):
        pass

    assert utils.validate_arguments(take_two, (1, 2), {}) == ((1, 2), {})
    assert utils.validate_arguments(take_two, (1, ), {"b": 2}) == ((1, 2), {})
    assert utils.validate_arguments(take_two_one_default, (1, ),
                                    {}) == ((1, 0), {})
    assert utils.validate_arguments(take_two_one_default, (1, 2),
                                    {}) == ((1, 2), {})

    pytest.raises(utils.ArgumentValidationError, utils.validate_arguments,
                  take_two, (), {})

    assert utils.validate_arguments(take_none, (1, 2), {"c": 3}) == ((), {})
    pytest.raises(
        utils.ArgumentValidationError,
        utils.validate_arguments,
        take_none,
        (1, ),
        {},
        drop_extra=False,
    )
    pytest.raises(
        utils.ArgumentValidationError,
        utils.validate_arguments,
        take_none,
        (),
        {"a": 1},
        drop_extra=False,
    )
Example #10
0
def test_validate_arguments():
    def take_none():
        pass

    def take_two(a, b):
        pass

    def take_two_one_default(a, b=0):
        pass

    assert utils.validate_arguments(take_two, (1, 2), {}) == ((1, 2), {})
    assert utils.validate_arguments(take_two, (1,), {"b": 2}) == ((1, 2), {})
    assert utils.validate_arguments(take_two_one_default, (1,), {}) == ((1, 0), {})
    assert utils.validate_arguments(take_two_one_default, (1, 2), {}) == ((1, 2), {})

    pytest.raises(
        utils.ArgumentValidationError, utils.validate_arguments, take_two, (), {}
    )

    assert utils.validate_arguments(take_none, (1, 2), {"c": 3}) == ((), {})
    pytest.raises(
        utils.ArgumentValidationError,
        utils.validate_arguments,
        take_none,
        (1,),
        {},
        drop_extra=False,
    )
    pytest.raises(
        utils.ArgumentValidationError,
        utils.validate_arguments,
        take_none,
        (),
        {"a": 1},
        drop_extra=False,
    )
Example #11
0
def adv_validate_arguments(callback, args, kwargs):
    """
    "Advanced version" of Werkzeug's "validate_arguments".
    - Knows how to handle object methods
    - Doesn't modify passed args and kwargs
    :return: (args, kwargs) to pass to original function
    """
    bind_args = list(args)
    bind_kwargs = kwargs.copy()
    if hasattr(callback, 'im_self'):
        bind_args.insert(0, callback.im_self)
    arguments, keyword_arguments = validate_arguments(callback, bind_args,
                                                      bind_kwargs)
    if hasattr(callback, 'im_self'):
        arguments = arguments[1:]
    return arguments, keyword_arguments
Example #12
0
    def handle_request(self, request, wrapper_args):
        """
        Dispatch a request to a resource.
        
        See :py:meth:`AbstractResource.handle_request` for accepted
        parameters.
        
        """
        method = request.method.upper()
        try:
            model = self.compose_model(wrapper_args)
            handler = self._extract_handler(request, method, model)

            args, kwargs = validate_arguments(handler.func, handler.args, wrapper_args)
            return handler.func(*args, **kwargs)
            
        except BaseException as err:
            return self.error_handler(err)
Example #13
0
 def _call_with_expected_args(self, method, method_is_bound=True):
     log.debug('calling w/ expected: %s %s' % (method, self.calling_args))
     """ handle argument conversion to what the method accepts """
     try:
         # validate_arguments is made for a function, not a class method
         # so we need to "trick" it by sending self here, but then
         # removing it before the bound method is called below
         pos_args = (self,) if method_is_bound else tuple()
         args, kwargs = validate_arguments(method, pos_args, self.calling_args.copy())
     except ArgumentValidationError as e:
         log.error('arg validation failed: %s, %s, %s, %s',
                   method, e.missing, e.extra, e.extra_positional)
         raise BadRequest('The browser failed to transmit all '
                          'the data expected.')
     if method_is_bound:
         # remove "self" from args since its a bound method
         args = args[1:]
     return method(*args, **kwargs)
Example #14
0
    def _exec_function(self, method_name, data, method_opts, debug=False):
        """
        Execute a function by method name, pickle-encoded data and method options

        :param method_name: the string with a method name
        :param data: pickle-loaded data with arguments and result id
        :param method_opts: the dictionary which for every method name contains
            function object and a cache key (if defined)
        """
        args, kwargs, result_id = pickle.loads(data)
        func = method_opts['function']

        # check the cache first (just in case)
        result = self._check_cache(method_name, method_opts, args, kwargs)
        if result is unset:

            # nothing is found? execute the function
            # the result is a list [function_result, exception]
            try:
                e_args, e_kwargs = validate_arguments(func, args[:], kwargs.copy())
                call_result = func(*e_args, **e_kwargs)
                result = [call_result, None]
            except Exception as e:
                tb = traceback.format_exc()
                print(tb)
                result = [None, e]
                if debug:
                    pdb.post_mortem()

            # cache the result if it should be cached
            redis_cache_key = self._get_redis_cache_key(method_name, method_opts, args, kwargs)
            if redis_cache_key is not None:
                self.r.set(redis_cache_key, pickle.dumps(result))
                if self.cache_expire is not None:
                    self.r.expire(redis_cache_key, self.cache_expire)

        # store the result where we were asked
        result_key = self._k('results', result_id)
        self.r.rpush(result_key, pickle.dumps(result))
        if self.result_expire is not None:
            self.r.expire(result_key, self.result_expire)