4

I am trying to test a function that is decorated. Is there a way to mock a decorator and test function in isolation, when decorator is already applied?

import mock


def decorator(func):
    def wrapper(*args, **kwargs):
        return 1
    return wrapper


def mocked(func):
    def wrapper(*args, **kwargs):
        return 2
    return wrapper


@decorator
def f():
    return 0


with mock.patch('test.decorator') as d:
    d.side_effect = mocked
    assert f() == 2  # error
scdekov
  • 153
  • 1
  • 12

1 Answers1

3

There is not a simple solution.

This is a similar question: How to strip decorators from a function in python

You can either modify the original code just for testing, or use something like this library: https://pypi.python.org/pypi/undecorated in order to write a helper function to switch from the original wrapper to the testing wrapper:

from undecorated import undecorated
mocked(undecorated(f))()
Community
  • 1
  • 1
JoseKilo
  • 2,343
  • 1
  • 16
  • 28