在 TestCases 中的 setUp 或 setUpClass 中修补装饰器不起作用

Patching decorator in setUp or setUpClass in TestCases does not work

我正在尝试在 unittest.TestCase 子类的 setUpsetUpClass 方法期间修补一些函数。

给定一个模块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

如果补丁在 setUpsetUpClass.

中有效,我不希望输出中出现两行 "I am not patched at..."

如何获得要在这些方法中应用的模拟补丁?

我认为你需要这样做:

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 with patch.TEST_PREFIX. By default, this is 'test', which matches the way unittest finds tests. You can specify an alternative prefix by setting patch.TEST_PREFIX.