讀取Excel測試用例結合pytest的簡單嘗試


這是我們寫的測試用例:

這里主要關注第七列,假設已經拿到了其它參數發送請求出去,根據響應內容獲取到響應消息體的retcode,與表中的code進行斷言判斷通過與否(比如0通過,2不通過)

以下是代碼實現:

 1 import pytest
 2 import xlrd
 3 import json
 4 
 5 
 6 lines = []  # 創建空表用來存Excel每一行內容
 7 worksheet = xlrd.open_workbook('../data/教管系統-測試用例V1.2.xls').sheet_by_index(2)
 8 rows = worksheet.nrows  # 獲取行數
 9 for i in range(1, rows):
10     line = worksheet.row_values(i)
11     lines.append(line)
12 
13 
14 @pytest.fixture(params=lines)  # pytest工廠函數,默認方法級別
15 def init_x(request):
16     return request.param  # 固定格式,每一次取出params的一個元素
17 
18 
19 class Test_x:
20     def test_x(self, init_x):
21         code = json.loads(init_x[6])  # 把第七列內容json格式的字符串轉成字典格式
22         code = code['code']  # 拿到code的值
23         assert code != 0  # 斷言是否通過

 或者使用參數化:

 1 import pytest
 2 import xlrd
 3 import json
 4 
 5 
 6 def get_data():
 7     lines = []
 8     worksheet = xlrd.open_workbook('../data/教管系統-測試用例V1.2.xls').sheet_by_index(2)
 9     rows = worksheet.nrows
10     for i in range(1, rows):
11         line = worksheet.row_values(i)
12         lines.append(line)
13     return lines
14 
15 
16 class Test_x:
17     @pytest.mark.parametrize("code", get_data())  # pytest參數化裝飾器,第一個參數寫自定義的參數名,第二個參數傳取到的數據
18     def test_x(self, code):  # 上面的參數名是什么,這里也要寫什么
19         retcode = json.loads(code[6])
20         retcode = retcode['code']
21         assert retcode != 0

 

 

運行結果:

共45個測試,顯示34個通過11個不通過,不通過的原因也能看到:0 != 0。

當然,實際的接口測試並不是規定0代表通過,2代表不通過,而是根據實際響應得到的retcode與code是否相等來判斷。

這里只是簡單的實踐一下,肯定有更好的實現方式。

等待你的評論。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM