pytest管理多个不同的python脚本文件的运行顺序

在pytest中管理多个不同Python脚本文件的运行顺序可以通过以下几种方法实现。以下是分步说明和示例:


1. 默认行为:按文件名和目录顺序

pytest默认按文件和目录的字母顺序执行测试。例如:

  • 文件顺序:test_a.pytest_b.pytest_c.py
  • 目录顺序:tests/下的子目录按字母顺序执行。

2. 显式控制单个测试文件的顺序

方法 1:修改文件名(简单但不够灵活)

通过为文件名添加数字前缀,手动控制顺序:

test_01_feature_a.py
test_02_feature_b.py
test_03_feature_c.py

方法 2:使用 pytest-ordering 插件(控制测试函数/类的顺序)

适用场景:需要控制测试函数或测试类的顺序,而不是文件级别。

  1. 安装插件:
    pip install pytest-ordering
    
  2. 在测试函数上标记顺序:
    import pytest
    
    @pytest.mark.run(order=2)
    def test_feature_a():
        assert True
    
    @pytest.mark.run(order=1)
    def test_feature_b():
        assert True
    

方法 3:使用 Hook 自定义文件顺序(推荐)

通过 pytest_collection_modifyitems 钩子在 conftest.py 中调整测试文件的执行顺序。

  1. 在项目根目录创建 conftest.py

    def pytest_collection_modifyitems(session, config, items):
        # 定义文件执行优先级(按模块名)
        priority_order = ["test_login.py", "test_api.py", "test_ui.py"]
        
        # 将测试用例按优先级排序
        items.sort(key=lambda item: priority_order.index(item.module.__name__))
    
  2. 按目录优先级排序

    def pytest_collection_modifyitems(items):
        items.sort(key=lambda item: item.fspath.mkdir().name)
    

3. **使用 pytest-dependency 插件处理测试依赖

适用场景:某些测试必须在其他测试通过后执行。

  1. 安装插件:
    pip install pytest-dependency
    
  2. 标记依赖关系:
    import pytest
    
    @pytest.mark.dependency()
    def test_login():
        assert True
    
    @pytest.mark.dependency(depends=["test_login"])
    def test_profile():
        assert True
    

4. 最佳实践建议

  • 避免依赖顺序:理想情况下,每个测试应独立运行,不依赖其他测试的状态。
  • 显式标记顺序:如果必须控制顺序,优先使用 pytest-ordering 或 Hook。
  • 分组测试:将需要顺序执行的测试放在同一个文件或目录中。

示例:通过 Hook 控制文件顺序

# conftest.py
def pytest_collection_modifyitems(session, config, items):
    # 定义文件优先级
    file_priority = {
        "test_login.py": 0,
        "test_api.py": 1,
        "test_ui.py": 2
    }
    
    # 对测试用例重新排序
    items.sort(key=lambda item: file_priority.get(item.module.__name__, 999))

通过以上方法,可以灵活控制 pytest 的测试执行顺序。优先推荐使用 Hook 或插件来实现动态调整。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值