繁体   English   中英

在pytest中按类进行组测试执行

[英]Group test execution by class in pytest

我用以下方式构造了测试用例。

app
  test_login.py
    class1
      test_11
      test_12
  test_function1.py
    class2
      test_21
      test_22

当我运行“ pytest.exe应用程序”时,pytest能够识别所有测试用例,但它以随机顺序执行。 例如,test11,test22,test12等

有什么办法可以更改此设置并首先在file :: class中执行所有测试用例,然后再移至另一个file :: class?

它以随机顺序执行

默认情况下,测试按模块排序; 在模块内部,将按照指定的顺序执行测试。 因此,您应该获得大致的订单,如下所示:

$ pytest --collect-only -q
test_function1.py::class2::test_21
test_function1.py::class2::test_22
test_login.py::class1::test_11
test_login.py::class1::test_12

有什么办法可以更改此设置并首先在file :: class中执行所有测试用例,然后再移至另一个file :: class?

如果要更改默认执行顺序,可以在pytest_collection_modifyitems挂钩中执行。 该示例按类名然后按测试名对收集的测试进行重新排序:

# conftest.py

import operator

def pytest_collection_modifyitems(items):
    items.sort(key=operator.attrgetter('cls.__name__', 'name'))

现在,在测试test_login将那些之前执行test_function1因为模块名称不会在订购计了:

$ pytest --collect-only -q
test_login.py::class1::test_11
test_login.py::class1::test_12
test_function1.py::class2::test_21
test_function1.py::class2::test_22

以下代码块解决了我的问题。 感谢@hoefling给您的时间和帮助。

# conftest.py
@pytest.hookimpl(hookwrapper=True)
def pytest_collection_modifyitems(items):
    yield
    items.sort(key=operator.attrgetter('cls.__name__'))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM