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.
Use
unittest.mock.patchas in @Flimm’s answer, if that’s available to you.Original Answer
Don’t do this:
But this:
And then you can inject
MY_CONFIG_VARIABLEinto the importedmy_module, without changing the system under test like so:I did something similar in my answer to How can I simulate input to stdin for pyunit? .