mcpField
P
python-pytest-patterns

python-pytest-patterns

github.com/0xdarkmatter测试与质量7859 次安装2 周前更新
代码仓库

关于 python-pytest-patterns

面向 Python 开发者的 pytest 模式参考技能,涵盖测试结构、fixture、参数化、异常、标记与模拟,并附带脚本和模板。

主要功能

  1. 01测试结构与断言
  2. 02Fixture 作用域与共享
  3. 03参数化和异常测试
  4. 04标记与模拟模式
  5. 05命令、脚本和配置模板

适用场景

  1. 01为测试添加可复用的 fixture
  2. 02为多组输入编写参数化测试
  3. 03模拟 API 调用并检查异常
  4. 04按名称或标记运行 pytest 测试

安装

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

$npx skills add https://github.com/0xdarkmatter/claude-mods --skill python-pytest-patterns

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

包含的文件

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

assets/
conftest.py.template
pytest.ini.template
references/
async-testing.md
coverage-strategies.md
fixtures-advanced.md
integration-testing.md
mocking-patterns.md
property-testing.md
test-architecture.md
scripts/
generate-conftest.sh
run-tests.sh

详细介绍

Python pytest 模式

用于高效测试的现代 pytest 模式。

基本测试结构

import pytest

def test_basic():
    """Simple assertion test."""
    assert 1 + 1 == 2

def test_with_description():
    """Descriptive name and docstring."""
    result = calculate_total([1, 2, 3])
    assert result == 6, "Sum should equal 6"

Fixtures

import pytest

@pytest.fixture
def sample_user():
    """Create test user."""
    return {"id": 1, "name": "Test User"}

@pytest.fixture
def db_connection():
    """Fixture with setup and teardown."""
    conn = create_connection()
    yield conn
    conn.close()

def test_user(sample_user):
    """Fixtures injected by name."""
    assert sample_user["name"] == "Test User"
Fixture 作用域
@pytest.fixture(scope="function")  # Default - per test
@pytest.fixture(scope="class")     # Per test class
@pytest.fixture(scope="module")    # Per test file
@pytest.fixture(scope="session")   # Entire test run

参数化

@pytest.mark.parametrize("input,expected", [
    (1, 2),
    (2, 4),
    (3, 6),
])
def test_double(input, expected):
    assert double(input) == expected

# Multiple parameters
@pytest.mark.parametrize("x", [1, 2])
@pytest.mark.parametrize("y", [10, 20])
def test_multiply(x, y):  # 4 test combinations
    assert x * y > 0

异常测试

def test_raises():
    with pytest.raises(ValueError) as exc_info:
        raise ValueError("Invalid input")
    assert "Invalid" in str(exc_info.value)

def test_raises_match():
    with pytest.raises(ValueError, match=r".*[Ii]nvalid.*"):
        raise ValueError("Invalid input")

标记

@pytest.mark.skip(reason="Not implemented yet")
def test_future_feature():
    pass

@pytest.mark.skipif(sys.platform == "win32", reason="Unix only")
def test_unix_feature():
    pass

@pytest.mark.xfail(reason="Known bug")
def test_buggy():
    assert broken_function() == expected

@pytest.mark.slow
def test_performance():
    """Custom marker - register in pytest.ini."""
    pass

模拟

from unittest.mock import Mock, patch, MagicMock

def test_with_mock():
    mock_api = Mock()
    mock_api.get.return_value = {"status": "ok"}
    result = mock_api.get("/endpoint")
    assert result["status"] == "ok"

@patch("module.external_api")
def test_with_patch(mock_api):
    mock_api.return_value = {"data": []}
    result = function_using_api()
    mock_api.assert_called_once()
pytest-mock(推荐)
def test_with_mocker(mocker):
    mock_api = mocker.patch("module.api_call")
    mock_api.return_value = {"success": True}
    result = process_data()
    assert result["success"]

conftest.py

# tests/conftest.py - Shared fixtures

import pytest

@pytest.fixture(scope="session")
def app():
    """Application fixture available to all tests."""
    return create_app(testing=True)

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

快速参考

命令描述
pytest运行所有测试
pytest -v输出详细信息
pytest -x首次失败时停止
pytest -k "test_name"运行匹配的测试
pytest -m slow运行已标记的测试
pytest --lf重新运行上次失败的测试
pytest --cov=src生成覆盖率报告
pytest -n auto并行运行(pytest-xdist)

更多资源

  • ./references/fixtures-advanced.md - 工厂 Fixture、自动使用和 conftest 模式
  • ./references/mocking-patterns.md - Mock、patch、MagicMock、side_effect
  • ./references/async-testing.md - pytest-asyncio 模式
  • ./references/coverage-strategies.md - pytest-cov、分支覆盖率和报告
  • ./references/integration-testing.md - 数据库 Fixture、API 测试和 testcontainers
  • ./references/property-testing.md - Hypothesis 框架、策略和收缩
  • ./references/test-architecture.md - 测试金字塔、组织方式和隔离策略

脚本

  • ./scripts/run-tests.sh - 使用推荐选项运行测试
  • ./scripts/generate-conftest.sh - 生成 conftest.py 样板代码

资源文件

  • ./assets/pytest.ini.template - 推荐的 pytest 配置
  • ./assets/conftest.py.template - 常用 Fixture 模式

另请参阅

相关技能:

  • python-typing-patterns - 类型安全的测试代码
  • python-async-patterns - 异步测试模式(pytest-asyncio)

特定框架的测试:

  • python-fastapi-patterns - TestClient、API 测试
  • python-database-patterns - 数据库 Fixture、事务

评论

支持 Markdown