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"])

学习安排上

如果你不想再体验一次学习时找不到资料,没人解答问题,坚持几天便放弃的感受的话,在这里我给大家分享一些自动化测试的学习资源,希望能给你前进的路上带来帮助。

在这里插入图片描述

视频文档获取方式:

这份文档和视频资料,对于想从事【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴我走过了最艰难的路程,希望也能帮助到你!以上均可以分享,点下方小卡片进群即可自行领取

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值