unittest.mock in Python
Replacing a collaborator so a test never touches the network.
from unittest.mock import Mock, patch
def send(client, payload):
response = client.post("/api/results", json=payload)
return response.status_code == 200
def test_posts_the_payload():
client = Mock()
client.post.return_value = Mock(status_code=200)
assert send(client, {"tpm": 104}) is True
client.post.assert_called_once_with("/api/results", json={"tpm": 104})
def test_patches_a_name():
with patch("time.time", return_value=1234.0) as clock:
import time
assert time.time() == 1234.0
assert clock.called
How it works
Mockrecords the calls it received.patchswaps a name for the duration of the block.- Assert on the call, not on the mock's internals.
Keywords and builtins used here
asassertdefreturnsendtest_patches_a_nametest_posts_the_payloadwith
The run, in numbers
- Lines
- 21
- Characters to type
- 510
- Tokens
- 126
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 69 seconds.
Step 2 of 3 in Selecting & faking, step 7 of 9 in Testing with pytest.