本篇內容介紹了“pytest中fixtures調用fixtures及fixture復用性實例分析”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
pytest最大的優點之一就是它非常靈活。
它可以將復雜的測試需求簡化為更簡單和有組織的函數,然后這些函數可以根據自身的需求去依賴別的函數。
fixtures可以調用別的fixtures正是靈活性的體現之一。
直接看一個簡單示例:
import pytest
# Arrange
@pytest.fixture
def first_entry():
# 這是一個fixture函數,返回值:"a"
return "a"
# Arrange
@pytest.fixture
def order(first_entry):
# 這是另一個fixture函數,請求了上一個fixture函數first_entry(),
# 并且把first_entry()的返回值,放進了列表[]里,最后返回
return [first_entry]
def test_string(order):
# Act
# 測試函數中請求了第二個fixture函數order,可以拿到返回的[]
order.append("b")
# Assert
assert order == ["a", "b"]可以看到,pytest中的某個fixture請求別的fixture,就像測試函數請求fixture一樣,所有的請求規則都適用。
同樣,如果這些事情換我們自己來做的話,應該是下面這樣子:
def first_entry():
return "a"
def order(first_entry):
return [first_entry]
def test_string(order):
# Act
order.append("b")
# Assert
assert order == ["a", "b"]
entry = first_entry()
the_list = order(first_entry=entry)
test_string(order=the_list)pytest中的fixtures還可以讓我們像使用普通函數一樣,能夠定義反復重用的通用setup步驟。
兩個不同的測試函數可以請求相同的fixture,每個測試函數都會獲得該fixture的各自結果。
這樣的優點就是,確保不同的測試函數之間不會相互影響。
我們可以使用這種機制來確保每個測試函數都獲得各自新的、干凈的、一致的數據。
import pytest
# Arrange
@pytest.fixture
def first_entry():
return "a"
# Arrange
@pytest.fixture
def order(first_entry):
return [first_entry]
def test_string(order):
# Act
order.append("b")
# Assert
assert order == ["a", "b"]
def test_int(order):
# Act
order.append(2)
# Assert
assert order == ["a", 2]從代碼可以看出,fixture函數order雖然先后被兩個測試函數調用,但是每次被調用給出的結果都是一樣的。并不會因為在測試函數test_string中,進行了order.append("b")后,就影響了order在測試函數test_int中的返回值。
同樣,這些事情換成我們自己來做,那就是這樣的:
def first_entry():
return "a"
def order(first_entry):
return [first_entry]
def test_string(order):
# Act
order.append("b")
# Assert
assert order == ["a", "b"]
def test_int(order):
# Act
order.append(2)
# Assert
assert order == ["a", 2]
entry = first_entry()
the_list = order(first_entry=entry)
test_string(order=the_list)
entry = first_entry()
the_list = order(first_entry=entry)
test_int(order=the_list)接下來,繼續跟著官方文檔解讀fixtures的特點:一次請求多個fixtures、fixtures被多次請求。
“pytest中fixtures調用fixtures及fixture復用性實例分析”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。