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%+,同时保持测试逻辑的清晰隔离。

相关推荐
昔我往昔5 天前
pytest日志问题排查记录
python·pytest
黄昏恋慕黎明8 天前
博客论坛技术迭代
python·pytest
2601_962078238 天前
Python接口自动化流程(pytest)
python·pytest·接口自动化·测试框架·断言
杨女士YRJ8 天前
python+pytest+01
python·pytest
2601_962078239 天前
Python接口自动化框架:pytest
python·pytest·接口自动化·测试框架·restfulapi
2601_962078199 天前
Appium+Python+pytest自动化测试框架详解
自动化测试·python·appium·pytest·移动应用
2601_9622845011 天前
安卓APP UI自动化测试:Python + UiAutomator2 + pytest + pytest-html
python·pytest·uiautomator2·ui自动化测试·安卓app
2601_9623008111 天前
基于pytest的接口自动化测试:使用requests模块的实战项目与接口关联方法详解
接口自动化测试·测试用例·pytest·接口关联·requests模块
2601_9623008111 天前
Python + Requests + Pytest + Excel + Allure:接口自动化测试项目实战
python·excel·pytest·allure·requests
11路没有终点12 天前
Pytest 安装、版本与第一个测试用例
测试用例·pytest