what is it?

a subclass of unittest Mock with default implementations of most of the magic methods. You can use MagicMock without having to configure the magic methods yourself

methods are preconfigured with a default return value:

  • __lt__: NotImplemented
  • __gt__: NotImplemented
  • __le__: NotImplemented
  • __ge__: NotImplemented
  • __int__: 1
  • __contains__: False
  • __len__: 0
  • __iter__: iter([])
  • __exit__: False
  • __aexit__: False
  • __complex__: 1j
  • __float__: 1.0
  • __bool__: True
  • __index__: 1
  • __hash__: default hash for the mock
  • __str__: default str for the mock
  • __sizeof__: default sizeof for the mock

patching defaults

set the return_value:

>>> MagicMock() == 3
False
>>> MagicMock() != 3
True
>>> mock = MagicMock()
>>> mock.__eq__.return_value = True
>>> mock == 3
True

more complex example

mocking a call to a db (link to medium article)

@patch("snowflake.connector.connect")
@mock.create_autospec
def test_snowflake_query(mocker):
    mock_conn = MagicMock()
    mocker.patch("snowflake.connector.connect", return_value=mock_conn)
 
    mock_cur = MagicMock()
    mock_conn.cursor.return_value = mock_cur
 
    mock_fetchall = MagicMock(return_value=expected_return_value)
    mock_cur.fetchall = mock_fetchall
 
	mock_fetchall.assert_called_once()
	assert result == expected_return_value