在Python单元测试框架中修改全局变量 [英] Modifying global variables in Python unittest framework
问题描述
我正在Python中进行一系列单元测试,其中一些取决于配置变量的值。这些变量存储在全局Python配置文件中,并用于其他模块。我想为不同的配置变量值编写单元测试,但还没有找到办法做到这一点。
我没有可能重写签名我正在测试的方法。
这就是我想达到的效果:
from my_module import my_function_with_global_var
class TestSomething(self.unittest):
def test_first_case(self):$ b $ from config import MY_CONFIG_VARIABLE
MY_CONFIG_VARIABLE = True
self.assertEqual(my_function_with_global_var(),First result)
def test_second_case(self):$ b $ from config import MY_CONFIG_VARIABLE
MY_CONFIG_VARIABLE = False
self.assertEqual(my_function_with_global_var(),Second result)
谢谢。 / p>
编辑:使示例代码更加明确。
Ť执行此操作:
from my_module import my_function_with_global_var
但是这样:
$ p $ import my_module
然后您可以在导入的 my_module $>中注入
MY_CONFIG_VARIABLE
c $ c>,而不需要改变被测系统,如下所示:
class TestSomething(unittest.TestCase):#您!
def test_first_case(self):
my_module.MY_CONFIG_VARIABLE = True
self.assertEqual(my_module.my_function_with_global_var(),First result)
def test_second_case(self):
my_module.MY_CONFIG_VARIABLE = False
self.assertEqual(my_module.my_function_with_global_var(),Second result)
我在做了类似的事情我的答案是 如何模拟pyunit的stdin输入?。
I am working on a series of unit tests in Python, some of which depend on the value of a configuration variable. These variables are stored in a global Python config file and are used in other modules. I would like to write unit tests for different values of the configuration variables but have not yet found a way to do this.
I do not have the possibility to rewrite the signatures of the methods I'm testing.
This is what I would like to achieve:
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")
Thanks.
Edit: Made the example code more explicite.
Don't do this:
from my_module import my_function_with_global_var
But this:
import my_module
And then you can inject MY_CONFIG_VARIABLE
into the imported my_module
, without changing the system under test like so:
class TestSomething(unittest.TestCase): # Fixed that for you!
def test_first_case(self):
my_module.MY_CONFIG_VARIABLE = True
self.assertEqual(my_module.my_function_with_global_var(), "First result")
def test_second_case(self):
my_module.MY_CONFIG_VARIABLE = False
self.assertEqual(my_module.my_function_with_global_var(), "Second result")
I did something similar in my answer to How can I simulate input to stdin for pyunit? .
这篇关于在Python单元测试框架中修改全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!