Home:ALL Converter>python testing a decorated decorator through a mock

python testing a decorated decorator through a mock

Ask Time:2012-11-13T19:10:05         Author:Rmatt

Json Formatter

This question is a follow-up to this brilliant answer on decorators in Python :

I use the given "snippet to make any decorator accept generically any argument".

Then I have this (here simplified) decorator:

@decorator_with_args
def has_permission_from_kwarg(func, *args, **kwargs):
    """Decorator to check simple access/view rights by the kwarg."""
    def wrapper(*args_1, **kwargs_1):
        if 'kwarg' in kwargs_1:
            kwarg = kwargs_1['kwarg']
        else:
            raise HTTP403Error()

        return func(*args_1, **kwargs_1)

    return wrapper
  1. Working with this decorator, no problem it does the job very well.
  2. Testing a similar decorator that does not require absolutely the kwargs, same outcome.
  3. But testing this decorator with the following mock does not work:

    def test_can_access_kwarg(self):
        """Test simple permission decorator."""
        func = Mock(return_value='OK')
        decorated_func = has_permission_from_slug()(func(kwarg=self.kwarg))
        # It will raise at the following line, whereas the kwarg is provided...
        response = decorated_func()
        self.assertTrue(func.called)
        self.assertEqual(response, 'OK')
    

It returns me the exception I am raising when I do not have a 'kwarg' keyword-argument...

Does anyone has a clue how to test (by mocking would be preferable) such a decorator decorated by another decorator that requires the access to one of the keyword arguments passed to the function ?

Author:Rmatt,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/13359727/python-testing-a-decorated-decorator-through-a-mock
yy