各位大佬好,我是来自python自动化13期的夜雨声烦。前面写过python 之 unittest初探(http://www.lemfix.com/topics/46)和 python 之 unittest+ddt(http://www.lemfix.com/topics/50)两篇文章。在之前的文章中,写过可以再次优化。今天写第三篇的目的,就是在原有基础上,基于 openpyxl模块再次优化。在第二篇中,注意到测试数据与代码写在一起,实在是难以维护操作,而我们平时书写测试用例,记录测试数据,通常会使用excel文件或者csv文件。因此,本篇主要使用openpyxl模块对xlsx文件的操作,读取或者写入数据,做到测试数据与代码分离。这样子测试用例也非常便于维护。在此之前,感谢柠檬班的接口自动化测试(python版)书籍给我提供的思路。
基于书中的源码,我做出了一些改动,可以做到在一定格式下,完全读取excel文件的测试数据。本次优化,需要先定义一个DoExcel类,在里面封装2个方法,一个是读取测试数据,另一个是写入数据。
废话少说,直接上代码:
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time :2018/12/11 13:13 # @Author :Yosef # @Email :wurz529@foxmail.com # @File: :tryopenpyxl.py # @Software :PyCharm Community Edition import openpyxl class DoExcel(): def __init__(self, filename, sheetname): self.filename = filename self.sheetname = sheetname ''' 读取文件中的所有测试数据: ''' def read_data(self): wb = openpyxl.load_workbook(self.filename) sh = wb[self.sheetname] # print(wb.active) col_max = sh.max_column testdata_key=[] for i in range(1,col_max+1): testdata_key.append(sh.cell(1, i).value) testdatas = [] row_max = sh.max_row for i in range(2, row_max+1): testdata = {} for j in range(1, col_max + 1): testdata[testdata_key[j-1]] = sh.cell(i, j).value testdatas.append(testdata) return testdatas ''' 往文件中写入数据 往文件中写入数据需要三个参数,分别是row(行),col(列),以及value ''' def write_data(self,row,col,value): wb = openpyxl.load_workbook(self.filename) ws = wb[self.sheetname] ws.cell(row,col).value = value wb.save(self.filename) if __name__ == "__main__": testdatas = DoExcel("hello.xlsx","data").read_data() # print(testdatas) for item in testdatas: print(item) DoExcel("hello.xlsx","data").write_data(10,10,"Test")
这个类写好之后,我们就可以在昨天的代码里使用啦~在此之前,我们先看一下excel文件内容:
然后,在之前的代码中稍作修改,将@data后面的具体测试数据换成我们读取的参数,然后再试一下。
import unittest from ddt import ddt, data import HTMLTestRunner import time from auto_test_interface.tryopenpyxl import DoExcel testdatas = DoExcel("hello.xlsx","data").read_data() @ddt # 代表这个测试类使用了数据驱动ddt class TestCases(unittest.TestCase): def setUp(self): print("*******************************") def tearDown(self): print("\n") @data(*testdatas) def test_testcases(self, value): # print("这是一条测试用例case") print(value) try: print("test pass") except Exception as e: print("出错啦,错误结果是%s" % e) print("test failed") raise e # if __name__ == "__main__": # unittest.main() suite = unittest.TestSuite() loader = unittest.TestLoader() suite.addTest(loader.loadTestsFromTestCase(TestCases)) report_dir = "../Test report" now = time.strftime("%Y-%m-%d %H-%M-%S") reportname = report_dir + "/" + now + " Test report.html" with open(reportname, "wb+") as file: runner = HTMLTestRunner.HTMLTestRunner(file, 2, title="Model test report", description="Hello testers! This is the description of Model test" "report") runner.run(suite)
运行代码之后,我们来看一下控制台的输出:
这是HTML的结果:
通过上图可以看到,在excel中的数据都已被取出。如果需要具体操作某一条数据,只需要从字典里取值就好了!这里的代码都是为了方便阅读写在了一起,自己试的时候,记得按照项目结构来写呀~如果有不足之处,欢迎各位大佬指正!
欢迎来到testingpai.com!
注册 关于