python-pytest-ops by 0xdarkmatter/claude-mods
npx skills add https://github.com/0xdarkmatter/claude-mods --skill python-pytest-ops现代 pytest 模式,用于高效测试。
import pytest
def test_basic():
"""简单断言测试。"""
assert 1 + 1 == 2
def test_with_description():
"""描述性名称和文档字符串。"""
result = calculate_total([1, 2, 3])
assert result == 6, "总和应等于 6"
import pytest
@pytest.fixture
def sample_user():
"""创建测试用户。"""
return {"id": 1, "name": "Test User"}
@pytest.fixture
def db_connection():
"""带有设置和清理的固件。"""
conn = create_connection()
yield conn
conn.close()
def test_user(sample_user):
"""通过名称注入的固件。"""
assert sample_user["name"] == "Test User"
@pytest.fixture(scope="function") # 默认 - 每个测试
@pytest.fixture(scope="class") # 每个测试类
@pytest.fixture(scope="module") # 每个测试文件
@pytest.fixture(scope="session") # 整个测试运行
@pytest.mark.parametrize("input,expected", [
(1, 2),
(2, 4),
(3, 6),
])
def test_double(input, expected):
assert double(input) == expected
# 多参数
@pytest.mark.parametrize("x", [1, 2])
@pytest.mark.parametrize("y", [10, 20])
def test_multiply(x, y): # 4 种测试组合
assert x * y > 0
Modern pytest patterns for effective testing.
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"
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"
@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
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
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="尚未实现")
def test_future_feature():
pass
@pytest.mark.skipif(sys.platform == "win32", reason="仅限 Unix")
def test_unix_feature():
pass
@pytest.mark.xfail(reason="已知错误")
def test_buggy():
assert broken_function() == expected
@pytest.mark.slow
def test_performance():
"""自定义标记器 - 在 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()
def test_with_mocker(mocker):
mock_api = mocker.patch("module.api_call")
mock_api.return_value = {"success": True}
result = process_data()
assert result["success"]
# tests/conftest.py - 共享固件
import pytest
@pytest.fixture(scope="session")
def app():
"""对所有测试可用的应用程序固件。"""
return create_app(testing=True)
@pytest.fixture
def client(app):
"""测试客户端固件。"""
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 - 工厂固件、自动使用、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 - 数据库固件、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 - 常见固件模式相关技能:
python-typing-ops - 类型安全的测试代码python-async-ops - 异步测试模式 (pytest-asyncio)特定框架测试:
python-fastapi-ops - TestClient、API 测试python-database-ops - 数据库固件、事务每周安装次数
2
代码仓库
GitHub 星标数
8
首次出现
1 天前
安全审计
安装于
amp2
cline2
opencode2
cursor2
kimi-cli2
codex2
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()
def test_with_mocker(mocker):
mock_api = mocker.patch("module.api_call")
mock_api.return_value = {"success": True}
result = process_data()
assert result["success"]
# 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()
| Command | Description |
|---|---|
pytest | Run all tests |
pytest -v | Verbose output |
pytest -x | Stop on first failure |
pytest -k "test_name" | Run matching tests |
pytest -m slow | Run marked tests |
pytest --lf | Rerun last failed |
pytest --cov=src | Coverage report |
pytest -n auto | Parallel (pytest-xdist) |
./references/fixtures-advanced.md - Factory fixtures, autouse, conftest patterns./references/mocking-patterns.md - Mock, patch, MagicMock, side_effect./references/async-testing.md - pytest-asyncio patterns./references/coverage-strategies.md - pytest-cov, branch coverage, reports./references/integration-testing.md - Database fixtures, API testing, testcontainers./references/property-testing.md - Hypothesis framework, strategies, shrinking./references/test-architecture.md - Test pyramid, organization, isolation strategies./scripts/run-tests.sh - Run tests with recommended options./scripts/generate-conftest.sh - Generate conftest.py boilerplate./assets/pytest.ini.template - Recommended pytest configuration./assets/conftest.py.template - Common fixture patternsRelated Skills:
python-typing-ops - Type-safe test codepython-async-ops - Async test patterns (pytest-asyncio)Testing specific frameworks:
python-fastapi-ops - TestClient, API testingpython-database-ops - Database fixtures, transactionsWeekly Installs
2
Repository
GitHub Stars
8
First Seen
1 day ago
Security Audits
Installed on
amp2
cline2
opencode2
cursor2
kimi-cli2
codex2
Word文档处理器:DOCX创建、编辑、分析与修订痕迹处理全指南 | 自动化办公解决方案
1,200 周安装