运行 Pytest 类 自定义顺序

Run Pytest Classes in Custom Order

我正在 pycharm 中用 pytest 编写测试。测试分为各种 classes。
我想指定某些 classes 必须 运行 在其他 classes 之前。
我在Whosebug上看到过各种问题(比如specifying pytest tests to run from a file and how to run a method before all other tests)。
这些问题和其他各种问题需要按顺序选择特定的 函数 到 运行。据我所知,这可以使用 fixturespytest ordering.
来完成 我不关心每个 class 运行 中的哪个函数优先。我只关心 classes 运行 按照我指定的顺序。这可能吗?

方法

您可以使用 pytest_collection_modifyitems hook 修改收集测试 (items) 的顺序。这具有无需安装任何第三方库的额外好处。

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

完整示例

假设我们有三个测试 classes:

  1. TestExtract
  2. TestTransform
  3. TestLoad

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

TestExtract -> TestLoad -> TestTransform

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

我们可以按如下方式将 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

对实现细节的一些评论:

  • 测试classes可以存在于不同的模块
  • CLASS_ORDER 不必详尽无遗。您可以仅重新排序那些要执行命令的 classes(但请注意:如果重新排序,任何未重新排序的 class 将在任何重新排序的 class 之前执行)
  • classes内的测试顺序保持不变
  • 假定测试 classes 具有唯一名称
  • items 必须就地修改,因此最后的 items[:] 赋值