pytestconftest.py使用的小结

Written by

in

文章目录
  • 核心配置文件,用于存放测试用例的共享逻辑 自动被 pytest 发现,无需显式导入 支持功能:夹具(fixture)、钩子函数(hooks)、插件配置
  • 安装 pytest: pip install pytest 创建项目结构: project/ ├── tests/ │ ├── conftest.py # 核心配置文件 │ ├── test_api.py # 测试用例1 │ └── test_db.py # 测试用例2
  • 场景:多个测试用例共享数据库连接在 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
  • 场景:自定义测试报告头信息在 conftest.py 中添加: def pytest_report_header(config): “””在报告中显示自定义环境信息””” return “测试环境: Production v2.1 | 执行人: ${USER}” 运行测试时将显示: ============================ test session starts ============================测试环境: Production v2.1 | 执行人: alice
  • 层级 说明 示例路径 目录级 影响当前目录及子目录 /tests/conftest.py 多级嵌套 支持不同目录的独立配置 /tests/api/conftest.py 全局 项目根目录的配置全局生效 /conftest.py 优先级规则: 子目录 > 父目录 就近原则
  • 场景:测试不同浏览器的兼容性在 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
  • 避免过度使用:仅在需要共享逻辑时使用 命名规范:夹具名称应具有描述性(如 db_connection) 作用域选择: function(默认):每个测试函数执行一次 class:每个测试类执行一次 module:每个模块执行一次 session:整个测试会话执行一次 调试技巧:查看夹具生效情况 pytest –fixtures # 显示所有可用夹具
  • 项目结构: project/ ├── conftest.py # 全局配置 ├── tests/ │ ├── conftest.py # 测试目录配置 │ ├── test_api.py │ └── web/ │ ├── conftest.py # 子目录专属配置 │ └── test_ui.py 层级配置生效顺序: web/conftest.py tests/conftest.py 根目录 conftest.py 通过合理使用 conftest.py,可将测试代码复用率提升 60%+,同时保持测试逻辑的清晰隔离。 到此这篇关于pytest conftest.py使用的小结的文章就介绍到这了,更多相关pytest conftest.py使用内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!  您可能感兴趣的文章: pytest中conftest.py使用小结 Pytest框架 conftest.py文件的使用详解 Pytest中conftest.py的用法 pytest conftest.py文件的使用讲解 python pytest进阶之conftest.py详解
  • 目录
    • 1. conftest.py 是什么?
    • 2. 基础环境搭建
    • 3. 夹具(fixture)实战
    • 4. 钩子函数(hooks)应用
    • 5. 作用域控制
    • 6. 高级技巧:参数化夹具
    • 7. 最佳实践
    • 8. 完整示例

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

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

    场景:多个测试用例共享数据库连接
    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
    

    场景:自定义测试报告头信息
    conftest.py 中添加:

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

    运行测试时将显示:

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

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

    优先级规则

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

    场景:测试不同浏览器的兼容性
    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
    

    1. 避免过度使用:仅在需要共享逻辑时使用
    2. 命名规范:夹具名称应具有描述性(如 db_connection
    3. 作用域选择
      • function(默认):每个测试函数执行一次
      • class:每个测试类执行一次
      • module:每个模块执行一次
      • session:整个测试会话执行一次
    4. 调试技巧:查看夹具生效情况
      pytest --fixtures  # 显示所有可用夹具
      

    项目结构:

    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使用内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客! 

    您可能感兴趣的文章:

    • pytest中conftest.py使用小结
    • Pytest框架 conftest.py文件的使用详解
    • Pytest中conftest.py的用法
    • pytest conftest.py文件的使用讲解
    • python pytest进阶之conftest.py详解

    站内搜索