Patching decorator in setUp or setUpClass in TestCases does not work

廉价感情. 提交于 2021-02-10 13:36:30

问题


I am trying to patch some functions during either the setUp or setUpClass methods of a unittest.TestCase subclass.

Given a module 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()

The test script output is

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

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?


回答1:


I think you need to do this:

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')

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.

Here is relevant quote from unittest docs

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.



来源:https://stackoverflow.com/questions/52972915/patching-decorator-in-setup-or-setupclass-in-testcases-does-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!