2015-06-29 37 views
1

我使用pytest最近做軟件測試,但在動態參數化測試裝置時遇到問題。測試時,我想能夠提供可以選擇:通過在安裝根目錄Pytest的addoptions問題和動態參數化測試裝置

下面是指定其文件名

B)測試中的所有文件

A)測試一個特定的文件我目前的conftest.py。我想要它做的是如果你選擇選項A(--file_name),使用指定的文件名創建一個參數化的測試夾具。如果您選擇選項B(--all_files),請提供所有文件的列表作爲參數化測試夾具。

import os 
import pytest 

def pytest_addoption(parser): 
    parser.addoption("--file_name", action="store", default=[], help="Specify file-under-test") 
    parser.addoption("--all_files", action="store_true", help="Option to test all files root directory") 

@pytest.fixture(scope='module') 
def file_name(request): 
    return request.config.getoption('--file_name') 

def pytest_generate_tests(metafunc): 
    if 'file_name' in metafunc.fixturenames: 
     if metafunc.config.option.all_files: 
      all_files = list_all_files() 
     else: 
      all_files = "?" 
     metafunc.parametrize("file_name", all_files) 


def list_all_files(): 
    root_directory = '/opt/' 
    if os.listdir(root_directory): 
     # files have .cool extension that need to be split out 
     return [name.split(".cool")[0] for name in os.listdir(root_directory) 
       if os.path.isdir(os.path.join(root_directory, name))] 
    else: 
     print "No .cool files found in {}".format(root_directory) 

我越是這種不甘示弱,我只能得到工作的選擇之一,但不是其他...什麼,我需要做的就是兩個選項(可能更多)動態地創建參數化的測試夾具?

回答

1

你在找這樣的嗎?

def pytest_generate_tests(metafunc): 
    if 'file_name' in metafunc.fixturenames: 
     files = [] 
     if metafunc.config.option.all_files: 
      files = list_all_files() 
     fn = metafunc.config.option.file_name 
     if fn: 
      files.append(fn) 
     metafunc.parametrize('file_name', all_files, scope='module') 

不需要定義file_name功能。

+0

這是部分工作......這真的很怪異,但它看起來像我的一些測試通過,有些不。對於失敗,我最終得到一個AttributeError:'list'對象沒有屬性'endswith'。看起來有時候我得到一個無參數化的夾具,因爲我可以在測試日誌輸出中看到整個文件列表,而不是隻有1個條目。 – t88

+0

@ t88這可能是因爲parser.addoption(「 - file_name」,...)中的'default = []'是錯誤的。爲了一致性,你應該做'default ='''。如果它沒有幫助,然後給我們看看測試。你刪除了'file_name'函數嗎? – freakish

+0

你是對的!另外,事實證明files.append(fn)正在返回一個列表,如果我指定了一個file_name,它將返回一個列表,而不是使用指定的字符串作爲參數化測試夾具。謝謝! – t88