【问题标题】:Run slow Pytest commands at the end of the test suite在测试套件结束时运行缓慢的 Pytest 命令
【发布时间】:2020-05-01 16:58:23
【问题描述】:

假设我有以下 pytest 脚本:

import pytest

def test_one():
    pass

def test_two():
    pass

@pytest.mark.slow
def test_three():
    pass

我可以使用一个命令来运行所有带有 slow 标记的测试吗?我知道我可以使用两个 pytest 命令执行此操作,但使用单个命令执行此操作会很棒:

pytest -v -m "not slow"
# test_markers.py::test_one PASSED                                                                                                                    
# test_markers.py::test_two PASSED

pytest -v -m slow
# test_markers.py::test_three PASSED

【问题讨论】:

标签: python pytest


【解决方案1】:

您可以添加对收集的测试的自定义排序,并将带有 slow 标记的项目放在最后。将以下代码放入项目或测试根目录的conftest.py 文件中:

from _pytest.mark import Mark


empty_mark = Mark('', [], {})


def by_slow_marker(item):
    return item.get_closest_marker('slow', default=empty_mark)


def pytest_collection_modifyitems(items):
    items.sort(key=by_slow_marker, reverse=True)

这会将具有slow 标记的项目放置在收集的测试序列的末尾。如果要打开和关闭此功能,请添加自定义命令行标志:

def pytest_addoption(parser):
    parser.addoption('--slow-last', action='store_true', default=False)


def pytest_collection_modifyitems(items, config):
    if config.getoption('--slow-last'):
        items.sort(key=by_slow_marker, reverse=True)

运行 pytest --slow-last 现在将使用这些项目。

【讨论】:

  • 效果很好!只需删除 reverse=True 即可让慢速测试最后运行。
猜你喜欢
  • 2018-03-16
  • 1970-01-01
  • 1970-01-01
  • 2011-04-29
  • 1970-01-01
  • 1970-01-01
  • 2015-05-09
  • 2015-11-25
  • 1970-01-01
相关资源
最近更新 更多