pytest-builder

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Pytest Builder

Pytest Builder

Build comprehensive test suites for Python projects using pytest, with specialized support for FastAPI, async code, and SQLModel/SQLAlchemy.
为Python项目使用pytest构建全面的测试套件,专门支持FastAPI、异步代码以及SQLModel/SQLAlchemy。

Quick Start

快速开始

Generate test file from existing code:
bash
python3 scripts/generate_test.py myapp/users.py --type unit
Setup pytest configuration:
bash
python3 scripts/setup_pytest_config.py . --template fastapi
Generate fixtures:
bash
python3 scripts/generate_fixtures.py --fixtures database api_client --output tests/conftest.py
从现有代码生成测试文件:
bash
python3 scripts/generate_test.py myapp/users.py --type unit
配置pytest环境:
bash
python3 scripts/setup_pytest_config.py . --template fastapi
生成Fixtures:
bash
python3 scripts/generate_fixtures.py --fixtures database api_client --output tests/conftest.py

Core Capabilities

核心功能

1. Generate Test Files

1. 生成测试文件

Create test files from existing Python code with proper structure:
bash
undefined
从现有Python代码创建结构规范的测试文件:
bash
undefined

Basic unit tests

基础单元测试

python3 scripts/generate_test.py myapp/module.py
python3 scripts/generate_test.py myapp/module.py

FastAPI integration tests

FastAPI集成测试

python3 scripts/generate_test.py myapp/routers/users.py --type integration
python3 scripts/generate_test.py myapp/routers/users.py --type integration

Async tests

异步测试

python3 scripts/generate_test.py myapp/async_service.py --async

The script extracts functions and classes from your code and generates test stubs.
python3 scripts/generate_test.py myapp/async_service.py --async

该脚本会从你的代码中提取函数和类,并生成测试桩代码。

2. Setup Pytest Configuration

2. 配置Pytest环境

Initialize pytest with recommended settings:
bash
undefined
使用推荐的设置初始化pytest:
bash
undefined

Basic Python project

基础Python项目

python3 scripts/setup_pytest_config.py . --template basic
python3 scripts/setup_pytest_config.py . --template basic

FastAPI project

FastAPI项目

python3 scripts/setup_pytest_config.py . --template fastapi
python3 scripts/setup_pytest_config.py . --template fastapi

Async project

异步项目

python3 scripts/setup_pytest_config.py . --template async

This creates:
- `pytest.ini` with optimal configuration
- `tests/` directory structure (unit/, integration/, test_data/)
- `tests/conftest.py` with common fixtures
python3 scripts/setup_pytest_config.py . --template async

这会创建:
- 配置最优的`pytest.ini`文件
- `tests/`目录结构(unit/、integration/、test_data/)
- 包含通用Fixtures的`tests/conftest.py`文件

3. Generate Fixtures

3. 生成Fixtures

Create reusable fixtures for common testing scenarios:
bash
undefined
为常见测试场景创建可复用的Fixtures:
bash
undefined

List available fixtures

列出可用的Fixtures

python3 scripts/generate_fixtures.py --list
python3 scripts/generate_fixtures.py --list

Generate specific fixtures

生成指定的Fixtures

python3 scripts/generate_fixtures.py --fixtures database api_client auth_token
python3 scripts/generate_fixtures.py --fixtures database api_client auth_token

Generate all fixtures

生成所有Fixtures

python3 scripts/generate_fixtures.py --fixtures all
python3 scripts/generate_fixtures.py --fixtures all

Append to existing conftest.py

追加到已有的conftest.py文件

python3 scripts/generate_fixtures.py --fixtures mock_external_api --append

Available fixture types:
- `database` - SQLModel in-memory database fixtures
- `async_database` - Async SQLAlchemy database fixtures
- `api_client` - FastAPI TestClient fixtures
- `async_client` - httpx AsyncClient fixtures
- `mock_external_api` - Mock external API calls
- `temp_files` - Temporary files and directories
- `sample_user` - Sample user model fixtures
- `auth_token` - Authentication token fixtures
python3 scripts/generate_fixtures.py --fixtures mock_external_api --append

可用的Fixture类型:
- `database` - SQLModel内存数据库Fixtures
- `async_database` - 异步SQLAlchemy数据库Fixtures
- `api_client` - FastAPI TestClient Fixtures
- `async_client` - httpx AsyncClient Fixtures
- `mock_external_api` - 模拟外部API调用的Fixtures
- `temp_files` - 临时文件和目录Fixtures
- `sample_user` - 示例用户模型Fixtures
- `auth_token` - 认证令牌Fixtures

Testing Patterns

测试模式

FastAPI Testing

FastAPI测试

For detailed FastAPI testing patterns, see references/fastapi-testing.md:
  • TestClient usage
  • Async endpoint testing with httpx
  • Dependency overrides
  • Authentication testing
  • Response validation
  • Error handling
Quick example:
python
from fastapi.testclient import TestClient
from myapp.main import app

client = TestClient(app)

def test_read_items():
    response = client.get("/items/")
    assert response.status_code == 200
    assert isinstance(response.json(), list)
有关详细的FastAPI测试模式,请查看references/fastapi-testing.md
  • TestClient的使用
  • 基于httpx的异步端点测试
  • 依赖项覆盖
  • 认证测试
  • 响应验证
  • 错误处理
快速示例:
python
from fastapi.testclient import TestClient
from myapp.main import app

client = TestClient(app)

def test_read_items():
    response = client.get("/items/")
    assert response.status_code == 200
    assert isinstance(response.json(), list)

Async Testing

异步测试

For async testing patterns, see references/async-testing.md:
  • pytest-asyncio setup
  • Async fixtures
  • Testing async endpoints
  • Concurrent operations
  • Error handling
Quick example:
python
import pytest
from httpx import AsyncClient

@pytest.mark.asyncio
async def test_async_endpoint():
    async with AsyncClient(app=app, base_url="http://test") as ac:
        response = await ac.get("/items/")
    assert response.status_code == 200
有关异步测试模式,请查看references/async-testing.md
  • pytest-asyncio配置
  • 异步Fixtures
  • 异步端点测试
  • 并发操作测试
  • 错误处理
快速示例:
python
import pytest
from httpx import AsyncClient

@pytest.mark.asyncio
async def test_async_endpoint():
    async with AsyncClient(app=app, base_url="http://test") as ac:
        response = await ac.get("/items/")
    assert response.status_code == 200

Database Testing

数据库测试

For database testing patterns, see references/database-testing.md:
  • In-memory database setup
  • Transaction rollback patterns
  • Testing CRUD operations
  • Testing relationships
  • Query testing
Quick example:
python
import pytest
from sqlmodel import Session, create_engine, SQLModel
from sqlmodel.pool import StaticPool

@pytest.fixture(name="session")
def session_fixture():
    engine = create_engine(
        "sqlite:///:memory:",
        connect_args={"check_same_thread": False},
        poolclass=StaticPool,
    )
    SQLModel.metadata.create_all(engine)
    with Session(engine) as session:
        yield session
有关数据库测试模式,请查看references/database-testing.md
  • 内存数据库配置
  • 事务回滚模式
  • CRUD操作测试
  • 关系测试
  • 查询测试
快速示例:
python
import pytest
from sqlmodel import Session, create_engine, SQLModel
from sqlmodel.pool import StaticPool

@pytest.fixture(name="session")
def session_fixture():
    engine = create_engine(
        "sqlite:///:memory:",
        connect_args={"check_same_thread": False},
        poolclass=StaticPool,
    )
    SQLModel.metadata.create_all(engine)
    with Session(engine) as session:
        yield session

Fixtures Library

Fixtures库

For comprehensive fixture patterns, see references/fixtures-library.md:
  • Fixture scopes (function, module, session, class)
  • Database fixtures
  • API client fixtures
  • Authentication fixtures
  • Mock fixtures
  • Parametrized fixtures
  • Fixture composition
有关全面的Fixture模式,请查看references/fixtures-library.md
  • Fixture作用域(function、module、session、class)
  • 数据库Fixtures
  • API客户端Fixtures
  • 认证Fixtures
  • 模拟Fixtures
  • 参数化Fixtures
  • Fixture组合

Common Workflows

常见工作流

Setting Up Tests for a New FastAPI Project

为新FastAPI项目配置测试

  1. Initialize pytest configuration:
bash
python3 scripts/setup_pytest_config.py . --template fastapi
  1. Generate fixtures:
bash
python3 scripts/generate_fixtures.py --fixtures database api_client sample_user
  1. Generate test files:
bash
python3 scripts/generate_test.py myapp/routers/items.py --type integration
  1. Run tests:
bash
pytest
  1. 初始化pytest配置:
bash
python3 scripts/setup_pytest_config.py . --template fastapi
  1. 生成Fixtures:
bash
python3 scripts/generate_fixtures.py --fixtures database api_client sample_user
  1. 生成测试文件:
bash
python3 scripts/generate_test.py myapp/routers/items.py --type integration
  1. 运行测试:
bash
pytest

Adding Tests to Existing Module

为现有模块添加测试

  1. Generate test file:
bash
python3 scripts/generate_test.py myapp/services/auth.py --output tests/unit/test_auth.py
  1. Review and customize generated tests
  2. Add specific fixtures if needed:
bash
python3 scripts/generate_fixtures.py --fixtures auth_token --append
  1. 生成测试文件:
bash
python3 scripts/generate_test.py myapp/services/auth.py --output tests/unit/test_auth.py
  1. 审核并自定义生成的测试
  2. 如有需要添加特定Fixtures:
bash
python3 scripts/generate_fixtures.py --fixtures auth_token --append

Testing Async Database Operations

测试异步数据库操作

  1. Generate async fixtures:
bash
python3 scripts/generate_fixtures.py --fixtures async_database async_client
  1. Create async tests following patterns in references/async-testing.md
  2. Run with pytest-asyncio:
bash
pytest --asyncio-mode=auto
  1. 生成异步Fixtures:
bash
python3 scripts/generate_fixtures.py --fixtures async_database async_client
  1. 按照references/async-testing.md中的模式创建异步测试
  2. 使用pytest-asyncio运行:
bash
pytest --asyncio-mode=auto

Best Practices

最佳实践

Test Organization:
  • Keep tests isolated and independent
  • Use descriptive test names:
    test_<feature>_<scenario>_<expected_outcome>
  • Test both happy paths and edge cases
  • Organize tests:
    tests/unit/
    for unit tests,
    tests/integration/
    for integration tests
Fixtures:
  • Use appropriate scopes (function, module, session)
  • Keep fixtures focused and reusable
  • Use fixture composition for complex setups
  • Clean up resources in fixtures using yield
FastAPI Testing:
  • Use dependency overrides for testing
  • Test authentication and authorization
  • Validate response schemas
  • Test error handling
Database Testing:
  • Use in-memory databases for speed
  • Isolate tests with transactions or fresh databases
  • Test relationships and cascades
  • Avoid N+1 query problems
Async Testing:
  • Use pytest-asyncio for async tests
  • Test concurrent operations
  • Handle timeouts and cancellations
  • Test async context managers
测试组织:
  • 保持测试的独立性和隔离性
  • 使用描述性的测试名称:
    test_<功能>_<场景>_<预期结果>
  • 测试正常路径和边缘情况
  • 组织测试目录:
    tests/unit/
    用于单元测试,
    tests/integration/
    用于集成测试
Fixtures:
  • 使用合适的作用域(function、module、session)
  • 保持Fixtures的聚焦性和可复用性
  • 使用Fixture组合实现复杂配置
  • 使用yield在Fixtures中清理资源
FastAPI测试:
  • 使用依赖项覆盖进行测试
  • 测试认证和授权
  • 验证响应Schema
  • 测试错误处理
数据库测试:
  • 使用内存数据库提升速度
  • 通过事务或全新数据库隔离测试
  • 测试关系和级联操作
  • 避免N+1查询问题
异步测试:
  • 使用pytest-asyncio进行异步测试
  • 测试并发操作
  • 处理超时和取消操作
  • 测试异步上下文管理器

Assets

资源文件

Template files for quick project setup:
  • assets/pytest.ini
    - Recommended pytest configuration
  • assets/conftest_basic.py
    - Basic conftest.py template
  • assets/conftest_fastapi.py
    - FastAPI-specific conftest.py
  • assets/test_template.py
    - Example test file with common patterns
Copy these templates to your project as starting points.
用于快速项目配置的模板文件:
  • assets/pytest.ini
    - 推荐的pytest配置
  • assets/conftest_basic.py
    - 基础conftest.py模板
  • assets/conftest_fastapi.py
    - 针对FastAPI的conftest.py模板
  • assets/test_template.py
    - 包含常见模式的示例测试文件
将这些模板复制到你的项目中作为起始点。

Installation Requirements

安装要求

bash
undefined
bash
undefined

Basic pytest

基础pytest

pip install pytest pytest-cov
pip install pytest pytest-cov

Async support

异步支持

pip install pytest-asyncio
pip install pytest-asyncio

FastAPI testing

FastAPI测试

pip install httpx
pip install httpx

Database testing

数据库测试

pip install sqlmodel
undefined
pip install sqlmodel
undefined