Pytest中使用Fixture替换Unittest的Setupclass及Pytest使用装饰器应用参数化

1  类里使用Fixture

        Pytest中夹具(Fixture)有几种生命周期:function->model->class->session->packages,其中默认为function。    

import pytest
from Common.logger import Log
from Common.Operator import *
from Common.Logins import Logins
from Page.Credentials.CredentialsPage import CredentialsPage as cp
from selenium.webdriver.common.by import By
import allurelog = Log("TestJohnDeere")class TestJohnDeere:driver = Nonelg = Nonepage = Nonecoll = (By.XPATH, '//*[@id="nav_arrow"]/div')@pytest.fixture()  # 使用默认值def begin(self):log.info('--------开始测试John Deere Credentials功能--------')self.driver = browser("chrome")self.lg = Logins()self.lg.login(self.driver, 'atcred@iicon004.com', 'Win.12345')self.driver.implicitly_wait(10)self.page = cp()ac = self.lg.get_attribute(self.coll, 'class')while True:if ac != 'icn collapse':ar = (By.ID, 'nav_arrow')self.page.click(ar)continueelse:breakself.lg.click(self.page.johndeere_menu)time.sleep(1)self.lg.switch_to_iframe(self.page.right_iframe)yield self.lgself.driver.quit()def add_jdlink(self, begin):log.info('点击 JD Link 的Add')if not begin.is_clickable(self.page.jdlink_add_btn):time.sleep(2)try:begin.click(self.page.jdlink_add_btn)time.sleep(1)self.driver.switch_to.window(self.driver.window_handles[1])time.sleep(2)txt = begin.get_text(self.page.jdlink_page_signin_lable)except Exception:log.info('Add 跳转失败!')return Falseelse:log.info('Add 跳转成功!')self.driver.switch_to.window(self.driver.window_handles[0])if txt == 'Sign In':return Trueelse:return False@allure.feature("测试Credentials功能")@allure.story("测试JD Link Credentials设置功能")def test_addJDlink(self, begin):"""测试Add JD Link功能"""res = self.add_jdlink(begin)if res:log.info('Add JD Link 测试成功!')else:log.info('Add JD Link 测试失败!')assert resif __name__ == '__main__':pytest.main(['-vs', 'TestJohnDeere.py'])  # 主函数模式

2  指定Fixture范围

        在类外写Fixture,通过@pytest.para.usefixtures("fixture name")来调用。

    


import pytest
from Common.logger import Log
from Common.Operator import *
from Common.Logins import Logins
from selenium.webdriver.common.by import By
import allurelog = Log("test_logins")# 定义fixture
@pytest.fixture(scope='class')
def starts():driver = browser("chrome")lg = Logins()lg.login(driver)driver.implicitly_wait(10)yield lgdriver.quit()# 使用fixtures
@pytest.mark.usefixtures('starts')
class TestLogins(Operator):home_log = (By.ID, 'button_home')btnuser = (By.ID, 'btnuser')loc = (By.ID, 'spanusername')# 修改密码元素changePwBtn_loc = (By.XPATH, '//*[@id="usermenu_panel"]/ul/li[2]/table/tbody/tr/td[2]/span')oldpw_loc = (By.ID, 'txt_old_pass')newpw_loc = (By.ID, 'txt_new_pass')confirmpw_loc = (By.ID, 'txt_new_pass2')changeOk_loc = (By.ID, 'button_submit')# 退出登录相关元素logout_loc = (By.XPATH, '//*[@id="usermenu_panel"]/ul/li[3]/table/tbody/tr/td[2]/span')loginB_loc = (By.ID, 'btn_login')@allure.feature("用户登录相关测试")@allure.story("测试登录功能")def test_login(self, starts):starts.click(self.home_log)time.sleep(2)starts.click(self.btnuser)time.sleep(1)displayname = starts.find_element(self.loc).textstarts.click(self.btnuser)assert displayname == 'Auto Test'def change_password(self, starts):starts.driver.refresh()time.sleep(2)starts.click(self.btnuser)try:starts.click(self.changePwBtn_loc)time.sleep(1)except Exception:log.info('open change password failed!')return Falseelse:starts.send_keys(self.oldpw_loc, 'Win.12345')starts.send_keys(self.newpw_loc, 'Win.12345')starts.send_keys(self.confirmpw_loc, 'Win.12345')time.sleep(1)try:starts.click(self.changeOk_loc)time.sleep(2)starts.driver.switch_to.alert.accept()time.sleep(1)except Exception:return Falseelse:return True@allure.feature("用户登录相关测试")@allure.story("测试修改密码")def test_change_password(self, starts):assert self.change_password(starts)@allure.feature("用户登录相关测试")@allure.story("测试退出功能")def test_logout(self, starts):starts.driver.refresh()time.sleep(3)starts.click(self.btnuser)time.sleep(1)starts.click(self.logout_loc)# 判断是否正确退出res = starts.is_text_in_value(self.loginB_loc, 'LOGIN')assert resif __name__ == '__main__':pytest.main(['-v', 'Testlogins.py'])

3  fixture和参数化同时使用

        fixture中不使用参数,测试用例使用参数化。

__author__ = 'ljzeng'import pytest
from Common.logger import Log
from Common.Operator import *
from Common.Logins import Logins
import allure
from Common.excel import *
from Common.queryMSSQL import updateSQL
from Page.ManageAssets.ManageDevicesPage import ManageDevicesPagelog = Log("TestManageDevices")
file_path = "TestData\\managedevice.xlsx"
testData = get_list(file_path)# 初始化数据库数据
def clearTestData():log.info('从数据库删除测试数据')dta = 'ironintel_admin'dtm = 'IICON_001_FLVMST'sqlstr = "delete from GPSDEVICES where CONTRACTORID='IICON_001' and Notes like '%AutoTest%'"sqls = "delete from COMMENTS where COMMENTS like '%AutoTest%'"updateSQL(dta, sqlstr)updateSQL(dtm, sqls)@pytest.fixture(scope='class')
def begin():driver = browser("chrome")lg = Logins()lg.login(driver, 'atdevice@iicon001.com', 'Win.12345')driver.implicitly_wait(10)clearTestData()lg.device = ManageDevicesPage()try:lg.switch_to_iframe(lg.device.iframe_loc)time.sleep(1)except Exception:log.info('------Open Manage Devices failed!')else:log.info('------Open Manage Devices completed!')yield lgclearTestData()driver.quit()@pytest.mark.usefixtures("begin")
class TestManageDevices:def saveDevices(self, begin, data):current_time1 = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))current_date1 = time.strftime('%m/%d/%Y')time.sleep(1)try:while not begin.is_clickable(begin.device.addBtn_loc):log.info('添加按钮不可点击,等待3秒再看')time.sleep(3)begin.click(begin.device.addBtn_loc)time.sleep(1)begin.switch_to_iframe(begin.device.addDeviceIframe_loc)time.sleep(1)except Exception:log.info('--------打开添加设备页面失败!--------')else:log.info('----测试:  %s' % data['casename'])time.sleep(3)begin.select_by_text(begin.device.selectSource_loc, data['source'])time.sleep(2)if data['source'] == 'Foresight ATU':begin.select_by_text(begin.device.seldeviceType_loc, data['type'])else:begin.send_keys(begin.device.deviceType_loc, data['type'])begin.send_keys(begin.device.deviceId_loc, data['sn'])time.sleep(2)begin.send_keys(begin.device.invoiceDate_loc, current_date1)begin.send_keys(begin.device.invoiceNo_loc, current_time1)begin.send_keys(begin.device.startDate_loc, current_date1)begin.send_keys(begin.device.notes_loc, 'AutoTestNotes' + current_time1)try:begin.click(begin.device.saveBtn_loc)time.sleep(1)mess = begin.get_text(begin.device.savemessage_loc)time.sleep(1)begin.click(begin.device.saveDialogOkBtn_loc)time.sleep(1)res = (mess == data['mess'])except Exception:log.info('-----保存设备添加失败!-----')res = Falseelse:begin.click(begin.device.exitWithoutSavingBtn_loc)time.sleep(3)begin.driver.switch_to.default_content()begin.switch_to_iframe(begin.device.iframe_loc)time.sleep(3)return res@allure.feature('测试设备管理相关功能')@allure.story('测试新建设备')@pytest.mark.parametrize('data', testData)def test_add_devices(self, begin, data):"""测试添加设备"""res = self.saveDevices(begin, data)assert resif __name__ == '__main__':pytest.main(['-vs', 'TestManageDevices.py']) 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/211748.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C#中的Attributes特性创建和结合反射应用举例

C#中的特性入门学习 Attributes官方介绍概述 Attributes provide a powerful method of associating metadata, or declarative information, with code (assemblies, types, methods, properties, and so forth). After an attribute is associated with a program entity, …

深入理解Vue.js中的this:解析this关键字及其使用场景

在Vue.js中,this 和 that 可能是指向不同对象的两个变量,或者是在代码中使用时的错误。 this: 在Vue组件中,this 指向当前组件的实例。可以通过 this 访问组件的属性和方法。 例如,在Vue组件的 data 属性中定义了一…

2023年第十届GIAC全球互联网架构大会-核心PPT资料下载

一、峰会简介 谈到一个应用,我们首先考虑的是运行这个应用所需要的系统资源。其次,是关于应用自身的架构模式。最后,还需要从软件工程的不同角度来考虑应用的设计、开发、部署、运维等。架构设计对应用有着深远的影响,它的好坏决…

Leetcode659. 分割数组为连续子序列

Every day a Leetcode 题目来源:659. 分割数组为连续子序列 解法1:哈希 贪心 定义两个哈希表: numsCount:统计数组 nums 中各元素出现次数。tailCount:存储以数字 i 结尾的且符合题意的连续子序列个数。 算法&a…

极兔单号查询,极兔快递物流查询,一键筛选出退回件

批量查询极兔快递单号的物流信息,一键筛选出其中的退回件。 所需工具: 一个【快递批量查询高手】软件 极兔快递单号若干 操作步骤: 步骤1:运行【快递批量查询高手】软件,并登录 步骤2:点击主界面左上角的…

【Bootloader学习理解----跳转优化异常】

笔者接着来介绍一下Bootloader的跳转代码以及优化 1、跳转代码理解 跳转代码可能要涉及到芯片架构的知识,要跳转到对应的位置,还要设置相关的SP 堆栈指针,具体可以参考笔者这篇文章BootLoader的理解与实现。 STM32的跳转代码如下所示: u32 …

ClickHouse为何如此之快

针对ClickHose为什么很快的问题,基于对ClickHouse的基础概念之上,一般会回答是因为是列式存储数据库,同时也会说是使用了向量化引擎,所以快。上面两方面的解释也都能够站得住脚,但是依然不能够解释真正核心的原因。因为…

AI:101-基于深度学习的航空影像中建筑物识别

🚀 本文选自专栏:人工智能领域200例教程专栏 从基础到实践,深入学习。无论你是初学者还是经验丰富的老手,对于本专栏案例和项目实践都有参考学习意义。 ✨✨✨ 每一个案例都附带有在本地跑过的核心代码,详细讲解供大家学习,希望可以帮到大家。欢迎订阅支持,正在不断更新…

2023_刷题_二叉树

文章目录 书leixingleixing 书 leixing leixing

基于以太坊的智能合约开发Solidity(基础篇)

参考教程:基于以太坊的智能合约开发教程【Solidity】_哔哩哔哩_bilibili 1、第一个程序——Helloworld: //声明版本号(程序中的版本号要和编译器版本号一致) pragma solidity ^0.5.17; //合约 contract HelloWorld {//合约属性变…

Python轴承故障诊断 (四)基于EMD-CNN的故障分类

目录 前言 1 经验模态分解EMD的Python示例 2 轴承故障数据的预处理 2.1 导入数据 2.2 制作数据集和对应标签 2.3 故障数据的EMD分解可视化 2.4 故障数据的EMD分解预处理 3 基于EMD-CNN的轴承故障诊断分类 3.1 训练数据、测试数据分组,数据分batch 3.2 定义…

D : DS查找——折半查找求平方根

Description 假定输入y是整数&#xff0c;我们用折半查找来找这个平方根。在从0到y之间必定有一个取值是y的平方根&#xff0c;如果我们查找的数x比y的平方根小&#xff0c;则x2<y&#xff0c;如果我们查找的数x比y的平方根大&#xff0c;则x2>y&#xff0c;我们可以据此…

stu05-前端的几种常用开发工具

前端的开发工具有很多&#xff0c;可以说有几十种&#xff0c;包括记事本都可以作为前端的开发工具。下面推荐的是常用的几种前端开发工具。 1.DCloud HBuilder&#xff08;轻量级&#xff09; HBuilder是DCloud&#xff08;数字天堂&#xff09;推出的一款支持HTML5的web开发…

硬件开发笔记(十四):RK3568底板电路LVDS模块、MIPI模块电路分析、LVDS硬件接口、MIPI硬件接口详解

若该文为原创文章&#xff0c;转载请注明原文出处 本文章博客地址&#xff1a;https://hpzwl.blog.csdn.net/article/details/134634186 红胖子网络科技博文大全&#xff1a;开发技术集合&#xff08;包含Qt实用技术、树莓派、三维、OpenCV、OpenGL、ffmpeg、OSG、单片机、软硬…

linux 关于$-的解释(帖子搜索合集)

在学习Linux的时候&#xff0c;今天遇到了$-&#xff0c;什么意思呢&#xff1f;网上搜索了一些帖子&#xff1a; 帖子1&#xff1a; linux命令 $- 是什么意思 $- 是什么意思&#xff1f;有什么用&#xff1f;可以判断什么交互式shell&#xff1f; $-记录着当前设置的shell…

软考高级备考-系统架构师(机考后新版教材的备考过程与资料分享)

软考高级-系统架构设计师 考试复盘1.考试结果2.备考计划3.个人心得 资料分享 考试复盘 1.考试结果 三科压线过&#xff0c;真是太太太太太太太幸运了。上天对我如此眷顾&#xff0c;那不得不分享下我的备考过程以及一些备考资料&#xff0c;帮助更多小伙伴通过考试。 2.备考…

time模块(python)

一.sleep休眠 [rootrhel8 day04]# vim demo01_time.py import time def banzhuan():print("搬砖")time.sleep(3.5) #让程序休眠3.5秒print("结束")banzhuan()[rootrhel8 day04]# python3 demo01_time.py 搬砖 结束运行时&#xff0c;会发现程序中间暂停…

【3DsMax】制作简单的骨骼动画

效果 步骤 首先准备4个板子模型展开放置好 添加一个4段的骨骼 选中其中的一块板子添加蒙皮命令 在蒙皮的参数面板中&#xff0c;设置每块板子对应哪块骨骼 设置好后你可以发现此时就已经可以通过骨骼来控制模型了 接下来就可以制作动画 点击左下角“时间配置”按钮 设置一下动…

HarmonyOS--ArkTS(1)--基本语法(1)

目录 基本语法概述 声明式UI描述 自定义组件 创建自定义组件 自定义组件的结构--struct &#xff0c;Component&#xff0c;build()函数 生命周期 基本语法概述 装饰器&#xff1a; 用于装饰类、结构、方法以及变量&#xff0c;并赋予其特殊的含义。如上述示例中Entry、C…

VSCode安装与使用

VS Code 安装及使用 1、下载 进入VS Code官网&#xff1a;地址&#xff0c;点击 DownLoad for Windows下载windows版本 注&#xff1a; Stable&#xff1a;稳定版Insiders&#xff1a;内测版 2、安装 双击安装包&#xff0c;选择我同意此协议&#xff0c;再点击下一步 选择你…