mcpField
P
python-pytest-ops

python-pytest-ops

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

关于 python-pytest-ops

为编写和运行测试的 Python 开发者提供 pytest 实用模式。内容涵盖 fixture、参数化、异常、标记、模拟,以及辅助脚本和模板。

主要功能

  1. 01组织测试结构与断言
  2. 02创建不同作用域的 fixture
  3. 03参数化测试用例
  4. 04测试异常并使用标记
  5. 05模拟依赖项
  6. 06运行测试并生成配置文件

适用场景

  1. 01组织 Python 项目的测试
  2. 02用参数化测试多种输入
  3. 03用模拟隔离外部调用
  4. 04筛选运行测试或查看覆盖率

安装

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

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

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

包含的文件

除 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
tests/
run.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

Mock

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()

快速参考

在项目环境中运行以下命令——在命令前加上 uv run(例如,uv run pytest -v)。 为简洁起见,下方展示的命令省略了 uv run。

命令描述
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 - 工厂 Fixtures、autouse、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 - 数据库 Fixtures、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-ops - 类型安全的测试代码
  • python-async-ops - 异步测试模式(pytest-asyncio)

特定框架的测试:

  • python-fastapi-ops - TestClient、API 测试
  • python-database-ops - 数据库 Fixtures、事务

评论

支持 Markdown