pytest之fixture
阿新 • • 發佈:2021-12-16
fixture [fɪkstʃɚ] 固定裝置 。一直有聽說這個很好用,所以學習了一下。但是網上文件有點多,搞得我很混亂,所以想理一理,記錄一下,可能有不正確的地方,歡迎指教。
一、conftest.py
pytest裡面預設讀取conftest.py裡面的配置,可單獨管理一些預置的操作場景, conftest.py配置需要注意以下點:1、conftest.py配置指令碼名稱是固定的,不能改名稱
2、conftest.py與執行的用例要在同一個目錄下,並且有__init__.py檔案
3、不需要import匯入 conftest.py,pytest用例會自動查詢
二、scope引數可以控制fixture的作用範圍:session>module>class>function 預設是function
1、function
test_case01.py 檔案
import pytest
def test_one(login1):
x = "this"
assert 'h' in x
def test_two(login2):
x = "this"
assert 'h' in x
def test_three(login1):
x = "this"
assert 'h' in x
class TestCase01():
def test_one(self,login1):
x = "this"
assert 'h' in x
def test_two(self,login2):
x = "this"
assert 'h' in x
def test_three(self,login1):
x = "this"
assert 'h' in x
if __name__ == "__main__":
pytest.main(['-s','test_case01.py'])
conftest.py檔案
import pytest
@pytest.fixture()
def login1():
print("輸入賬號1,密碼先登入")
@pytest.fixture(scope='function')
def login2():
print("輸入賬號2,密碼先登入")
執行結果:
test_case01.py 輸入賬號1,密碼先登入
.輸入賬號2,密碼先登入
.輸入賬號1,密碼先登入
.輸入賬號1,密碼先登入
.輸入賬號2,密碼先登入
.輸入賬號1,密碼先登入
2、class
conftest.py檔案改為如下
import pytest
@pytest.fixture(scope='class')
def login1():
print("輸入賬號1,密碼先登入")
@pytest.fixture(scope='class')
def login2():
print("輸入賬號2,密碼先登入")
執行結果:
test_case01.py 輸入賬號1,密碼先登入
.輸入賬號2,密碼先登入
.輸入賬號1,密碼先登入
.輸入賬號1,密碼先登入
.輸入賬號2,密碼先登入
3、module
conftest.py檔案改為如下
import pytest
@pytest.fixture(scope='module')
def login1():
print("輸入賬號1,密碼先登入")
@pytest.fixture(scope='module')
def login2():
print("輸入賬號2,密碼先登入")
執行結果:
test_case01.py 輸入賬號1,密碼先登入
.輸入賬號2,密碼先登入
4、session
conftest.py檔案改為如下
import pytest
@pytest.fixture(scope='session')
def login1():
print("輸入賬號1,密碼先登入")
@pytest.fixture(scope='session')
def login2():
print("輸入賬號2,密碼先登入")
執行結果:
test_case01.py 輸入賬號1,密碼先登入
.輸入賬號2,密碼先登入