【问题标题】:Python Unit Test - Module in if statement is not definedPython 单元测试 - if 语句中的模块未定义
【发布时间】:2018-05-11 23:38:16
【问题描述】:

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

import some_module
if some_module.DO_IMPORT:
   import other_module

def my_func(self):
   print(some_module.DO_IMPORT)
   if some_module.DO_IMPORT:
      print(other_module.OTHER_VAR)
      return true
   return false

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

from unittest.mock import patch, Mock
import my_code

class TestMyCode(self):

   @patch('my_code.other_module', OTHER_VAR='Other Var')
   @patch('my_code.some_module', DO_IMPORT=True)
   def_test_my_func(self, *_):
      ret = my_code.my_func()
      self.assertTrue(ret)

这是抛出错误:

NameError: name 'other_module' is not defined

即使我已修补 some_module.DO_IMPORT 以返回 True,它也不会导入 other_module。 (我确信这一点,因为 some_module.DO_IMPORT 打印为 True)。 some_module.DO_IMPORT 的实际值设置为 False。我可以修补它,但导入仍然无法正常工作。如何让它发挥作用?

【问题讨论】:

  • other_module 没有被导入,因为 some_module.DO_IMPORT 是 False 当它被检查时 - 只有在执行 my_func 时它才会被猴子修补为 True。
  • 感谢@Josh。有解决方法吗?我想覆盖单元测试中的所有代码,但不能更改 DO_IMPORT 的实际值。

标签: python unit-testing mocking patch


【解决方案1】:

您可以在导入要测试的模块之前直接更改它,而不是使用 unittest 来猴子补丁some_module.DO_IMPORT

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

【讨论】:

  • 所以这只会在测试执行期间设置 some_module.DO_IMPORT = True ?
  • 按原样,这只会将 some_module.DO_IMPORT 设置为 True 永远,但您可以在测试完成后将其设置回来(可能在 tearDown 方法或其他方法中,我没有使用 unittest一段时间)。
【解决方案2】:

另一种方法是在 mock_do_import 设置为 True 之后执行 import my_code,范围最小。

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    • 2021-06-10
    • 2016-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-27
    相关资源
    最近更新 更多