能够使用配置文件存储被测试页面上页面元素的定位方式和定位表达式,做到定位数据和程序的分离。
1.页面元素定位表达式配置文件,“.ini”文件,可用text文本编辑保存后直接修改文件后缀
[sogou] searchBox=id>query searchButton=id>stb
2.ObjectMap工具类文件,供测试程序调用
#!usr/bin/env python #-*- coding:utf-8 -*- """ @author: sleeping_cat @Contact : zwy24zwy@163.com """ from selenium.webdriver.support.ui import WebDriverWait import configparser#在python 3 中ConfigParser模块名已更名为configparser import os class ObjectMap(object): def __init__(self): self.uiObjMapPath = os.path.dirname(os.path.abspath(__file__))+"\\UiObjectMap.ini" print(self.uiObjMapPath) def getElementObject(self,driver,webSiteName,elementName): try: cf = configparser.ConfigParser() cf.read(self.uiObjMapPath) locators = cf.get(webSiteName,elementName).split(">") locatorMethod = locators[0] locatprExpression = locators[1] print(locatorMethod,locatprExpression) element = WebDriverWait(driver,10). until(lambda x: x.find_element(locatorMethod,locatprExpression)) except Exception as e: raise e else: return element
3.调用ObjectMap工具类实现测试逻辑
#!usr/bin/env python #-*- coding:utf-8 -*- """ @author: sleeping_cat @Contact : zwy24zwy@163.com """ from selenium import webdriver import unittest,time,traceback from ObjectMap import ObjectMap class TestSoGouSearch(unittest.TestCase): def setUp(self): self.obj = ObjectMap() self.driver = webdriver.Firefox() def testSoGouSearch(self): url = ‘http://www.sogou.com‘ self.driver.get(url) try: searchBox = self.obj.getElementObject(self.driver,‘sogou‘,‘searchBox‘) searchBox.send_keys(‘WebDriver实战宝典‘) searchButton = self.obj.getElementObject(self.driver,‘sogou‘,‘searchButton‘) searchButton.click() time.sleep(3) self.assertTrue(‘吴晓华‘ in self.driver.page_source,‘assert error!‘) except Exception as e: print(traceback.print_exc()) def tearDown(self): self.driver.quit() if __name__ == ‘__main__‘: unittest.main()
说明:
实现了程序与数据分离,首先从UI对象库文件“xxx.ini”文件中取得需要操作的页面元素的定位方式,然后再ObjectMap类中取得该页面元素的实例对象,最后返回给测试用例方法中进行后续处理。