Search code examples
python-unittestpython-unittest.mock

How to mock a variable from another module in python3?


Below is my source code

#src.py
from common.configs import MANDATORY_FIELDS

def check_mf():
   if set(MANDATORY_FIELDS).issubset(['a','b','c']):
      return True
   else:
      raise Exception("Error in mandatory fields")

And here is my test code

#test_src.py
from unittest import TestCase, main, mock
from src import check_mf

class TestMailSenderUtil(TestCase):
  def test_method(self):
      with mock.patch('src.MANDATORY_FIELDS') as mocked_mf:
           mocked_mf.return_value = ['a','b','c','d']
           self.assertRaises(ValidationException, check_mf)

when i run this code the test is not passing. It throws an error saying that

AssertionError: ValidationException not raised by check_mf

Why do i get this error? FYI, when i try to print MANDATORY_FIELDS in src.py file while running unittesting i get this

<MagicMock name='MANDATORY_FIELDS' id='139766761401144'>

Why the mocking is not working here?


Solution

  • There is no return_value for a variable MANDATORY_FIELDS. Just pass new value as second parameter for patch().

    E.g. (Python 3.9.2)

    src.py:

    from configs import MANDATORY_FIELDS
    
    class ValidationException(Exception):
        pass
    
    def check_mf():
        print(MANDATORY_FIELDS)
        if set(MANDATORY_FIELDS).issubset(['a', 'b', 'c']):
            return True
        else:
            raise ValidationException("Error in mandatory fields")
    

    configs.py:

    MANDATORY_FIELDS=['a']
    

    test_src.py:

    from unittest import TestCase, main, mock
    from src import check_mf, ValidationException
    
    
    class TestMailSenderUtil(TestCase):
        def test_method(self):
            with mock.patch('src.MANDATORY_FIELDS', ['a', 'b', 'c', 'd']) as mocked_mf:
                self.assertRaises(ValidationException, check_mf)
    
    
    if __name__ == '__main__':
        main()
    

    unit test result:

    ['a', 'b', 'c', 'd']
    .
    ----------------------------------------------------------------------
    Ran 1 test in 0.000s
    
    OK
    Name                                     Stmts   Miss  Cover   Missing
    ----------------------------------------------------------------------
    src/stackoverflow/68162471/configs.py        1      0   100%
    src/stackoverflow/68162471/src.py            8      1    88%   9
    src/stackoverflow/68162471/test_src.py       8      0   100%
    ----------------------------------------------------------------------
    TOTAL                                       17      1    94%