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 ...
随机推荐
- prometheus 监控 redis + rabbitmq
1.安装部署 1.1 wget https://github.com/oliver006/redis_exporter/releases/download/v0.15.0/redis_exporter ...
- Gradle DSL Walle渠道包后安装启动APP
DSL(Domain-Specific Language) Gradle 是一个编译打包工具,但实际上它也是一个编程框架. Task 是 Gradle 中的一种数据类型,它代表了一些要执行或者要干的工 ...
- fcntl和flock两个系统调用的区别
总的来说,flock函数只能锁定整个文件,无法锁定文件的某一区域.而fcntl可以利用struct flock结构体,来实现文件里部分区域锁定的操作. 附:fcntl(文件描述词操作) 相关函数 op ...
- Nginx05---负载均衡 upsteam
参考 https://www.cnblogs.com/linjiqin/p/5494783.html
- Python 中 参数* 和 **
举个例子就知道了 class test(): def __init__(self, *a, **b): print(a) print(b) print(b.get('test')) tester = ...
- 新拉的项目在idea中启动时报如下错误:org.apache.catalina.core.ContainerBase.addChildInternal ContainerBase.addChild: start:
今天真的是很苦恼,之前启动项目没有任何问题,今天突然启动时给我报了如下一个错误. 详细报错信息: org.apache.catalina.core.ContainerBase.addChildInte ...
- Kubernetes---Pod phase
⒈Pod phase Pod的status字段是一个PodStatus对象,PodStatus中有一个 phase字段. Pod的相位(phase)是Pod 在其生命周期中的简单宏观概述.该阶段并不是 ...
- 基础python规范
一.注释 合理的代码注释应该占源代码的 1/3 左右,Python 语言允许在任何地方插入空字符或注释,但不能插入到标识符和字符串中间. 在 Python 中,通常包括 3 种类型的注 ...
- 【AC自动机】玄武密码
[题目链接] https://loj.ac/problem/10058 [题意] 对于每一段文字,其前缀在母串上的最大匹配长度是多少呢 [参考别人的题解] https://www.luogu.org/ ...
- hdu 2610 2611 dfs的判重技巧
对于全排列枚举的数列的判重技巧 1:如果查找的是第一个元素 那么 从0开始到当前的位置看有没有出现过这个元素 出现过就pass 2: 如果查找的不是第一个元素 那么 从查找的子序列当前位置的前一个元素 ...