python-testing

A Python testing guide built around pytest, a Python test framework, and TDD, a method of writing a failing test before the code that makes it pass.

In plain words
What is it for?
Use it when adding or reviewing Python code, designing a test suite, or setting up testing. It covers fixtures, mocks, parameterized tests, the red-green-refactor cycle, and coverage requirements.
Why use it?
It gives a repeatable way to design tests, check behavior, and measure whether important code paths are covered.

Skill for Claude CodeCodex

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add skills/luohaothu/everything-codex/python-testing
Any agent
npx skills add Luohaothu/everything-codex --skill python-testing
Clone the repo
git clone --depth 1 https://github.com/Luohaothu/everything-codex

Made for: Claude Code, Codex.

Per session 26 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 4,607 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 1 finding. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00026 $0.04607
Opus 5 $0.00013 $0.02303
Sonnet 5 $0.00005 $0.00921
Haiku 4.5 $0.00003 $0.00461

Measured 2d ago against content hash a32ca141a566, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

python-testing scanned grade A with 1 finding against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 2d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Makes network callslowCapability

Not a fault in itself. Listed so you know the mod talks to something, and to what.

response = requests.get("https://api.example.com")
docs/zh-CN/skills/python-testing/SKILL.md · 816 lines

How it starts

The opening of the file, as written. The whole thing — 816 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Python 测试模式

使用 pytest、TDD 方法论和最佳实践的 Python 应用程序全面测试策略。

何时激活

  • 编写新的 Python 代码(遵循 TDD:红、绿、重构)
  • 为 Python 项目设计测试套件
  • 审查 Python 测试覆盖率
  • 设置测试基础设施

核心测试理念

测试驱动开发 (TDD)

始终遵循 TDD 循环:

  1. :为期望的行为编写一个失败的测试
  2. 绿:编写最少的代码使测试通过
  3. 重构:在保持测试通过的同时改进代码
# Step 1: Write failing test (RED)
def test_add_numbers():
    result = add(2, 3)
    assert result == 5

# Step 2: Write minimal implementation (GREEN)
def add(a, b):
    return a + b

# Step 3: Refactor if needed (REFACTOR)

覆盖率要求

  • 目标:80%+ 代码覆盖率
  • 关键路径:需要 100% 覆盖率
  • 使用 pytest --cov 来测量覆盖率
pytest --cov=mypackage --cov-report=term-missing --cov-report=html

pytest 基础

基本测试结构

import pytest

def test_addition():
    """Test basic addition."""
    assert 2 + 2 == 4

def test_string_uppercase():
    """Test string uppercasing."""
    text = "hello"
    assert text.upper() == "HELLO"

def test_list_append():
    """Test list append."""
    items = [1, 2, 3]
    items.append(4)
    assert 4 in items
    assert len(items) == 4

断言

# Equality
assert result == expected

# Inequality
assert result != unexpected

# Truthiness
assert result  # Truthy
assert not result  # Falsy
assert result is True  # Exactly True
assert result is False  # Exactly False
assert result is None  # Exactly None

# Membership
assert item in collection
assert item not in collection

# Comparisons
assert result > 0
assert 0 <= result <= 100

# Type checking
assert isinstance(result, str)

# Exception testing (preferred approach)
with pytest.raises(ValueError):
    raise ValueError("error message")

# Check exception message
with pytest.raises(ValueError, match="invalid input"):
    raise ValueError("invalid input provided")

# Check exception attributes
with pytest.raises(ValueError) as exc_info:
    raise ValueError("error message")
assert str(exc_info.value) == "error message"

夹具

基本夹具使用

import pytest

@pytest.fixture
def sample_data():
    """Fixture providing sample data."""
    return {"name": "Alice", "age": 30}

def test_sample_data(sample_data):
    """Test using the fixture."""
    assert sample_data["name"] == "Alice"
    assert sample_data["age"] == 30

Read the full file on GitHub · 816 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 2d ago First seen · 816 lines · 26 tokens per session scan A a32ca141a566

Subscribe to this mod's changes

python-testing is a skill published in the GitHub repository Luohaothu/everything-codex (24 stars, last pushed 21d ago), licensed MIT. It adds 26 tokens to every session and 4,607 once invoked, about $0.0001 per session on Opus 5. A static security scan graded it A with 1 finding (makes network calls). No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.

Related

Other skills, from other repositories

systematic-debugging

Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes.

obra/superpowers · 21 tokens

next-cache-components-adoption

Turn on Cache Components in a Next.js app and resolve the blocking routes it surfaces. Use when the user wants to enable, adopt, or migrate to Cache Components, flip the cacheComponents flag, work through a flood of blocking-prerender / instant validation errors, run the cache-components-instant-false codemod, or…

vercel/next.js · 95 tokens

babysit-pr

Babysit a GitHub pull request after creation by continuously polling review comments, CI checks/workflow runs, and mergeability state until the PR is merged/closed or user help is required. Diagnose failures, retry likely flaky failures up to 3 times, auto-fix/push branch-related issues when appropriate, and keep…

openai/codex · 114 tokens

imagegen

Generate or edit raster images when the task benefits from AI-created bitmap visuals such as photos, illustrations, textures, sprites, mockups, or transparent-background cutouts. Use when Codex should create a brand-new image, transform an existing image, or derive visual variants from references, and the output…

openai/codex · 113 tokens

cpu-profile-analysis

Analyze V8/Chrome CPU profiles (.cpuprofile) and DevTools trace files (Trace-.json). Use when: profiling performance, investigating slow functions, comparing code paths, finding bottlenecks, analyzing timeToRequest, understanding call trees from sampling profiler data, analyzing layout/paint/rendering, investigating…

microsoft/vscode · 71 tokens

next-cache-components-optimizer

Drive a Next.js route to instant navigation by setting up an agentic loop, under Cache Components / PPR, on initial load (hard navigation) and client-side navigation (soft navigation). Encode the goal as a failing @next/playwright instant() e2e and work it to green, one verified route at a time; the shipped test then…

vercel/next.js · 170 tokens