Testing & modern typing
pytest basics, mocks, type hints, TypedDict, Protocol, and static-checking patterns.
Dependency Injection in Python for Testability
Inject a config dependency into a service so you can swap a real environment-based config for a fake one in tests.
import os
class Config:
"""Simple config loader that can be easily faked in tests."""
def get(self, key, default=None):
return os.environ.get(key, default)
class UserService:
def __init__(self, config):
self.config = config
def get_timeout(self):
return int(self.config.get(…
How to Mock open() in Python for Reading File Data
This example shows how to mock Python's built-in open() function using unittest.mock to simulate file reading without touching the disk.
import builtins
from unittest.mock import patch
def read_file_data(filename):
with open(filename, 'r') as f:
return f.read()
def mock_read_data():
fake_data = "This is mocked file content"
class FakeFile:
def __enter__(self):
return self
def __exit__(self, *args):…
How to Mock pathlib Path.read_text with mock_open in Python
Mock pathlib.Path.read_text using patch and mock_open to test file-reading code without touching the filesystem.
import pathlib
from unittest.mock import mock_open, patch
def read_config(filepath: pathlib.Path) -> str:
"""Read file content with pathlib."""
return filepath.read_text()
if __name__ == "__main__":
mock_data = "version: 1.0\nname: demo-app"
with patch("pathlib.Path.open", mock_open(read_data=mo…
How to Mock requests.get in Python
Mock requests.get with unittest.mock to test code that makes HTTP calls without hitting the network.
import requests
from unittest.mock import Mock, patch
def fetch_user_data(user_id):
response = requests.get(f"https://api.example.com/users/{user_id}")
return response.json()
def process_user(user_id):
mock_response = Mock()
mock_response.json.return_value = {"id": user_id, "name": "Alice", "age": 30…
How to Mock return_value with MagicMock in Python unittest
Use unittest.mock.MagicMock to replace a dependency and set return_value to control what a mocked method returns during unit tests.
import unittest
from unittest.mock import MagicMock
class PaymentGateway:
def charge(self, amount):
raise NotImplementedError
class OrderService:
def __init__(self, gateway):
self.gateway = gateway
def process_order(self, amount):
return self.gateway.charge(amount)
class Test…
How to Mock subprocess.run returncode in Python
Simulate subprocess.run return codes in tests with unittest.mock.patch and CompletedProcess.
import subprocess
from unittest.mock import patch
def run_command(cmd):
result = subprocess.run(cmd, capture_output=True, text=True)
return result.returncode
if __name__ == "__main__":
with patch("subprocess.run") as mock_run:
# Simulate a successful command (returncode 0)
mock_run.retu…
How to Use mock.assert_called_with in Python
Verify that a MagicMock received a call with specific positional and keyword arguments using assert_called_with in unittest.
import unittest
from unittest.mock import MagicMock
class TestMockAssertions(unittest.TestCase):
def test_assert_called_with(self):
# Create a mock object
mock = MagicMock()
# Call the mock with specific arguments
mock.send_email("alice@example.com", subject="Greetings", body="Hel…
How to Write a Contract Test with Mock in Python
Use unittest.mock to verify a consumer's expectations match the provider's response shape in a Python contract test.
from unittest.mock import Mock
# Contract test: verify consumer expects data shape that provider delivers.
# We mock the provider and assert the consumer's calls match the agreed contract.
def fetch_user(provider_client, user_id):
"""Consumer code: expects provider to return {'id', 'name', 'email'}."""
respo…
How to freeze time in Python tests with freezegun
Use the freezegun decorator to freeze datetime.now() at a fixed timestamp so tests that depend on current time run deterministically.
from datetime import datetime
from freezegun import freeze_time
@freeze_time("2024-01-15 12:30:00")
def test_frozen_time():
now = datetime.now()
return now
if __name__ == "__main__":
result = test_frozen_time()
print(result)
How to use unittest mock side_effect with a sequence in Python
Demonstrates using Mock.side_effect with a list to return different values per call and raise an exception at a specific call in unittest.
import unittest
from unittest.mock import Mock
class TestMockSideEffectSequence(unittest.TestCase):
def test_side_effect_sequence(self):
mock = Mock()
mock.side_effect = [1, 2, 3, Exception("boom")]
self.assertEqual(mock(), 1)
self.assertEqual(mock(), 2)
self.asser…
Interface Segregation with Fake Test Implementations in Python
Defines segregated abstract interfaces (Printer, Scanner) and uses a FakePrinter to record calls for unit testing without real resources.
from abc import ABC, abstractmethod
class Printer(ABC):
@abstractmethod
def print_document(self, doc: str) -> str:
pass
class Scanner(ABC):
@abstractmethod
def scan_document(self) -> str:
pass
class MultiFunctionPrinter(Printer, Scanner):
def print_document(self, doc: str) -> …
Mock datetime with time-machine in Python
Use the time-machine library to travel to a fixed datetime when running tests or scripts, mocking datetime.utcnow().
from time_machine import travel
from datetime import datetime
@travel("2020-01-01 10:30:00")
def check_date():
return datetime.utcnow()
if __name__ == "__main__":
print(check_date())
Mock datetime.now to freeze time in Python
Use unittest.mock.patch to replace datetime.now with a fixed value so your code always sees the same time during tests.
from datetime import datetime
from unittest.mock import patch
def current_message():
now = datetime.now()
return f"Current time: {now:%Y-%m-%d %H:%M:%S}"
if __name__ == "__main__":
with patch("__main__.datetime") as mock_dt:
mock_dt.now.return_value = datetime(2024, 3, 15, 10, 30, 0)
prin…
Browse by section
Each section groups closely related Python snippets.
Testing & modern typing — Python code examples
What you will find here
This page collects testing & modern typing snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.