Mock Python Mocking and Testing Library

In unit testing, you use mocks to simulate the behavior of other code parts in controlled ways. mock is a Python library for testing that allows you to replace parts of the system under test with mock objects and make assertions about how they have been used. mock has been integrated the Python standard library since version 3.3 under the name unittest.mock.

mock provides a core Mock class that removes the need to create stubs. After performing an action, you can make assertions about which methods / attributes were used and arguments they were called with. You can also specify return values and set needed attributes in the normal way. mock also provides a patch() decorator that handles patching module and class level attributes within the scope of a test, along with sentinel for creating unique objects. Mock is based on the ‘action -> assertion’ pattern instead of ‘record -> replay’ used by many mocking frameworks.

The documentation of mock is really well written with a user guide that provides multiple examples on how to use this library in your python unit tests. It goes beyond being a simple documentation of the tool and provides valuable material on how to do mocking in python with plenty of code.

Read the full mock documentation on