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'])