1. 程式人生 > >介面自動化 之 unittest+ddt+openpyxl 綜合

介面自動化 之 unittest+ddt+openpyxl 綜合

 

前面寫過python 之 unittest初探 和 python 之 unittest+ddt 兩篇文章。在之前的文章中,寫過可以再次優化。今天寫第三篇的目的,就是在原有基礎上,基於 openpyxl模組再次優化。在第二篇中,注意到測試資料與程式碼寫在一起,實在是難以維護操作,而我們平時書寫測試用例,記錄測試資料,通常會使用excel檔案或者csv檔案。因此,本篇主要使用openpyxl模組對xlsx檔案的操作,讀取或者寫入資料,做到測試資料與程式碼分離。這樣子測試用例也非常便於維護。 基於書中的原始碼,我做出了一些改動,可以做到在一定格式下,完全讀取excel檔案的測試資料。本次優化,需要先定義一個DoExcel類,在裡面封裝2個方法,一個是讀取測試資料,另一個是寫入資料。 廢話少說,直接上程式碼:

 1 #!/usr/bin/python3
 2 # -*- coding: utf-8 -*-
 3 # @Time     :2018/12/11 13:13
 4 # @Author   :Yosef
 5 # @Email    :[email protected]
 6 # @File:    :tryopenpyxl.py
 7 # @Software :PyCharm Community Edition
 8 import openpyxl
 9 class DoExcel():
10     def __init__(self, filename, sheetname):
11 self.filename = filename 12 self.sheetname = sheetname 13 14 ''' 15 讀取檔案中的所有測試資料: 16 ''' 17 def read_data(self): 18 wb = openpyxl.load_workbook(self.filename) 19 sh = wb[self.sheetname] 20 # print(wb.active) 21 22 col_max = sh.max_column
23 testdata_key=[] 24 for i in range(1,col_max+1): 25 testdata_key.append(sh.cell(1, i).value) 26 27 testdatas = [] 28 row_max = sh.max_row 29 for i in range(2, row_max+1): 30 testdata = {} 31 for j in range(1, row_max-1): 32 testdata[testdata_key[j-1]] = sh.cell(i, j).value 33 testdatas.append(testdata) 34 35 return testdatas 36 37 ''' 38 往檔案中寫入資料 39 往檔案中寫入資料需要三個引數,分別是row(行),col(列),以及value 40 ''' 41 def write_data(self,row,col,value): 42 wb = openpyxl.load_workbook(self.filename) 43 ws = wb[self.sheetname] 44 45 ws.cell(row,col).value = value 46 wb.save(self.filename) 47 48 if __name__ == "__main__": 49 testdatas = DoExcel("hello.xlsx","data").read_data() 50 # print(testdatas) 51 for item in testdatas: 52 print(item) 53 DoExcel("hello.xlsx","data").write_data(10,10,"Test")

這個類寫好之後,我們就可以在昨天的程式碼裡使用啦~在此之前,我們先看一下excel檔案內容:

然後,在之前的程式碼中稍作修改,將@data後面的具體測試資料換成我們讀取的引數,然後再試一下。

 1 import unittest
 2 from ddt import ddt, data
 3 import HTMLTestRunner
 4 import time
 5 from auto_test_interface.tryopenpyxl import DoExcel
 6 
 7 testdatas = DoExcel("hello.xlsx","data").read_data()
 8 
 9 @ddt # 代表這個測試類使用了資料驅動ddt
10 class TestCases(unittest.TestCase):
11 
12     def setUp(self):
13         print("*******************************")
14 
15     def tearDown(self):
16         print("\n")
17 
18     @data(*testdatas)
19     def test_testcases(self, value):
20         # print("這是一條測試用例case")
21         print(value)
22         try:
23 
24             print("test pass")
25         except Exception as e:
26             print("出錯啦,錯誤結果是%s" % e)
27             print("test failed")
28             raise e
29 
30 # if __name__ == "__main__":
31 #     unittest.main()
32 
33 suite = unittest.TestSuite()
34 loader = unittest.TestLoader()
35 suite.addTest(loader.loadTestsFromTestCase(TestCases))
36 
37 report_dir = "../Test report"
38 now = time.strftime("%Y-%m-%d %H-%M-%S")
39 reportname = report_dir + "/" + now + " Test report.html"
40 
41 with open(reportname, "wb+") as file:
42     runner = HTMLTestRunner.HTMLTestRunner(file, 2, title="Model test report",
43                                            description="Hello testers! This is the description of Model test"
44                                                        "report")
45     runner.run(suite)

執行程式碼之後,我們來看一下控制檯的輸出:

這是HTML的結果:

通過上圖可以看到,在excel中的資料都已被取出。如果需要具體操作某一條資料,只需要從字典裡取值就好了!這裡的程式碼都是為了方便閱讀寫在了一起,自己試的時候,記得按照專案結構來寫呀~如果有不足之處,歡迎各位大佬指正!