Community生產力與協作github.com

wshobson/python-testing-patterns

使用 pytest、fixtures、mocking 和測試驅動開發來實現全面的測試策略。在編寫 Python 測試、設置測試套件或實施測試最佳實踐時使用。

python-testing-patterns 是什麼?

此 AI 助手技能專注於提供 Python 測試策略與模式,支援 pytest 框架、fixtures、mocking 及測試驅動開發(TDD)。它能幫助開發者編寫健壯的測試案例、設計可重用的測試套件,並採用行業最佳實踐來提升程式碼品質與可靠性。此技能適用於多種 AI 代理平台(如 Claude Code、Cursor、Codex 等),並透過 SKILL.md 文檔提供詳細指引。透過利用 fixtures 建立可重複使用的測試環境、使用 unittest.mock 進行模擬以隔離外部依賴,以及遵循 Given-When-Then 模式編寫清晰的測試,開發者可確保測試易於維護且具有高覆蓋率。此外,它還涵蓋參數化測試以減少重複程式碼,並整合 pytest-timeout 等工具來處理非同步操作和超時情況,讓開發流程更高效且穩固。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/wshobson/agents/tree/main/skills/python-testing-patterns

Installed? Explore more 生產力與協作 skills: steipete/gemini, steipete/gh-issues, steipete/skill-creator · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

python-testing-patterns 是做什麼的?

使用 pytest、fixtures、mocking 和測試驅動開發來實現全面的測試策略。在編寫 Python 測試、設置測試套件或實施測試最佳實踐時使用。

概述

此技能提供了一套完整的 Python 測試模式與最佳實踐,主要圍繞 pytest 生態系統。它涵蓋了從基本測試撰寫到進階主題(如 fixtures、mocking、參數化測試和 TDD)的所有內容。無論是為現有專案新增測試,還是從零開始建立測試套件,此模式都能協助你創建可靠且易於維護的測試。

核心模式

1. 基礎測試結構

import pytest
from my_module import add

def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0

2. 使用 Fixtures

Fixtures 允許你建立可重複使用的測試元件。

import pytest

@pytest.fixture
def database():
    # 設置:建立資料庫連接
    db = create_database()
    yield db
    # 清理:關閉連接
    db.close()

def test_query(database):
    result = database.query("SELECT * FROM users")
    assert len(result) > 0

3. Mocking 外部依賴

使用 unittest.mock 來隔離測試與外部服務。

from unittest.mock import Mock, patch

def test_api_call():
    with patch('my_module.requests.get') as mock_get:
        mock_get.return_value.json.return_value = {'key': 'value'}
        response = my_function()
        assert response == {'key': 'value'}

4. 測試驅動開發 (TDD) 模式

遵循紅-綠-重構循環:

  1. 紅:先編寫一個會失敗的測試。
  2. 綠:撰寫最簡單的程式碼讓測試通過。
  3. 重構:在不破壞測試的情況下改進程式碼。

5. 參數化測試

使用參數化減少重複程式碼。

@pytest.mark.parametrize("input,expected", [
    (1, 1),
    (2, 4),
    (3, 9),
])
def test_square(input, expected):
    assert square(input) == expected

最佳實踐

  • 使用明確的測試名稱以描述預期行為。
  • 保持測試獨立且可隔離執行。
  • 善用 Fixtures 進行設置和清理。
  • 將 Mock 僅用於測試邊界。
  • 採用 Given-When-Then 模式撰寫測試。
  • 將測試檔案放在 tests/ 目錄中。

進階 Fixtures

範圍 Fixtures

@pytest.fixture(scope="session")
def global_config():
    return load_config()

支援的範圍:function(預設)、class、module、session。

使用 Fixtures 的 Fixtures

@pytest.fixture
def user(database):
    return database.create_user(username="test")

非同步測試

支援非同步測試。

@pytest.mark.asyncio
async def test_async_function():
    result = await async_function()
    assert result == expected_value

錯誤測試

def test_raises_exception():
    with pytest.raises(ValueError):
        function_that_raises()

覆蓋率

確保高覆蓋率。

pytest --cov=my_module tests/

持續整合

整合至 CI 流程。

# .github/workflows/test.yml
name: Test
on: [push]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Run tests
        run: pytest --cov-report=xml

疑難排解

  • 確保 pytest 已安裝:pip install pytest pytest-cov pytest-asyncio
  • 檢查測試發現規則。
  • 使用 pytest -v 獲取詳細輸出。
  • 使用 pytest --tb=short 縮短回溯資訊。

整合範例

結合多個模式。

import pytest
from unittest.mock import patch

@pytest.fixture
def mock_external_service():
    with patch('my_module.external_service') as mock:
        mock.return_value = "mocked"
        yield mock

def test_integration(mock_external_service):
    result = my_function()
    assert result == "mocked"

常見陷阱

  • 測試順序依賴:避免測試間互相依賴。
  • 過度 Mock:只 mock 你需要隔離的元件。
  • 忽略邊界情況:測試邊界值。
  • 不充分的清理:確保 Fixtures 能正確清理。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

wshobson/accessibility-compliance

Implement WCAG 2.2 compliant interfaces with mobile accessibility, inclusive design patterns, and assistive technology support. Use when auditing accessibility, implementing ARIA patterns, building for screen readers, or ensuring inclusive user experiences.

wshobson/airflow-dag-patterns

Build production Apache Airflow DAGs with best practices for operators, sensors, testing, and deployment. Use when creating data pipelines, orchestrating workflows, or scheduling batch jobs.

wshobson/angular-migration

Migrate from AngularJS to Angular using hybrid mode, incremental component rewriting, and dependency injection updates. Use when upgrading AngularJS applications, planning framework migrations, or modernizing legacy Angular code.

wshobson/anti-reversing-techniques

Understand anti-reversing, obfuscation, and protection techniques encountered during software analysis. Use this skill when analyzing malware evasion techniques, when implementing anti-debugging protections for CTF challenges, when reverse engineering packed binaries, or when building security research tools that need to detect virtualized environments.

wshobson/api-design-principles

Master REST and GraphQL API design principles to build intuitive, scalable, and maintainable APIs that delight developers. Use when designing new APIs, reviewing API specifications, or establishing API design standards.

wshobson/architecture-decision-records

Write and maintain Architecture Decision Records (ADRs) following best practices for technical decision documentation. Use when documenting significant technical decisions, reviewing past architectural choices, or establishing decision processes.

wshobson/architecture-patterns

Implement proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design. Use this skill when designing clean architecture for a new microservice, when refactoring a monolith to use bounded contexts, when implementing hexagonal or onion architecture patterns, or when debugging dependency cycles between application layers.

wshobson/async-python-patterns

Master Python asyncio, concurrent programming, and async/await patterns for high-performance applications. Use when building async APIs, concurrent systems, or I/O-bound applications requiring non-blocking operations.

wshobson/attack-tree-construction

Build comprehensive attack trees to visualize threat paths. Use when mapping attack scenarios, identifying defense gaps, or communicating security risks to stakeholders.

wshobson/auth-implementation-patterns

Master authentication and authorization patterns including JWT, OAuth2, session management, and RBAC to build secure, scalable access control systems. Use when implementing auth systems, securing APIs, or debugging security issues.

wshobson/avoid-ai-writing

Audit and rewrite prose so it stops reading as machine-generated. Use this skill when asked to remove AI-isms, clean up AI writing, edit a draft for AI tells, audit a README, changelog, release note, PR description, or blog post for machine-sounding prose, or make text sound less like AI. Supports a detect-only mode, a rewrite mode, and an edit-in-place mode, with optional voice and context profiles.

wshobson/backtesting-frameworks

Build robust backtesting systems for trading strategies with proper handling of look-ahead bias, survivorship bias, and transaction costs. Use when developing trading algorithms, validating strategies, or building backtesting infrastructure.

wshobson/bash-defensive-patterns

Master defensive Bash programming techniques for production-grade scripts. Use when writing robust shell scripts, CI/CD pipelines, or system utilities requiring fault tolerance and safety.

wshobson/bats-testing-patterns

Master Bash Automated Testing System (Bats) for comprehensive shell script testing. Use when writing tests for shell scripts, CI/CD pipelines, or requiring test-driven development of shell utilities.

wshobson/bazel-build-optimization

Optimize Bazel builds for large-scale monorepos. Use when configuring Bazel, implementing remote execution, or optimizing build performance for enterprise codebases.

wshobson/before-you-build

Pre-build product and feature risk review for founders, product managers, and AI-assisted builders. Use this skill when the user is about to build a landing page, MVP, SaaS product, internal tool, agent workflow, or major feature and needs to check demand, positioning, monetization, retention, trust, distribution, and adoption risk before implementation starts.

wshobson/billing-automation

Build automated billing systems for recurring payments, invoicing, subscription lifecycle, and dunning management. Use when implementing subscription billing, automating invoicing, or managing recurring payment systems.

wshobson/binary-analysis-patterns

Master binary analysis patterns including disassembly, decompilation, control flow analysis, and code pattern recognition. Use when analyzing executables, understanding compiled code, or performing static analysis on binaries.

wshobson/block-no-verify-hook

Configure a PreToolUse hook to prevent AI agents from skipping git pre-commit hooks with --no-verify and other bypass flags. Use when setting up Claude Code projects that enforce commit quality gates.

wshobson/brand-landingpage

Brand-first landing page designer — runs a brand-identity interview (colors, typography, shape language), then generates and iterates on a polished landing page via Stitch with deployment-ready HTML. Use when the user asks to create, design, or build a landing page, homepage, or marketing page and has no established visual direction. Skip when they have a design mockup, need a dashboard or app UI, are working at component level, building a multi-page app, or restyling with known design tokens — use frontend-design instead.

相關技能