Search code examples
pythonunit-testingpython-unittestpython-mockpython-unittest.mock

Test (unittest, mock) if a global variable list is updated


file.py:

GLOB_VAR = []

def my_func(x, msg):
    if x:
        logging.warning(msg)
    GLOB_VAR.append(x)

test.py:

@patch('file.GLOB_VAR', [])
@patch('logging.Logger.warning')
def test_file_with_msg(self, logging):
    x = 'test_x'
    msg = 'test_msg'

    my_func(x=x, msg=msg)
    logging.assert_called_with(message)
    assert x in GLOB_VAR

I always get an AssertionError. from the line assert x in GLOB_VAR

Let me say that I DO need a global variable


Solution

  • It turned out that I shouldn't have patched the global variable as I need to assert against the file's global variable and not against the a mock's instance global variable.

    This does does the trick:

    test.py

    from file import my_func, GLOB_VAR
    
    @patch('logging.Logger.warning')
    def test_file_with_msg(self, logging):
        x = 'test_x'
        msg = 'test_msg'
    
        my_func(x=x, msg=msg)
        logging.assert_called_with(message)
        assert x in GLOB_VAR