pytest练习

🏆 1. Requests 库测试套件

项目地址https://github.com/psf/requests
学习重点

  • 参数化测试 (@pytest.mark.parametrize)

  • HTTP 接口测试的 Mock 技巧

  • 复杂 Fixture 设计(如会话级缓存)

  • 异常测试 (pytest.raises)

实践亮点

python

复制代码
# 典型测试案例 (tests/test_requests.py)
@pytest.mark.parametrize(
    "method", ["GET", "POST", "PUT", "PATCH", "DELETE"]
)
def test_http_methods(session, method):
    # 使用内置 fixture 'session' 模拟 HTTP 会话
    url = "http://httpbin.org/" + method.lower()
    func = getattr(session, method.lower())
    response = func(url)
    assert response.status_code == 200

学习路径

  1. 研究 tests/conftest.py 中的全局 Fixture 设计

  2. 分析 test_requests.py 中的 Mock 响应实现

  3. 学习 pytest.ini 中的自定义配置


🧪 2. Pytest 自身测试套件

项目地址https://github.com/pytest-dev/pytest
学习重点

  • 元测试(测试框架自身的测试)

  • 插件系统测试模式

  • 临时目录管理 (tmp_path Fixture)

  • 测试覆盖率优化 (pytest-cov)

经典案例

python

复制代码
# 测试插件加载 (testing/test_config.py)
def test_plugin_loading(testdir):
    # testdir 是 pytest 内置 Fixture
    testdir.makepyfile(
        """
        import pytest
        @pytest.hookimpl
        def pytest_configure(config):
            config.addinivalue_line("env", "TEST=123")
    """)
    result = testdir.runpytest()
    assert result.ret == 0

学习价值

  • 深度理解 pytest 内部机制

  • 学习超过 2000 个测试案例的设计模式

  • 查看顶级 Fixture 实现(如 monkeypatch 源码)


📦 3. FastAPI 测试套件

项目地址https://github.com/tiangolo/fastapi
学习重点

  • 异步测试 (pytest.mark.asyncio)

  • API 端到端测试 (TestClient)

  • 数据库集成测试(回滚机制)

  • 依赖注入测试

最佳实践

python

复制代码
# 数据库事务测试 (tests/test_db.py)
@pytest.mark.asyncio
async def test_transactional_db(async_client):
    # 使用自动回滚的事务 Fixture
    response = await async_client.post("/users/", json={"name": "Test"})
    assert response.status_code == 201
    user_id = response.json()["id"]
    
    # 验证独立事务中数据不可见
    async with AsyncClient(app=app, base_url="http://test") as ac:
        response = await ac.get(f"/users/{user_id}")
        assert response.status_code == 404  # 回滚后数据不存在

学习路径

  1. 研究 tests/conftest.py 中的数据库 Fixture 架构

  2. 分析异步测试实现 (tests/test_main.py)

  3. 学习 OpenAPI 规范验证测试


💡 推荐学习方式

技能 实践方法 目标
Fixture 设计 复制项目的 conftest.py 改造 实现 Session 级 DB 连接
参数化测试 为现有测试添加新参数组合 覆盖边界值用例
插件开发 基于 pytest-requests 创建自定义插件 实现自动重试机制
覆盖率优化 pytest --cov 分析未被覆盖代码 将覆盖率提升至 95%+

建议按此顺序学习:Requests → Pytest → FastAPI,从基础测试模式逐步过渡到复杂场景。每个项目都包含 2000+ 测试案例,每天研究 10 个案例并动手复现,一个月即可掌握工业级测试开发技能。

相关推荐
好家伙VCC4 小时前
# Pytest发散创新:从基础测试到智能断言的实战进阶指南在现代软
java·python·pytest
小罗和阿泽1 天前
GUI 自动化测试 pywinauto测试框架
开发语言·python·功能测试·测试工具·pytest
文人sec1 天前
抛弃 Postman!用 Pytest+Requests+Allure+Playwright+Minium 搭建高逼格接口+UI自动化测试平台
自动化测试·python·测试工具·ui·pytest·playwright
曲幽2 天前
FastAPI单元测试实战:别等上线被喷才后悔,TestClient用对了真香!
python·单元测试·pytest·api·fastapi·web·httpx·testclient·依赖项覆盖
小罗和阿泽2 天前
接口测试系列 接口自动化测试 pytest框架(四)
pytest
python开发笔记2 天前
pytest(16) mark用法
pytest
忘忧记2 天前
pytest 基础用法教程
pytest
我的xiaodoujiao3 天前
3、API 接口自动化测试详细图文教程学习系列3--相关Python基础知识2
python·学习·测试工具·pytest