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.pswp.cn/news/211748.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/211748.shtml
英文地址,請注明出處:http://en.pswp.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;再點擊下一步 選擇你…