Types of mocks

The standard library provides Mock and MagicMock objects in the unittest.mock module. The former is a test double that can be configured to return any value and will keep track of the calls that were made to it. The latter does the same, but it also supports magic methods. This means that, if we have written idiomatic code that uses magic methods (and parts of the code we are testing will rely on that), it's likely that we will have to use a MagicMock instance instead of just a Mock.

Trying to use Mock when our code needs to call magic methods will result in an error. See the following code for an example of this:

class GitBranch:    def __init__(self, commits: List[Dict]):        self._commits = {c["id"]: c for c in commits} def __getitem__(self, ...

Get Clean Code 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.