mcpField
P
python-testing-patterns

python-testing-patterns

github.com/nickcrew测试与质量6287 次安装18 周前更新
代码仓库

关于 python-testing-patterns

python-testing-patterns 为构建和维护 Python 测试套件的开发者提供参考指南,涵盖 pytest、夹具、模拟、异步、集成及基于属性的测试,并按主题提供详细资料。

主要功能

  1. 01pytest 测试结构与发现
  2. 02夹具设置、作用域与清理
  3. 03参数化测试与模拟
  4. 04异步及基于属性的测试
  5. 05集成测试与覆盖率指南

适用场景

  1. 01为 Python 项目搭建 pytest 套件
  2. 02测试 API、数据库和外部服务
  3. 03检查异步代码与边界情况
  4. 04衡量覆盖率并组织测试运行

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/nickcrew/claude-cortex --skill python-testing-patterns

安装后在 Claude Code 中输入/python-testing-patterns确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
async-testing.md
best-practices.md
coverage.md
fixtures.md
integration-testing.md
mocking.md
monkeypatch.md
parametrized-tests.md
property-based-testing.md
pytest-fundamentals.md
test-organization.md
validation/
rubric.yaml

详细介绍

Python 测试模式

全面介绍如何使用 pytest、fixtures、模拟、参数化和基于属性的测试,在 Python 中实施稳健的测试策略。

何时使用此技能

  • 为 Python 函数和类编写单元测试
  • 搭建全面的测试套件和基础设施
  • 实施测试驱动开发(TDD)工作流
  • 为 API、数据库和服务创建集成测试
  • 模拟外部依赖项和第三方服务
  • 测试异步代码和并发操作
  • 使用 Hypothesis 实施基于属性的测试
  • 搭建 CI/CD 测试自动化
  • 调试失败的测试并提升测试覆盖率

核心概念

测试发现:文件名匹配 test_*.py 或 *_test.py,函数名以 test_ 开头

Fixtures:带有设置和清理步骤的可复用测试资源

  • 作用域:function(默认)、class、module、session
  • 组合:通过简单 fixtures 构建复杂 fixtures
  • 在 conftest.py 中共享,以便整个项目使用

断言:使用 assert 语句,使用 pytest.raises() 检查异常

组织结构:分设 unit/、integration/、e2e/ 目录

快速参考

按需加载特定主题的详细参考资料:

任务参考文件
Pytest 基础、测试结构、AAA 模式skills/python-testing-patterns/references/pytest-fundamentals.md
Fixtures、作用域、设置/清理、conftest.pyskills/python-testing-patterns/references/fixtures.md
参数化、多种测试用例skills/python-testing-patterns/references/parametrized-tests.md
模拟、打补丁、unittest.mock、pytest-mockskills/python-testing-patterns/references/mocking.md
异步测试、pytest-asyncio、事件循环skills/python-testing-patterns/references/async-testing.md
基于属性的测试、Hypothesis、策略skills/python-testing-patterns/references/property-based-testing.md
Monkeypatch、环境变量、属性skills/python-testing-patterns/references/monkeypatch.md
测试结构、标记、conftest.py 模式skills/python-testing-patterns/references/test-organization.md
覆盖率测量、报告、阈值skills/python-testing-patterns/references/coverage.md
数据库、API、Redis、消息队列测试skills/python-testing-patterns/references/integration-testing.md
最佳实践、测试质量、fixture 设计skills/python-testing-patterns/references/best-practices.md

工作流

1. 基本测试设置
# test_example.py
import pytest

def test_something():
    """Descriptive test name."""
    # Arrange
    expected = 5

    # Act
    result = 2 + 3

    # Assert
    assert result == expected

运行测试:

pytest                    # Run all tests
pytest -v                 # Verbose output
pytest tests/unit/        # Specific directory
pytest -k "test_user"     # Match pattern
pytest -m unit            # Run marked tests
2. 使用 Fixtures
@pytest.fixture
def sample_data():
    """Provide test data."""
    data = {"key": "value"}
    yield data
    # Cleanup if needed

def test_with_fixture(sample_data):
    assert sample_data["key"] == "value"
3. 参数化测试
@pytest.mark.parametrize("input,expected", [
    (2, 4),
    (3, 9),
    (4, 16),
])
def test_square(input, expected):
    assert input ** 2 == expected
4. 模拟外部依赖项
from unittest.mock import patch

@patch("module.external_api_call")
def test_with_mock(mock_api):
    mock_api.return_value = {"status": "ok"}

    result = my_function()

    assert result["status"] == "ok"
    mock_api.assert_called_once()
5. 覆盖率测量
pytest --cov=src --cov-report=term-missing
pytest --cov=src --cov-report=html
pytest --cov=src --cov-fail-under=80
6. 测试配置

pytest.ini:

[pytest]
testpaths = tests
python_files = test_*.py
addopts = -v --strict-markers --cov=src
markers =
    unit: Unit tests
    integration: Integration tests
    slow: Slow tests

常见模式

异常测试:

with pytest.raises(ValueError, match="error message"):
    function_that_raises()

异步测试:

@pytest.mark.asyncio
async def test_async_function():
    result = await async_operation()
    assert result is not None

临时文件:

def test_file_operation(tmp_path):
    test_file = tmp_path / "test.txt"
    test_file.write_text("content")
    assert test_file.read_text() == "content"

用于筛选测试的标记:

@pytest.mark.slow
@pytest.mark.integration
def test_database_operation():
    pass

常见错误

  1. 不使用 fixtures:在多个测试中重复设置代码

    • 解决方案:在 conftest.py 中创建 fixtures
  2. 测试依赖执行顺序:全局状态受到污染

    • 解决方案:使用适当的 fixtures 确保测试彼此独立
  3. 过度模拟:模拟内部实现

    • 解决方案:仅模拟外部边界(API、数据库)
  4. 遗漏边界情况:只测试正常路径

    • 解决方案:测试边界条件、错误和无效输入
  5. 测试缓慢:频繁运行完整的集成测试

    • 解决方案:分开单元测试和集成测试,使用标记,并优化 fixtures
  6. 忽视覆盖率缺口:不测量测试覆盖率

    • 解决方案:使用 pytest-cov 并跟踪指标
  7. 测试名称不佳:使用 test_1() 之类的通用名称

    • 解决方案:使用描述性名称:test_<behavior>_<condition>_<expected>
  8. 没有清理:资源未释放

    • 解决方案:使用带有适当清理步骤的 fixtures(yield 模式)

资源

评论

支持 Markdown