Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

62 matches
Automation & scripting easy

How to Mock subprocess Calls in Python with unittest.mock

A Python script that wraps Vagrant up/destroy commands using subprocess, with tests that mock the subprocess call to simulate outputs and errors.

subprocess unittest.mock vagrant
Python
import subprocess
from unittest.mock import patch, Mock


def run_vagrant(action: str) -> str:
    result = subprocess.run(
        ["vagrant", action],
        capture_output=True,
        text=True,
        check=False,
    )
    return result.stdout.strip()


def vagrant_wrapper(action: str) -> str:
    if action n…
14 0 Open
Automation & scripting easy

Mock a Helm Upgrade Install Command in Python

Use unittest mock to simulate a Helm upgrade --install call for testing automation scripts without a real cluster.

mock helm testing
Python
from unittest.mock import MagicMock, patch


class HelmClient:
    def upgrade_install(self, release, chart, namespace="default"):
        # Simulates the helm upgrade --install command
        return f"Release {release} upgraded/installed in {namespace} using chart {chart}"


@patch("helm_client.HelmClient.upgrade_in…
13 0 Open
Git + Python medium

How to Mock Git Cherry-Pick in Python for Tests

Mock the `repo.git.cherry_pick` method with `unittest.mock` to test a Git cherry-pick helper without a real repository.

git mock unittest
Python
from unittest.mock import patch, MagicMock

class GitCherryPicker:
    def __init__(self):
        self.applied_commits = []
    
    def cherry_pick(self, commit_hash, repo):
        try:
            result = repo.git.cherry_pick(commit_hash)
            self.applied_commits.append(commit_hash)
            return f"A…
14 0 Open
Git + Python medium

How to Mock Git Stash and Pop in Python

Mock Git stash, apply, and pop operations using unittest.mock so you can test Git automation without touching a real repository.

git mock gitpython
Python
import git
from unittest.mock import Mock, patch

def stash_and_pop(repo):
    """Mock a stash operation and then pop it back."""
    repo.git.stash("save", "WIP: temp changes")
    stashed_output = repo.git.stash("list")
    
    # Simulate the stash was applied, then pop
    repo.git.stash("apply", "stash@{0}")
    …
14 0 Open
Git + Python medium

How to Mock open() in Python Using unittest.mock.patch

This code shows how to use unittest.mock.patch with mock_open to test a function that checks if a Git patch can be reverse-applied by reading file content.

unittest mocking git
Python
import unittest
from unittest.mock import patch, mock_open


def apply_reverse_check(file_path, expected_patch):
    """
    Check if a patch can be reverse-applied by comparing file content
    with the expected patch's reverse result.
    """
    try:
        with open(file_path, "r") as f:
            content = f.r…
15 0 Open
Git + Python easy

How to Mock subprocess.run in Python Tests

Mock subprocess.run to test a Git submodule update command without executing it in your test suite.

unittest.mock subprocess git
Python
import subprocess
from unittest.mock import Mock, patch

def update_submodules():
    subprocess.run(["git", "submodule", "update", "--init", "--recursive"], check=True)

with patch("subprocess.run") as mock_run:
    mock_run.return_value = Mock(returncode=0)
    update_submodules()
    mock_run.assert_called_once_wit…
13 0 Open
Git + Python medium

Mock smtplib to Test Patch Email Series in Python

Simulate sending a numbered series of patch emails with smtplib and verify the calls using unittest.mock without a real mail server.

smtplib unittest.mock email
Python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from unittest.mock import patch, Mock

def send_patch_series(subject_prefix, patches, smtp_host="localhost", smtp_port=25):
    """Simulate sending a series of patch emails."""
    for i, patch_content in enumerate(patch…
13 0 Open
Cloud + Python medium

How to Mock Azure Key Vault Secret Get in Python

Mock an Azure Key Vault client's get_secret method with unittest.mock to test functions that retrieve secret values without hitting the real service.

azure key-vault unittest
Python
import unittest
from unittest.mock import MagicMock, patch


def get_secret(key_vault_client, secret_name):
    """Retrieve a secret value from an Azure Key Vault client."""
    secret = key_vault_client.get_secret(secret_name)
    return secret.value


class TestKeyVaultSecretGet(unittest.TestCase):
    def test_get_…
13 0 Open
Cloud + Python medium

How to mock boto3 S3 upload in Python

Shows how to mock the boto3 S3 client with unit tests and wrap an upload function to return a dictionary with status details.

boto3 s3 mocking
Python
import boto3
from unittest.mock import Mock, patch

class S3Uploader:
    def __init__(self, bucket_name):
        self.bucket_name = bucket_name
        self.s3 = boto3.client("s3", region_name="us-east-1")

    def upload_file(self, local_path, s3_key):
        self.s3.upload_file(local_path, self.bucket_name, s3_ke…
12 0 Open
Modern tooling easy

How to Mock BugSnag Notify in Python

Use unittest.mock to simulate BugSnag notifications, verify calls, and test error handling without external dependencies.

mocking bugsnag testing
Python
import mock

bugsnag = mock.MagicMock()

def notify_error(message, severity="error"):
    bugsnag.notify(message, severity=severity)

if __name__ == "__main__":
    notify_error("Test error", severity="warning")
    bugsnag.notify.assert_called_once_with("Test error", severity="warning")
    print("Mocked BugSnag noti…
16 0 Open
Modern tooling medium

How to Mock CLI Output in Typer with unittest.mock

Mock and capture Typer CLI output using unittest.mock.patch and io.StringIO for testing command-line applications.

typer cli testing
Python
import typer
from unittest.mock import patch
import io

app = typer.Typer()

@app.command()
def greet(name: str, age: int = 18, uppercase: bool = False):
    """Greet a person with optional formatting."""
    message = f"Hello {name}, age {age}"
    if uppercase:
        message = message.upper()
    typer.echo(messag…
11 0 Open
Modern tooling medium

How to Mock a PEP 517 Build Backend in Python

Use unittest.mock.Mock to simulate a PEP 517 backend interface, stub build hooks, and verify calls for package build automation.

pep517 unittest.mock packaging
Python
import json
from unittest.mock import Mock

# Simulate a PEP 517 backend interface
class Pep517Backend:
    def build_wheel(self, wheel_directory, config_settings=None, metadata_directory=None):
        return f"{wheel_directory}/mock_package-1.0.0-py3-none-any.whl"

    def get_requires_for_build_wheel(self, config_s…
14 0 Open
Modern tooling easy

How to Mock isort Output to Test Import Sorting in Python

Uses isort with check mode and a unittest mock to verify whether a Python source string has correctly sorted imports.

isort import-sorting mock
Python
import isort
from unittest.mock import patch

code = """
import os
import sys
import json
import pathlib
"""

def check_imports_sorted(code_str):
    with patch("isort.api.output") as mock_output:
        isort.code(code_str, check=True, show_diff=True)
        return mock_output.called

if __name__ == "__main__":
   …
10 0 Open
Modern tooling easy

How to Mock setuptools_scm get_version in Python

This code demonstrates how to mock setuptools_scm.get_version in Python using unittest.mock.patch to test version retrieval logic without installing or relying on the actual package.

setuptools-scm mock unittest
Python
```python
from unittest.mock import patch

def get_version_from_scm():
    try:
        import setuptools_scm
        return setuptools_scm.get_version()
    except (ImportError, LookupError):
        return None

if __name__ == "__main__":
    with patch("setuptools_scm.get_version", return_value="1.2.3"):
        pr…
14 0 Open
Modern tooling medium

How to Mock subprocess.run for Black Formatter in Python

Use unittest.mock to simulate subprocess.run calls in a Python function that runs the Black formatter, allowing isolated testing without executing external commands.

unittest mock subprocess
Python
import subprocess
from unittest.mock import Mock, patch

def run_black_formatter(file_path: str, check_only: bool = False) -> dict:
    """Run black formatter on a file via subprocess."""
    cmd = ["black", "--check" if check_only else "-", file_path]
    result = subprocess.run(cmd, capture_output=True, text=True)
 …
15 0 Open
Modern tooling easy

How to Run Coverage Report and Generate HTML in Python

Use the coverage module to measure test coverage, save the report, and generate an HTML report in Python.

coverage testing unittest
Python
import coverage
import unittest


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


class TestAdd(unittest.TestCase):
    def test_add_positive(self):
        self.assertEqual(add(2, 3), 5)


if __name__ == "__main__":
    cov = coverage.Coverage(source=["__main__"])
    cov.start()
    suite = unittest.defaultTestLoader.loadTestsFro…
12 0 Open
Modern tooling medium

How to mock argparse nested subparsers in Python

Build an argparse parser with nested subparsers and test it using unittest.mock.patch for sys.argv and sys.stdout.

argparse subparsers unittest
Python
import argparse
from unittest.mock import patch
from io import StringIO

def build_parser():
    parser = argparse.ArgumentParser(prog="app")
    subparsers = parser.add_subparsers(dest="command", required=True)

    # Outer subparser
    outer = subparsers.add_parser("outer")
    outer_sub = outer.add_subparsers(dest…
15 0 Open
Modern tooling medium

Mock Python version with unittest.mock.patch

Use unittest.mock.patch to simulate a specific Python version and test version-dependent behavior.

unittest mock version
Python
import sys
import unittest
from unittest.mock import patch

class TestPythonVersion(unittest.TestCase):
    @patch("sys.version_info", (3, 9, 0, "final", 0))
    def test_python_version_pinned(self):
        self.assertEqual(sys.version_info[:2], (3, 9))
        print(f"Pinned version: {sys.version_info.major}.{sys.ve…
13 0 Open
Modern tooling easy

Mock pdm build and publish in Python

Simulate pdm build and publish commands with unittest.mock to test packaging workflows without triggering real builds or uploads.

pdm mock unittest
Python
from unittest.mock import Mock, patch

import pdm


def build_package() -> str:
    """Simulate building a package with pdm."""
    build_mock = Mock(return_value="dist/mypackage-0.1.0-py3-none-any.whl")
    with patch.object(pdm, "build", build_mock):
        result = pdm.build()
    return result


def publish_packa…
12 0 Open
Testing & modern typing medium

How to Mock a Factory Boy Model Instance in Python

Create a factory boy factory, then patch its Meta.model with a Mock to control instance behavior in tests.

factory-boy mocking unit-testing
Python
import factory
from dataclasses import dataclass
from unittest.mock import Mock, patch
import builtins


@dataclass
class User:
    name: str
    age: int


class UserFactory(factory.Factory):
    class Meta:
        model = User

    name = "Alice"
    age = 30


def get_user_name(user):
    return user.name


def ma…
15 0 Open
Testing & modern typing medium

How to Mock an Object Method in Python unittest

Mock a method on an instance or class with @patch.object, set its return value, and assert its call arguments in Python unittest.

unittest mock patch
Python
import unittest
from unittest.mock import patch

class Calculator:
    def add(self, a, b):
        return a + b
    
    def multiply(self, a, b):
        return a * b

class TestCalculator(unittest.TestCase):
    def test_add_normal(self):
        calc = Calculator()
        result = calc.add(2, 3)
        self.asse…
14 0 Open
Testing & modern typing medium

How to Mock and Stub API Calls in Playwright E2E Tests with Python

This code demonstrates how to mock and stub API responses in Playwright end-to-end tests using Python's unittest.mock patch and Playwright's APIRequestContext.

playwright e2e-testing mocking
Python
import re
from unittest.mock import patch
from playwright.sync_api import sync_playwright

def verify_api_mock(page, mock_url, mock_response):
    with patch("playwright.sync_api.APIRequestContext.get") as mock_get:
        mock_get.return_value.json.return_value = mock_response
        mock_get.return_value.status_co…
13 0 Open
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

Browse by section

Each section groups closely related Python snippets.

Guide: free Python code samples library

Copy-ready Python snippets for learners and developers

PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.

How to use this library

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. Run it in the IDE, tweak values, then take a related quiz or tutorial lesson

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.