2016-10-12 44 views
1

我正在使用py.test,我想获取包含标记信息的测试列表。 当我使用- 仅收集标志时,我获得测试功能。有没有办法为每个测试获得指定的标记?用标记收集py.test测试信息


基于弗兰克牛逼的答案,我创建了一个解决方法的代码示例:

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() 

回答

0

我不认为pytest具有内置行为列出测试功能与标记信息一起为那些测试。 A --markers命令会列出所有已注册的标记,但这不是您想要的。我简要地看了看list of pytest plugins,并没有看到任何看起来相关的东西。

你可以编写自己的pytest插件列出测试以及标记信息。 Here是编写pytest插件的文档。

我会尝试使用"pytest_collection_modifyitems"挂钩。它传递了收集的所有测试的列表,并且不需要修改它们。 (Here是所有挂钩的列表。)

到该钩通过测试有一个get_marker()方法,如果您知道标记的您正在寻找的名称(见this code为例)。当我查看代码时,找不到列出所有标记的官方API。我发现这可以完成这项工作:test.keywords.__dict__['_markers'](请参阅herehere)。

+0

感谢您的建议,我基于它们创建了一个解决方法。 –

0

你可以找到一个name属性标记在request.function.pytestmark对象

@pytest.mark.scenarious1 
@pytest.mark.scenarious2 
@pytest.mark.scenarious3 
def test_sample(): 
    pass 

@pytest.fixture(scope='function',autouse=True) 
def get_markers(): 
    print([marker.name for marker in request.function.pytestmark]) 

>>> ['scenarious3', 'scenarious2', 'scenarious1'] 

注意,他们是在默认情况下相反的顺序列出。