測(cè)試驅(qū)動(dòng)技術(shù)(TDD)系列之-pytest實(shí)現(xiàn)測(cè)試數(shù)據(jù)驅(qū)動(dòng)
本篇文章則介紹如何使用Python進(jìn)行數(shù)據(jù)驅(qū)動(dòng)。這里以pytest測(cè)試框架為例,重點(diǎn)講解pytest參數(shù)化相關(guān)知識(shí)。(關(guān)于pytest的環(huán)境配置以及基礎(chǔ)使用不在本文的討論范圍)
pytest中使用標(biāo)簽@pytest.mark.parametrize 實(shí)現(xiàn)參數(shù)化功能,在執(zhí)行用例的時(shí)候該標(biāo)簽迭代中的每組數(shù)據(jù)都會(huì)作為一個(gè)用例執(zhí)行。
一組參數(shù)化數(shù)據(jù)
定義參數(shù)化數(shù)據(jù),代碼如下:
- class TestDemo1:
- @pytest.mark.parametrize('actual_string, expect_string', [(1, 1), ('BB', 'BB'),('AA', 'BB')])
- def test_1(self, actual_string, expect_string):
- assert (expect_string == actual_string)
運(yùn)行結(jié)果如下,三組數(shù)據(jù)在三條測(cè)試用例中運(yùn)行,其中數(shù)據(jù)('AA', 'BB')運(yùn)行失敗!

多組參數(shù)化數(shù)據(jù)
在一個(gè)測(cè)試類(lèi)中,可以定義多組參數(shù)化數(shù)據(jù)(參數(shù)化數(shù)據(jù)個(gè)數(shù)不同,test_1二個(gè),test_2三個(gè)),代碼如下:
- class TestDemo1:
- @pytest.mark.parametrize('actual_string, expect_string', [(1, 1), ('BB', 'BB'),('AA', 'BB')])
- def test_1(self, actual_string, expect_string):
- assert (expect_string == actual_string)
- @pytest.mark.parametrize('result, a,b', [(1, 1,0),(2, 1,0) ])
- def test_2(self, result, a,b):
- assert (result == a+b)
運(yùn)行結(jié)果如下,二組數(shù)據(jù)分別在test_1和test_2中運(yùn)行!

從excel中讀取數(shù)據(jù)作為參數(shù)
我們可以自定義一些方法,對(duì)外部文件進(jìn)行讀取,然后把讀取的數(shù)據(jù)作為參數(shù)在pytest
中引用。把測(cè)試數(shù)據(jù)保存在excel中,如下圖

寫(xiě)一個(gè)讀取excel類(lèi)文件的方法,使用模塊pandas ,使用命令pip install pandas 安裝模塊,源碼如下:
- import pandas as pd
- # 讀取Excel文件 -- Pandas
- def read_data_from_pandas(excel_file, sheet_name):
- if not os.path.exists(excel_file):
- raise ValueError("File not exists")
- s = pd.ExcelFile(excel_file)
- df = s.parse(sheet_name)#解析sheet頁(yè)的數(shù)據(jù)
- return df.values.tolist()#數(shù)據(jù)返回為list
從excel中讀取數(shù)據(jù),并賦值給變量進(jìn)行參數(shù)化,代碼如下:
- @pytest.mark.parametrize('actual_string, expect_string', read_data_from_pandas('E:/TestData.xls', 'data1'))
- def test_3(self, actual_string, expect_string):
- assert (expect_string == actual_string)
運(yùn)行結(jié)果如下,三組數(shù)據(jù)在三條測(cè)試用例中運(yùn)行!

注意:excel中的首行,默認(rèn)不會(huì)作為測(cè)試數(shù)據(jù)處理。