測試驅動技術(TDD)系列之-pytest實現測試數據驅動
本篇文章則介紹如何使用Python進行數據驅動。這里以pytest測試框架為例,重點講解pytest參數化相關知識。(關于pytest的環境配置以及基礎使用不在本文的討論范圍)
pytest中使用標簽@pytest.mark.parametrize 實現參數化功能,在執行用例的時候該標簽迭代中的每組數據都會作為一個用例執行。
一組參數化數據
定義參數化數據,代碼如下:
- 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)
運行結果如下,三組數據在三條測試用例中運行,其中數據('AA', 'BB')運行失敗!

多組參數化數據
在一個測試類中,可以定義多組參數化數據(參數化數據個數不同,test_1二個,test_2三個),代碼如下:
- 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)
運行結果如下,二組數據分別在test_1和test_2中運行!

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

寫一個讀取excel類文件的方法,使用模塊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頁的數據
- return df.values.tolist()#數據返回為list
從excel中讀取數據,并賦值給變量進行參數化,代碼如下:
- @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)
運行結果如下,三組數據在三條測試用例中運行!

注意:excel中的首行,默認不會作為測試數據處理。