1. 程式人生 > 其它 >pytest之fixture

pytest之fixture

  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

-function:每一個函式或方法都可以呼叫 -class: 每一個類呼叫一次,一個類中可以有多個方法 -module:每一個.py檔案呼叫一次,該檔案內又有多個function和class -session:是多個檔案呼叫一次,可以跨.py檔案呼叫,每個.py檔案就是module 下面來嘗試並驗證一下

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,密碼先登入