关于 pytest-skill
pytest-skill 是一份使用 pytest 编写和运行 Python 测试的参考技能,涵盖常见测试模式,并提供进阶实践手册。
主要功能
- 01Fixture 与资源清理
- 02参数化测试与标记
- 03模拟与断言模式
- 04筛选测试和统计覆盖率的命令
- 05reference/playbook.md 中的进阶模式
适用场景
- 01复用测试环境设置与清理
- 02批量验证输入及预期结果
- 03模拟外部调用并检查异常
- 04运行指定测试或统计覆盖率
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ lambdatest/ agent-skills --skill pytest-skill安装后在 Claude Code 中输入/pytest-skill确认已加载。
附带文件reference/advanced-patterns.mdreference/playbook.md
详细介绍
Pytest 测试技能
核心模式
基本测试
import pytest
def test_addition():
assert 2 + 3 == 5
def test_exception():
with pytest.raises(ValueError, match="invalid"):
int("not_a_number")
class TestCalculator:
def test_add(self):
calc = Calculator()
assert calc.add(2, 3) == 5
def test_divide_by_zero(self):
with pytest.raises(ZeroDivisionError):
Calculator().divide(10, 0)
Fixture
@pytest.fixture
def calculator():
return Calculator()
@pytest.fixture
def db_connection():
conn = Database.connect("test_db")
yield conn # teardown after yield
conn.rollback()
conn.close()
@pytest.fixture(scope="module")
def api_client():
client = APIClient(base_url="http://localhost:8000")
yield client
client.logout()
# conftest.py - shared fixtures
@pytest.fixture(autouse=True)
def reset_state():
State.reset()
yield
State.cleanup()
# Usage
def test_add(calculator):
assert calculator.add(2, 3) == 5
参数化
@pytest.mark.parametrize("input,expected", [
("hello", 5), ("", 0), ("pytest", 6),
])
def test_string_length(input, expected):
assert len(input) == expected
@pytest.mark.parametrize("a,b,expected", [
(2, 3, 5), (-1, 1, 0), (0, 0, 0),
])
def test_add(calculator, a, b, expected):
assert calculator.add(a, b) == expected
标记
@pytest.mark.slow
def test_large_dataset(): ...
@pytest.mark.skip(reason="Not implemented")
def test_future_feature(): ...
@pytest.mark.skipif(sys.platform == "win32", reason="Unix only")
def test_unix_permissions(): ...
@pytest.mark.xfail(reason="Known bug #123")
def test_known_bug(): ...
模拟
from unittest.mock import patch, MagicMock
def test_send_email(mocker):
mock_smtp = mocker.patch("myapp.email.smtplib.SMTP")
send_welcome_email("[email protected]")
mock_smtp.return_value.sendmail.assert_called_once()
def test_api_call(mocker):
mock_response = mocker.Mock()
mock_response.status_code = 200
mock_response.json.return_value = {"users": [{"name": "Alice"}]}
mocker.patch("myapp.service.requests.get", return_value=mock_response)
users = get_users()
assert len(users) == 1
@patch("myapp.service.database")
def test_save_user(mock_db):
mock_db.save.return_value = True
assert save_user({"name": "Alice"}) is True
mock_db.save.assert_called_once()
断言
assert x == y
assert x != y
assert x in collection
assert isinstance(obj, MyClass)
assert 0.1 + 0.2 == pytest.approx(0.3)
with pytest.raises(ValueError) as exc_info:
raise ValueError("bad")
assert "bad" in str(exc_info.value)
反模式
| 不佳做法 | 推荐做法 | 原因 |
|---|---|---|
self.assertEqual() | assert x == y | pytest 的重写机制能提供更好的输出 |
在 __init__ 中进行设置 | @pytest.fixture | 生命周期管理 |
| 全局状态 | 使用 yield 的 Fixture | 妥善清理 |
| 过大的测试函数 | 小而专注的测试 | 更易调试 |
快速参考
| 任务 | 命令 |
|---|---|
| 运行全部测试 | pytest |
| 运行指定文件 | pytest tests/test_login.py |
| 运行指定测试 | pytest tests/test_login.py::test_login_success |
| 按标记筛选 | pytest -m slow |
| 按关键字筛选 | pytest -k "login and not invalid" |
| 显示详细信息 | pytest -v |
| 首次失败时停止 | pytest -x |
| 上次失败的测试 | pytest --lf |
| 覆盖率 | pytest --cov=myapp --cov-report=html |
| 并行运行 | pytest -n auto(pytest-xdist) |
pyproject.toml
[tool.pytest.ini_options]
testpaths = ["tests"]
markers = ["slow: slow tests", "integration: integration tests"]
addopts = "-v --tb=short"
深入模式
生产级模式请参阅 reference/playbook.md:
| 章节 | 内容 |
|---|---|
| §1 配置 | pytest.ini + pyproject.toml,包含标记和覆盖率 |
| §2 Fixture | 作用域、工厂、拆卸、autouse、tmp_path |
| §3 参数化 | 基础用法、带 ID、笛卡尔积、间接参数化 |
| §4 模拟 | pytest-mock、monkeypatch、间谍、环境变量 |
| §5 异步 | pytest-asyncio、异步 Fixture、异步客户端 |
| §6 异常 | pytest.raises(match=)、警告 |
| §7 标记和插件 | 自定义标记、收集钩子 |
| §8 基于类的测试 | 嵌套类、autouse 设置 |
| §9 CI/CD | GitHub Actions 矩阵、覆盖率门槛 |
| §10 调试表 | 10 个常见问题及修复方法 |
| §11 最佳实践 | 15 项生产级检查清单 |
评论
支持 Markdown