python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > pytest conftest.py使用

pytest conftest.py使用的小结

作者:一半烟火以谋生

pytest的conftest.py是核心配置文件, 本文就来详细介绍pytest conftest.py使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

1. conftest.py 是什么?

2. 基础环境搭建

  1. 安装 pytest:
    pip install pytest
    
  2. 创建项目结构:
    project/
    ├── tests/
    │   ├── conftest.py    # 核心配置文件
    │   ├── test_api.py    # 测试用例1
    │   └── test_db.py     # 测试用例2
    

3. 夹具(fixture)实战

场景:多个测试用例共享数据库连接
conftest.py 中添加:

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):

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 中添加:

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

运行测试时将显示:

============================ test session starts ============================
测试环境: Production v2.1 | 执行人: alice

5. 作用域控制

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

优先级规则

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

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

场景:测试不同浏览器的兼容性
conftest.py 中添加:

import pytest

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

测试用例自动运行3次:

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. 调试技巧:查看夹具生效情况
    pytest --fixtures  # 显示所有可用夹具
    

8. 完整示例

项目结构:

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

到此这篇关于pytest conftest.py使用的小结的文章就介绍到这了,更多相关pytest conftest.py使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

您可能感兴趣的文章:
阅读全文