Skip to content

Instantly share code, notes, and snippets.

@comalex
Last active February 12, 2020 07:41
Show Gist options
  • Save comalex/b6eaeb3a700fab164467eaae9978c58d to your computer and use it in GitHub Desktop.
Save comalex/b6eaeb3a700fab164467eaae9978c58d to your computer and use it in GitHub Desktop.
Mock python cheatsheet

Python unittest.mock Cheat Sheet

Basic usage

mock.Mock()
mock.MagicMock()

Asserts

assert_called_with: This method asserts that the last call was made with the given parameters assert_called_once_with: This assertion checks that the method was called exactly once and was with the given parameters
assert_any_call: This checks that the given call was made at some point during the execution assert_has_calls: This assertion checks that a list of calls occurred

Specification

class PrintAction:
    def run(self, description):
        print("{0} was executed".format(description))

mock_1 = mock.Mock()
mock_1.execute("sample alert") # Does not give an error”

mock_2 = mock.Mock(spec=PrintAction)
mock_2.execute("sample alert") # Gives an error

Returning value

  mock.Mock(return_value=True)
  rule = mock.MagicMock()
  rule.matches.return_value = True
  rule.matches()
  
  m.side_effect = Exception()
  m.side_effect = [1, 2, 3]

Patch

patcher = mock.patch('builtins.print') patcher.stop() with mock.patch('builtins.print') as mock_print: .... @mock.patch("builtins.print") def test():

@mock.patch("builtins.print") class Test: ... ....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment