Chapter 8: Monkeypatching

Alfredo Deza

The Python testing community has had quite a few mocking and patching libraries. Perhaps the most popular one is mock which is now part of the standard library. The mock library is very flexible and has lots of different helpers meant to ease testing. When Python 3 was not available, it wasn’t surprising to see projects declare mock as a dependency, but since Python 3.3 it is available in Python as the unittest.mock module.

Pytest has the monkeypatching fixture that can also be used, and it does offer a few ways to patch objects properly. Explaining patching can be tricky, especially for a dynamic language like Python, but in short, it allows us to (safely) replace code at runtime with other code that ...

Get Testing In Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.