Python unittest assert expection as a parameter

Question:

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'))
Asked By: jereczq22

||

Answers:

Mock main.ValueError itself, so you can control the exception that you expect myFunc to be called on.

@patch('main.ValueError', return_value=ValueError('valueError'))
@patch('main.myFunc')
def test(mock_myFunc, mock_exc):
    mainFunc()
    mock_myFunc.assert_called_with(mock_exc)
Answered By: chepner

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.

Answered By: PirateNinjas