Background Image
Table of Contents Table of Contents
Previous Page  329 / 478 Next Page
Information
Show Menu
Previous Page 329 / 478 Next Page
Page Background

On Mocking in Python

The Mock library

Michael Foord (who used to work for the company that spawned PythonAnywhere,

just before I joined) wrote the excellent “Mock” library that’s now been integrated

into the standard library of Python 3. It contains most everything you might need

for mocking in Python.

The patch decorator

unittest.mock

provides a function called

patch

, which can be used to “mock out”

any object from the module you’re testing. It’s commonly used as a decorator on a

test method, or even at the class level, where it’s applied to all the test methods of

that class.

Mocks are truthy and can mask errors

Be aware that mocking things out can cause counterintuitive behaviour in

if

state‐

ments. Mocks are truthy, and they can also mask errors, because they have all at‐

tributes and methods.

Too many mocks are a code smell

Overlymocky tests end up very tightly coupled to their implementation. Sometimes

this is unavoidable. But, in general, try to find ways of organising your code so that

you don’t need too many mocks.

Finishing Off Our FT, Testing Logout

|

301