'''當用例需要調用fixture時,前面講到可以直接在用例里加fixture參數,如果一個測試class都需要用到fixture,每個用例都去傳參,會比較麻煩,這個時候,
可以在class外面加usefixtures裝飾器,讓整個class都調用fixture'''
'''
調用fixture的三種方法
1.函數或類里面方法直接傳fixture的函數名稱
2.使用裝飾器@pyets.mark.usefixtures()修飾
3.autouse=True自動使用
'''
'''用例傳fixture參數
方法一:先定義start功能 用例全部傳start參數,調用該功能
'''
import time
import pytest
@pytest.fixture(scope="function")
def start(request):
print("\n-----開始執行function-----")
def test_a(start):
print("-----用例a執行-----")
class Test_aaa():
def test_o1(self,start):
print("----用例01---------")
def test_02(self,start):
print("----用例02---------")
if __name__ == '__main__':
pytest.main(["-s","usefixtures.py"])
'''
運行結果
usefixtures.py
-----開始執行function-----
.-----用例a執行-----
-----開始執行function-----
.----用例01---------
-----開始執行function-----
.----用例02---------
'''
'''裝飾器usefixtures
方法二:使用裝飾器@pytest.mark.usefixtures()修飾需要運行的用例
'''
@pytest.fixture(scope="function")
def start():
print("\n-----開始執行function------")
@pytest.mark.usefixtures("start")
def test_a():
print("------用例a執行------")
@pytest.mark.usefixtures("start")
class Test_aaa():
def test_01(self):
print("------用例01-------")
def test_02(self):
print("------用例02-------")
if __name__ == '__main__':
pytest.main(["-s","usefixtures.py"])
'''
疊加fixture
如果class用例需要同時調用多個fixture,可以使用@pytest.mark.usefixtures()疊加。注意疊加順序,先執行的放底層,后執行的放上層
'''
@pytest.fixture(scope="module")
def first():
print("第一步:操作aaa")
@pytest.fixture(scope="module")
def second():
print("第二步:操作bbb")
@pytest.mark.usefixtures("second")
@pytest.mark.usefixtures("first")
class TestFix():
def test_1(self):
print("用例1")
assert 1==1
def test_2(self):
print("用例2")
assert 2==2
if __name__ == '__main__':
pytest.main(["-s","usefixtures.py"])
'''
usefixtures與傳fixture區別
通過上面2個案例,對usefixtures使用基本方法已經掌握了,但是你會發現,我上面給的2個案例的fixture是沒有返回值的。如果fixture有返回值,那么usefixtures就無法獲取到返回值了,這個是它與用例直接傳fixture參數的區別。
也就是說當fixture用return值需要使用時,只能在用例里面傳fixture參數了。
當fixture沒有return值的時候,兩種方法都可以。
'''