Search⌘ K
AI Features

MagicMock and Context Managers

Explore how to use the MagicMock object in pytest for mocking functions and context managers. Understand key assertion methods to verify calls, manage mock resets, and simulate context manager behavior to isolate and test code effectively.

We'll cover the following...

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