我正在使用py.test,并且希望获取包含标记信息的测试列表。当我使用--collect-only标志时,我得到了测试函数。是否有一种方法也可以获取每个测试分配的标记?
根据Frank T的答案,我创建了一个解决方法代码示例:
from _pytest.mark import MarkInfo, MarkDecorator
import json
def pytest_addoption(parser):
parser.addoption(
'--collect-only-with-markers',
action='store_true',
help='Collect the tests with marker information without executing them'
)
def pytest_collection_modifyitems(session, config, items):
if config.getoption('--collect-only-with-markers'):
for item in items:
data = {}
# Collect some general information
if item.cls:
data['class'] = item.cls.__name__
data['name'] = item.name
if item.originalname:
data['originalname'] = item.originalname
data['file'] = item.location[0]
# Get the marker information
for key, value in item.keywords.items():
if isinstance(value, (MarkDecorator, MarkInfo)):
if 'marks' not in data:
data['marks'] = []
data['marks'].append(key)
print(json.dumps(data))
# Remove all items (we don't want to execute the tests)
items.clear()
markers = [mark.name for mark in item.iter_markers()]
检索标记。 - xverges