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

相关推荐
我的xiaodoujiao3 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 24--数据驱动--参数化处理 Excel 文件 1
python·学习·测试工具·pytest
西游音月5 天前
(2)pytest+Selenium自动化测试-环境准备
selenium·测试工具·pytest
我的xiaodoujiao6 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 23--数据驱动--参数化处理 Yaml 文件
python·学习·测试工具·pytest
我的xiaodoujiao9 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 22--数据驱动--参数化处理 Json 文件
python·学习·测试工具·pytest
胜天半月子9 天前
Python自动化测试 | 快速认识并了解pytest的基本使用
服务器·python·pytest
北珣.13 天前
自动化框架pytest基础
自动化·pytest
程序员杰哥14 天前
Pytest之收集用例规则与运行指定用例
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
学习3人组15 天前
Python + requests + pytest + allure + Jenkins 构建完整的接口自动化测试框架
python·jenkins·pytest
shao91851618 天前
Gradio全解14——使用Gradio构建MCP的服务器与客户端(4)——Python包命令:uv与uvx实战
pytest·uv·1024程序员节·npx·uvx·uv pip·ruff
我的xiaodoujiao19 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 20--PO(POM) 设计模式和用例撰写
python·学习·测试工具·设计模式·pytest