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

标签 python testing mocking python-unittest

我正在尝试在 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 中工作,我不希望输出中出现两行“我没有在...打补丁”。

如何让模拟补丁应用到这些方法中?

最佳答案

我认为你需要这样做:

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.

关于python - 在 TestCases 中的 setUp 或 setUpClass 中修补装饰器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52972915/

相关文章:

ruby - 规范: "describe MyClass::Something do"

unit-testing - Dart Angular 在单元测试中用模拟替换提供者

python - 如何在 django 模型实例中转换 json?

python - url调度中找到favicon.ico的 Pyramid 路由,但同时遍历没有找到

python - 如何在 pandas groupby 中移动整个组

java - 如何使用 Mockito 模拟 void 方法

jquery - 请推荐一个库来在浏览器中模拟 ajax 请求

python - 这些 Haskell 高阶函数的 Python 等价物是什么?

c - 如果有任何未发现的错误,如何测试字数统计程序?

ios - 独立软件开发人员如何在他们没有的设备上测试应用程序