如何创建接受参数的新pytest命令行标志

2024-09-29 23:29:06 发布

您现在位置:Python中文网/ 问答频道 /正文

如何创建接受参数的新pytest命令行标志

例如,我有以下几点:

test_A.py::test_a
@pytest.mark.lvl1
def test_a():...
.
.
.
test_B.py::test_b
@pytest.mark.lvl10
def test_b():...

test_C.py::test_c
@pytest.mark.lvl20
def test_c():...

在命令行上,我只想运行标记级别小于等于lvl10的测试(因此lvl1到lvl10测试)

我如何做到这一点而不必在命令行pytest上手动键入-m'lvl1或lvl2或lvl3…'

我想创建一个新的命令行pytest arg,如: pytest--lte=“lvl10”(lte小于等于)

我在想,我想定义--lte标志来执行以下操作:

markers =[]

执行pytest collect以查找包含“lvl”标记的所有测试,并且仅当“lvl”后的整数小于等于10(lvl10)时,才将该标记添加到标记列表中。然后在标记列表上调用pytest-m('lvl1或lvl2或lvl3…')


Tags: 命令行py标记test列表pytest标志def
1条回答
网友
1楼 · 发布于 2024-09-29 23:29:06

如果修改标记以接受级别作为参数,则可以通过向conftest.py添加自定义pytest_runtest_setup来运行小于或等于指定级别的所有测试

样本测试

@pytest.mark.lvl(1)
def test_a():
   ...

conftest.py

import pytest

def pytest_addoption(parser):
    parser.addoption(
        " level", type=int, action="store", metavar="num",
        help="only run tests matching the specified level or lower",
    )


def pytest_configure(config):
    # register the "lvl" marker
    config.addinivalue_line(
        "markers", "lvl(num): mark test to run only on named environment"
    )


def pytest_runtest_setup(item):
    test_level = next(item.iter_markers(name="lvl")).args[0]
    req_level  = item.config.getoption(" level")
    if test_level > req_level:
        pytest.skip(f"tests with level less than or equal to {req_level} was requested")

示例调用

pytest   level 10

相关问题 更多 >

    热门问题