pytest
安装方式
先用 Prompt 核对来源与依赖。也可下载安装包。
用 AI 助手安装
复制提示词,让助手先核对固定版本和依赖。
查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "pytest":https://skillpi.com/zh/skills/deepskill-7f1080735ec5c87a58dfe83bd6e031b0da12e8ac5afdc2d861098ef3d6e4d5c7。安装前核对上游来源和版本:https://github.com/TerminalSkills/skills。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。
来源与配置
github.com
配置方式待核实
请查看原始来源中的适用工具、依赖和权限要求。
安装实测待补充
pytest:用于测试 Python 代码的框架。适合编写单元测试、设置测试夹具、模拟依赖、运行异步测试、测量覆盖率以及实施测试驱动开发(TDD)。
介绍来源: third_party · TerminalSkills · 1.0.0 参考来源
SkillPi 解读
- 实测状态
- 未测试
文件浏览
Frontmatter
name: pytest
description: >-
Test Python code with pytest. Use when a user asks to write unit tests,
set up test fixtures, mock dependencies, run async tests, measure coverage,
or implement test-driven development in Python.
license: Apache-2.0
compatibility: 'Python 3.8+'
metadata:
author: terminal-skills
version: 1.0.0
category: development
tags:
- pytest
- testing
- python
- tdd
- fixturespytest
Overview
pytest is the standard Python testing framework. It uses plain assert statements (no self.assertEqual), fixtures for setup/teardown, parametrize for data-driven tests, and plugins for async, coverage, and mocking.
Instructions
Step 1: Basic Tests
# tests/test_users.py — Simple test functions
from app.services.users import create_user, validate_email
def test_create_user_returns_user_object():
user = create_user(name="Alice", email="alice@example.com")
assert user.name == "Alice"
assert user.email == "alice@example.com"
assert user.id is not None
def test_validate_email_rejects_invalid():
assert validate_email("not-an-email") is False
assert validate_email("") is False
assert validate_email("user@") is False
def test_validate_email_accepts_valid():
assert validate_email("user@example.com") is True
assert validate_email("user+tag@example.co.uk") is True
class TestUserService:
"""Group related tests in a class."""
def test_duplicate_email_raises(self):
create_user(name="Alice", email="alice@example.com")
with pytest.raises(ValueError, match="Email already exists"):
create_user(name="Bob", email="alice@example.com")
Step 2: Fixtures
# conftest.py — Shared fixtures
import pytest
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
from app.models import Base
@pytest.fixture
async def db():
"""Fresh database for each test."""
engine = create_async_engine("sqlite+aiosqlite:///:memory:")
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
session_maker = async_sessionmaker(engine, expire_on_commit=False)
async with session_maker() as session:
yield session
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
@pytest.fixture
def sample_user(db):
"""Pre-created user for tests that need one."""
user = User(name="Test User", email="test@example.com", role="member")
db.add(user)
db.commit()
return user
@pytest.fixture
def api_client(db):
"""FastAPI test client with database override."""
from fastapi.testclient import TestClient
from app.main import app
from app.dependencies import get_db
app.dependency_overrides[get_db] = lambda: db
yield TestClient(app)
app.dependency_overrides.clear()
Step 3: Parametrize
# tests/test_pricing.py — Data-driven tests
import pytest
@pytest.mark.parametrize("plan,users,expected_price", [
("free", 1, 0),
("free", 5, 0),
("starter", 1, 29),
("starter", 10, 29),
("pro", 1, 79),
("pro", 50, 79),
("enterprise", 100, 199),
])
def test_calculate_price(plan, users, expected_price):
assert calculate_price(plan, users) == expected_price
@pytest.mark.parametrize("input_text,expected_slug", [
("Hello World", "hello-world"),
(" Spaces Everywhere ", "spaces-everywhere"),
("Special!@#$Characters", "specialcharacters"),
("Already-a-slug", "already-a-slug"),
("UPPERCASE", "uppercase"),
])
def test_slugify(input_text, expected_slug):
assert slugify(input_text) == expected_slug
Step 4: Mocking
# tests/test_notifications.py — Mock external services
from unittest.mock import AsyncMock, patch
@pytest.mark.asyncio
async def test_send_welcome_email(db, sample_user):
with patch("app.services.email.send_email", new_callable=AsyncMock) as mock_send:
mock_send.return_value = {"id": "msg_123"}
result = await send_welcome_email(sample_user.id)
mock_send.assert_called_once_with(
to=sample_user.email,
subject="Welcome!",
template="welcome",
)
assert result["id"] == "msg_123"
@pytest.mark.asyncio
async def test_payment_webhook_handles_failure(api_client):
with patch("app.services.stripe.verify_signature", return_value=True):
response = api_client.post("/webhooks/stripe", json={
"type": "payment_intent.failed",
"data": {"object": {"id": "pi_123"}},
})
assert response.status_code == 200
Step 5: Run
pytest # run all tests
pytest -x # stop on first failure
pytest -k "test_create" # run tests matching pattern
pytest --cov=app --cov-report=html # coverage report
pytest -n auto # parallel execution (pytest-xdist)
Guidelines
- Use plain
assert— pytest rewrites assertions to show detailed failure info. - Fixtures with
yieldhandle cleanup automatically — no try/finally needed. conftest.pyfixtures are available to all tests in the directory and below.- Use
@pytest.mark.asynciofor async tests (requirespytest-asyncioplugin). - Aim for fast tests: in-memory SQLite for unit tests, real database for integration tests.
当前收录版本
1.0.0
安全与评测信息
质量评测
满分100 · 来自 SkillPi LAB 实验室的评测报告。
亮点
- 提供完整的 pytest 测试框架端到端指南,覆盖单元测试、夹具、参数化、模拟、异步测试和覆盖率等核心场景
- 内容面向 Python 开发者高频刚需,实用价值高
亮点
- 触发描述清晰完整,明确列出六大使用场景,边界清晰,无歧义
待提升项
-
缺少显式 When to Use 章节 原报告严重程度:轻微
文档未设置独立的 When to Use 章节,但 frontmatter 的 description 已充分覆盖触发场景
改进建议:可考虑在正文开头添加显式的 When to Use 小节以提升可读性
亮点
- 文档结构清晰,分步骤组织,每步含完整可执行代码示例
- frontmatter 完整,包含名称、描述、许可证、兼容性、元数据等必要信息
亮点
- 工具来源明确(pytest 标准库及常用插件),参数使用正确
- 示例代码完整,涵盖异常处理(pytest.raises)和异步测试标记
- 提供多种运行命令选项,满足不同测试需求
取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。
正文静态检测
100 / 100 · skillpi-20261123-no-r3-v1
正文未命中当前规则。
分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。
权限与使用前检查
根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。
未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。
安全评级与访问范围
safe · 静态证据核验,不代表运行安全保证。
使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。
用户讨论
还没有已核实的点评。