跟著節奏繼續來探索fixtures的靈活性,
一、一個測驗函式/fixture一次請求多個fixture
在測驗函式和fixture函式中,每一次并不局限于請求一個fixture,他們想要多少就可以要多少,
下面是另一個簡單的例子:
import pytest
# Arrange
@pytest.fixture
def first_entry():
return "a"
# Arrange
@pytest.fixture
def second_entry():
return 2
# Arrange
@pytest.fixture
def order(first_entry, second_entry):
# 這是一個fixture函式,請求了2個其他的fixture函式
return [first_entry, second_entry]
# Arrange
@pytest.fixture
def expected_list():
return ["a", 2, 3.0]
def test_string(order, expected_list):
# 這是一個測驗函式,請求了2個不同的fixture函式
# Act
order.append(3.0)
# Assert
assert order == expected_list
可以看出,在fixture函式order中,請求了2個其他的fixture函式,分別是:first_entry、second_entry,
在測驗函式test_string中,請求了2個不同的fixture函式,分別是:order、expected_list,
二、每個測驗函式可以多次請求fixtures(回傳值被快取)
在同一個測驗函式中,fixture也可以被請求多次,但是在這個測驗函式中,pytest在第一次執行fixture函式之后,不會再次執行它們,
如果第一次執行fixture函式有回傳值,那么回傳值會被快取起來,
import pytest
# Arrange
@pytest.fixture
def first_entry():
return "a"
# Arrange
@pytest.fixture
def order():
return []
# Act
@pytest.fixture
def append_first(order, first_entry):
# 在這里order第一次被請求,回傳一個串列[]
# 接著,order空串列增加了first_entry的回傳值,此時的order變成了["a"],被快取起來
return order.append(first_entry)
def test_string_only(append_first, order, first_entry):
# 在測驗函式里,order第二次被請求,但是并不會拿到空串列[],而且拿到了被快取起來的["a"]
# 所以斷言order == [first_entry],其實就是 ["a"] == ["a"],測驗通過
# Assert
assert order == [first_entry]
從示例中可以看出:
- 在fixture函式
append_first中,order第一次被請求,回傳一個串列[],被快取起來, - 接著,
order.append(first_entry)在[]中增加了first_entry的回傳值,所以,此時的order變成了["a"], - 最后,在測驗函式
test_string_only中,order第二次被請求,但是并不會拿到空串列[],而且拿到了被快取起來的["a"],
這樣的話,最后的斷言assert order == [first_entry]就會成功,
反過來,如果同一個fixture在一個測驗函式中每次都去請求一次,那上面的測驗函式必然失敗,
因為,這樣一來,雖然在append_first中的回傳值仍然是["a"],但是在test_string_only中,
又去重新請求了一次order,拿到的其實是空串列[],所以最后斷言會失敗,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/265609.html
標籤:其他
上一篇:【分享】開發中的單元測驗、模塊測驗、介面測驗是什么?
下一篇:Eolinker集成介紹
