Python&Selenium 数据驱动测试【unittest+ddt+xml】
一、摘要
本博文将介绍Python和Selenium做自动化测试时,基于unittest框架,借助ddt模块,使用xml文件作为测试输入。
二、xml文件
保存路径:D:\\Programs\\Python\\PythonUnittest\\TestData\\TestData.xml
文件名:TestData.xml
<?xml version = "1.0" encoding = "utf-8"?> <bookList type = "technology"> <book> <name>selenium xml datadriven</name> <author>davieyang</author> </book> <book> <name>selenium excel datadriven</name> <author>davieyang</author> </book> <book> <name>selenium ddt data list</name> <author>davieyang</author> </book> </bookList>
三、解析XML文件
文件路径:Util\ParseXMLUtil
文件名:ParseXMLUtil
# 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"])
四、测试脚本
文件可命名为:data_driven_by_xml.py
# encoding = utf-8 """ __title__ = '' __author__ = 'davieyang' __mtime__ = '2018/4/21' """ from selenium import webdriver import unittest import time import logging import traceback import ddt from Util.ParseXMLUtil import ParseXML from selenium.common.exceptions import NoSuchElementException # 初始化日志对象 logging.basicConfig( # 日志级别 level=logging.INFO, # 时间、代码所在文件名、代码行号、日志级别名字、日志信息 format='%(asctime)s %(filename)s[line: %(lineno)d] %(levelname)s %(message)s', # 打印日志的时间 datefmt='%a, %d %b %Y %H:%M:%S', # 日志文件存放的目录及日志文件名 filename='D:\\Programs\\Python\\PythonUnittest\\Reports\\TestResults.TestResults', # 打开日志的方式 filemode='w' ) # currentPath = os.path.dirname(os.path.abspath(__file__)) # dataFilePath = os.path.join(currentPath, "TestData.xml") dataFilePath = "E:\\数据驱动\\TestData.xml" print(dataFilePath) # 创建ParseXML类实例对象 xml = ParseXML(dataFilePath) @ddt.ddt class DataDrivenTestByXML(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome(executable_path=r"F:\automation\webdriver\chromedriver.exe") @ddt.data(* xml.getDataFromXml()) def test_dataDrivenByXML(self, data): testData, expectData = data["name"], data["author"] url = "http://www.baidu.com" self.driver.get(url) self.driver.maximize_window() self.driver.implicitly_wait(10) try: self.driver.find_element_by_id("kw").send_keys(testData) self.driver.find_element_by_id("su").click() time.sleep(3) self.assertTrue(expectData in self.driver.page_source) except NoSuchElementException as e: logging.error(u"查找的页面元素不存在,异常堆栈信息为:" + str(traceback.format_exc())) except AssertionError as e: logging.info(u"搜索 ‘%s’,期望 ‘%s’ ,失败" % (testData, expectData)) except Exception as e: logging.error(u"未知错误,错误信息:" + str(traceback.format_exc())) else: logging.info(u"搜索 ‘%s’,期望 ‘%s’ ,通过" % (testData, expectData)) def tearDown(self): self.driver.quit() if __name__ == "__main__": unittest.main()
test_dataDrivenByXML