跳到正文
Skillpedia
测试48k · #5544

pytest-skill

它能做什么

这个工具可以借助 pytest 库,帮你为 Python 代码创建自动化测试。它生成的测试能验证你的代码是否按预期工作,也能覆盖较复杂的场景。

适用场景

  • ✓当你需要为 Python 代码编写测试时。
  • ✓当你正在使用 pytest 库,并希望利用它的高级功能时。
  • ✓当你想确保 Python 代码在各种情况下都能正确运行时。

技能链接

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/pytest-skill/SKILL.md

复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。

使用方法

最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。

可直接粘贴的消息

请用这个技能帮我:https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/pytest-skill/SKILL.md 阅读该链接中的 SKILL.md 文件,并在我的任务中按照它的说明来做。
想让你的 AI 自己找到这样的技能吗?安装免费的 Skillpedia MCP:只需一行,每次任务前它都会在 15,000+ 个技能中搜索。1 分钟完成安装 →

可以这样问 AI

“为我的两数相加函数创建 pytest 测试,使用 fixture 和参数化(parametrize)。”

每周 5 个新技能,1 分钟读完。

工作原理

这个工具会使用 pytest 的常见写法:用 fixture 准备测试环境,用参数化对多组数据运行同一个测试,并用标记(marker)对测试进行分类。它还可以模拟(mock)代码的某些部分,从而把被测对象单独隔离出来。

技术内容(原始 SKILL.md)

作者在 GitHub 上的英文原文。

Pytest Testing Skill

When to Use

Use this skill when you need generates production-grade pytest tests in Python with fixtures, parametrize, markers, mocking, and conftest patterns. Use when user mentions "pytest", "conftest", "@pytest.fixture", "@pytest.mark", "Python test". Triggers on: "pytest", "conftest", "Python test", "parametrize", "Python...

Core Patterns

Basic Test

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)

Fixtures

@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

Parametrize

@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

Markers

@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(): ...

Mocking

from unittest.mock import patch, MagicMock

def test_send_email(mocker):
    mock_smtp = mocker.patch("myapp.email.smtplib.SMTP")
    send_welcome_email("user@test.com")
    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()

Assertions

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)

Anti-Patterns

Bad Good Why
self.assertEqual() assert x == y pytest rewrites give better output
Setup in __init__ @pytest.fixture Lifecycle management
Global state Fixture with yield Proper cleanup
Huge test functions Small focused tests Easier debugging

Quick Reference

Task Command
Run all pytest
Run file pytest tests/test_login.py
Run specific pytest tests/test_login.py::test_login_success
By marker pytest -m slow
By keyword pytest -k "login and not invalid"
Verbose pytest -v
Stop first fail pytest -x
Last failed pytest --lf
Coverage pytest --cov=myapp --cov-report=html
Parallel pytest -n auto (pytest-xdist)

pyproject.toml

[tool.pytest.ini_options]
testpaths = ["tests"]
markers = ["slow: slow tests", "integration: integration tests"]
addopts = "-v --tb=short"

Deep Patterns

For production-grade patterns, see reference/playbook.md:

Section What's Inside
§1 Config pytest.ini + pyproject.toml with markers, coverage
§2 Fixtures Scoping, factories, teardown, autouse, tmp_path
§3 Parametrize Basic, with IDs, cartesian, indirect
§4 Mocking pytest-mock, monkeypatch, spies, env vars
§5 Async pytest-asyncio, async fixtures, async client

…

常见问题

什么是 fixture?

fixture 可以理解为测试的准备工作。它会在测试运行前搭建所需的环境或数据,并在测试结束后进行清理。

什么是 parametrize(参数化)?

参数化可以让同一个测试使用不同的数据运行多次,这样你就不必反复编写相同的测试代码。

什么是 mocking(模拟)?

模拟是指为代码中的某些部分(比如网络请求或数据库操作)创建假的版本,这样你就可以单独测试主要代码。

详情

作者的原始描述

Generates production-grade pytest tests in Python with fixtures, parametrize, markers, mocking, and conftest patterns. Use when user mentions \"pytest\", \"conftest\", \"@pytest.fixture\", \"@pytest.mark\", \"Python test\".

repo: sickn33/agentic-awesome-skills

热度

GitHub 星标
48k
排名
#5544
许可证
MIT
更新时间
2026/10/15

这个技能有用吗?

0

登录 后即可投票。

评论

  • …

同一仓库的更多技能

相似技能