相关疑难解决方法(0)

在Python unittest框架中修改全局变量

我正在使用Python进行一系列单元测试,其中一些测试依赖于配置变量的值.这些变量存储在全局Python配置文件中,并在其他模块中使用.我想为配置变量的不同值编写单元测试,但尚未找到实现此目的的方法.

我没有可能重写我正在测试的方法的签名.

这就是我想要实现的目标:

from my_module import my_function_with_global_var

class TestSomething(self.unittest):

    def test_first_case(self):
         from config import MY_CONFIG_VARIABLE
         MY_CONFIG_VARIABLE = True
         self.assertEqual(my_function_with_global_var(), "First result")

    def test_second_case(self):
         from config import MY_CONFIG_VARIABLE
         MY_CONFIG_VARIABLE = False
         self.assertEqual(my_function_with_global_var(), "Second result")
Run Code Online (Sandbox Code Playgroud)

谢谢.

编辑:使示例代码更明确.

python unit-testing global-variables

38
推荐指数
2
解决办法
4万
查看次数

标签 统计

global-variables ×1

python ×1

unit-testing ×1