2016-10-12 16 views
1

py.testを使用しています。マーカー情報が含まれているテストのリストを取得したいと思います。 --collect-onlyフラグを使用すると、テスト機能が使用できます。各テストに割り当てられたマーカーも取得する方法はありますか?私は回避策のコードサンプル作成フランクTの回答に基づいてマーカーを使って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が組み込まれている行動のマーカー情報と共にテスト機能をリストするとは思いませんそれらのテストのために。 --markersコマンドは登録されているすべてのマーカーを一覧表示しますが、それはあなたが望むものではありません。私は簡単にlist of pytest pluginsを見て、関連性があると思われるものは見ませんでした。

あなた自身のpytestプラグインを使って、マーカー情報と共にテストをリストすることができます。 Hereは、pytestプラグインの作成に関するドキュメントです。

私は"pytest_collection_modifyitems"フックを試してみます。収集されたすべてのテストのリストが渡され、それらを変更する必要はありません。 (Hereは、すべてのフックのリストです。)あなたが探しているマーカーの名前を知っていれば

そのフックに渡されたテストは、(例えばthis codeを参照)get_marker()メソッドを持っています。そのコードを調べてみると、すべてのマーカーを一覧表示するための公式のAPIは見つかりませんでした。私は仕事を完了するためにこれを見つけた:test.keywords.__dict__['_markers']herehereを参照)。

+0

ありがとう、私はそれらに基づいて回避策を作成しました。 –

0

あなたは彼らが、デフォルトでは逆の順に表示されたことを、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'] 

注意をname属性によってマーカーを見つけることができます。

関連する問題