我如何搭建自动化测试框架_06 PageObject
我原本以为有便宜的视频教程可以看一下,但是一看,好贵,有钱的哥们可以去看看哈,我就不看了,之前也接触过,重新温习一下就好了.毕竟贵死了,钱要是这么好赚的话,我也去开视频教学得了
https://edu.csdn.net/learn/7003/139865?spm=1002.2001.3001.4143
还是参考学习这个教程吧,这个教程还是有那个抛转引玉的作用的.虽然写的不是非常漂亮和实用化,但是一看就知道在写什么,能把道理原理讲得明明白白https://blog.csdn.net/huilan_same/article/details/76572776
核心在于将测试用例的各个部分来分成,比如分成Page、common、case、suite四个目录:
Page主要封装页面上UI,以及UI的操作方法,
common主要封装共同的方法比如日志,截图,以及测试类的继承这些,
case则是上层业务用例的封装,直观看起来就是对用例的描述
suite则是编写用例能力的组装,比如见过的一种就是UI元素和UI的操作方法的组装
今天,我就来写一个比较简单的啦,仅仅为学习
封装Browser类,这个给后面的Page类去继承,这种思想,好像就是把浏览器和页面融为一体的意思,但是我这里不去调试代码了,直接写死浏览器驱动位置
import time
import os
from selenium import webdriver
from utils.config import DRIVER_PATH, REPORT_PATH
CHROMEDRIVER_PATH = DRIVER_PATH + 'chromedriver.exe'
IEDRIVER_PATH = DRIVER_PATH + 'IEDriverServer.exe'
PHANTOMJSDRIVER_PATH = DRIVER_PATH + '\phantomjs.exe'
TYPES = {'firefox': webdriver.firefox, 'chrome': webdriver.Chrome}
EXECUTABLE_PATH = {'firefox': 'wires', 'chrome': CHROMEDRIVER_PATH}
class UnSupportBrowserTypeError(Exception):
pass
class Browser(object):
def __init__(self, browser_type='chrome'):
self._type = browser_type.lower()
if self._type in TYPES:
self.browser = TYPES[self._type]
else:
raise UnSupportBrowserTypeError("仅支持%s!" % ''.join(TYPES.keys()))
self.driver = None
def get(self, url, maximize_window=True, implicitly_wait=30):
# self.driver = self.browser(executable_path=EXECUTABLE_PATH[self._type])
driver_path = r"E:\代码空间\auto_test_framework\drivers\chromedriver.exe"
#TODO
self.driver = webdriver.Chrome(executable_path=driver_path)
self.driver.get(url)
if maximize_window:
self.driver.maximize_window()
self.driver.implicitly_wait(implicitly_wait)
return self
def save_screen_shot(self, name='screen_shot'):
day = time.strftime('%y%m%d', time.localtime(time.time()))
screenshot_path = REPORT_PATH + '\screenshot_%s' % day
if not os.path.exists(screenshot_path):
os.makedirs(screenshot_path)
tm = time.strftime('%y%m%d', time.localtime(time.time()))
screenshot = self.driver.save_screenshot(screenshot_path + '\\%s_%s.png' % (name, tm))
def close(self):
self.driver.close()
def quit(self):
self.driver.quit()
先来封装一个Page类,这个类是直接继承driver类的,然后driver类的选择还封装了一下
from test.common.browser import Browser
class Page(Browser):
def __init__(self, page=None, browser_type='firefox'):
if page:
self.driver = page.driver
else:
super(Page, self).__init__(browser_type=browser_type)
def get_driver(self):
return self.driver
def find_element(self, *args):
return self.driver.find_element(*args)
def find_elements(self, *args):
return self.driver.find_element(*args)
再来封装一个真实的页面,也就是百度的首页,以及响应的页面baidu_main_page.py
from selenium.webdriver.common.by import By
from test.common.page import Page
class BaiDuMainPage(Page):
loc_search_input = (By.ID, 'kw')
loc_search_button = (By.ID, 'su')
def search(self, kw):
"""搜索功能"""
self.find_element(*self.loc_search_input).send_keys(kw)
self.find_element(*self.loc_search_button).click()
和一个baidu_result_page.py的页面
from selenium.webdriver.common.by import By
from test.page.baidu_main_page import BaiDuMainPage
class BaiDuResultPage(BaiDuMainPage):
loc_result_links = (By.XPATH, '//div[contains(@class, "result")]/h3/a')
@property
def result_links(self):
return self.find_elements(*self.loc_result_links)
再来写一个用例
import time
import unittest
from utils.config import Config, DATA_PATH, REPORT_PATH
from utils.log import Logger
from utils.excel_reader import ExcelReader
from XTestRunner import HTMLTestRunner ##这里直接使用的另外一个大佬封装的HTMLTestRunner
from test.page.baidu_result_page import BaiDuMainPage, BaiDuResultPage
from cases.baseCase.base_case import BaseCase
class TestBaiDu(BaseCase):
URL = Config().get('URL')
rd_excel = DATA_PATH + '/baidu.xlsx'
rd_sheet = "Sheet1"
def sub_setUp(self):
# 初始页面是main page,传入浏览器类型打开浏览器
self.page = BaiDuMainPage(browser_type='chrome').get(self.URL, maximize_window=False)
def sub_tearDown(self):
self.page.quit()
def test_search(self):
# datas = ExcelReader(self.excel).data
# excel = ExcelReader()
# datas = excel.get_sheet_data_by_file_and_sheet_name(self.rd_excel, self.rd_sheet)
# print("datas", datas)
rd_excel = r"E:\代码空间\auto_test_framework\data\测试用例数据.xlsx"
rd_sheet = "Sheet1"
excel = ExcelReader()
datas = excel.get_sheet_data_by_file_and_sheet_name(rd_excel, rd_sheet) #这里是直接使用的自己的写的读excel的代码
for d in datas:
with self.subTest(data=d):
self.sub_setUp()
self.page.search(d) ##TODO这里有点问题,这里会跳出百度的一个验证
time.sleep(2)
self.page = BaiDuResultPage(self.page) # 页面跳转到result page,这样子就有了面向对象的感觉了
links = self.page.result_links
for link in links:
self.log.info(link.text)
self.sub_tearDown()
if __name__ == '__main__':
report = REPORT_PATH + '\\report.html'
with open(report, 'wb') as f:
runner = HTMLTestRunner(f, verbosity=2, title='从0搭建测试框架 灰蓝', description='修改html报告')
runner.run(TestBaiDu('test_search'))
try:
runner.send_email(
user="1696746432@qq.com",
password="xqcxfzujvsoxcfhg",
host="smtp.qq.com",
to="1696746432@qq.com",
subject="自动化测试的邮件",
attachments=report
)
except Exception as err:
print("err", err)
参考https://blog.csdn.net/huilan_same/article/details/76572776
emmm,PO模式是一个很优美的设计,限于篇幅和能力原因,此处仅仅为借鉴,并做笔记
https://github.com/WaterLoran/auto_test_framework