UI对象库-定位元素与程序分离

释放双眼,带上耳机,听听看~!

1.前言

  这几天有人问我,UI自动化测试中使用到的页面定位元素应该存放在哪里比较合适?我想说的是如果你使用的是PO设计模式设计测试用例的话,可以把定位元素存在每一个page页面,一个page存放对应的TestCase的页面元素,当页面变动的时候方便修改。还有一种就是存放在配置文件下,这样对于不懂得自动化测试的人员也可以配置。那么下面我看就来看一下如何存放到配置文件中?如何来读取并定位?

2.目录结构

UI对象库-定位元素与程序分离

测试地址:http://www.sogou.com

测试步骤:1.打开网址2.搜索框输入python3.点击搜索按钮4.判断python是否包含在页面源码中

文件说明:WebElement.ini 存放定位元素。GetElement.py用来读取配置文件并查找页面元素。SouGouTc.py用来编写测试用例

3.实例代码

WebElement.ini

[sogou]
queryBox=id:query
queryBtn=id:stb

GetElement.py

 1 from selenium.webdriver.support.ui import WebDriverWait
 2 import configparser
 3 import os
 4 from selenium import webdriver
 5 class getElement():
 6     \'\'\'
 7     从配置文件中来获取定位信息
 8     \'\'\'
 9     def __init__(self):
10         self.elementIni = os.path.dirname(os.path.abspath(__file__))\\
11                           +r\'\\WebElement.ini\' # 配置文件所在目录
12     def getElement(self, driver, sogouSection, sogouOption):
13         try:
14             f = configparser.ConfigParser()
15             f.read(self.elementIni) # 读配置文件内容到内存中
16             locators = f.get(sogouSection, sogouOption).split(\':\')
17             # 获取定位方式
18             locaMethod = locators[0]
19             # 获取定位表达式
20             locaExpression = locators[1]
21             # 通过显示等待的方式获取页面的元素
22             element = WebDriverWait(driver,5).until(lambda x : x.find_element(locaMethod, locaExpression))
23         except Exception as e:
24             raise e
25         else:
26             return element
27 
28 if __name__ == \'__main__\':
29     ele = getElement()
30     print(ele.elementIni)
31     driver = webdriver.Firefox()
32     driver.get(\'http://www.sogou.com\')
33     element = ele.getElement(driver, \'sougou\', \'queryBox\')
34     element.send_keys(\'python\')

SouGouTc.py

 1 from selenium import webdriver
 2 import unittest
 3 import time
 4 from programDataSeparate.GetElement import getElement
 5 class sogouTc(unittest.TestCase):
 6 
 7     def setUp(self):
 8         self.obj = getElement()
 9         self.driver = webdriver.Firefox()
10         self.driver.get(\'http://www.sogou.com\')
11     def testSoGou(self):
12         elementQuery = self.obj.getElement(self.driver, \'sogou\', \'queryBox\') # 搜索框
13         elementQuery.send_keys(\'python\')
14         elementBtn = self.obj.getElement(self.driver, \'sogou\', \'queryBtn\') # 搜索按钮
15         elementBtn.click()
16         time.sleep(2)
17         self.assertTrue(\'python\' in self.driver.page_source) # 断言
18     def tearDown(self):
19         self.driver.quit()
20 
21 if __name__ == \'__main__\':
22     unittest.main()

总结

  本实例实现了程序与数据的分离,首先从UI对象库文件WebElement.ini中取得sogou首页中需要操作的页面元素的定位方式和定位表达式,然后在GetElement.py中取得该页面元素的实例对象,最后返回给测试用例方法中进行后续处理,这样做的好处是即使不懂得测试的人员也可以配置用例。

给TA打赏
共{{data.count}}人
人已打赏
站长资讯

大整数相乘 分治法 和 循环暴力法

2020-11-9 3:44:41

站长资讯

Docker最全教程之使用Docker搭建Java开发环境(十七)

2020-11-9 3:44:43

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索