Reference library

Testing & modern typing

pytest basics, mocks, type hints, TypedDict, Protocol, and static-checking patterns.

11 matches
Testing & modern typing easy

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.

mock unittest file-io
Python
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):…
14 0 Open
Testing & modern typing easy

How to Mock requests.get in Python

Mock requests.get with unittest.mock to test code that makes HTTP calls without hitting the network.

mocking requests unit-testing
Python
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…
12 0 Open
Testing & modern typing easy

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.

unittest mock magicmock
Python
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…
12 0 Open
Testing & modern typing easy

How to Mock subprocess.run returncode in Python

Simulate subprocess.run return codes in tests with unittest.mock.patch and CompletedProcess.

unittest mock subprocess
Python
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…
14 0 Open
Testing & modern typing easy

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.

unittest mock testing
Python
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…
14 0 Open
Testing & modern typing easy

How to Use setUp and tearDown in Python unittest TestCase

Demonstrates how to structure unit tests with setUp and tearDown methods in Python's unittest framework for reusable test fixtures.

unittest testing setupteardown
Python
import unittest


class ExampleTest(unittest.TestCase):
    def setUp(self):
        self.data = [1, 2, 3]

    def tearDown(self):
        self.data = None

    def test_length(self):
        self.assertEqual(len(self.data), 3)

    def test_contains(self):
        self.assertIn(2, self.data)


if __name__ == "__main…
13 0 Open
Testing & modern typing easy

How to Verify Formatted Output with an Approval Test in Python

Write a small Python approval test that verifies a function's exact formatted output using unittest.

approval-testing unittest formatting
Python
import sys
from io import StringIO
import unittest

def generate_output(name, score):
    return f"Player: {name} | Score: {score:03d}"

class TestFormattedOutput(unittest.TestCase):
    def test_output_format(self):
        expected = "Player: Alice | Score: 042"
        result = generate_output("Alice", 42)
        …
13 0 Open
Testing & modern typing easy

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.

contract-testing unittest mock
Python
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…
13 0 Open
Testing & modern typing easy

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.

unittest mock side_effect
Python
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…
13 0 Open
Testing & modern typing easy

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.

datetime mock unittest
Python
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…
14 0 Open
Testing & modern typing easy

Table-Driven Tests in Python (unittest)

Run a single unittest test against many input cases using a list of tuples and subTest.

unittest table-driven testing
Python
import unittest

def add(a, b):
    return a + b

class TestAddFunction(unittest.TestCase):

    def test_add_with_table(self):
        cases = [
            (1, 2, 3),
            (-1, 1, 0),
            (0, 0, 0),
            (2, -3, -1),
        ]
        for x, y, expected in cases:
            with self.subTest(x…
14 0 Open

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.