Pytest進階 -- fixture/yield
阿新 • • 發佈:2022-05-13
fixture
使用介紹:
@pytest.fixture() #加fixture裝飾器,可以讓這個方法後面被呼叫
def login():
print("\nlogin.....\n")
def test_search():
print("search")
def test_order(login): #只需要在括號內填入加了fixture裝飾器的方法,就可以實現在這個測試用例前呼叫login方法
print("ordering")
def test_cart():
print("shopping cart..")
作用域:
取值 | 範圍 | 說明 |
---|---|---|
function | 函式級 | 每一個函式或方法都會呼叫 |
class | 類級別 | 每個測試類只執行一次 |
module | 模組級 | 每一個.py檔案呼叫一次 |
package | 包級 | 每一個python包只調用一次(暫不支援) |
session | 會話級 | 每次會話只需要執行一次,會話內所有方法及類,模組都共享這個方法 |
module
import pytest #fixture作用域 -- module @pytest.fixture(scope= "module") #避免以test開頭 def login(): print("\nlogin.....\n") def test_search(): print("search") def test_order(login): print("ordering") def test_cart(login): print("shopping cart..") class TestDemo: def test_case_1(self): print("test case 1") def test_case_2(self,login): print("test case 2")
輸出:
test_demo.py::test_search search
PASSED
test_demo.py::test_order
login..... #整個py檔案只執行一次
ordering
PASSED
test_demo.py::test_cart shopping cart..
PASSED
test_demo.py::TestDemo::test_case_1 test case 1
PASSED
test_demo.py::TestDemo::test_case_2 test case 2
PASSED
class
類裡面只執行一次
#fixture作用域 @pytest.fixture(scope= "class") #避免以test開頭 def login(): print("\nlogin.....\n") def test_search(): print("search") def test_order(login): #只需要在括號內填入加了fixture裝飾器的方法,就可以實現在這個測試用例前呼叫login方法 print("ordering") def test_cart(login): print("shopping cart..") class TestDemo: def test_case_1(self,login): print("test case 1") def test_case_2(self,login): print("test case 2")
輸出:
test_demo.py::test_search search
PASSED
test_demo.py::test_order
login.....#類外每次都會呼叫
ordering
PASSED
test_demo.py::test_cart
login.....#類外每次都會呼叫
shopping cart..
PASSED
test_demo.py::TestDemo::test_case_1
login.....#類內只調用一次
test case 1
PASSED
test_demo.py::TestDemo::test_case_2 test case 2
PASSED
yield
#fixture作用域
"""
@pytest.fixture
def fixture_name():
setup操作
yield 返回值
teardown操作
"""
@pytest.fixture() #避免以test開頭
def login():
print("\nlogin.....\n")
token = '123'
yield token #返回token值
print("\nlogout.....\n")
def test_search():
print("search")
def test_order(login): #只需要在括號內填入加了fixture裝飾器的方法,就可以實現在這個測試用例前呼叫login方法
print("ordering")
print(f"token:{login}") #這時候使用fixture的方法來代表yield返回的值token
yield也可以返回多個數值
yield token,name