[Python] How can I patch a Python decorator before it wraps a function?
As title, Python decorator could be a problem if you want to write some unit cases that test these functions which contains decorators because you cannot use Mock to patch your decorators. Why? Please refer to the following link to check out:
Let me give an exmple:
Here is a decorator function(user_passes_test) in the following file path
If you have a function using this decorator and need to write the test case for it as follows:
Then, you can put your patch code in the beginning of the tests python file like this:def mock_function(test_func, login_url=None, redirect_field_name=None): def wrapped_f(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def decorator_view(request, *args, **kwargs): return view_func(request, *args, **kwargs) return decorator_function return wrapped_f from django.contrib.auth.decorators import user_passes_test user_passes_test = mock_functionAfter doing so, the decorator: user_passes_test() won't infect your test case any more~