我正在尝试在 unittest.TestCase
子类的 setUp
或 setUpClass
方法期间修补一些函数。
给定一个模块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)
以下脚本产生的输出比我预期的要多。
# 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
中工作,我不希望输出中出现两行“我没有在...打补丁”。
如何让模拟补丁应用到这些方法中?
最佳答案
我认为你需要这样做:
class PatchMeNotTests(unittest.TestCase):
@classmethod
<b>@patch('patch_me_not.patch_me', lambda x: None)</b>
def setUpClass(cls):
print('I am the setUpClass.')
patch_me_not('setUpClass')
<b>@patch('patch_me_not.patch_me', lambda x: None)</b>
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"
。这就是您的解决方案不起作用的原因。
这是来自 unittest 文档的相关引用
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
.
关于python - 在 TestCases 中的 setUp 或 setUpClass 中修补装饰器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52972915/