selenium自动化设计框架之 page object设计模式介绍
pageobject设计思想出自于马丁·福勒(Martin Flower,对,没错,就是软件教父)官网的一篇文章,官网连接:https://martinfowler.com/bliki/PageObject.html
还有一篇针对官网文章的中文翻译版:http://huangbowen.net/blog/2013/09/17/page-object
所以,如果你的英文不是很好,不妨看下中文版的,文章讲解的非常详细
PageObject 简介
在为 UI 页面写测试用例时(比如 Web 页面,移动端页面),测试用例会存在大量元素和操作细节。如何面对当 UI 变化时,测试用例也要跟着变化这个问题?PageObject 设计模式闪亮登场(由 IT 大佬 Martin Flower 提出)。
使用 UI 自动化测试工具时(Selenium、Appium 等),如果无统一模式进行规范,随着用例的增多会变得难以维护,而 PageObject 让自动化脚本井井有序,将 page 单独维护并封装细节,可以使 testcase 更稳健,不需要大改动。
PageObject 使用
具体做法:把元素信息和操作细节封装到 Page 类中,在测试用例上调用 Page 对象(PageObject),比如存在一个功能“选取相册标题”,需要为之建立函数selectAblumWithTitle(),函数内部是操作细节findElementsWithClass('album')等:
以选“取相册标题”举例,伪代码如下:
selectAblumWithTitle() {
#选取相册
findElementsWithClass('album')
#选取相册标题
findElementsWithClass('title-field')
#返回标题内容
return getText()
}
PageObject 的主要原则是提供一个简单接口 (或者函数,比如上述的 selectAblumWithTitle ),让调用者在页面上可以做任何操作,点击页面元素,在输入框输入内容等。因此,如果要访问一个文本字段,Page Object 应该有获取和返回字符串的方法。Page Object 应该封装对数据的操作细节,比如查找元素和点击元素。当页面元素改动时,应该只改变 Page 类中的内容,不需要改变调用它的地方。
不要为每个 UI 页面都创建一个 page 类,应该只为页面中重要的元素创建 page 类。比如,一个页面显示多个相册,应该创建一个相册列表 page object,它包含许多相册 page object。如果某些复杂 UI 的层次结构只是用来组织 UI,那么它就不应该出现在 page object 中。page object 的目的是通过给页面建模,从而对应用程序的使用者变得有意义:
如果你想导航到另一个页面,初始 page 对象应当 return 另一个 page 对象,比如点击注册,进入注册页面,在代码中就应该 return Register()。如果想获取页面信息,可以 return 基本类型(字符串、日期)。
建议不要在 page object 中放断言。应该去测 page object,而不是让 page object 自己测自己,page object 的责任是提供页面的状态信息。这里仅用 HTML 描述 Page Object,这种模式还可以用来隐藏 Java swing UI 细节,它可用于所有 UI 框架。
PageObject 六大原则
Selenium 针对 PageObject 的核心思想凝聚出了六大原则,掌握六大原则精髓,才可以进行 PageObject 最佳实践演练:
- 公共方法代表页面提供的服务
- 不要暴露页面细节
- 不要把断言和操作细节混用
- 方法可以 return 到新打开的页面
- 不要把整页内容都放到PO 中
- 相同的行为会产生不同的结果,可以封装不同结果
下面,对上述六大原则进行更详细的实操解释:
原则一:要封装页面中的功能(或者服务),比如点击页面中的元素,可以进入到新的页面,于是,可以为这个服务封装方法“进入新页面”。
原则二:封装细节,对外只提供方法名(或者接口)。
原则三:封装的操作细节中不要使用断言,把断言放到单独的模块中,比如 testcase。
原则四:点击一个按钮会开启新的页面,可以用 return 方法表示跳转,比如return MainPage()表示跳转到新的PO:MainPage。
原则五:只为页面中重要的元素进行 PO 设计,舍弃不重要的内容。
原则六:一个动作可能产生不同结果,比如点击按钮后,可能点击成功,也可能点击失败,为两种结果
基于钉钉打卡的 PO 实战案例
用 Page Object 原则为页面建模,这里涉及三个页面:登录页,首页,工作台页面,考勤打卡页。在代码中创建对应的三个类LoginPage,MainPage,WorkBenchPage,AttendancePage,(本次演示由于涉及功能点较少,所需功能都封装在了MainPage中)
实战代码
目录结构
BasePage 是所有 page object 的父类,它为子类提供公共的方法,比如下面的 BasePage 提供初始化 driver 和退出 driver,代码中在 base_page 模块的 BasePage 类中使用 init 初始方法进行初始化操作,包括 driver 的复用,driver 的赋值,全局等待的设置(隐式等待)等等:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:chenshifeng
@file:base_page.py
@time:2020/11/19
@功能:实现钉钉自动打卡
"""
import logging
import os
import time
import yaml
from appium.webdriver import WebElement
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
file_name = 'case_' + time.strftime("%Y_%m_%d", time.localtime()) + '.log'
home_dir = (os.path.dirname(os.path.dirname(os.path.abspath(file))))
log_file = os.path.join(home_dir, 'log', file_name)
class BasePage:
root_logger = logging.getLogger()
print(f"root_logger.handlers:{root_logger.handlers}")
for h in root_logger.handlers[:]:
root_logger.removeHandler(h)
logging.basicConfig(format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s',
level=logging.INFO, filename=log_file, filemode='a')
<span class="hljs-comment"># logging.StreamHandler(sys.stderr).setLevel(logging.INFO)</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, driver: WebDriver = <span class="hljs-literal">None</span></span>):</span>
self.driver = driver
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">find</span>(<span class="hljs-params">self, by, locator=<span class="hljs-literal">None</span>, timeout=<span class="hljs-number">20</span></span>) -> WebElement:</span>
<span class="hljs-string">'''
查找元素
:param by:
:param locator:
:return:
'''</span>
logging.info(<span class="hljs-string">f'find.by:<span class="hljs-subst">{by}</span>'</span>)
logging.info(<span class="hljs-string">f'find.locator:<span class="hljs-subst">{locator}</span>'</span>)
<span class="hljs-keyword">if</span> locator <span class="hljs-keyword">is</span> <span class="hljs-literal">None</span>:
result = WebDriverWait(self.driver, timeout).until(expected_conditions.element_to_be_clickable(*by))
<span class="hljs-keyword">else</span>:
result = WebDriverWait(self.driver, timeout).until(
expected_conditions.element_to_be_clickable((by, locator)))
logging.info(<span class="hljs-string">f'查找结果:<span class="hljs-subst">{result}</span>'</span>)
<span class="hljs-keyword">return</span> result
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">parse_yaml</span>(<span class="hljs-params">self, path, func_name</span>):</span>
logging.info(<span class="hljs-string">f'parse_yaml.path:<span class="hljs-subst">{path}</span>'</span>)
logging.info(<span class="hljs-string">f'parse_yaml.func_name:<span class="hljs-subst">{func_name}</span>'</span>)
<span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(path, encoding=<span class="hljs-string">'UTF-8'</span>) <span class="hljs-keyword">as</span> f:
datas = yaml.safe_load(f)
self.parse(datas[func_name])
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">parse</span>(<span class="hljs-params">self, steps</span>):</span>
<span class="hljs-keyword">for</span> step <span class="hljs-keyword">in</span> steps:
<span class="hljs-keyword">if</span> <span class="hljs-string">'clear'</span> <span class="hljs-keyword">in</span> step[<span class="hljs-string">'action'</span>]:
self.find(step[<span class="hljs-string">'by'</span>], step[<span class="hljs-string">'loactor'</span>]).clear()
<span class="hljs-keyword">if</span> <span class="hljs-string">'click'</span> <span class="hljs-keyword">in</span> step[<span class="hljs-string">'action'</span>]:
self.find(step[<span class="hljs-string">'by'</span>], step[<span class="hljs-string">'loactor'</span>]).click()
<span class="hljs-keyword">if</span> <span class="hljs-string">'send_keys'</span> <span class="hljs-keyword">in</span> step[<span class="hljs-string">'action'</span>]:
self.find(step[<span class="hljs-string">'by'</span>], step[<span class="hljs-string">'loactor'</span>]).send_keys(step[<span class="hljs-string">'context'</span>])
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_pagesource</span>(<span class="hljs-params">self</span>):</span>
<span class="hljs-keyword">return</span> self.driver.page_source
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_screenshot</span>(<span class="hljs-params">self, path</span>):</span>
<span class="hljs-keyword">return</span> self.driver.save_screenshot(path)
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">assert_result</span>(<span class="hljs-params">self, element, timeout=<span class="hljs-number">20</span></span>):</span>
result = WebDriverWait(self.driver, timeout).until(<span class="hljs-keyword">lambda</span> x: element <span class="hljs-keyword">in</span> x.page_source) <span class="hljs-comment"># 解决手机卡顿造成的误判</span>
logging.info(<span class="hljs-string">f'断言结果:<span class="hljs-subst">{result}</span>'</span>)
<span class="hljs-keyword">return</span> result
由于钉钉是移动端的APP,所以我单独写了个APP类,包含了登录,停止,重启,关闭APP等功能
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:chenshifeng
@file:app.py
@time:2020/11/19
app.py 模块,存放app相关的一些操作。
比如 启动应用,重启应用,停止应用,登录App,进入到首页
"""
import os
import yaml
from appium import webdriver
from dingding.page.base_page import BasePage
from dingding.page.main_page import MainPage
home_dir = (os.path.dirname(os.path.dirname(os.path.abspath(file))))
appconfig_file = os.path.join(home_dir,'config','appconfig.yml')
with open(appconfig_file,encoding='UTF-8') as f:
datas = yaml.safe_load(f)
desired_caps = datas['desired_caps']
ip = datas['ip']
class APP(BasePage):
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">start</span>(<span class="hljs-params">self</span>):</span>
<span class="hljs-keyword">if</span> self.driver <span class="hljs-keyword">is</span> <span class="hljs-literal">None</span>:
self.driver = webdriver.Remote(<span class="hljs-string">f'http://<span class="hljs-subst">{ip}</span>/wd/hub'</span>, desired_caps)
self.driver.implicitly_wait(<span class="hljs-number">5</span>)
<span class="hljs-keyword">else</span>:
self.driver.launch_app()
<span class="hljs-keyword">return</span> self
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">login</span>(<span class="hljs-params">self</span>):</span>
MainPage(self.driver).login()
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">restart</span>(<span class="hljs-params">self</span>):</span>
<span class="hljs-keyword">pass</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">stop</span>(<span class="hljs-params">self</span>):</span>
<span class="hljs-keyword">pass</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">close</span>(<span class="hljs-params">self</span>):</span>
<span class="hljs-keyword">pass</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">goto_main_page</span>(<span class="hljs-params">self</span>):</span>
<span class="hljs-keyword">return</span> MainPage(self.driver)
LoginPage是钉钉登录页 page object,它存在两个方法,进入注册 page object 和进入登陆 page object,这里 return 方法返回 page object 实现了页面跳转,比如:goto_register方法return Register,实现从首页跳转到注册页,演示代码中的登录写在了APP类中,这个可以试个人习惯封装,没有固定的模板
MainPage是钉钉登录后的主页,WorkBenchPage是工作台页,AttendancePage是考勤页,本次由于涉及功能较少,统一封装到MainPage类
#!\usr\bin\python
# -*- coding: UTF-8 -*-
"""
@author:chenshifeng
@file:main_page.py
@time:2020\11\19
@tip:由于我们只需部分功能,故本次把所有所需功能都放入本页面内,不做多个页面的封装
"""
import os
from dingding.page.base_page import BasePage
home_dir = (os.path.dirname(os.path.dirname(os.path.abspath(_file_))))
main_page_file = os.path.join(home_dir, 'config', 'main_page.yml')
class MainPage(BasePage):
def login(self):
self.parse_yaml(main_page_file, 'login')
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">goto_workbench</span><span class="hljs-params">(<span class="hljs-keyword">self</span>)</span></span>:
<span class="hljs-keyword">self</span>.parse_yaml(main_page_file, <span class="hljs-string">'goto_workbench'</span>)
<span class="hljs-keyword">return</span> <span class="hljs-keyword">self</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">chose_company</span><span class="hljs-params">(<span class="hljs-keyword">self</span>)</span></span>:
<span class="hljs-keyword">self</span>.parse_yaml(main_page_file, <span class="hljs-string">'chose_company'</span>)
<span class="hljs-keyword">return</span> <span class="hljs-keyword">self</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">goto_attendance</span><span class="hljs-params">(<span class="hljs-keyword">self</span>)</span></span>:
<span class="hljs-keyword">self</span>.parse_yaml(main_page_file, <span class="hljs-string">'goto_attendance'</span>)
<span class="hljs-keyword">return</span> <span class="hljs-keyword">self</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">clock_in</span><span class="hljs-params">(<span class="hljs-keyword">self</span>)</span></span>:
<span class="hljs-keyword">self</span>.parse_yaml(main_page_file, <span class="hljs-string">'clock_in'</span>)
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">clock_out</span><span class="hljs-params">(<span class="hljs-keyword">self</span>)</span></span>:
<span class="hljs-keyword">self</span>.parse_yaml(main_page_file, <span class="hljs-string">'clock_out'</span>)
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">update_clock_out</span><span class="hljs-params">(<span class="hljs-keyword">self</span>)</span></span>:
<span class="hljs-keyword">self</span>.parse_yaml(main_page_file, <span class="hljs-string">'update_clock_out'</span>)
conftest.py文件是pytest框架特有的,用来做一些用例前置操作
import os
import signal
import time
import pytest
import subprocess
@pytest.fixture(scope='module', autouse=True)
def case_before():
# 启动appium
file_name = <span class="hljs-string">'appium_'</span> + <span class="hljs-built_in">time</span>.strftime(<span class="hljs-string">"%Y_%m_%d"</span>, <span class="hljs-built_in">time</span>.localtime()) + <span class="hljs-string">'.log'</span>
home_dir = (<span class="hljs-built_in">os</span>.<span class="hljs-built_in">path</span>.dirname(<span class="hljs-built_in">os</span>.<span class="hljs-built_in">path</span>.dirname(<span class="hljs-built_in">os</span>.<span class="hljs-built_in">path</span>.abspath(__file__))))
log_file = <span class="hljs-built_in">os</span>.<span class="hljs-built_in">path</span>.join(home_dir, <span class="hljs-string">'log'</span>, file_name)
command = f<span class="hljs-string">'appium -p 4723 --session-override --log-timestamp --local-timezone >> {log_file}'</span>
p_appium = subprocess.Popen(command, shell=True, <span class="hljs-built_in">stdout</span>=subprocess.PIPE, <span class="hljs-built_in">stderr</span>=subprocess.STDOUT)
# <span class="hljs-built_in">yield</span>
# p_appium.kill()
# 解锁手机
# <span class="hljs-literal">true</span>值为锁屏,<span class="hljs-literal">false</span>为解锁
mIsShowing = subprocess.getstatusoutput(<span class="hljs-string">'adb shell dumpsys window policy | find "mIsShowing="'</span>)[<span class="hljs-number">1</span>]
mIsShowing = mIsShowing.split(<span class="hljs-string">'='</span>)[<span class="hljs-number">1</span>]
# OFF 黑屏 ON 亮屏
power = subprocess.getstatusoutput(<span class="hljs-string">'adb shell dumpsys power | find "Display Power: state="'</span>)[<span class="hljs-number">1</span>]
power = power.split(<span class="hljs-string">'='</span>)[<span class="hljs-number">1</span>]
# 尝试解锁
# <span class="hljs-built_in">os</span>.system(<span class="hljs-string">'adb shell input keyevent 82'</span>)
<span class="hljs-keyword">if</span> power == <span class="hljs-string">'OFF'</span>: # 判断是否黑屏(默认黑屏自动锁屏)
<span class="hljs-built_in">os</span>.system(<span class="hljs-string">'adb shell input keyevent 26'</span>) # 亮屏
<span class="hljs-built_in">os</span>.system(<span class="hljs-string">'adb shell input swipe 540 2000 540 500 50'</span>) # 滑动解锁
<span class="hljs-keyword">if</span> power == <span class="hljs-string">'ON'</span> <span class="hljs-keyword">and</span> mIsShowing == <span class="hljs-string">'true'</span>: # 判断是否锁屏
<span class="hljs-built_in">os</span>.system(<span class="hljs-string">'adb shell input swipe 540 2000 540 500 50'</span>) # 滑动解锁
# # 录屏功能
# video_file_name = <span class="hljs-string">'video_'</span> + <span class="hljs-built_in">time</span>.strftime(<span class="hljs-string">"%Y_%m_%d"</span>, <span class="hljs-built_in">time</span>.localtime()) + <span class="hljs-string">'.mp4'</span>
# video_log_file = <span class="hljs-built_in">os</span>.<span class="hljs-built_in">path</span>.join(home_dir, <span class="hljs-string">'video'</span>, video_file_name)
# command = f<span class="hljs-string">"scrcpy --record {video_log_file}"</span>
# p_video = subprocess.Popen(command, shell=True, <span class="hljs-built_in">stdout</span>=subprocess.PIPE, <span class="hljs-built_in">stderr</span>=subprocess.STDOUT)
# <span class="hljs-built_in">yield</span>
# <span class="hljs-built_in">print</span>(p_appium.pid)
# # p = subprocess.getstatusoutput(f<span class="hljs-string">'taskkill /PID {p_appium.pid} /F'</span>)
# <span class="hljs-built_in">print</span>(subprocess.getstatusoutput(f<span class="hljs-string">'taskkill /PID {p_appium} /F'</span>))
test_gooffwork和test_gotowork 模块是对上述功能的测试,它独立于 page 类,在 TestIndex 类中只需要调用 page 类提供的方法即可
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:chenshifeng
@file:test_gotowork.py
@time:2020/11/19
@case:钉钉上班打卡case
"""
import subprocess
import pytest
from dingding.page.app import APP
class TestGoToWork:
def setup(self):
self.app = APP()
self.main = self.app.start()
# 登录处理
try:
self.main.login()
except Exception:
pass
self.page = self.main.goto_main_page()
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">teardown</span>(<span class="hljs-params">self</span>):</span>
<span class="hljs-comment"># 关闭appium</span>
p_appium = subprocess.getstatusoutput(<span class="hljs-string">'netstat -ano|findstr 4723|findstr LISTENING'</span>)[<span class="hljs-number">1</span>]
<span class="hljs-comment"># print(p_appium)</span>
p_appium = p_appium.split(<span class="hljs-string">' '</span>)[<span class="hljs-number">-1</span>]
appium_kill = subprocess.getstatusoutput(<span class="hljs-string">f'taskkill /PID <span class="hljs-subst">{p_appium}</span> /F '</span>)[<span class="hljs-number">0</span>]
print(appium_kill)
@pytest.mark.flaky(reruns=3, reruns_delay=2) # 失败重跑
def test_gotowork(self):
self.attendance_page = self.page.goto_workbench().chose_company().goto_attendance()
self.attendance_page.clock_in()
assert self.attendance_page.assert_result('打卡成功')
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:chenshifeng
@file:test_gooffwork.py
@time:2020/11/19
@case:钉钉下班打卡case
"""
import subprocess
import pytest
from dingding.page.app import APP
class TestGoOffWork:
def setup(self):
self.app = APP()
self.main = self.app.start()
# 登录处理
try:
self.main.login()
except Exception:
pass
self.page = self.main.goto_main_page()
def teardown(self):
# 关闭appium
p_appium = subprocess.getstatusoutput('netstat -ano|findstr 4723|findstr LISTENING')[1]
print(p_appium)
p_appium = p_appium.split(' ')[-1]
appium_kill = subprocess.getstatusoutput(f'taskkill /PID {p_appium} /F ')[0]
print(appium_kill)
@pytest.mark.flaky(reruns=3, reruns_delay=2) # 失败重跑
def test_gooffwork(self):
self.attendance_page = self.page.goto_workbench().chose_company().goto_attendance()
# 若打卡失败,进行更新打卡
try:
self.attendance_page.clock_out()
except Exception:
self.attendance_page.update_clock_out()
assert self.attendance_page.assert_result('打卡成功')
另外还有一个配置文件夹config用开配置初始化APP和元素的定位
appconfig.yml文件
desired_caps:
"platformName": "Android"
"automationName": "UiAutomator2"
"platformVersion": "10"
"deviceName": "test"
"appActivity": 'com.alibaba.android.rimet.biz.LaunchHomeActivity'
"appPackage": 'com.alibaba.android.rimet'
# "settings[waitForIdleTimeout]": 0
"noReset": True # 不重置APP
"skipServerInstallation": True # 跳过 uiAutomator2服务器安装
# "dontStopAppOnReset": True,
"skipDeviceInitialization": True # 跳过设备初始化
# "unicodeKeyboard": True # 默认启用 Unicode 输入
# "resetKeyboard": True # 与上面合用,可以输入中文
ip:
127.0.0.1:4723
main_page.yml
login:
# 登陆
- by : id
loactor: 'com.alibaba.android.rimet:id/et_phone_input'
action: clear,send_keys
context: '1865xxxx166'
-
by: id
loactor: 'com.alibaba.android.rimet:id/et_pwd_login'
action: send_keys
context: '123456'
-
by : id
loactor: 'com.alibaba.android.rimet:id/tv'
action: click
goto_workbench:
进入工作台
- by : xpath
loactor: '//*[@text="工作台"]'
action: click
chose_company:
选择企业
-
by: id
loactor: 'com.alibaba.android.rimet:id/menu_current_company'
action: click
-
by: xpath
loactor: '//*[@text="阿里外包钉钉考勤专用组"]'
action: click
goto_attendance:
进入考勤页
- by: -android uiautomator
loactor: 'new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(new UiSelector().text("考勤打卡").instance(0));'
action: click
clock_in:
上班打卡
- by : xpath
loactor: '//*[@text="上班打卡"]'
action: click
clock_out:
下班打卡
- by : xpath
loactor: '//*[@text="下班打卡"]'
action: click
update_clock_out:
更新下班打卡
-
by : xpath
loactor: '//*[@text="更新打卡"]'
action: click
-
by: xpath
loactor: '//*[@text="确定"]'
action: click
cheack_result:
更新下班打卡
- by : xpath
loactor: '//*[@text="更新打卡"]'
action: click
- by: xpath
loactor: '//*[@text="确定"]'
action: click