接口自动化 之 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中的数据都已被取出。如果需要具体操作某一条数据,只需要从字典里取值就好了!这里的代码都是为了方便阅读写在了一起,自己试的时候,记得按照项目结构来写呀~如果有不足之处,欢迎各位大佬指正!

猜你喜欢

转载自www.cnblogs.com/wlyhy/p/10112108.html