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
Truemore 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