嗨,我想模拟我的装饰器,因为我不想实际调用/执行这个函数。但我似乎找不到下面的解决方案是我的代码
# This is the decorator located in my project
# This is located in custom.mydecorators.decorator_file.custom_decorator
Base = declarative_base()
def custom_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("This message is still printed even when I try to patch this function")
try:
#code here
my_var = CoolClass()
retval = func(*args, **kwargs)
except Exception as e:
#rollback code here
raise e
return retval
return wrapper
现在我正在尝试使用此代码修补它
patch('custom.mydecorators.decorator_file.custom_decorator', lambda x: x).start()
class TestMockDecoratorsCallingClass(unittest.TestCase):
def test_should_return_success_if_decorators_are_mocked(self):
# Code here
我的装饰器在非单元测试文件中正常工作。但是如果我模拟这个装饰器,它会失败说在赋值之前引用了局部变量“my_var”
注意: my_var 在我试图模拟/修补的装饰器内,即使我尝试修补它,打印消息仍然会执行