1、fixture是對測試用例執行的環境准備和清理,相當於unittest中的setUp/tearDown/setUpClass/tearDownClass作用
2、fixture的主要目的
如測試用例運行時都需要進行登錄和退出操作時,使用fixture后,可以只進行一次登錄和退出操作,不需要每個用例執行時都進行登錄和退出
3、如何使用fixture
在測試函數之前加上@pytest.fixture
1、需要在測試包下新建一個conftest.py文件,名字不能是其他的
2、在該文件中寫用例執行的前置條件和后置條件,首先需要聲明他是一個fixture,@pytest.fixture
1 import pytest 2 from selenium import webdriver 3 from TestDatas import Common_Datas as CD 4 from PageObjects.login_page import LoginPage 5 6 7 driver=None 8 # 聲明一個它是一個fixture 9 # scope='class'表示access_web的作用域在類上,執行測試用例時,類只執行一次 10 @pytest.fixture(scope='class') 11 def access_web(): 12 # 前置條件 13 global driver #聲明driver為全局變量 14 print("========所有測試用例之前的,整個測試用例只執行一次=========") 15 driver=webdriver.Chrome() 16 driver.maximize_window() 17 driver.get(CD.web_login_url) 18 # 實例化LoginPage類 19 lg=LoginPage(driver) 20 # yield 同時可以返回值(driver,lg),相當於return,在使用返回值的時候直接用函數名 21 yield (driver,lg) ##前面是前置條件、后面是后置條件 22 # 后置條件 23 print("========所有測試用例之后的,整個測試用例只執行一次=========") 24 driver.quit() 25 @pytest.fixture() 26 # @pytest.fixture()表示函數默認作用域access_web的作用域在函數上,執行測試用例時,每個函數都執行一次 27 def refresh_page(): 28 global driver 29 # 前置操作 30 yield 31 # 后置操作 32 driver.refresh()
3、在函數中直接使用就可以,不需要引用py文件
- access_web函數名直接接收返回值,使用函數名可以直接使用返回值
1 from PageObjects.index_page import IndexPage 2 from TestDatas import login_datas as LD 3 import pytest 4 5 # 使用access_web,作用域是類級別,類上只執行一次 6 @pytest.mark.usefixtures("access_web") 7 #使用refresh_page,作用域是函數級別,作用在每一個函數上 8 @pytest.mark.usefixtures("refresh_page") 9 class TestLogin: 10 # # 正常用例--登錄成功 11 @pytest.mark.somke 12 @pytest.mark.one 13 def test_login_1_success(self,access_web): 14 ''' 15 :param access_web: 使用access_web函數名稱來接收conftest中access_web函數的返回值,返回值為元組形式yield (driver,lg),使用返回值直接用函數名和下表 eg:access_web[0],access_web[1],如果access_web函數中沒有返回值,則無需傳參 16 :return: 17 ''' 18 # 2、步驟 19 # 調用login方法 20 access_web[1].login(LD.success_data['user'],LD.success_data['pwd']) 21 # 3、斷言 22 assert IndexPage(access_web[0]).isExist_logout_ele()