Python&Selenium 关键字驱动测试框架之数据文件解析
摘要:在关键字驱动测试框架中,除了PO模式以及一些常规Action的封装外,一个很重要的内容就是读写EXCEL,在团队中如何让不会写代码的人也可以进行自动化测试? 我们可以将自动化测试用例按一定的规格写到EXCEL中去(如下图所示)

然后通过代码实现对具备这种规格的EXCEL进行解析,让你的代码获取EXCEL中的步骤,关键字,页面元素定位,操作方式,最后在写入执行结果,附上异常截图即可;团队中不会写代码的人居多,改改Excel执行也可以实现自动化测试
此处在初始化类的时候定义了两个颜色放进字典中,之后会当做参数传给写EXCEL的函数,当测试用例执行通过 用绿色字体标注pass,当执行失败的时候用红色字体标注failed
具体实现代码如下
# 用于实现读取Excel数据文件代码封装
# encoding = utf-8
"""
__project__ = 'KeyDri'
__author__ = 'davieyang'
__mtime__ = '2018/4/21'
"""
import openpyxl
from openpyxl.styles import Border, Side, Font
import time class ParseExcel(object): def __init__(self):
self.workBook = None
self.excelFile = None
self.font = Font(color=None)
self.RGBDict = {'red': 'FFFF3030', 'green': 'FF008B00'} def loadWorkBook(self, excelPathAndName):
# 将Excel加载到内存,并获取其workbook对象
try:
self.workBook = openpyxl.load_workbook(excelPathAndName)
except Exception as e:
raise e
self.excelFile = excelPathAndName
return self.workBook def getSheetByName(self, sheetName):
# 根据sheet名获取该sheet对象
try:
# sheet = self.workBook.get_sheet_by_name(sheetName)
sheet = self.workBook[sheetName]
return sheet
except Exception as e:
raise e def getSheetByIndex(self, sheetIndex):
# 根据sheet的索引号获取该sheet对象
try:
# sheetname = self.workBook.get_sheet_names()[sheetIndex]
sheetname = self.workBook.sheetnames[sheetIndex]
except Exception as e:
raise e
# sheet = self.workBook.get_sheet_by_name(sheetname)
sheet = self.workBook[sheetname]
return sheet def getRowsNumber(self, sheet):
# 获取sheet中有数据区域的结束行号
return sheet.max_row def getColsNumber(self, sheet):
# 获取sheet中有数据区域的结束列号
return sheet.max_column def getStartRowNumber(self, sheet):
# 获取sheet中有数据区域的开始的行号
return sheet.min_row def getStartColNumber(self, sheet):
# 获取sheet中有数据区域的开始的列号
return sheet.min_column def getRow(self, sheet, rowNo):
# 获取sheet中某一行,返回的是这一行所有数据内容组成的tuple
# 下标从1开始,sheet.rows[1]表示第一行
try:
# return sheet.rows[rowNo - 1] 因为sheet.rows是生成器类型,不能使用索引
# 转换成list之后再使用索引,list(sheet.rows)[2]这样就获取到第二行的tuple对象。
return list(sheet.rows)[rowNo - 1]
except Exception as e:
raise e def getCol(self, sheet, colNo):
# 获取sheet中某一列,返回的是这一列所有数据内容组成的tuple
# 下标从1开始,sheet.columns[1]表示第一列
try:
return list(sheet.columns)[colNo - 1]
except Exception as e:
raise e def getCellOfValue(self, sheet, coordinate = None, rowNo = None, colNo = None):
# 根据单元格所在的位置索引获取该单元格中的值,下标从1开始
# sheet.cell(row = 1, column = 1).value,表示excel中的第一行第一列的值
if coordinate is not None:
try:
return sheet.cell(coordinate=coordinate).value
except Exception as e:
raise e
elif coordinate is None and rowNo is not None and colNo is not None:
try:
return sheet.cell(row=rowNo, column=colNo).value
except Exception as e:
raise e
else:
raise Exception("Insufficient Coordinates of cell!") def getCellOfObject(self, sheet, coordinate = None, rowNo = None, colNo = None):
# 获取某个单元格对象,可以根据单元格所在的位置的数字索引,也可以直接根据Excel中单元格的编码及坐标
# 如getCellOfObject(sheet, coordinate='A1) or getCellOfObject(sheet, rowNo = 1, colNo = 2) if coordinate is not None:
try:
return sheet.cell(coordinate=coordinate)
except Exception as e:
raise e
elif coordinate is None and rowNo is not None and colNo is not None:
try:
return sheet.cell(row=rowNo, column=colNo)
except Exception as e:
raise e
else:
raise Exception("Insufficient Coordinates of cell!") def writeCell(self, sheet, content, coordinate = None, rowNo = None, colNo = None, style=None):
# 根据单元格在Excel中的编码坐标或者数字索引坐标向单元格中写入数据,下标从1开始
# 参数style表示字体的颜色的名字,如red,green
if coordinate is not None:
try:
sheet.cell(coordinate=coordinate).value = content
if style is not None:
sheet.cell(coordinate=coordinate).font = Font(color=self.RGBDict[style])
self.workBook.save(self.excelFile)
except Exception as e:
raise e
elif coordinate is None and rowNo is not None and colNo is not None:
try:
sheet.cell(row=rowNo, column=colNo).value = content
if style is not None:
sheet.cell(row=rowNo, column=colNo).font = Font(color=self.RGBDict[style])
self.workBook.save(self.excelFile)
except Exception as e:
raise e
else:
raise Exception("Insufficient Coordinates of cell!") def writeCellCurrentTime(self, sheet, coordinate = None, rowNo = None, colNo = None):
# 写入当前时间,下标从1开始
now = int(time.time()) # 显示为时间戳
timeArray = time.localtime(now)
currentTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
if coordinate is not None:
try:
sheet.cell(coordinate=coordinate).value = currentTime
self.workBook.save(self.excelFile)
except Exception as e:
raise e
elif coordinate is None and rowNo is not None and colNo is not None:
try:
sheet.cell(row=rowNo, column=colNo).value = currentTime
self.workBook.save(self.excelFile)
except Exception as e:
raise e if __name__ == "__main__":
from Configurations.VarConfig import dataFilePath163
pe = ParseExcel()
pe.loadWorkBook(dataFilePath163)
print("通过名称获取sheet对象名字:")
pe.getSheetByName(u"联系人")
print("通过Index序号获取sheet对象的名字")
pe.getSheetByIndex(0)
sheet = pe.getSheetByIndex(0)
print(type(sheet))
print(pe.getRowsNumber(sheet))
print(pe.getColsNumber(sheet))
cols = pe.getCol(sheet, 1)
for i in cols:
print(i.value)
# 获取第一行第一列单元格内容
print(pe.getCellOfValue(sheet, rowNo=1, colNo=1))
pe.writeCell(sheet, u'中国北京', rowNo=11, colNo=11, style='red')
pe.writeCellCurrentTime(sheet, rowNo=10, colNo=11)
那么我们的测试数据除了放在Excel中,还可以存储在XML里,然后关键字驱动框架中提供解析XML的API
# encoding = utf-8
"""
__title__ = ''
__author__ = 'davieyang'
__mtime__ = '2018/4/21'
"""
from xml.etree import ElementTree class ParseXML(object):
def __init__(self, xmlPath):
self.xmlPath = xmlPath def getRoot(self):
# 打开将要解析的XML文件
tree = ElementTree.parse(self.xmlPath)
# 获取XML文件的根节点对象,然后返回给调用者
return tree.getroot() def findNodeByName(self, parentNode, nodeName):
# 通过节点的名字获取节点对象
nodes = parentNode.findall(nodeName)
return nodes def getNodeofChildText(self, node):
# 获取节点node下所有子节点的节点名作为key,本节点作为value组成的字典对象
childrenTextDict = {i.tag: i.text for i in list(node.iter())[1:]}
# 上面代码等价于
'''
childrenTextDict = {}
for i in list(node.iter())[1:]:
fhildrenTextDict[i.tag] = i.text
'''
return childrenTextDict def getDataFromXml(self):
# 获取XML文档的根节点对象
root = self.getRoot()
# 获取根节点下所有名为book的节点对象
books = self.findNodeByName(root, "book")
dataList = []
# 遍历获取到的所有book节点对象
# 取得需要的测试数据
for book in books:
childrenText = self.getNodeofChildText(book)
dataList.append(childrenText)
return dataList if __name__ == "__main__":
xml = ParseXML(r"F:\seleniumWithPython\TestData\TestData.xml")
datas = xml.getDataFromXml()
for i in datas:
print(i["name"], i["author"])
Python&Selenium 关键字驱动测试框架之数据文件解析的更多相关文章
- Selenium关键字驱动测试框架Demo(Java版)
Selenium关键字驱动测试框架Demo(Java版)http://www.docin.com/p-803493675.html
- UI自动化测试框架之Selenium关键字驱动
一.原理及特点 1. 关键字驱动测试是数据驱动测试的一种改进类型 2. 主要关键字包括三类:被操作对象(Item).操作(Operation)和值(value),用面向对象形式可将其表现为Item.O ...
- UI自动化测试框架之Selenium关键字驱动 (转)
摘要 自动化测试框架demo,用关键字的形式将测试逻辑封装在数据文件中,测试工具解释这些关键字即可对其应用自动化 一.原理及特点 1. 关键字驱动测试是数据驱动测试的一种改进类型 2. 主要 ...
- 【转】UI自动化测试框架之Selenium关键字驱动
原网址:https://my.oschina.net/hellotest/blog/531932#comment-list 摘要: 自动化测试框架demo,用关键字的形式将测试逻辑封装在数据文件中,测 ...
- python之robotframework+ride测试框架
一.robotframework简介 Robot Framework是一款python编写的功能自动化测试框架.具备良好的可扩展性,支持关键字驱动,可以同时测试多种类型的客户端或者接口,可以进行分布式 ...
- 自动化测试架构设计 &&自动化持续集成测试任务实战[线性测试、模块驱动测试、数据驱动测试、关键字驱动测试]
1 为什么设计自动化测试架构 1.1 企业现状分析 压力大:产品需求不明确,上线时间确定,压力山大. 混乱:未立项,开发时间已过半,前期无控制,后期无保障. 疲于应付:开发人员交付的文件质量差,测试跟 ...
- Selenium WebDriver 数据驱动测试框架
Selenium WebDriver 数据驱动测试框架,以QQ邮箱添加联系人为示例,测试框架结构如下图,详细内容请阅读吴晓华编著<Selenium WebDiver 实战宝典>: Obje ...
- Python+selenium+unittest+HTMLTestReportCN单元测试框架分享
分享一个比较基础的,系统性的知识点.Python+selenium+unittest+HTMLTestReportCN单元测试框架分享 Unittest简介 unittest是Python语言的单元测 ...
- 简单学习一下ibd数据文件解析
来源:原创投稿 作者:花家舍 简介:数据库技术爱好者. GreatSQL社区原创内容未经授权不得随意使用,转载请联系小编并注明来源. 简单学习一下数据文件解析 这是尝试使用Golang语言简单解析My ...
随机推荐
- 记录编译<Separable Subsurface Scattering demo>工程遇到的问题
1. Separable Subsurface Scattering demo 可以从 https://github.com/iryoku/separable-sss 下载下来,但是默认的sln 是 ...
- [OpenBenchMarking] AMD CPU 的性能简单对比
来源: https://openbenchmarking.org/result/1710193-AL-EPYC7351P64 1. 2. 3. 4.
- superset部署
superset功能概述: 丰富的数据可视化集 易于使用的界面,用于探索和可视化数据 创建和共享仪表板 与主要身份验证提供程序集成的企业级身份验证(通过Flask AppBuilder进行数据库,Op ...
- 【51nod】2606 Secondary Substring
51nod 2606 Secondary Substring 感觉有趣的一道计数,实际上不难 感觉好久没用这种技巧了,导致我还在错误的道路上想了好久... 观察题目性质,可以发现就是左边第一次出现两遍 ...
- fiddler笔记:Composer选项卡
1.Composer选项卡介绍 Composer选项卡功能是可以手动构建和发送HTTP.HTTPS和FTP请求. 支持将Web Session列表中选中的Session拖入Composer选项卡,然后 ...
- 3.解决git不可用问题
升级gityum -y update git 配置阿里云yum源yum -y update nssyum -y update nss curl libcurl
- 【Trie】Nikitosh 和异或
[参考博客]: LOJ#10051」「一本通 2.3 例 3」Nikitosh 和异或(Trie [题目链接]: https://loj.ac/problem/10051 [题意]: 找出两个不相交区 ...
- Prometheus Operator 的安装
Prometheus Operator 的安装 接下来我们用自定义的方式来对 Kubernetes 集群进行监控,但是还是有一些缺陷,比如 Prometheus.AlertManager 这些组件服务 ...
- 关于FSM的C语言实现与详解
最近一个项目有一个需求,考量了一下决定使用状态机,实现完需求以后,不得不感慨,状态机在处理逻辑上面实现起来很有优势,也便于管理. 在这里分享一下我所修改的状态机实现.改动的地方不多,参考了<C语 ...
- linux - 卸载python
2019年10月15日12:05:42 [root@spider1 bin]# rpm -qa|grep python|xargs rpm -ev --allmatches --nodeps ##强制 ...