1.什么是PO模式
PO模式就是Page Object的缩写,即页面对象。PO模式的目的为页面对象与测试代码的分离,使得自动化测试代码可以快速构建。当自动化测试以页面为单位时,将页面中的控件抽取出来然后封装成对象,并定义每个控件的操作方法,那么当页面发生改变时修改测试代码将很方便。
2.PO模式
传统的PO模式,是将页面对象和测试代码分离,以页面为单位为每个页面创建一个页面对象。接下来我们以百度首页为例,首先需要创建百度主页页面对象文件,该文件用于封装百度主要页面对象以及操作页面对象的各类方法,代码如下所示:
# encoding = utf-8
from selenium.webdriver.common.by import By
from time import sleep
class Page(object):
"""基础类,继承页面对象类"""
login_url = "https://www.baidu.com"
"""初始化函数,定义timeout/driver/base_url"""
def __init__(self, driver, base_url=login_url):
self.base_url = base_url
self.driver = driver
self.timeout = 30
"""定义目标页面"""
def target_page(self):
return self.driver.current_url == self.base_url
"""定义打开网页的函数"""
def open(self):
url = self.base_url
self.driver.get(url)
print(self.driver.current_url)
"""定义获取元素基础方法"""
def find_element(self, *loc):
return self.driver.find_element(*loc)
class SearchPage(Page):
"""百度首页,页面对象类"""
url = '/'
input_loc = (By.NAME, "wd")
search_button_loc = (By.ID, "su")
"""每个页面封装对应方法"""
def input_search_string(self, search_string):
self.find_element(*self.input_loc).send_Keys(search_string) #输入要检索的字符串
def click_search_button(self):
self.find_element(*self.search_button_loc).click() #点击百度按钮
#定义检索字符串函数
def search_string(driver, string):
search_Page = SearchPage(driver)
search_Page.open()
search_Page.input_search_string(string)
sleep(3)
search_Page.click_search_button()
接下来,编写测试代码,代码如下所示:
from selenium import webdriver
from PageObject import Baidu_Main_Page
from time import sleep
import unittest
class Search_Page(unittest.TestSuite):
def setUp(self):
self.chrome_driver=webdriver.Chrome()
self.string ="dangjunquan"
def test_search_dangjunquan(self):
try:
"""调用封装好的search_string()"""
Baidu_Main_Page.search_string(self.chrome_driver,self.string)
sleep(3)
self.assertTrue("dangjunquan" in self.chrome_driver.page_source)
except AssertionError as e:
raise e
def tearDown(self):
self.chrome_driver.quit()
if __name__ == "__main__":
unittest.main()
3.执行测试结果
运行测试代码后,结果如下图所示:
C:\PO\venv\Scripts\python.exe C:/PO/TestScript/Test_Baidu_Main_Page.py
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
Process finished with exit code 0