在测试用例中的 setUp 或 setUpClass 中修补装饰器不起作用 [英] Patching decorator in setUp or setUpClass in TestCases does not work
问题描述
我试图在 unittest.TestCase
子类的 setUp
或 setUpClass
方法中修补一些函数.
I am trying to patch some functions during either the setUp
or setUpClass
methods of a unittest.TestCase
subclass.
给定一个模块 patch_me_not.py
# patch_me_not.py
def patch_me(at):
print('I am not patched at {}.'.format(at))
def patch_me_not(at):
patch_me(at)
以下脚本产生的输出超出了我的预期.
The following script produces more output that I would expect.
# main.py
import unittest
from unittest.mock import patch
from patch_me_not import patch_me_not
@patch('patch_me_not.patch_me', lambda x: None)
class PatchMeNotTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
print('I am the setUpClass.')
patch_me_not('setUpClass')
def setUp(self):
print('I am the setUp.')
patch_me_not('setUp')
def test_print(self):
print('I am the test')
patch_me_not('test_print')
if __name__ == '__main__':
unittest.main()
测试脚本输出为
I am the setUpClass.
I am not patched at setUpClass.
I am the setUp.
I am not patched at setUp.
I am the test
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
如果补丁在 setUp
和 setUpClass
中工作,我不希望输出中出现两行I am not patched at...".
Where I would not expect the two "I am not patched at..." lines in the output if the patch worked in setUp
and setUpClass
.
如何才能在这些方法中应用模拟补丁?
How can I get the mock patch to be applied in these methods?
推荐答案
我认为你需要这样做:
class PatchMeNotTests(unittest.TestCase):
@classmethod
@patch('patch_me_not.patch_me', lambda x: None)
def setUpClass(cls):
print('I am the setUpClass.')
patch_me_not('setUpClass')
@patch('patch_me_not.patch_me', lambda x: None)
def setUp(self):
print('I am the setUp.')
patch_me_not('setUp')
def test_print(self):
print('I am the test')
patch_me_not('test_print')
修补您的测试用例不起作用,因为当将 patch
应用于 TestCase
时,它仅 修补测试方法或更具体地说:方法以可配置的前缀 patch.TEST_PREFIX
开头,默认值为 "test"
.这就是您的解决方案不起作用的原因.
Patching your test case did not work because when patch
is applied to TestCase
it patches only test methods or to be more specific: methods that start with a configurable prefix patch.TEST_PREFIX
which default value is "test"
. That's why your solution did not work.
这是来自 unittest 文档的相关引用
Here is relevant quote from unittest docs
Patch 可以用作 TestCase 类装饰器.它的工作原理装饰类中的每个测试方法.这减少了样板当您的测试方法共享一个通用补丁集时,补丁()
通过查找以开头的方法名称来查找测试patch.TEST_PREFIX
.默认情况下,这是'test'
,匹配方式unittest 查找测试.您可以通过设置指定替代前缀patch.TEST_PREFIX
.
Patch can be used as a TestCase class decorator. It works by decorating each test method in the class. This reduces the boilerplate code when your test methods share a common patchings set.
patch()
finds tests by looking for method names that start withpatch.TEST_PREFIX
. By default, this is'test'
, which matches the way unittest finds tests. You can specify an alternative prefix by settingpatch.TEST_PREFIX
.
这篇关于在测试用例中的 setUp 或 setUpClass 中修补装饰器不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!