What is your single favorite mocking library for Python?
mock is a library for testing in Python. It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used. unittest. mock provides a core Mock class removing the need to create a host of stubs throughout your test suite.
With Mock you can mock magic methods but you have to define them. MagicMock has "default implementations of most of the magic methods.". If you don't need to test any magic methods, Mock is adequate and doesn't bring a lot of extraneous things into your tests.
When you patch a function using mock, you have the option to specify autospec as True: If you set autospec=True then the mock with be created with a spec from the object being replaced. All attributes of the mock will also have the spec of the corresponding attribute of the object being replaced.
patch() unittest. mock provides a powerful mechanism for mocking objects, called patch() , which looks up an object in a given module and replaces that object with a Mock . Usually, you use patch() as a decorator or a context manager to provide a scope in which you will mock the target object.
I've only used one, but I've had good results with Michael Foord's Mock: http://www.voidspace.org.uk/python/mock/.
Michael's introduction says it better than I could:
There are already several Python mocking libraries available, so why another one?
Most mocking libraries follow the 'record -> replay' pattern of mocking. I prefer the 'action -> assertion' pattern, which is more readable and intuitive particularly when working with the Python unittest module.
...
It also provides utility functions / objects to assist with testing, particularly monkey patching.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With