Skip to content

Instantly share code, notes, and snippets.

@willienillie
Last active April 15, 2024 18:13
Show Gist options
  • Save willienillie/364287531de8ea70b006571c71eaa3aa to your computer and use it in GitHub Desktop.
Save willienillie/364287531de8ea70b006571c71eaa3aa to your computer and use it in GitHub Desktop.
Python MagicMock Mocking Cheatsheet
# needed imports
from mock import MagicMock, call
if __name__ == "__main__":
# create magic mock
mocker = MagicMock()
# make a single call
mocker("foo")
# check if method was called
mocker.assert_called_once_with("foo") # check if the method was only called once with "foo"
assert 1 == mocker.call_count # get the number of times the mock was called
# setup return
mocker.return_value = "bar"
assert mocker("whatever") == "bar"
# reset mock after settings expectations
mocker.rest_mock()
# setup multiple returns
mocker.side_effect = ["bar","baz"]
assert mocker("what") == "bar"
assert mocker("ever") == "baz"
# get the values the method was called with
# get the last call
assert mocker.call_args == call("ever")
# get all calls the mock has
assert mocker.call_args_list == [call("foo"), call("whatever"), call("what"), call("ever")]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment