我有一个带有装饰器的函数,我正在尝试在 Python Mock 的帮助下进行测试图书馆。我想使用 mock.patch
将真正的装饰器替换为只调用函数的模拟“绕过”装饰器。
我想不通的是如何在真正的装饰器包装函数之前应用补丁。我在补丁目标上尝试了一些不同的变体,并对补丁和导入语句重新排序,但没有成功。有什么想法吗?
最佳答案
需要注意的是,这里的几个答案会为整个测试 session 而不是单个测试实例修补装饰器;这可能是不可取的。以下是如何修补仅通过单个测试持续存在的装饰器。
我们的单元要使用不受欢迎的装饰器进行测试:
# app/uut.py
from app.decorators import func_decor
@func_decor
def unit_to_be_tested():
# Do stuff
pass
来自装饰器模块:
# app/decorators.py
def func_decor(func):
def inner(*args, **kwargs):
print "Do stuff we don't want in our test"
return func(*args, **kwargs)
return inner
在测试运行期间收集到我们的测试时,不需要的装饰器已经应用于我们的测试单元(因为这发生在导入时)。为了摆脱这种情况,我们需要手动替换装饰器模块中的装饰器,然后重新导入包含我们的 UUT 的模块。
我们的测试模块:
# test_uut.py
from unittest import TestCase
from app import uut # Module with our thing to test
from app import decorators # Module with the decorator we need to replace
import imp # Library to help us reload our UUT module
from mock import patch
class TestUUT(TestCase):
def setUp(self):
# Do cleanup first so it is ready if an exception is raised
def kill_patches(): # Create a cleanup callback that undoes our patches
patch.stopall() # Stops all patches started with start()
imp.reload(uut) # Reload our UUT module which restores the original decorator
self.addCleanup(kill_patches) # We want to make sure this is run so we do this in addCleanup instead of tearDown
# Now patch the decorator where the decorator is being imported from
patch('app.decorators.func_decor', lambda x: x).start() # The lambda makes our decorator into a pass-thru. Also, don't forget to call start()
# HINT: if you're patching a decor with params use something like:
# lambda *x, **y: lambda f: f
imp.reload(uut) # Reloads the uut.py module which applies our patched decorator
清理回调 kill_patches 恢复原始装饰器并将其重新应用于我们正在测试的单元。这样,我们的补丁只在单个测试中持续存在,而不是整个 session ——这正是任何其他补丁应该表现的方式。此外,由于清理调用了 patch.stopall(),我们可以在 setUp() 中启动我们需要的任何其他补丁,它们将在一个地方全部清理。
了解此方法的重要一点是重新加载将如何影响事物。如果一个模块花费的时间太长或具有在导入时运行的逻辑,您可能只需要耸耸肩并将装饰器作为单元的一部分进行测试。 :( 希望你的代码比那写得更好。对吧?
如果不关心补丁是否应用于整个测试 session ,最简单的方法是在测试文件的顶部:
# test_uut.py
from mock import patch
patch('app.decorators.func_decor', lambda x: x).start() # MUST BE BEFORE THE UUT GETS IMPORTED ANYWHERE!
from app import uut
确保使用装饰器而不是 UUT 的本地范围修补文件,并在使用装饰器导入单元之前启动修补程序。
有趣的是,即使补丁被停止,所有已经导入的文件仍然会将补丁应用于装饰器,这与我们开始的情况相反。请注意,此方法将修补测试运行中随后导入的任何其他文件——即使它们自己没有声明修补程序。
关于python - 我可以在包装函数之前修补 Python 装饰器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7667567/