Modifying global variables in Python unittest framework

前端 未结 3 1687
长发绾君心
长发绾君心 2020-12-08 18:48

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 an

3条回答
  •  暖寄归人
    2020-12-08 19:25

    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:

    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? .

提交回复
热议问题