一、fixture有效性
fixture有效性,說白了就是fixture函式只有在它定義的使用范圍內,才可以被請求到,比如,在類里面定義了一個fixture,
那么就只能是這個類中的測驗函式才可以請求,但是,如果一個fixture定義的范圍是整個模塊,那么這個模塊下的每個測驗函式都可以去請求,
這里還有另一個影響fixture有效性的引數autouse=True,默認為False,等于True的話會在其他fixture之前先執行該fixture,后面有需要
另起一篇,這里簡短帶過,
另外,一個fixture函式還可以請求任何其他的fixture函式,不管被請求的那個fixture函式在哪里定義,只要測驗函式請求了它們,fixture函式就可以,
看示例代碼(為了更直觀的看效果,在官方代碼基礎上我加了幾個fixture函式的print):
# content of test_module1.py
import pytest
@pytest.fixture
def order():
print("\n運行fixture函式-order")
return []
@pytest.fixture
def outer(order, inner):
print("運行fixture函式-outer")
order.append("outer")
class TestOne:
@pytest.fixture
def inner(self, order):
print("運行TestOne下的fixture-inner")
order.append("one")
def test_order(self, order, outer):
assert order == ["one", "outer"]
class TestTwo:
@pytest.fixture
def inner(self, order):
print("運行TestTwo下的fixture-inner")
order.append("two")
def test_order(self, order, outer):
assert order == ["two", "outer"]
注意:
- 這里有一個fixture函式
outer在測驗類的外部 - 另外還有2個名字都叫
inner的fixture函式,分別在測驗類TestOne和TestTwo中, - 在外部的fixture函式
outer中,又請求了內部的fixture函式inner,
現在我只運行類TestOne,看運行結果:
test_module1.py
運行fixture函式-order
運行TestOne下的fixture-inner
運行fixture函式-outer
. [100%]
============================== 1 passed in 0.01s ==============================
Process finished with exit code 0
說明測驗函式里的斷言通過,測驗函式執行的時候,外部outer請求的inner是TestOne下的,
雖然TestOne類下的inner,只能作用于TestOne下的測驗函式,但是,由于測驗函式請求了
外部的outer,所以,外部的outer也就可以請到內部的inner,
官方還給出一個示意圖,可以結合著上述的思路,理解一下,

注意,fixture定義的范圍與它將被實體化的順序無關:實體化順序由呼叫邏輯強制執行(可以參考這篇),
二、跨檔案共享fixtures
如果你把fixture函式放到conftest.py檔案中,那么在這個檔案所在的整個目錄下,都可以直接請求里面的fixture,不需要匯入,
在實際場景中,我們的測驗目錄或者包可能有多層的嵌套,這種情況下,每個目錄都可以有一個自己的conftest檔案,
比如,像這樣:

各層級里的內容是這樣的:
tests/
__init__.py
conftest.py
# content of tests/conftest.py
import pytest
@pytest.fixture
def order():
return []
@pytest.fixture
def top(order, innermost):
order.append("top")
test_top.py
# content of tests/test_top.py
import pytest
@pytest.fixture
def innermost(order):
order.append("innermost top")
def test_order(order, top):
assert order == ["innermost top", "top"]
subpackage/
__init__.py
conftest.py
# content of tests/subpackage/conftest.py
import pytest
@pytest.fixture
def mid(order):
order.append("mid subpackage")
test_subpackage.py
# content of tests/subpackage/test_subpackage.py
import pytest
@pytest.fixture
def innermost(order, mid):
order.append("innermost subpackage")
def test_order(order, top):
assert order == ["mid subpackage", "innermost subpackage", "top"]
同樣的,這里也有一張作用域邊界圖幫助理解,

知識點:
- 頂層下的
conftest里的order和top對當前層和下層級的所有可用(一個圈就對應各自的作用域), - 測驗函式只可以向上層級搜索可用的fixture函式(出圈),但是出圈查找的程序中,不能再進到別的圈子向下查找,
所以,tests/subpackage/test_subpackage.py::test_order可以找到定義在tests/subpackage/test_subpackage.py里的innermost,
但是,另一個定義在tests/test_top.py中,名字也叫innermost的fixture,對test_order來說就不可用了,
其實對于上述,按照我的白話來說,想用conftest里的fixture函式,你只能用同層級或者上層級的,但是上級里的其他兄弟目錄或者包,以及他們
的下層級的conftest,你是不能用的,
但是讀了官方檔案,我覺得官方的那個圈子描述挺不錯的,更嚴謹,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/279784.html
標籤:其他
上一篇:SQL注入常用爆庫陳述句
