unittest(3):openpyxl结合excel练习

Excel用例管理

在项目下,新建一个文件夹:data,文件夹下新建一个cases.xlsx文件,用来存放测试用例。

 

 以下,是一个简单的登录测试用例设计模板

 

 

 

 

 可以根据该表格生成实际结果,并将测试结果写入(Pass、Fail)表格。
既然有了用例模板,我们就开始从用openpyxl模块对excel读写数据。如下,在common文件夹下,新建excel_handle.py,用于封装操作excel的类。

添加异常类来控制异常

 

 excel_handle.py

import openpyxl
import os
from common.Exception_handle import excel_Exception
class ExcelHandler(object):
def __init__(self,wbname,sheetname):
self.wbname=wbname
self.sheetname=sheetname
def open_Excel(self):
'''
openpyxl.load_workbook获取excel
再通过列表的形式获得sheet页
:return:
'''
wb=openpyxl.load_workbook(self.wbname)
sh=wb[self.sheetname]
return sh
def get_header(self):
'''
行级元素再sheet页里也是列表存在
调用同一个类的方法也是使用self
'''
sh=self.open_Excel()
head_data=[]
for i in sh[1]:
head_data.append(i.value)
return head_data
def get_data(self):
'''
sh.rows获取所有行数据
data_list所有数据列表
raw_data单行数据列表
     value获取每一个单元格的数据
:return:
'''
sh=self.open_Excel()
rows=list(sh.rows)
head_data=self.get_header()
data_list=[]
for row in rows[1:]:
raw_data=[]
for cell in row:
raw_data.append(cell.value)
dict_zip=dict(zip(head_data,raw_data))
data_list.append(dict_zip)
return data_list
if __name__ == '__main__':
try:
osPath = os.path.join(os.path.dirname(os.path.dirname(__file__)), r'data/case1.xlsx')
if os.path.exists(osPath):
Ex = ExcelHandler(osPath, 'Second')
print(Ex.get_data())
else:
raise excel_Exception(osPath)
except excel_Exception as e:
print('发现错误')
finally:
print('结束')

Exception_handle.py

class excel_Exception(Exception):
def __init__(self,excel):
self.excel=excel
print('{0}不存在'.format(self.excel))
posted @ 2021-07-10 15:21  Tester-**  阅读(65)  评论(0编辑  收藏  举报