未定义if语句中的Python单元测试模块

未定义if语句中的Python单元测试模块,python,unit-testing,mocking,patch,Python,Unit Testing,Mocking,Patch,我有一个要测试的Python文件(my_code.py): 这是我的测试类(test_my_code.py): 这将抛出错误: NameError: name 'other_module' is not defined 即使我修补了某个_模块。DO_IMPORT返回True,它也不会导入另一个_模块。(我确信这一点,因为某些_module.DO _IMPORT打印为True)。某些_module.DO_导入的实际值设置为False。我可以修补它,但导入仍然不起作用。如何使其工作?而不是使用un

我有一个要测试的Python文件(my_code.py):

这是我的测试类(test_my_code.py):

这将抛出错误:

NameError: name 'other_module' is not defined

即使我修补了某个_模块。DO_IMPORT返回True,它也不会导入另一个_模块。(我确信这一点,因为某些_module.DO _IMPORT打印为True)。某些_module.DO_导入的实际值设置为False。我可以修补它,但导入仍然不起作用。如何使其工作?

而不是使用unittest来修补某些模块。要导入,只需在导入要测试的模块之前直接更改即可:

from unittest.mock import patch, Mock
import some_module
some_module.DO_IMPORT = True
import my_code
# then do the test

另一种方法是在mock\u do\u import设置为
True
后执行
导入我的代码
,范围最小

import unittest
import mock


class TestMyCode(unittest.TestCase):

    @mock.patch('python2_unittests.lib.app.OTHER_VAR')
    @mock.patch('python2_unittests.lib.remove3.DO_IMPORT')
    def test_my_func(self, mock_import, mock_other):
        mock_import.return_value = True
        mock_other.return_value = 'others'
        from python2_unittests.lib import my_code
        ret = my_code.my_func()
        self.assertTrue(ret)

other_module
没有被导入,因为
some_module.DO_IMPORT
在选中时为False–只有在执行
my_func
时,它才被monkey patched为True。谢谢@Josh。有办法解决这个问题吗?我想覆盖单元测试中的所有代码,但无法更改DO_IMPORT的实际值。因此,这将设置某些模块。DO_IMPORT=True仅用于测试执行期间?照此,这将只将
some_模块。DO_IMPORT
永久设置为True,但您可以在测试完成后将其设置回True(可能是在一种拆卸方法中,我已经有一段时间没有使用unittest了)。
from unittest.mock import patch, Mock
import some_module
some_module.DO_IMPORT = True
import my_code
# then do the test
import unittest
import mock


class TestMyCode(unittest.TestCase):

    @mock.patch('python2_unittests.lib.app.OTHER_VAR')
    @mock.patch('python2_unittests.lib.remove3.DO_IMPORT')
    def test_my_func(self, mock_import, mock_other):
        mock_import.return_value = True
        mock_other.return_value = 'others'
        from python2_unittests.lib import my_code
        ret = my_code.my_func()
        self.assertTrue(ret)