mcpField
P
python-testing

python-testing

github.com/autumnsgrove测试与质量672 次安装6 天前更新
代码仓库

关于 python-testing

python-testing 面向编写或运行测试的 Python 开发者和编码 Agent,提供 pytest 测试结构、夹具、模拟及覆盖率配置指导。

主要功能

  1. 01pytest 测试配置与运行
  2. 02Arrange-Act-Assert 测试结构
  3. 03夹具与参数化测试
  4. 04模拟、异常和临时文件测试
  5. 05覆盖率配置与命名规范

适用场景

  1. 01为 Python 代码编写单元测试
  2. 02配置 pytest 和共享夹具
  3. 03模拟 API 调用并测试错误
  4. 04运行测试并查看覆盖率

安装

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

$npx skills add https://github.com/autumnsgrove/lattice --skill python-testing

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

详细介绍

Python 测试技能

何时启用

在以下情况下启用此技能:

  • 编写 Python 单元测试
  • 创建测试文件或测试目录
  • 设置 pytest 配置
  • 使用测试夹具或模拟
  • 运行测试或检查覆盖率

快速命令

# Run all tests
uv run pytest

# Run specific file
uv run pytest tests/test_auth.py

# Run with coverage
uv run pytest --cov=src --cov-report=html

# Run verbose with output
uv run pytest -v -s

# Run tests matching pattern
uv run pytest -k "test_user"

# Run last failed
uv run pytest --lf

测试结构:AAA 模式

遵循 准备-执行-断言 模式,让测试清晰且易于维护:

def test_user_registration():
    # Arrange - set up test data
    email = "[email protected]"
    password = "secure_pass123"
    user_service = UserService()

    # Act - execute the function
    result = user_service.register(email, password)

    # Assert - verify the outcome
    assert result.success is True
    assert result.user.email == email

目录结构

project/
├── src/
│   └── myapp/
├── tests/
│   ├── conftest.py      # Shared fixtures
│   ├── unit/
│   │   └── test_utils.py
│   ├── integration/
│   │   └── test_api.py
│   └── e2e/
│       └── test_workflows.py
└── pyproject.toml

测试夹具(conftest.py)

import pytest
from myapp import create_app

@pytest.fixture
def app():
    """Create application for testing."""
    app = create_app("testing")
    yield app

@pytest.fixture
def client(app):
    """Create test client."""
    return app.test_client()

@pytest.fixture
def sample_user():
    """Create a sample user for testing."""
    return User(email="[email protected]", username="testuser")

参数化测试

@pytest.mark.parametrize("email,expected", [
    ("[email protected]", True),
    ("invalid.email", False),
    ("[email protected]", True),
])
def test_email_validation(email, expected):
    assert is_valid_email(email) == expected

模拟

from unittest.mock import Mock, patch

def test_api_call():
    mock_response = Mock()
    mock_response.json.return_value = {"data": "success"}

    with patch("requests.get", return_value=mock_response):
        result = fetch_data("https://api.example.com")
        assert result == {"data": "success"}

常见模式

测试异常
def test_division_by_zero():
    with pytest.raises(ValueError, match="Cannot divide by zero"):
        divide(10, 0)
使用临时文件进行测试
def test_file_processing(tmp_path):
    test_file = tmp_path / "test.txt"
    test_file.write_text("Hello World")
    result = process_file(str(test_file))
    assert result.word_count == 2
测试环境变量
def test_config_from_env(monkeypatch):
    monkeypatch.setenv("API_KEY", "test_key_123")
    assert load_config().api_key == "test_key_123"

覆盖率配置

# pyproject.toml
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-v --cov=src --cov-report=term-missing"

[tool.coverage.run]
source = ["src"]
omit = ["tests/*"]

命名约定

  • 测试文件:test_*.py
  • 测试函数:test_*
  • 测试类:Test*

相关资源

请参阅 AgentUsage/testing_python.md,了解完整文档,包括:

  • 异步测试模式
  • 集成测试示例
  • CI/CD 集成
  • 测试优先级指南

评论

支持 Markdown