mock: Swapping Out Part of the System

The mock package is used to swap out pieces of the system to isolate bits of our code under test from the rest of the system. Mock objects are sometimes called test doubles, spies, fakes, or stubs. Between pytest’s own monkeypatch fixture (covered in Using monkeypatch) and mock, you should have all the test double functionality you need.

Mocks Are Weird

images/aside-icons/warning.png

If this is the first time you’ve encountered test doubles like mocks, stubs, and spies, it’s gonna get real weird real fast. It’s fun though, and quite powerful.

The mock package is shipped as part of the Python standard library as unittest.mock as of ...

Get Python Testing with pytest 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.