pytest
Installation
Review the source and dependencies with a prompt. A package is available to download.
Install with an AI assistant
Copy the prompt so your assistant can review the pinned revision and dependencies first.
View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "pytest" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-7f1080735ec5c87a58dfe83bd6e031b0da12e8ac5afdc2d861098ef3d6e4d5c7. Verify the upstream source and version against https://github.com/TerminalSkills/skills before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.
Source and setup
github.com
Setup guidance pending
See the original source for supported tools, dependencies, and permissions.
Installation test pending
pytest: A framework for testing Python code. Suitable for writing unit tests, setting up fixtures, mocking dependencies, running asynchronous tests, measuring coverage, and practicing test-driven development (TDD).
Introduction source: third_party · TerminalSkills · 1.0.0 Reference
SkillPi interpretation
- Testing
- Not tested
Browse files
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.
Current listing version
1.0.0
Safety and assessment details
Quality assessment
Out of 100 · Assessment report from SkillPi LAB.
Highlights
- 提供完整的 pytest 测试框架端到端指南,覆盖单元测试、夹具、参数化、模拟、异步测试和覆盖率等核心场景
- 内容面向 Python 开发者高频刚需,实用价值高
Highlights
- 触发描述清晰完整,明确列出六大使用场景,边界清晰,无歧义
Areas to improve
-
缺少显式 When to Use 章节 Reported severity: Minor
文档未设置独立的 When to Use 章节,但 frontmatter 的 description 已充分覆盖触发场景
Recommendation: 可考虑在正文开头添加显式的 When to Use 小节以提升可读性
Highlights
- 文档结构清晰,分步骤组织,每步含完整可执行代码示例
- frontmatter 完整,包含名称、描述、许可证、兼容性、元数据等必要信息
Highlights
- 工具来源明确(pytest 标准库及常用插件),参数使用正确
- 示例代码完整,涵盖异常处理(pytest.raises)和异步测试标记
- 提供多种运行命令选项,满足不同测试需求
The arithmetic mean of the first four original scores, rounded to a whole number.
Static text checks
100 / 100 · skillpi-20261123-no-r3-v1
No current rules matched the text.
This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.
Permissions and checks before use
Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.
These common operations were not identified in the main document. This does not mean no permissions or risks exist.
Security rating and access scope
safe · Static evidence review; not a runtime safety guarantee.
Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.
User discussion
No verified reviews yet.