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 个案例并动手复现,一个月即可掌握工业级测试开发技能。

相关推荐
小小龙学IT18 小时前
Python pytest 测试框架深度解析:从断言重写到插件生态的工程化测试体系
网络·python·pytest
落魄大学生之流水线上谋生计3 天前
pytest 入门与实践:从第一个测试到可维护的测试体系
pytest
念越4 天前
Allure 测试报告保姆级教程:从安装到 pytest 集成与报告生成
pytest·allure
念越5 天前
接口自动化测试从入门到实战:接口用例设计、Requests、Pytest、YAML、JSON Schema 与 Allure 报告
python·测试工具·自动化·json·pytest
霍格沃兹测试学院-小舟畅学9 天前
AI+Swagger:一键生成500条pytest接口用例
人工智能·pytest
把头塞进显示器18 天前
电商平台-测试报告
python·selenium·pytest
昔我往昔22 天前
pytest日志问题排查记录
python·pytest
黄昏恋慕黎明1 个月前
博客论坛技术迭代
python·pytest
2601_962078231 个月前
Python接口自动化流程(pytest)
python·pytest·接口自动化·测试框架·断言
杨女士YRJ1 个月前
python+pytest+01
python·pytest