cleanpy 0.1.3

Python 3.12+ 最佳实践知识库 - MCP 服务器
Documentation
---
topic: pytest_intro
title: Pytest 简介
when_to_use: 编写 Python 单元测试和集成测试时
keywords:
  - pytest
  - 测试
  - unittest
  - TDD
---

# Pytest:Python 测试的事实标准

## 为什么选择 Pytest

- ✅ 简单、Pythonic 的语法
- ✅ 强大的 fixture 系统
- ✅ 优秀的插件生态系统
- ✅ 详细的失败报告
- ✅ 参数化测试
- ✅ 并行执行

## 安装

```bash
# 使用 UV
uv add --dev pytest pytest-cov pytest-asyncio pytest-mock
```

## 基本测试示例

```python
# tests/unit/test_users/test_models.py
import pytest
from my_project.users.models import User

class TestUser:
    """用户模型的测试。"""

    def test_user_creation(self):
        """测试用户可以创建。"""
        user = User(name="Alice", email="alice@example.com")

        assert user.name == "Alice"
        assert user.email == "alice@example.com"

    def test_user_validation(self):
        """测试用户验证。"""
        with pytest.raises(ValueError, match="Invalid email"):
            User(name="Bob", email="invalid")

    @pytest.mark.parametrize("name,email", [
        ("Alice", "alice@example.com"),
        ("Bob", "bob@test.org"),
        ("Charlie", "charlie@domain.net"),
    ])
    def test_multiple_users(self, name, email):
        """测试创建多个用户。"""
        user = User(name=name, email=email)
        assert user.name == name
        assert user.email == email
```

## 运行测试

```bash
# 运行所有测试
pytest

# 运行特定文件
pytest tests/unit/test_users/test_models.py

# 详细输出
pytest -v

# 并行运行测试
uv add --dev pytest-xdist
pytest -n auto
```

## 相关链接

- [Pytest 官方文档]https://docs.pytest.org/
- [Pytest 插件列表]https://docs.pytest.org/en/latest/reference/plugin_list.html