2016-02-23 62 views
5

嗨如何爲列表或文件數動態生成測試方法。 假設我有在json中的輸入值的file1,file2和filen。現在我需要運行像下面多個值相同的測試,pytest動態生成測試方法

class Test_File(unittest.TestCase): 
    def test_$FILE_NAME(self): 
     return_val = validate_data($FILE_NAME) 
     assert return_val 

我使用下面的命令來運行py.test生成html和JUnit報告

py.test test_rotate.py --tb=long --junit-xml=results.xml --html=results.html -vv 

目前我手動定義方法如下,

def test_lease_file(self): 
    return_val = validate_data(lease_file) 
    assert return_val 

def test_string_file(self): 
    return_val = validate_data(string_file) 
    assert return_val 

def test_data_file(self): 
    return_val = validate_data(data_file) 
    assert return_val 

請讓我知道如何指定py test來動態生成test_came方法,同時給出報告。

我期待究竟這是在這個博客「http://eli.thegreenplace.net/2014/04/02/dynamically-generating-python-test-cases

但上述博客使用單元測試,並提到,如果我使用,我不能當我們使用固定裝置,生成HTML和JUnit報告

下面我得到錯誤像它需要2個參數,

test_case = [] 
class Memory_utlization(unittest.TestCase): 
@classmethod 
def setup_class(cls): 
    fname = "test_order.txt" 
    with open(fname) as f: 
     content = f.readlines() 
    file_names = [] 
    for i in content: 
     file_names.append(i.strip()) 
    data = tuple(file_names) 
    test_case.append(data) 
    logging.info(test_case) # here test_case=[('dhcp_lease.json'),('dns_rpz.json'),] 

@pytest.mark.parametrize("test_file",test_case) 
def test_eval(self,test_file): 
    logging.info(test_case) 

當我執行上述我得到以下錯誤,

>    testMethod() 
E    TypeError: test_eval() takes exactly 2 arguments (1 given) 
+0

我想這可能會幫助你? https://pytest.org/latest/parametrize.html – adarsh

回答

6

This可能會幫助你。然後

你的測試類會是什麼樣子

class Test_File(): 
    @pytest.mark.parametrize(
     'file', [ 
      (lease_file,), 
      (string_file,), 
      (data_file,) 
     ] 
    ) 
    def test_file(self, file): 
     assert validate_data(file) 
+0

如果我沒有上課,它可以正常工作,如pytest fixtures doc中所述。但是當我使用setup方法並使用self時,它會失敗,並顯示錯誤TypeError:test_eval()只需要2個參數(給出1) –

+0

您可以添加它作爲您的問題的編輯,因爲它對我而言有點不清楚 – adarsh

+0

@NaggappanRamukannan,不要忘記刪除''self'' –