简单UI自动化测试实例:实现定位方式数据与测试用例分离
一、读取存储在配置文件中的定位方式数据
object_map.py
"""
本实例实现了程序与数据分离,首先从UI对象库文件ui_project_map.ini 文件中取得Sogou首页中需要操作的页面元素的定位方式,
然后再object_map 类中取得该页面元素的实例对象,最后返回给测试用例方法中进行后续处理。这样做的好处是可以在一定条件下满足一部分不会编码的测试人员实施自动化测试。
"""
from selenium.webdriver.support.ui import WebDriverWait
import configparser
import os
class ObjectMap(object):
def __init__(self):
self.ui_object_path = os.path.dirname(os.path.abspath(__file__)) + "\\ui_project_map.ini"
print(self.ui_object_path)
def get_element_object(self, driver, web_site_name, element_name):
try:
cf = configparser.ConfigParser()
cf.read(self.ui_object_path)
locators = cf.get(web_site_name, element_name).split(">")
locator_method = locators[0]
locator_expression = locators[1]
print(locator_method,locator_expression)
#
element = WebDriverWait(driver,10).until(lambda x:x.find_element(locator_method,locator_expression))
except Exception as e:
raise e
else:
return element
二、测试用例:使用读取数据方法读取存储在配置文件中的定位方式数据
test_sogou.py
import traceback
import unittest
from selenium import webdriver
# from selenium.common.exceptions import WebDriverException
# from selenium.webdriver.chrome.service import Service
# from selenium.common.exceptions import NoSuchElementException
# from selenium.webdriver.common.by import By
# from selenium.webdriver.common.keys import Keys
import time
import os
from selenium_unittest.webdrivber_unittest.webdriver_hight.ui_test.object_map import ObjectMap
class TestSogou(unittest.TestCase):
def setUp(self):
self.obj_map = ObjectMap()
file_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
"../../driver/chromedriver/chromedriver.exe")
self.driver = webdriver.Chrome(executable_path=file_path)
self.driver.refresh()
self.driver.maximize_window()
url = "https://www.sogou.com"
self.driver.get(url)
def test_ui_sogou(self):
try:
search_box = self.obj_map.get_element_object(self.driver, "sogou", "search_box")
search_box.send_keys(u"Webdriver实战宝典")
time.sleep(3)
search_button = self.obj_map.get_element_object(self.driver, "sogou", "search_button")
search_button.click()
time.sleep(3)
self.assertTrue(u"吴晓华" in self.driver.page_source, "assert error")
except Exception:
print(traceback.print_exc())
def tearDown(self):
self.driver.refresh()
self.driver.quit()
if __name__ == '__main__':
unittest.main()
三、存储定位方式的配置文件
ui_project_map.ini 文件内容
[sogou]
search_box = id>query
search_button = id>stb