Modifying Global Variables In Python Unittest Framework
Solution 1:
You probably want to mock those global variables instead. The advantage of this is that the globals get reset once you're done. Python ships with a mocking module that lets you do this.
unittest.mock.patch
be used as a decorator:
classTestSomething(self.unittest):
@patch('config.MY_CONFIG_VARIABLE', True)deftest_first_case(self):
self.assertEqual(my_function_with_global_var(), "First result")
You can also use it as a context manager:
deftest_first_case(self):
with patch('config.MY_CONFIG_VARIABLE', True):
self.assertEqual(my_function_with_global_var(), "First result")
Solution 2:
Use unittest.mock.patch
as in @Flimm's answer, if that's available to you.
Original Answer
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:
classTestSomething(unittest.TestCase): # Fixed that for you!deftest_first_case(self):
my_module.MY_CONFIG_VARIABLE = True
self.assertEqual(my_module.my_function_with_global_var(), "First result")
deftest_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 toHow can I simulate input to stdin for pyunit? .
Solution 3:
You code imports MY_CONFIG_VARIABLE
into the local scope and then immediately overwrites the name with a different object. That won't change the value in the config
module. Try
import configconfig.MY_CONFIG_VARIABLE = False
instead.
Post a Comment for "Modifying Global Variables In Python Unittest Framework"