Pytest收集用例

发布时间 2023-07-22 18:02:54作者: 韩志超

有时候我们需要收集一下当前的测试用例,获的所有测试用例的列表,在使用pytest的测试框架里,我们可以使用

pytest <path> --collect-only -q

来仅收集(不运行)用例。但是使用这个命令用例列表只会显示在命令行中,如何在代码中使用并得到这个用例列表呢?
除了使用os.popen()或subprocess从命令行执行,获得并解析命令行输出外,我们还可以使用Pytest的钩子方法pytest_collection_modifyitems,在收集用例时,将用例存起来。
实现方式如下:

import pytest
from io import StringIO
from contextlib import redirect_stdout

class TestCollection:
    def __init__(self):
        self.collected = []

    def pytest_collection_modifyitems(self, items):
        for item in items:
            self.collected.append(item.nodeid)

def get_testcases(testpath):
    coll = TestCollection()

    temp_stdout = StringIO()
    with redirect_stdout(temp_stdout):  # 不显示命令行输出
        pytest.main([testpath, '--collect-only', '-q'], plugins=[coll]) # 指定插件
    return coll.collected

get_testcases('./testcases')

上面我们定义了一个插件TestCollection,插件中包含一个钩子方法,在收集用例时,将用例节点id添加到插件的collected属性中。
使用pytest.main运行时,可以指定使用该插件,然后从插件对象coll中获取结果即可。