1

Similar questions were asked before:

functools.wraps creates a magic method called __wrapped__ in the decorator, which allows to access the wrapped function. When you have multiple decorators, though, this would return an inner decorator, not the original function.

How to avoid or bypass multiple decorators?

1 Answer 1

3

To bypass or avoid multiple decorators and access the inner most function, use this recursive method:

def unwrap(func):
    if not hasattr(func, '__wrapped__'):
        return func

    return unwrap(func.__wrapped__)

In pytest, you can have this function in conftest.py and access throughout your tests with:

# conftest.py
import pytest

@pytest.fixture
def unwrap():
    def unwrapper(func):
        if not hasattr(func, '__wrapped__'):
            return func

        return unwrapper(func.__wrapped__)

    yield unwrapper
# my_unit_test.py
from my_module import decorated_function

def test_my_function(unwrap):
    decorated_function_unwrapped = unwrap(decorated_function)
    assert decorated_function_unwrapped() == 'something'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.