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

相关推荐
黄昏恋慕黎明17 小时前
博客论坛技术迭代
python·pytest
2601_9620782319 小时前
Python接口自动化流程(pytest)
python·pytest·接口自动化·测试框架·断言
杨女士YRJ20 小时前
python+pytest+01
python·pytest
2601_962078232 天前
Python接口自动化框架:pytest
python·pytest·接口自动化·测试框架·restfulapi
2601_962078192 天前
Appium+Python+pytest自动化测试框架详解
自动化测试·python·appium·pytest·移动应用
2601_962284504 天前
安卓APP UI自动化测试:Python + UiAutomator2 + pytest + pytest-html
python·pytest·uiautomator2·ui自动化测试·安卓app
2601_962300814 天前
基于pytest的接口自动化测试:使用requests模块的实战项目与接口关联方法详解
接口自动化测试·测试用例·pytest·接口关联·requests模块
2601_962300814 天前
Python + Requests + Pytest + Excel + Allure:接口自动化测试项目实战
python·excel·pytest·allure·requests
11路没有终点5 天前
Pytest 安装、版本与第一个测试用例
测试用例·pytest
11路没有终点6 天前
pytest 参数化与 Mark 标记
pytest