pytest conftest.py 使用教程

pytest conftest.py 使用教程

1. conftest.py 是什么?
  • 核心配置文件,用于存放测试用例的共享逻辑
  • 自动被 pytest 发现,无需显式导入
  • 支持功能:夹具(fixture)、钩子函数(hooks)、插件配置

2. 基础环境搭建
  1. 安装 pytest:

    bash 复制代码
    pip install pytest
  2. 创建项目结构:

    bash 复制代码
    project/
    ├── tests/
    │   ├── conftest.py    # 核心配置文件
    │   ├── test_api.py    # 测试用例1
    │   └── test_db.py     # 测试用例2

3. 夹具(fixture)实战

场景 :多个测试用例共享数据库连接

conftest.py 中添加:

python 复制代码
import pytest
import psycopg2

@pytest.fixture(scope="module")
def db_connection():
    """创建数据库连接(模块级共享)"""
    conn = psycopg2.connect("dbname=test user=postgres")
    yield conn  # 测试执行时返回连接
    conn.close()  # 测试结束后自动关闭

在测试用例中使用(test_db.py):

python 复制代码
def test_user_count(db_connection):
    cursor = db_connection.cursor()
    cursor.execute("SELECT COUNT(*) FROM users")
    assert cursor.fetchone()[0] > 0

4. 钩子函数(hooks)应用

场景 :自定义测试报告头信息

conftest.py 中添加:

python 复制代码
def pytest_report_header(config):
    """在报告中显示自定义环境信息"""
    return "测试环境: Production v2.1 | 执行人: ${USER}"

运行测试时将显示:

bash 复制代码
============================ test session starts ============================
测试环境: Production v2.1 | 执行人: alice

5. 作用域控制
层级 说明 示例路径
目录级 影响当前目录及子目录 /tests/conftest.py
多级嵌套 支持不同目录的独立配置 /tests/api/conftest.py
全局 项目根目录的配置全局生效 /conftest.py

优先级规则

  1. 子目录 > 父目录
  2. 就近原则

6. 高级技巧:参数化夹具

场景 :测试不同浏览器的兼容性

conftest.py 中添加:

python 复制代码
import pytest

@pytest.fixture(params=["chrome", "firefox", "edge"])
def browser(request):
    """参数化浏览器驱动"""
    driver = setup_browser(request.param)
    yield driver
    driver.quit()

测试用例自动运行3次:

python 复制代码
def test_login(browser):
    browser.get("https://example.com/login")
    # 断言登录页面标题
    assert "Login" in browser.title

7. 最佳实践
  1. 避免过度使用:仅在需要共享逻辑时使用

  2. 命名规范 :夹具名称应具有描述性(如 db_connection

  3. 作用域选择

    • function(默认):每个测试函数执行一次
    • class:每个测试类执行一次
    • module:每个模块执行一次
    • session:整个测试会话执行一次
  4. 调试技巧 :查看夹具生效情况

    bash 复制代码
    pytest --fixtures  # 显示所有可用夹具

8. 完整示例

项目结构:

bash 复制代码
project/
├── conftest.py                 # 全局配置
├── tests/
│   ├── conftest.py             # 测试目录配置
│   ├── test_api.py
│   └── web/
│       ├── conftest.py         # 子目录专属配置
│       └── test_ui.py

层级配置生效顺序:

  1. web/conftest.py
  2. tests/conftest.py
  3. 根目录 conftest.py

通过合理使用 conftest.py,可将测试代码复用率提升 60%+,同时保持测试逻辑的清晰隔离。

相关推荐
少云清1 分钟前
【接口测试】4_代码实现 _pytest框架
pytest·接口测试
屋顶那猫1 小时前
使用pyinstaller打包pytest项目
python·pytest
zyx没烦恼1 天前
pytest框架
pytest
兴趣使然黄小黄3 天前
【Pytest】Pytest常用的第三方插件
python·pytest
我的xiaodoujiao3 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 34--基础知识 9--文件上传功能
前端·python·测试工具·ui·pytest
我一定会有钱3 天前
pytest测试框架基础
python·单元测试·自动化·pytest
我的xiaodoujiao3 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 35--二次封装MySQL数据库连接操作
python·学习·测试工具·pytest
给你一页白纸4 天前
Pytest 测试用例自动生成:接口自动化进阶实践
python·pytest·接口自动化
工会主席-阿冰4 天前
使用pytest-selenium插件,ui自动化示例
selenium·pytest
工会主席-阿冰4 天前
pytest,ui自动化示例
pytest·ui自动化