当前位置:网站首页>Pytest电商项目实战(下)
Pytest电商项目实战(下)
2022-08-01 11:23:00 【司小幽】
1.文件目录结构
2.POM进阶之logic封装实战应用
""" 变量统一管理文件,为了方便代码中识别,目录,文件,变量名全部大写 """
# 购物车登录页链接
CART_LOGIN_URL = "CART_LOGIN_URL"
# 用户名
USERNAME = "云纱璃英"
# 密码
PASSWD = "xxx"
# 淘宝首页
TAOBAO_URL = "http://www.taobao.com"
-
txt: 迈巴赫
import yaml
def load_yaml(path):
file = open(path,'r',encoding='utf-8')
data = yaml.load(file,Loader = yaml.Fullloader)
return data
chrome.exe --remote-debugging-port=9222
""" 使用编写的脚本以debug模式启动谷歌浏览器,脚本内容如下 chrome.exe --remote-debugging-port=9222 必须通过脚本执行,使用os.system执行命令无效 """
# os.popen("d:/chrome.bat")
# sleep(3)
# 加载浏览器驱动
from time import sleep
from class37.p07.VAR.TAOBAO_VAR import USERNAME, PASSWD
from class37.p07.key_world.keyword import WebKeys
from class37.p07.locate import allPages
from selenium import webdriver
options = webdriver.ChromeOptions()
options.debugger_address = '127.0.0.1:9222'
driver = webdriver.Chrome(options=options)
sleep(2)
# 加载浏览器驱动
wk = WebKeys(driver)
# 点击加入购物车
wk.locator(*allPages.page_goodsDetail_cartBtn).click()
sleep(1)
# 切换frame
el = wk.locator(*allPages.page_goodsDetail_loginFrame)
wk.change_frame(el)
# sleep(1)
# 填账号密码
wk.locator(*allPages.page_indexLogin_user).send_keys(USERNAME)
# sleep(2)
wk.locator(*allPages.page_indexLogin_pwd).send_keys(PASSWD)
# sleep(1)
wk.locator(*allPages.page_indexLogin_loginBtn).click()
sleep(3)
# 切换到滑块的iframe
el = wk.locator('xpath', "//div[@id='login']//iframe")
wk.change_frame(el)
wk.slider_by_step("//center//span[@id='nc_1_n1z']")
# 定义关键字驱动类/工具类/基类
from time import sleep
import allure
from selenium import webdriver
from selenium.common import UnexpectedAlertPresentException
from selenium.webdriver import ActionChains
class WebKeys:
# 构造方法,用于接收driver对象
def __init__(self,driver):
self.driver = driver
# 编代码用,写完删掉
# self.driver = webdriver.Chrome()
# 打开浏览器
def open(self,url):
self.driver.get(url)
# 元素定位
def locator(self,name,value):
""" :param name: 元素定位的方式 :param value: 元素定位的路径 :return: """
el = self.driver.find_element(name,value)
# 将定位的元素框出来
self.locate_station(el)
return el
# 显示定位的地方,方便确认定位的位置
def locate_station(self,element):
self.driver.execute_script(
"arguments[0].setAttribute('style',arguments[1]);",
element,
"border: 2px solid green" #边框,green绿色
)
# 获取title,获取网页标题栏
def get_title(self):
return self.driver.title
# 窗口切换
def change_window(self, n):
# 获取句柄
handles = self.driver.window_handles
# 切换到原始页面,n = 0
# 切换句柄到第二个页面,n = 1 ,以此类推
self.driver.switch_to.window(handles[n])
# 关闭当前窗口
def close_window(self):
self.driver.close()
# 鼠标点击并悬停
def mouse_hold(self, url):
btn = self.driver.find_elements_by_xpath(url)[0]
action = ActionChains(self.driver)
action.click_and_hold(btn).perform()
# 切换frame
def change_frame(self, a):
self.driver.switch_to.frame(a)
# 切换回主框架
def change_defaultFrame(self):
self.driver.switch_to.default_content()
# 网页title检查
@allure.step("网页title检查:{expect_title}")
def assert_title(self, expect_title):
# 结果检查
result = self.driver.title
with allure.step("结果检查:(预期){1} in (实际){0}".format(result, expect_title)):
assert expect_title in result
sleep(2)
# 滑动解锁
@allure.step("滑动解锁")
def slider(self, url):
# 滑动解锁
# 定位滑动块
# slider = driver.find_element_by_class_name("cpt-drop-btn")[0]
# slider = driver.find_elements_by_class_name("cpt-drop-btn")[0]
slider = self.driver.find_elements_by_xpath(url)[0]
action = ActionChains(self.driver)
action.click_and_hold(slider).perform()
action.move_by_offset(350, 0).perform()
# 滑动解锁
@allure.step("滑动解锁,慢滑版")
def slider_by_step(self, url):
slider = self.driver.find_elements_by_xpath(url)[0]
action = ActionChains(self.driver)
# 单击并按下鼠标左键
action.click_and_hold(slider).perform()
for index in range(300):
try:
# 移动鼠标,第一个参数为 x 坐标距离,第二个参数为 y 坐标距离
action.move_by_offset(10, 0).perform()
except UnexpectedAlertPresentException:
break
# 重置 action
# action.reset_actions()
sleep(0.1) # 等待停顿时间
def locate_by_js(self):
# js = "document.querySelector({}).scrollIntoView(true);".format(css_url)
js = "document.querySelector('center span#nc_1_n1z').scrollIntoView(true);"
self.driver.execute_script(js)
""" 淘宝首页登录 https://login.taobao.com/ page_indexLogin """
# 用户名
page_indexLogin_user = ['id','fm-login-id']
# 密码
page_indexLogin_pwd = ['id','fm-login-password']
# 登录按钮
page_indexLogin_loginBtn = ['xpath', "//div[@class='fm-btn']"]
""" 淘宝首页 www.taobao.com page_index """
#搜索框
page_index_search = ["xpath",'//div[@class="search-suggest-combobox"]/input']
#搜索框
page_index_searchBtn = ["xpath","//div[@class='search-button']"]
""" 购物车详情页 CART_LOGIN_URL page_cartDetail """
# 全选按钮
page_cartDetail_selectAll = ["id","J_SelectAll1"]
# 结算按钮
page_cartDetail_payBtn = ["xpath","//div[@class='btn-area']"]
# 提交订单按钮
page_cartDetail_submitBtn = ["link text","提交订单"]
# 删除按钮
page_cartDetail_delBtn = ["link text","删除"]
# 关闭按钮
page_cartDetail_closeBtn = ["partial link text","闭"]
# 确定按钮
page_cartDetail_confirmBtn = ["partial link text","确"]
# 颜色分类栏
page_cartDetail_colorClum = "//p[@class='sku-line']"
# SKU修改按钮
page_cartDetail_modifyBtn = ["xpath","//span[text()='修改']"]
# 颜色分类
page_cartDetail_colors = ["xpath","//div[@class='sku-edit-content']/div/dl/dd/ul/li[2]"]
# 颜色分类确认按钮
page_cartDetail_colorsConfirmBtn = ["xpath","//div[@class='sku-edit-content']/div/p/a"]
# 移入收藏夹
page_cartDetail_favorites = ["link text","移入收藏夹"]
# 单一商品信息栏
page_cartDetail_singleGoodsClum = "//div[@class='order-content']"
# 相似宝贝超链接
page_cartDetail_similarGoodsLink = ["link text","相似宝贝"]
# 翻页按钮
# page_cartDetail_simlarGoddsNext = ["xpath","//a[@class='fss-navigator fss-next J_fs_next ']"]
page_cartDetail_simlarGoddsNext = ["xpath","//a[contains(@class,'J_fs_next')]"]
# 相似宝贝
page_cartDetail_simlarGoods = ["xpath","//div[@class='find-similar-body']/div/div/div[2]"]
from time import sleep
import allure
from class37.p07.VAR.TAOBAO_VAR import PASSWD, USERNAME
from class37.p07.key_world.keyword import WebKeys
from class37.p07.locate import allPages
from class37.p07.logic.cartLogin_page import CatLoginPage
class CartPage(WebKeys):
# 商品结算
@allure.step("商品结算")
def pay(self):
# 在报告里展示代码路径,方便查找
with allure.step("流程代码路径: %s" % __file__):
pass
# 复用登录流程
loginPage = CatLoginPage(self.driver)
loginPage.login(USERNAME,PASSWD)
with allure.step("点击全选按钮"):
self.locator(*allPages.page_cartDetail_selectAll).click()
sleep(1)
with allure.step("点击结算按钮"):
self.locator(*allPages.page_cartDetail_payBtn).click()
sleep(1)
# 以页面为单位,封装常用的行为操作代码和元素定位代码
from time import sleep
import allure
from class37.p07.key_world.keyword import WebKeys
from class37.p07.locate import allPages
class CatLoginPage(WebKeys):
#登录操作
@allure.step("登录")
def login(self,username,password,expect_title):
""" :param username: :param password: :param expect_title: 登录后断言,期望网页title包含字符串 :return: """
# 在报告里展示代码路径,方便查找
with allure.step("流程代码路径: %s"%__file__):
pass
with allure.step("打开网页"):
self.open("CART_LOGIN_URL")
with allure.step("输入账户"):
# 定位到账户名文本框
# self.locator(allPages.page_indexLogin_user[0],allPages.page_indexLogin_user[1]).send_keys(username)
self.locator(*allPages.page_indexLogin_user).send_keys(username)
with allure.step("输入密码"):
# 定位到密码框
self.locator(*allPages.page_indexLogin_pwd).send_keys(password)
with allure.step("点击登录"):
# 点击方式
self.locator(*allPages.page_indexLogin_loginBtn).click()
sleep(2)
# 结果检查
self.assert_title(expect_title)
# 购物车登录
from time import sleep
import allure
import pytest
# 跳过用例
from class37.p07.VAR.TAOBAO_VAR import USERNAME, PASSWD, TAOBAO_URL
from class37.p07.key_world.keyword import WebKeys
from class37.p07.logic.cartLogin_page import CatLoginPage
from class37.p07.logic.cart_page import CartPage
from class37.p07.data import yaml_driver
from class37.p07.locate import allPages
# 实现购物车的结算
# def test_case_pay(browser):
# # 初始化购物车页面对象
# cartPage = CartPage(browser)
# cartPage.pay()
@allure.title("淘宝搜索")
@pytest.mark.parametrize('data',yaml_driver.load_yaml('./data/taobao_search.yaml'))
def test_taobao_search(browser,data):
# 初始化工具类
wk = WebKeys(browser)
with allure.step("打开淘宝首页"):
wk.open(TAOBAO_URL)
sleep(2)
with allure.step("淘宝搜索: "+data["txt"]):
wk.locator(*allPages.page_index_search.send_keys(data["txt"]))
wk.locator(*allPages.page_index_searchBtn).click()
import os
from time import sleep
import allure
import pytest
# 每个用例如果引用了这个fixture,都会在用例执行前执行一下这个fixture
from selenium import webdriver
@pytest.fixture(scope='function')
def browser():
""" 全局定义浏览器驱动,方便下面的hook函数引用driver :return: """
global driver
os.popen("d:/chrome.bat")
sleep(3)
# 加载浏览器驱动
options = webdriver.ChromeOptions()
options.debugger_address = '127.0.0.1:9222'
driver = webdriver.Chrome(options=options)
sleep(2)
# 隐式等待10秒
driver.implicitly_wait(10)
""" yield之前的代码是用例前置 yield之后的代码是用例后置 """
yield driver
# 浏览器退出
""" 这种debug模式,下面的方法无法退出浏览器 driver.quit() driver.close() """
# 通过命令杀死进程
os.system('taskkill /im chromedriver.exe /F')
os.system('taskkill /im chrome.exe /F')
""" 装饰器@pytest.hookimpl(hookwrapper=True)等价于@pytest.mark.hookwrapper的作用: a.可以获取测试用例的信息,比如用例函数的描述 b.可以获取测试用例的结果,yield,返回一个result对象 """
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport():
# 可以获取测试用例的执行结果,yield,返回一个result对象
out = yield
""" 从返回一个result对象(out)获取调用结果的测试报告,返回一个report对象 report对象的属性 包括when(setup,call,teardown三个值)、nodeid(测试用例的名字)、 outcome(用例的执行结果:passed,failed) """
report = out.get_result()
# 仅仅获取用例call阶段的执行结果,不包含setup和teardown
if report.when == 'call':
# 获取用例call执行结果为结果为失败的情况
xfail = hasattr(report,"wasfail")
if(report.skipped and xfail) or (report.failed and not xfail):
# 添加allure报告截图
with allure.step("添加失败截图。。"):
# 使用allure自带的添加附件的方法:三个参数分别为:源文件、文件名 、 文件类型
allure.attach(driver.get_screenshot_as_png(),"失败截图",allure.attachment_type.PNG)
import os
import pytest
def run():
pytest.main(['-v','--alluredir','./report/result','--clean-alluredir'
#,'--allure-no-capture'
])
os.system('allure generate ./report/result -o ./report/report_allure/ --clean')
if __name__ == '__main__':
run()
3.Web自动化用例编写
""" 变量统一管理文件,为了方便代码中识别,目录,文件,变量名全部大写 """
# 购物车登录页链接
CART_LOGIN_URL = "CART_LOGIN_URL"
# 用户名
USERNAME = "云纱璃英"
# 密码
PASSWD = "xxx"
# 淘宝首页
TAOBAO_URL = "http://www.taobao.com"
-
txt: 迈巴赫
import yaml
def load_yaml(path):
file = open(path,'r',encoding='utf-8')
data = yaml.load(file,Loader = yaml.Fullloader)
return data
chrome.exe --remote-debugging-port=9222
""" 使用编写的脚本以debug模式启动谷歌浏览器,脚本内容如下 chrome.exe --remote-debugging-port=9222 必须通过脚本执行,使用os.system执行命令无效 """
# os.popen("d:/chrome.bat")
# sleep(3)
# 加载浏览器驱动
from time import sleep
from class37.p08.VAR.TAOBAO_VAR import USERNAME, PASSWD
from class37.p08.key_world.keyword import WebKeys
from class37.p08.locate import allPages
from selenium import webdriver
options = webdriver.ChromeOptions()
options.debugger_address = '127.0.0.1:9222'
driver = webdriver.Chrome(options=options)
sleep(2)
# 加载浏览器驱动
wk = WebKeys(driver)
# 点击加入购物车
wk.locator(*allPages.page_goodsDetail_cartBtn).click()
sleep(1)
# 切换frame
el = wk.locator(*allPages.page_goodsDetail_loginFrame)
wk.change_frame(el)
# sleep(1)
# 填账号密码
wk.locator(*allPages.page_indexLogin_user).send_keys(USERNAME)
# sleep(2)
wk.locator(*allPages.page_indexLogin_pwd).send_keys(PASSWD)
# sleep(1)
wk.locator(*allPages.page_indexLogin_loginBtn).click()
sleep(3)
# 切换到滑块的iframe
el = wk.locator('xpath', "//div[@id='login']//iframe")
wk.change_frame(el)
wk.slider_by_step("//center//span[@id='nc_1_n1z']")
# 定义关键字驱动类/工具类/基类
from time import sleep
import allure
from selenium import webdriver
from selenium.common import UnexpectedAlertPresentException
from selenium.webdriver import ActionChains
class WebKeys:
# 构造方法,用于接收driver对象
def __init__(self,driver):
self.driver = driver
# 编代码用,写完删掉
# self.driver = webdriver.Chrome()
# 打开浏览器
def open(self,url):
self.driver.get(url)
# 元素定位
def locator(self,name,value):
""" :param name: 元素定位的方式 :param value: 元素定位的路径 :return: """
el = self.driver.find_element(name,value)
# 将定位的元素框出来
self.locate_station(el)
return el
# 显示定位的地方,方便确认定位的位置
def locate_station(self,element):
self.driver.execute_script(
"arguments[0].setAttribute('style',arguments[1]);",
element,
"border: 2px solid green" #边框,green绿色
)
# 获取title,获取网页标题栏
def get_title(self):
return self.driver.title
# 窗口切换
def change_window(self, n):
# 获取句柄
handles = self.driver.window_handles
# 切换到原始页面,n = 0
# 切换句柄到第二个页面,n = 1 ,以此类推
self.driver.switch_to.window(handles[n])
# 关闭当前窗口
def close_window(self):
self.driver.close()
# 鼠标点击并悬停
def mouse_hold(self, url):
btn = self.driver.find_elements_by_xpath(url)[0]
action = ActionChains(self.driver)
action.click_and_hold(btn).perform()
# 切换frame
def change_frame(self, a):
self.driver.switch_to.frame(a)
# 切换回主框架
def change_defaultFrame(self):
self.driver.switch_to.default_content()
# 网页title检查
@allure.step("网页title检查:{expect_title}")
def assert_title(self, expect_title):
# 结果检查
result = self.driver.title
with allure.step("结果检查:(预期){1} in (实际){0}".format(result, expect_title)):
assert expect_title in result
sleep(2)
# 滑动解锁
@allure.step("滑动解锁")
def slider(self, url):
# 滑动解锁
# 定位滑动块
# slider = driver.find_element_by_class_name("cpt-drop-btn")[0]
# slider = driver.find_elements_by_class_name("cpt-drop-btn")[0]
slider = self.driver.find_elements_by_xpath(url)[0]
action = ActionChains(self.driver)
action.click_and_hold(slider).perform()
action.move_by_offset(350, 0).perform()
# 滑动解锁
@allure.step("滑动解锁,慢滑版")
def slider_by_step(self, url):
slider = self.driver.find_elements_by_xpath(url)[0]
action = ActionChains(self.driver)
# 单击并按下鼠标左键
action.click_and_hold(slider).perform()
for index in range(300):
try:
# 移动鼠标,第一个参数为 x 坐标距离,第二个参数为 y 坐标距离
action.move_by_offset(10, 0).perform()
except UnexpectedAlertPresentException:
break
# 重置 action
# action.reset_actions()
sleep(0.1) # 等待停顿时间
def locate_by_js(self):
# js = "document.querySelector({}).scrollIntoView(true);".format(css_url)
js = "document.querySelector('center span#nc_1_n1z').scrollIntoView(true);"
self.driver.execute_script(js)
""" 淘宝首页登录 https://login.taobao.com/ page_indexLogin """
# 用户名
page_indexLogin_user = ['id','fm-login-id']
# 密码
page_indexLogin_pwd = ['id','fm-login-password']
# 登录按钮
page_indexLogin_loginBtn = ['xpath', "//div[@class='fm-btn']"]
""" 淘宝首页 www.taobao.com page_index """
#搜索框
page_index_search = ["xpath",'//div[@class="search-suggest-combobox"]/input']
#搜索框
page_index_searchBtn = ["xpath","//div[@class='search-button']"]
""" 搜索结果页 https://s.taobao.com/search page_searchResults """
# 商品
page_searchResults_good = ["xpath","//div[@class='items']/div[@data-index='0']"]
# 二手页签
page_searchResults_old = ["link text","二手"]
""" 购物车详情页 CART_LOGIN_URL page_cartDetail """
# 全选按钮
page_cartDetail_selectAll = ["id","J_SelectAll1"]
# 结算按钮
page_cartDetail_payBtn = ["xpath","//div[@class='btn-area']"]
# 提交订单按钮
page_cartDetail_submitBtn = ["link text","提交订单"]
# 删除按钮
page_cartDetail_delBtn = ["link text","删除"]
# 关闭按钮
page_cartDetail_closeBtn = ["partial link text","闭"]
# 确定按钮
page_cartDetail_confirmBtn = ["partial link text","确"]
# 颜色分类栏
page_cartDetail_colorClum = "//p[@class='sku-line']"
# SKU修改按钮
page_cartDetail_modifyBtn = ["xpath","//span[text()='修改']"]
# 颜色分类
page_cartDetail_colors = ["xpath","//div[@class='sku-edit-content']/div/dl/dd/ul/li[2]"]
# 颜色分类确认按钮
page_cartDetail_colorsConfirmBtn = ["xpath","//div[@class='sku-edit-content']/div/p/a"]
# 移入收藏夹
page_cartDetail_favorites = ["link text","移入收藏夹"]
# 单一商品信息栏
page_cartDetail_singleGoodsClum = "//div[@class='order-content']"
# 相似宝贝超链接
page_cartDetail_similarGoodsLink = ["link text","相似宝贝"]
# 翻页按钮
# page_cartDetail_simlarGoddsNext = ["xpath","//a[@class='fss-navigator fss-next J_fs_next ']"]
page_cartDetail_simlarGoddsNext = ["xpath","//a[contains(@class,'J_fs_next')]"]
# 相似宝贝
page_cartDetail_simlarGoods = ["xpath","//div[@class='find-similar-body']/div/div/div[2]"]
""" 商品详情页 https://item.taobao.com/item.htm page_goodsDetail """
# 颜色分类
page_goodsDetail_color = ["xpath","//div[@class='tb-skin']/dl/dd/ul/li"]
# 购买数量
page_goodsDetail_num = ["xpath","//input[@title='请输入购买量']"]
# 加入购物车按钮
page_goodsDetail_cartBtn = ["partial link text","加入购物"]
# 登陆frame框
page_goodsDetail_loginFrame = ["xpath","//iframe[@class]"]
# 会员名输入框
page_goodsDetail_loginUser = ["id","fm-login-id"]
# 密码
page_goodsDetail_loginPwd = ["id","fm-login-password"]
# 登陆按钮
page_goodsDetail_loginBtn = ["xpath","//div[@class='fm-btn']"]
# 去购物结算按钮
page_goodsDetail_payBtn = ["partial link text","去购物车结算"]
from time import sleep
import allure
from class37.p08.VAR.TAOBAO_VAR import PASSWD, USERNAME
from class37.p08.key_world.keyword import WebKeys
from class37.p08.locate import allPages
from class37.p08.logic.cartLogin_page import CatLoginPage
class CartPage(WebKeys):
# 商品结算
@allure.step("商品结算")
def pay(self):
# 在报告里展示代码路径,方便查找
with allure.step("流程代码路径: %s" % __file__):
pass
with allure.step("点击全选按钮"):
self.locator(*allPages.page_cartDetail_selectAll).click()
sleep(1)
with allure.step("点击结算按钮"):
self.locator(*allPages.page_cartDetail_payBtn).click()
sleep(1)
# 以页面为单位,封装常用的行为操作代码和元素定位代码
from time import sleep
import allure
from class37.p08.key_world.keyword import WebKeys
from class37.p08.locate import allPages
class CatLoginPage(WebKeys):
#登录操作
@allure.step("登录")
def login(self,username,password,expect_title):
""" :param username: :param password: :param expect_title: 登录后断言,期望网页title包含字符串 :return: """
# 在报告里展示代码路径,方便查找
with allure.step("流程代码路径: %s"%__file__):
pass
with allure.step("打开网页"):
self.open("CART_LOGIN_URL")
with allure.step("输入账户"):
# 定位到账户名文本框
# self.locator(allPages.page_indexLogin_user[0],allPages.page_indexLogin_user[1]).send_keys(username)
self.locator(*allPages.page_indexLogin_user).send_keys(username)
sleep(2)
with allure.step("输入密码"):
# 定位到密码框
self.locator(*allPages.page_indexLogin_pwd).send_keys(password)
sleep(2)
with allure.step("点击登录"):
# 点击方式
self.locator(*allPages.page_indexLogin_loginBtn).click()
sleep(3)
# 结果检查
self.assert_title(expect_title)
from time import sleep
import allure
from class37.p08.VAR.TAOBAO_VAR import PASSWD, USERNAME
from class37.p08.key_world.keyword import WebKeys
from class37.p08.locate import allPages
from class37.p08.logic.cartLogin_page import CatLoginPage
from class37.p08.logic.cart_page import CartPage
class GoodsSale(WebKeys):
@allure.step("淘宝搜索商品:{goodsname}")
def goodsSearch(self,goodsname):
""" :param goodsname:搜索商品名 :return: """
# 在报告里展示代码路径,方便查找
with allure.step("流程代码路径: %s" % __file__):
pass
with allure.step("搜索: "+goodsname):
self.locator(*allPages.page_index_search).send_keys(goodsname)
self.locator(*allPages.page_index_searchBtn).click()
sleep(2)
# 网页title检查
self.assert_title(goodsname)
@allure.step("登录框登录")
def login_frame(self,username,passwd,expect_title):
# 在报告里展示代码路径,方便查找
with allure.step("流程代码路径: %s" % __file__):
pass
el = self.locator(*allPages.page_goodsDetail_loginFrame)
with allure.step("切换到登录框frame"):
self.change_frame(el)
sleep(3)
# 执行登录流程
# 调用登录流程
with allure.step("调用登录流程"):
login = CatLoginPage(self.driver)
login.login(USERNAME, PASSWD)
with allure.step("切换回默认的frame"):
self.change_defaultFrame()
sleep(3)
# 结果检查
self.assert_title(expect_title)
sleep(2)
@allure.step("淘宝购买商品")
def shopping(self):
with allure.step("流程代码路径: %s" % __file__):
pass
''' 找不到元素,也能继续运行 方法1: try: elem = driver.find_element_by_name('...') except: pass 方法2: elems = driver.find_elements_by_name('...') if len(elems)>0: elem = elems[0] '''
with allure.step("判断是否有登录页,有就登录"):
try:
# 调用登录流程
login = CatLoginPage(self.driver)
login.login(USERNAME,PASSWD)
except:
with allure.step("未出现登录页,跳过"):
pass
with allure.step("选择二手"):
self.locator(*allPages.page_searchResults_old).click()
sleep(2)
with allure.step("选择商品"):
self.locator(*allPages.page_searchResults_good).click()
sleep(2)
with allure.step("窗口切换"):
self.change_window(1)
sleep(1)
with allure.step("点击加入购物车按钮"):
self.locator(*allPages.page_goodsDetail_cartBtn).click()
sleep(1)
with allure.step("判断是否有登录框,有就登录"):
try:
# 调用登录框登录流程
self.login_frame(USERNAME,PASSWD,'成功')
except:
with allure.step("未出现登录页,跳过"):
pass
with allure.step("点击购物车结算按钮"):
self.locator(*allPages.page_goodsDetail_payBtn).click()
sleep(3)
# 结果检查
self.assert_title("我的购物车")
sleep(5)
# 调用购物车结算流程
cartPay = CartPage(self.driver)
cartPay.pay()
# 购物车登录
from time import sleep
import allure
import pytest
# 跳过用例
from class37.p08.VAR.TAOBAO_VAR import USERNAME, PASSWD, TAOBAO_URL
from class37.p08.key_world.keyword import WebKeys
from class37.p08.logic.cartLogin_page import CatLoginPage
from class37.p08.logic.cart_page import CartPage
from class37.p08.data import yaml_driver
from class37.p08.locate import allPages
# 实现购物车的结算
# def test_case_pay(browser):
# # 初始化购物车页面对象
# cartPage = CartPage(browser)
# cartPage.pay()
@allure.title("淘宝搜索")
@pytest.mark.parametrize('data',yaml_driver.load_yaml('./data/taobao_search.yaml'))
def test_taobao_search(browser,data):
# 初始化工具类
wk = WebKeys(browser)
with allure.step("打开淘宝首页"):
wk.open(TAOBAO_URL)
sleep(2)
with allure.step("淘宝搜索: "+data["txt"]):
wk.locator(*allPages.page_index_search.send_keys(data["txt"]))
wk.locator(*allPages.page_index_searchBtn).click()
from time import sleep
import allure
from class37.p08.VAR.TAOBAO_VAR import *
from class37.p08.logic.shopping_page import GoodsSale
from class37.p08.locate import allPages
@allure.title("淘宝商品订购")
def test_goodsSale(browser):
goodssale = GoodsSale(browser)
with allure.step("打开浏览器:"+TAOBAO_URL):
goodssale.open(TAOBAO_URL)
# 搜索商品
goodssale.goodsSearch("膳魔师")
# 进行购物
goodssale.shopping()
@allure.title("删除全部购物车的商品"):
def test_del_goods(browser):
# 复用商品购物流程
goodssale = GoodsSale(browser)
with allure.step("打开浏览器:" + TAOBAO_URL):
goodssale.open(TAOBAO_URL)
# 搜索商品
goodssale.goodsSearch("膳魔师")
# 进行购物
goodssale.shopping()
with allure.step("打开购物车"):
goodssale.open(CART_LOGIN_URL)
with allure.step("全选商品"):
goodssale.locator(*allPages.page_cartDetail_selectAll).click()
sleep(3)
with allure.step("点击删除按钮"):
goodssale.locator(*allPages.page_cartDetail_delBtn).click()
sleep(3)
with allure.step("点击确认按钮"):
goodssale.locator(*allPages.page_cartDetail_colorsConfirmBtn).click()
sleep(3)
import os
from time import sleep
import allure
import pytest
# 每个用例如果引用了这个fixture,都会在用例执行前执行一下这个fixture
from selenium import webdriver
@pytest.fixture(scope='function')
def browser():
""" 全局定义浏览器驱动,方便下面的hook函数引用driver :return: """
global driver
os.popen("d:/chrome.bat")
sleep(3)
# 加载浏览器驱动
options = webdriver.ChromeOptions()
options.debugger_address = '127.0.0.1:9222'
driver = webdriver.Chrome(options=options)
sleep(2)
# 隐式等待10秒
driver.implicitly_wait(10)
""" yield之前的代码是用例前置 yield之后的代码是用例后置 """
yield driver
# 浏览器退出
""" 这种debug模式,下面的方法无法退出浏览器 driver.quit() driver.close() """
# 通过命令杀死进程
os.system('taskkill /im chromedriver.exe /F')
os.system('taskkill /im chrome.exe /F')
""" 装饰器@pytest.hookimpl(hookwrapper=True)等价于@pytest.mark.hookwrapper的作用: a.可以获取测试用例的信息,比如用例函数的描述 b.可以获取测试用例的结果,yield,返回一个result对象 """
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport():
# 可以获取测试用例的执行结果,yield,返回一个result对象
out = yield
""" 从返回一个result对象(out)获取调用结果的测试报告,返回一个report对象 report对象的属性 包括when(setup,call,teardown三个值)、nodeid(测试用例的名字)、 outcome(用例的执行结果:passed,failed) """
report = out.get_result()
# 仅仅获取用例call阶段的执行结果,不包含setup和teardown
if report.when == 'call':
# 获取用例call执行结果为结果为失败的情况
xfail = hasattr(report,"wasfail")
if(report.skipped and xfail) or (report.failed and not xfail):
# 添加allure报告截图
with allure.step("添加失败截图。。"):
# 使用allure自带的添加附件的方法:三个参数分别为:源文件、文件名 、 文件类型
allure.attach(driver.get_screenshot_as_png(),"失败截图",allure.attachment_type.PNG)
import os
import pytest
def run():
pytest.main(['-v','--alluredir','./report/result','--clean-alluredir','./test_case/test_taobao2.py'
#,'--allure-no-capture'
])
os.system('allure generate ./report/result -o ./report/report_allure/ --clean')
if __name__ == '__main__':
run()
边栏推荐
- 石头科技打造硬核品牌力 持续出海拓展全球市场
- 小程序毕设作品之微信美食菜谱小程序毕业设计成品(2)小程序功能
- Solve vscode input! Unable to quickly generate skeletons (three methods for the new version of vscode to quickly generate skeletons)
- 小程序毕设作品之微信美食菜谱小程序毕业设计成品(3)后台功能
- 如何从完美的智能合约中窃取 1 亿美元
- 小程序毕设作品之微信美食菜谱小程序毕业设计成品(4)开题报告
- 各位大拿,安装Solaris 11.4操作系统,在安装数据库依赖包的时候包这个错,目前无原厂支持,也无安装盘,联网下载后报这个错,请教怎么解决?
- 如何成功通过 CKA 考试?
- A new generation of ultra-safe cellular batteries, Sihao Airun goes on sale starting at 139,900 yuan
- .NET深入解析LINQ框架(三:LINQ优雅的前奏)
猜你喜欢
Online - GCeasy GC log analysis tools
新一代超安全蜂窝电池, 思皓爱跑上市13.99万元起售
石头科技打造硬核品牌力 持续出海拓展全球市场
mysql进阶(二十二)MySQL错误之Incorrect string value中文字符输入错误问题分析
复现assert和eval成功连接或失败连接蚁剑的原因
leetcode/submatrix element sum
Mini Program Graduation Works WeChat Food Recipes Mini Program Graduation Design Finished Products (4) Opening Report
小程序毕设作品之微信美食菜谱小程序毕业设计成品(4)开题报告
xss-labs靶场挑战
What is a stepper motor?40 pictures to show you!
随机推荐
Promise learning (1) What is Promise?how to use?How to solve callback hell?
ACL 2022 | 文本生成的相关前沿进展
.NET analyzes the LINQ framework in depth (three: the elegant prelude of LINQ)
Guangyu Mingdao was selected into the list of pilot demonstration projects for the development of digital economy industry in Chongqing in 2022
[CLion] CLion always prompts "This file does not belong to any project target xxx" solution
leetcode/子矩阵元素和
Qt supports HEIC/HEIF format images
slice、splice、split傻傻分不清
Promise learning (2) An article takes you to quickly understand the common APIs in Promise
如何从完美的智能合约中窃取 1 亿美元
表连接详解
Transfer learning to freeze the network:
Promise学习(四)异步编程的终极解决方案async + await:用同步的方式去写异步代码
activiti工作流的分页查询避坑
xss漏洞学习
【社区明星评选】第24期 8月更文计划 | 笔耕不辍,拒绝躺平!更多原创激励大礼包,还有华为WATCH FIT手表!
The difference between undefined and null in JS
深入理解 Istio —— 云原生服务网格进阶实战
如何获取微信视频号的地址(微信公众号的链接地址)
R语言ggplot2可视化:使用ggpubr包的ggscatter函数可视化散点图、使用xscale函数指定X轴坐标轴度量调整方式、设置x轴坐标为scientific使用科学计数法显示坐标值