Search code examples
pythonpython-3.xpython-unittest

Python unittest assert expection as a parameter


How to assert called function which gets exception as a parameter?

In my code:

def mainFunc:
  # ...
  raise ValueError('valueError')
  # ...
  except Exception as e:
    myFunc(e)

In the test:

from unittest.mock import patch

# ...
@patch('main.myFunc')
def test(mock):
  mainFunc()
  mock.assert_called_with(ValueError('valueError'))
  

And I got:

AssertionError: expected call not found.
Expected: myFunc(ValueError('valueError'))
Actual: myFunc(ValueError('valueError'))

Solution

  • This is a bit clunky, but you can do something like:

    @patch('main.myFunc')
    def test(mock):
      mainFunc()
      assert mock.call_args[0][0].args[0] == 'valueError'
    

    Your test doesn't work because the ValueError that gets raised has a traceback, while the one in your tests doesn't. This modified version checks the mock is called with an exception with the correct message only.