Modifying global variables in Python unittest framework

前端 未结 3 1686
长发绾君心
长发绾君心 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条回答
  •  -上瘾入骨i
    2020-12-08 19:33

    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:

    class TestSomething(self.unittest):
    
        @patch('config.MY_CONFIG_VARIABLE', True)
        def test_first_case(self):
             self.assertEqual(my_function_with_global_var(), "First result")
    

    You can also use it as a context manager:

        def test_first_case(self):
            with patch('config.MY_CONFIG_VARIABLE', True):
                self.assertEqual(my_function_with_global_var(), "First result")
    

提交回复
热议问题