準備先利用之前整理的python自帶的unittest框架 整合excel 實現介面自動化測試功能 先看看excel表格設置: 下來是對excel獲取的代碼: 之後是unittest框架 利用迴圈執行所有用例 現在只要在excel里添加介面測試用例 運行腳本 即可 ...
準備先利用之前整理的python自帶的unittest框架
整合excel 實現介面自動化測試功能
先看看excel表格設置:
下來是對excel獲取的代碼:
1 #!/usr/bin/env python 2 # -*- coding: utf_8 -*- 3 4 import xlrd 5 import json 6 7 class Create_excel: 8 def open_excel(self,path): 9 workbook = xlrd.open_workbook(path) 10 table = workbook.sheets()[0] 11 return table 12 #獲取sheet 13 14 def get_nrows(self,table): 15 nrows = table.nrows 16 return nrows 17 #獲取行號 18 19 def testname(self,table,nrows): 20 TestName = [] 21 for i in range(1,nrows): 22 TestName.append(table.cell(i,0).value) 23 return TestName 24 #獲取用例name 25 26 def testdata(self,table,nrows): 27 TestData = [] 28 for i in range(1,nrows): 29 data = json.loads(table.cell(i,1).value) 30 TestData.append(data) 31 return TestData 32 #獲取data介面參數 33 34 def testurl(self,table,nrows): 35 TestUrl = [] 36 for i in range(1,nrows): 37 TestUrl.append(table.cell(i,2).value) 38 return TestUrl 39 #獲取介面測試url 40 41 def testpattern(self,table,nrows): 42 TestPattern = [] 43 for i in range(1,nrows): 44 TestPattern.append(table.cell(i,3).value) 45 return TestPattern 46 #獲取介面期望響應結果 47 48 def testreport(self,table,nrows): 49 TestReport = [] 50 for i in range(1,nrows): 51 TestReport.append(table.cell(i,4).value) 52 return TestReport 53 #獲取用例期望的運行結果 54 55 if __name__ == "__main__": 56 Create_excel()
之後是unittest框架
1 #!/usr/bin/env python 2 # -*- coding: utf_8 -*- 3 4 import requests 5 import re 6 import unittest 7 from myexcel import Create_excel 8 9 class Testapi(): 10 def testapi(self,url,data): 11 results = requests.post(url,data) 12 return results 13 14 class Testcase(unittest.TestCase): 15 def setUp(self): 16 print "介面測試開始" 17 18 def tearDown(self): 19 print "介面測試結束" 20 21 def test_post(self): 22 global report 23 api = Testapi() 24 excel = Create_excel() 25 testpath = "testcase.xls" 26 testtable = excel.open_excel(testpath) 27 testnrows = excel.get_nrows(testtable) 28 for i in range(0,testnrows-1): 29 testname = excel.testname(testtable,testnrows)[i] 30 testdata = excel.testdata(testtable,testnrows)[i] 31 testurl = excel.testurl(testtable,testnrows)[i] 32 testpattern = excel.testpattern(testtable,testnrows)[i] 33 testreport = excel.testreport(testtable,testnrows)[i] 34 testresults = api.testapi(testurl,testdata) 35 pattern = re.compile(testpattern) 36 match = pattern.search(testresults.url) 37 try: 38 if testresults.status_code == 200: 39 if match.group() == testpattern: 40 report = "pass" 41 else: 42 print "測試請求失敗" 43 except AttributeError: 44 report = "no" 45 if report == testreport: 46 print "用例名稱:",testname,"測試結果:測試通過" 47 else: 48 print "用例名稱:",testname,"測試結果:測試失敗" 49 50 if __name__ == "__main__": 51 unittest.main()
利用迴圈執行所有用例
現在只要在excel里添加介面測試用例
運行腳本 即可