<p>需要注意的是,这里的几个答案将为整个测试会话而不是单个测试实例修补decorator;这可能是不可取的。下面是如何修补只在单个测试中持续存在的decorator。</p>
<p>我们的单位将与不受欢迎的装修商进行测试:</p>
<pre><code># app/uut.py
from app.decorators import func_decor
@func_decor
def unit_to_be_tested():
# Do stuff
pass
</code></pre>
<p>来自decorators模块:</p>
<pre><code># 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
</code></pre>
<p>在测试运行期间收集测试时,不需要的decorator已经应用到了被测单元(因为这发生在导入时)。为了消除这个问题,我们需要手动替换decorator模块中的decorator,然后重新导入包含UUT的模块。</p>
<p>我们的测试模块:</p>
<pre><code># 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
</code></pre>
<p>清理回调kill_patches,恢复原始的decorator并将其重新应用到我们正在测试的单元。这样,我们的补丁只在一个测试中持续运行,而不是整个会话——这正是任何其他补丁的行为方式。此外,由于清理调用patch.stopall(),我们可以在setUp()中启动所需的任何其他修补程序,它们将在一个位置全部清理。</p>
<p>关于这个方法,重要的是要了解重新加载将如何影响事物。如果一个模块花费的时间太长,或者有在导入时运行的逻辑,您可能只需要耸耸肩并将decorator作为单元的一部分进行测试。:(希望你的代码写得更好。正确的?</p>
<p><strong>如果不关心补丁是否应用于整个测试会话,最简单的方法是在测试文件的顶部:</p>
<pre><code># 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
</code></pre>
<p>确保用decorator而不是UUT的本地作用域修补文件,并在用decorator导入单元之前启动修补程序。</p>
<p>有趣的是,即使修补程序停止了,所有已经导入的文件仍然会将修补程序应用到decorator,这与我们开始的情况相反。请注意,此方法将修补测试运行中随后导入的任何其他文件—即使它们自己没有声明修补程序。</p>