Python testing pytest

From findscripter/everything-skills · View interactive version

Python testing pytest is an AI agent skill from the GitHub repository findscripter/everything-skills. 当为 Python 项目搭建 pytest 测试体系、写单元/集成测试或 mock 外部依赖时使用;用 fixture/参数化/mock/monkeypatch 按 AAA 模式产出可执行测试、conftest 与覆盖率配置;不适用于非 Python 语言或拿测试替代环境验证与专家评审。触发词:pytest、fixture、参数化、mock、覆盖率

How to use this skill

Skill file

何时使用

不该用:

步骤 / 指令

  1. 选测试类型:单元(隔离测函数/类)/ 集成(测组件交互)/ 端到端 / 性能。优先单元,金字塔下宽上窄。
  2. 单测按 AAA 写:Arrange 准备数据与前置 → Act 执行被测代码 → Assert 验证结果。命名描述「行为」:test_login_fails_with_invalid_password,别用 test_1。
  3. 重复的 setup/teardown 抽成 @pytest.fixture(用 yield 分隔 setup/teardown),按需设 scope(function/module/session);跨文件共享放 conftest.py。
  4. 同逻辑多输入用 @pytest.mark.parametrize,特殊用例用 pytest.param(..., id=...) 命名。
  5. 隔离外部副作用:HTTP/SDK 用 unittest.mock(patch/Mock/side_effect);环境变量与对象属性用内置 monkeypatch(setenv/delenv/setattr);临时文件用 tmp_path。
  6. 异常路径用 pytest.raises(Exc, match="..."),需要细节时 as exc_info 取 exc_info.value。
  7. 异步代码用 pytest-asyncio:测试与 fixture 加 @pytest.mark.asyncio,并发用 asyncio.gather。
  8. 用 marks(slow/integration/...)分类,pytest.ini 里 --strict-markers 防拼错;跑 pytest -m "not slow" 等筛选。
  9. 接 pytest-cov 量覆盖率,CI 上 --cov-fail-under=80 卡门槛,关注质量而非纯百分比。
  10. 保持测试独立:无共享状态、各自清理;测试先行或与代码同步写。

示例

最小用例 + fixture + 参数化 + mock + 异常:

# test_demo.py
import pytest
from unittest.mock import patch, Mock
import requests

class Calculator:
    def add(self, a, b): return a + b
    def divide(self, a, b):
        if b == 0: raise ValueError("Cannot divide by zero")
        return a / b

@pytest.fixture
def calc():            # setup → yield → teardown
    c = Calculator()
    yield c

@pytest.mark.parametrize("a,b,expected", [(2, 3, 5), (-1, 1, 0), (0, 0, 0)])
def test_add(calc, a, b, expected):       # AAA + 参数化
    assert calc.add(a, b) == expected

def test_divide_by_zero(calc):            # 测异常
    with pytest.raises(ValueError, match="Cannot divide by zero"):
        calc.divide(5, 0)

def test_http_mock():                     # mock 外部依赖
    resp = Mock()
    resp.json.return_value = {"id": 1}
    resp.raise_for_status.return_value = None
    with patch("requests.get", return_value=resp) as m:
        assert requests.get("http://x/users/1").json()["id"] == 1
        m.assert_called_once_with("http://x/users/1")

环境变量 / 临时文件 / 异步:

def test_env(monkeypatch):
    monkeypatch.setenv("DATABASE_URL", "postgresql://localhost/test")
    monkeypatch.delenv("CACHE", raising=False)

def test_file(tmp_path):
    f = tmp_path / "a.txt"; f.write_text("hi")
    assert f.read_text() == "hi"

@pytest.mark.asyncio
async def test_async():
    import asyncio
    results = await asyncio.gather(*(asyncio.sleep(0, r) for r in (1, 2, 3)))
    assert results == [1, 2, 3]

属性测试(hypothesis):

from hypothesis import given, strategies as st

@given(st.text())
def test_reverse_twice(s):
    assert s[::-1][::-1] == s

覆盖率与配置:

pip install pytest-cov
pytest --cov=myapp --cov-report=term-missing --cov-fail-under=80 tests/
# pytest.ini
[pytest]
testpaths = tests
python_files = test_*.py
addopts = -v --strict-markers --tb=short --cov=myapp --cov-report=term-missing
markers =
    slow: marks tests as slow
    integration: marks integration tests

注意事项

互见


采编自 sickn33/antigravity-awesome-skills(MIT)。

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.