gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:27:03 25 4
gpt4 key购买 nike

我有一个想要测试的 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。我可以修补它,但导入仍然无法正常工作。如何让它发挥作用?

最佳答案

您可以在导入要测试的模块之前直接更改它,而不是使用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

关于Python 单元测试 - if 语句中的模块未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50301531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com