MagicMock and Context Managers

Learn to mock functions and context managers using MagicMock.

MagicMock object

In addition to mocker.patch(), mocker also provides a mocker.MagicMock object that can be used to create mock objects with custom attributes.

Here are some of the methods provided by the MagicMock object:

  • assert_called_once(): This method is used to assert that a mock object was called exactly once. If the mock object was never called or called more than once, the assertion fails.

  • assert_called_with(arg1, arg2, …): This method is used to assert that a mock object was called with the specified arguments. If the mock object was called with different arguments or was not called at all, the assertion fails.

  • assert_not_called(): This method is used to assert that a mock object was never called. If the mock object was called at least once, the assertion fails.

  • assert_any_call(arg1, arg2, …): This method is used to assert that a mock object was called with the specified arguments at least once. If the mock object was never called with the specified arguments, the assertion fails.

Get hands-on with 1200+ tech skills courses.