2016-11-26 143 views
1

使用pytest,我試圖測試一個像分層場景的樹。 允許使用文檔的結構的例子:pytest樹狀數據嵌套參數化

Document --- Chapter --- Paragraph 
     1 n  1 n 

凡文檔包含多個章節;一章包含多個段落。

當開始測試新文檔時,需要運行一些設置代碼;當新章節開始時,需要運行其他一些設置代碼;段落也一樣。

寫成僞代碼:

for doc in documents: 
    setup_doc(doc) 
    for chapter in doc.chapters: 
     setup_chapter(chapter) 
     for paragraph in chapter.paragraphs: 
      setup_paragraph(paragraph) 
      test_it(doc, chapter, paragraph) 
      teardown_paragraph(paragraph) 
     teardown_chapter(chapter) 
    teardown_doc(doc) 

如果我們有如下的數據:

Document Alpha 
    chapter A 
     Paragraph A1 
     Paragraph A2 
    chapter B 
     Paragraph B1 

我希望收集到的測試案例是:

test_it[Alpha, A, A1] 
test_it[Alpha, A, A2] 
test_it[Alpha, B, B1] 

我已經嘗試了pytest_generate_tests,類場景,燈具和參數化測試函數的不同組合,但沒有b能夠實現這一點。

任何指針將不勝感激。

回答

0

Pytest fixutes應該是獨立的。 所以要解決你的任務,你必須建立一個與所有功能組合(文檔 - 章 - 段)的清單一個夾具。

你可以用簡單的工具來做到這一點,該工具返回這樣一個列表的一個元素,或者你可以在測試生成階段生成這個列表,如下面的代碼所示。

documents = { 
     'Alpha': { 
      'A': {'A1': {},'A2': {}}, 
      'B': {'B1': {}} 
     } 
    } 


def pytest_generate_tests(metafunc): 
    """Documents tree from documents""" 
    if 'document' in metafunc.fixturenames: 
     documents_plain = [] 
     for document in documents.keys(): 
      for chapter in documents[document].keys(): 
       for paragraph in documents[document][chapter].keys(): 
        documents_plain.append({'document': document, 'chapter': chapter, 'paragraph': paragraph}) 
     metafunc.parametrize(
      'document', 
      documents_plain, 
      scope='session') 


def test_it(document): 
    print('{}, {}, {}'.format(document['document'], document['chapter'], document['paragraph'])) 


py.test -s 

Alpha, B, B1 
Alpha, A, A1 
Alpha, A, A2 
0

如果像我一樣,你想通過documentdocument,一些參數化的documentchapter還有一些一些測試,chapterparagraph我的方法(安德烈·索羅金的啓發)如下。

conftest.py

import pytest 

documents = { 
    'Alpha': { 
     'A': {'A1': {},'A2': {}}, 
     'B': {'B1': {}} 
    } 
} 

def pytest_generate_tests(metafunc): 
    if 'document' in metafunc.fixturenames: 
     if 'chapter' in metafunc.fixturenames: 
      if 'paragraph' in metafunc.fixturenames: 
       metafunc.parametrize(
        ['document', 'chapter', 'paragraph'], 
        [(d, c, p) for d, cs in documents.items() 
           for c, ps in cs.items() 
           for p in ps.keys() 
        ]) 
      else: 
       metafunc.parametrize(
        ['document', 'chapter'], 
        [(d, c) for d, cs in documents.items() 
          for c in cs.keys() 
        ]) 
     else: 
      metafunc.parametrize(
        'document', documents.keys()) 

然後在test.py

def test_d(document): 
    print(document) 

def test_dc(document, chapter): 
    print(document, chapter) 

def test_dcp(document, chapter, paragraph): 
    print(document, chapter, paragraph) 

運行

>>> pytest test.py -s 
test.py Alpha 
.Alpha A 
.Alpha B 
.Alpha A A2 
.Alpha A A1 
.Alpha B B1 
.