I. Summary
This blog will introduce Python and Selenium doing automated testing, based unittest framework, with ddt module, use the xml input file as a test.
Two, xml file
Save path: D: \\ Programs \\ Python \\ PythonUnittest \\ TestData \\ TestData.xml
File name: 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>
Third, parsing XML file
File Path: Util \ ParseXMLUtil
File name: ParseXMLUtil
Encoding = UTF. 8-# "" " __title__ = '' __author__ = 'davieyang' __mtime__ = '2018/4/21' " "" from the ElementTree xml.etree Import class parseXML (Object): DEF the __init __ (Self, XMLPath): = XMLPath self.xmlPath DEF getRoot (Self): # open XML file to be parsed Tree = ElementTree.parse (self.xmlPath) # get the root object of an XML file, and then returned to the caller return a shortcut for tree.getroot () DEF findNodeByName (Self, parentNode, nodeName): # get the name of a node by node object nodes = parentNode.findall (nodeName) return nodes DEF getNodeofChildText (Self, the node): # Get the name of the node for all child nodes under the node as the node key, the composition of the present node as a value dictionary object for book in books: = {i.tag childrenTextDict: i.text for I in List (node.iter ()) [. 1:]} # is equivalent to the code above '' ' childrenTextDict = {} for I in List (node.iter ()) [1:]: fhildrenTextDict [i.tag] = i.text '' ' return childrenTextDict DEF getDataFromXml (Self): # get the root node of the XML document objects root = self.getRoot () # get at the root of all named book the node objects Books = self.findNodeByName (root, "book") dataList = [] # traversed to get all the book node object # achieve the required test data 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"])
Fourth, the test script
Files can be named: data_driven_by_xml.py
Encoding = UTF. 8-# "" " __title__ = '' __author__ = 'davieyang' __mtime__ = '2018/4/21' " "" from the webdriver Selenium Import Import the unittest Import Time Import the logging Import the traceback Import DDT from Util.ParseXMLUtil Import parseXML Import NoSuchElementException selenium.common.exceptions from # initialize the log object logging.basicConfig ( # log level level = logging.info, # time code where the file name, line number, name of the log level, the log information format = '% (asctime) s% (filename) s [line :% (lineno) d]% (levelname) s% (message) s ', the time # printing log datefmt ='% a,% d % b% Y% H:% M: % S ', # Log files are stored in the directory and log file name 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’ ,Failure "% (testData, expectData)) Exception AS E the except: logging.error (u "Unknown error, an error message:" + STR (traceback.format_exc ())) the else: logging.info (U "Search '% s', expected '% s', through the"% (testData, expectData )) DEF tearDown (Self): self.driver.quit () IF __name__ == "__main__": unittest.main ()
test_dataDrivenByXML