Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 11.4 — Mocks, Fakes and Patching
Python · Example 1 of 4

Mock: return_value, side_effect, call records

Add a third call to sender.send and watch call_count change. Then fix the last assertion so it passes.

A mock or fake is a stand-in for something slow, unsafe or unpredictable (the network, the clock, a database, an AI model), so a test checks only your own code. unittest.mock provides Mock, MagicMock and patch for this.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a FakeClock class with a now() method that returns a time you set, and a function greeting(clock) that returns "Good morning" before 12 and "Good afternoon" otherwise. Test both cases.

02

Use Mock(side_effect=[...]) to test a fetch_with_retry(client) function that retries once if the first call raises ConnectionError.

03

Use patch.object to replace a method on a class for one with block and show that the original returns afterwards.

Explain it without notes

01

What is the difference between a stub, a fake and a mock?

02

Where should you patch: where a name is defined or where it is used? Explain with an example.

03

How do you test a function that calls an AI model without calling the model?

04

What is over-mocking and how do you avoid it?

05

What does create_autospec give you that a plain Mock does not?

Mock: return_value, side_effect, call records
Sign in to run this example in your browser.

Expected output

call count: 2
last call: call('sara@example.com', 'Welcome!')
all calls: [call('amit@example.com', 'Welcome!'), call('sara@example.com', 'Welcome!')]
rate: 83.5
attempt 1 -> error: down
attempt 2 -> ok
len: 3
assertion failed: Expected 'send' to be called once. Called 2 times.