use*_*613 6 python class function pytest pycharm
我正在 pycharm 中使用 pytest 编写测试。测试分为不同的类别。
我想指定某些类必须在其他类之前运行。
我在 stackoverflow 上看到了各种问题(例如指定从文件运行 pytest 测试以及如何在所有其他测试之前运行方法)。
这些和其他各种问题想要选择特定的函数按顺序运行。fixtures据我了解,这可以使用或 with来完成pytest ordering。
我不关心每个类的哪些函数首先运行。我所关心的是课程按照我指定的顺序运行。这可能吗?
您可以使用pytest_collection_modifyitems挂钩来修改收集的测试 ( items) 的顺序。这样做的另一个好处是无需安装任何第三方库。
通过一些自定义逻辑,这允许按类别排序。
假设我们有三个测试类:
TestExtractTestTransformTestLoad还可以说,默认情况下,测试的执行顺序将按字母顺序排列,即:
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
Run Code Online (Sandbox Code Playgroud)
关于实施细节的一些评论:
CLASS_ORDER不必是详尽无遗的。您可以仅对那些想要强制执行顺序的类进行重新排序(但请注意:如果重新排序,任何未重新排序的类将在任何重新排序的类之前执行)items必须就地修改,因此最终items[:]分配