按自定义顺序运行Pytest类 [英] Run Pytest Classes in Custom Order

查看:38
本文介绍了按自定义顺序运行Pytest类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用pycharm写pytest测试。考试分成不同的班级。
我要指定必须在其他类之前运行的某些
我看到了关于堆栈溢出的各种问题(例如specifying pytest tests to run from a filehow to run a method before all other tests)。
这些问题和其他各种问题都希望选择特定的函数按顺序运行。我的理解是,这可以使用fixturespytest ordering来完成。
我不在乎每个类中的哪个函数首先运行。我只关心是否按我指定的顺序运行。这可能吗?

推荐答案

方法

您可以使用pytest_collection_modifyitems hook修改收集的测试的顺序(items)。这还有一个额外的好处,即不必安装任何第三方库。

使用某些自定义逻辑,这允许按类排序。

完整示例

假设我们有三个测试类:

  1. TestExtract
  2. TestTransform
  3. TestLoad

还可以说,默认情况下,执行的测试顺序是按字母顺序排列的,即:

TestExtract->;TestLoad->;TestTransform

由于测试类相互依赖,这对我们不起作用。

我们可以将pytest_collection_modifyitems添加到conftest.py,如下所示以强制执行所需的执行顺序:

# conftest.py
def pytest_collection_modifyitems(items):
    """Modifies test items in place to ensure test classes run in a given order."""
    CLASS_ORDER = ["TestExtract", "TestTransform", "TestLoad"]
    class_mapping = {item: item.cls.__name__ for item in items}

    sorted_items = items.copy()
    # Iteratively move tests of each class to the end of the test queue
    for class_ in CLASS_ORDER:
        sorted_items = [it for it in sorted_items if class_mapping[it] != class_] + [
            it for it in sorted_items if class_mapping[it] == class_
        ]
    items[:] = sorted_items

实施细节备注:

  • 测试类可以位于不同的模块中
  • CLASS_ORDER不必详尽。您可以仅对要强制执行顺序的那些类进行重新排序(但注意:如果重新排序,则任何未重新排序的类将在任何重新排序的类之前执行)
  • 类内的测试顺序保持不变
  • 假定测试类具有唯一名称
  • items必须原地修改,因此最终的items[:]作业

这篇关于按自定义顺序运行Pytest类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆