当前位置:网站首页>Pytest e-commerce project combat (below)
Pytest e-commerce project combat (below)
2022-08-01 11:25:00 【Si Xiaoyou】
1.文件目录结构
2.POM进阶之logicEncapsulation practical application
""" The unified management of variable file,In order to facilitate the code recognition,目录,文件,变量名全部大写 """
# Shopping cart login page links
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 Must through the script execution,使用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)
# Fill in the account password
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)
# Switch to the slide blockiframe
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
# Switch to the original page,n = 0
# Handle to switch to the second page,n = 1 ,以此类推
self.driver.switch_to.window(handles[n])
# 关闭当前窗口
def close_window(self):
self.driver.close()
# The mouse to click and hover
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)
# Switch back to the main frame
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("滑动解锁,Slow skater")
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: After logging in assert that,Expect web pagetitle包含字符串 :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自动化用例编写
""" The unified management of variable file,In order to facilitate the code recognition,目录,文件,变量名全部大写 """
# Shopping cart login page links
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 Must through the script execution,使用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)
# Fill in the account password
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)
# Switch to the slide blockiframe
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
# Switch to the original page,n = 0
# Handle to switch to the second page,n = 1 ,以此类推
self.driver.switch_to.window(handles[n])
# 关闭当前窗口
def close_window(self):
self.driver.close()
# The mouse to click and hover
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)
# Switch back to the main frame
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("滑动解锁,Slow skater")
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']"]
# Second-hand TAB
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='Please enter the purchase']"]
# 加入购物车按钮
page_goodsDetail_cartBtn = ["partial link text","加入购物"]
# 登陆frame框
page_goodsDetail_loginFrame = ["xpath","//iframe[@class]"]
# Members of the input box
page_goodsDetail_loginUser = ["id","fm-login-id"]
# 密码
page_goodsDetail_loginPwd = ["id","fm-login-password"]
# 登陆按钮
page_goodsDetail_loginBtn = ["xpath","//div[@class='fm-btn']"]
# Go to shopping and settlement button
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: After logging in assert that,Expect web pagetitle包含字符串 :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:Search brand name :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("Switch to the login boxframe"):
self.change_frame(el)
sleep(3)
# 执行登录流程
# Call the login process
with allure.step("Call the login process"):
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("Determine whether there is a login page,有就登录"):
try:
# Call the login process
login = CatLoginPage(self.driver)
login.login(USERNAME,PASSWD)
except:
with allure.step("Does not appear the login page,跳过"):
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("Determine whether there is a login box,有就登录"):
try:
# Call the login box login process
self.login_frame(USERNAME,PASSWD,'成功')
except:
with allure.step("Does not appear the login page,跳过"):
pass
with allure.step("Click on the shopping cart and settlement button"):
self.locator(*allPages.page_goodsDetail_payBtn).click()
sleep(3)
# 结果检查
self.assert_title("我的购物车")
sleep(5)
# Call the shopping cart checkout process
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("Taobao order goods")
def test_goodsSale(browser):
goodssale = GoodsSale(browser)
with allure.step("打开浏览器:"+TAOBAO_URL):
goodssale.open(TAOBAO_URL)
# 搜索商品
goodssale.goodsSearch("膳魔师")
# 进行购物
goodssale.shopping()
@allure.title("Delete all the shopping cart of goods"):
def test_del_goods(browser):
# Reuse the shopping process
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()
边栏推荐
- 小程序毕设作品之微信美食菜谱小程序毕业设计成品(3)后台功能
- 轮询和长轮询的区别
- retired paddling
- C language implementation!20000 in 4 seconds
- 监视网络连接的ss命令
- Push the local project to the remote repository
- 正则表达式
- How I secured 70,000 ETH and won a 6 million bug bounty
- Introduction to data warehouse layering (real-time data warehouse architecture)
- Pve delete virtual machine "for a collection"
猜你喜欢
Qt supports HEIC/HEIF format images
【likeshop】回收租凭系统100%开源无加密 商城+回收+租赁
Flutter Widget 如何启用和屏蔽点击事件
小程序毕设作品之微信美食菜谱小程序毕业设计成品(3)后台功能
Mysql index related knowledge review one
千万级乘客排队系统重构&压测方案——总结篇
xss-labs靶场挑战
2022 Go生态圈 rpc 框架 Benchmark
回归预测 | MATLAB实现TPA-LSTM(时间注意力注意力机制长短期记忆神经网络)多输入单输出
Promise学习(二)一篇文章带你快速了解Promise中的常用API
随机推荐
在线GC日志分析工具——GCeasy
Promise to learn several key questions (3) the Promise - state change, execution sequence and mechanism, multitasking series, abnormal penetration, interrupt the chain of Promise
从零开始Blazor Server(4)--登录系统
Hot review last week (7.25 7.31)
判断JS数据类型的四种方法
Envoy 源码流程图
Promise learning (4) The ultimate solution for asynchronous programming async + await: write asynchronous code in a synchronous way
slice、splice、split傻傻分不清
一文说明白ECDSA spec256k1 spec256r1 EdDSA ed25519千丝万缕的关系
Introduction to STM32 development Introduce IIC bus, read and write AT24C02 (EEPROM) (using analog timing)
回归预测 | MATLAB实现TPA-LSTM(时间注意力注意力机制长短期记忆神经网络)多输入单输出
【社区明星评选】第24期 8月更文计划 | 笔耕不辍,拒绝躺平!更多原创激励大礼包,还有华为WATCH FIT手表!
小程序毕设作品之微信美食菜谱小程序毕业设计成品(3)后台功能
leetcode/子矩阵元素和
Online - GCeasy GC log analysis tools
Aeraki Mesh 正式成为 CNCF 沙箱项目
Cross-domain network resource file download
C#/VB.NET convert PPT or PPTX to image
mysql进阶(二十二)MySQL错误之Incorrect string value中文字符输入错误问题分析
2022 Go生态圈 rpc 框架 Benchmark