Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock python decorator in unit tests

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
like image 789
scdekov Avatar asked Oct 22 '25 12:10

scdekov


1 Answers

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))()
like image 139
JoseKilo Avatar answered Oct 25 '25 02:10

JoseKilo