Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is your favorite Python mocking library? [closed]

Tags:

python

mocking

What is your single favorite mocking library for Python?

like image 426
Daryl Spitzer Avatar asked Sep 18 '08 23:09

Daryl Spitzer


People also ask

What is mocking in 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.

What is the difference between mock and MagicMock?

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.

What is Autospec in Python?

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.

What does mock patch do?

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.


1 Answers

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.

like image 160
Daryl Spitzer Avatar answered Oct 20 '22 19:10

Daryl Spitzer