按自定义顺序运行Pytest类

2024-08-11Python开发问题
4

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

问题描述

我正在用pycharm写pytest测试。考试分成不同的班级。
我要指定必须在其他类之前运行的某些
我看到了关于堆栈溢出的各种问题(例如specifying pytest tests to run from a file和how 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类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11