API 參考¶
此頁包含 pytest API 的完整參考。
常數¶
pytest.__version__¶
目前的 pytest 版本,以字串形式表示
>>> import pytest
>>> pytest.__version__
'7.0.0'
pytest.version_tuple¶
在版本 7.0 中新增。
目前的 pytest 版本,以元組形式表示
>>> import pytest
>>> pytest.version_tuple
(7, 0, 0)
對於預發佈版本,最後一個組件將是包含預發佈版本的字串
>>> import pytest
>>> pytest.version_tuple
(7, 0, '0rc1')
函數¶
pytest.approx¶
- approx(expected, rel=None, abs=None, nan_ok=False)[source]¶
斷言兩個數字(或兩個有序的數字序列)在一定容差範圍內彼此相等。
由於 浮點算術:問題和限制,我們直覺上預期相等的數字並不總是如此
>>> 0.1 + 0.2 == 0.3 False
這個問題在編寫測試時很常見,例如,當確保浮點值是您期望的值時。 解決這個問題的一種方法是斷言兩個浮點數在某個適當的容差範圍內相等
>>> abs((0.1 + 0.2) - 0.3) < 1e-6 True
然而,像這樣的比較很繁瑣且難以理解。 此外,通常不鼓勵像上面這樣的絕對比較,因為沒有適用於所有情況的容差。
1e-6
對於 1 左右的數字來說很好,但對於非常大的數字來說太小,對於非常小的數字來說又太大。 最好將容差表示為期望值的分數,但像這樣的相對比較更難以正確且簡潔地編寫。approx
類別使用盡可能直觀的語法執行浮點比較>>> from pytest import approx >>> 0.1 + 0.2 == approx(0.3) True
相同的語法也適用於有序的數字序列
>>> (0.1 + 0.2, 0.2 + 0.4) == approx((0.3, 0.6)) True
numpy
陣列>>> import numpy as np >>> np.array([0.1, 0.2]) + np.array([0.2, 0.4]) == approx(np.array([0.3, 0.6])) True
以及針對標量的
numpy
陣列>>> import numpy as np >>> np.array([0.1, 0.2]) + np.array([0.2, 0.1]) == approx(0.3) True
僅支援有序序列,因為
approx
需要推斷序列的相對位置而沒有歧義。 這表示不支援sets
和其他無序序列。最後,也可以比較字典值
>>> {'a': 0.1 + 0.2, 'b': 0.2 + 0.4} == approx({'a': 0.3, 'b': 0.6}) True
如果兩個映射具有相同的鍵,並且它們各自的值與預期的容差匹配,則比較結果為 true。
容差
預設情況下,
approx
認為數字在其預期值的1e-6
相對容差(即百萬分之一)內是相等的。 如果預期值為0.0
,則這種處理方式會導致令人驚訝的結果,因為只有0.0
本身相對接近0.0
。 為了更不令人意外地處理這種情況,approx
也認為數字在其預期值的1e-12
絕對容差內是相等的。 無窮大和 NaN 是特殊情況。 無論相對容差如何,無窮大僅被視為等於自身。 預設情況下,NaN 不被視為等於任何值,但您可以將nan_ok
引數設定為 True,使其等於自身。 (這旨在方便比較使用 NaN 表示「無資料」的陣列。)相對容差和絕對容差都可以透過將引數傳遞給
approx
建構函式來更改>>> 1.0001 == approx(1) False >>> 1.0001 == approx(1, rel=1e-3) True >>> 1.0001 == approx(1, abs=1e-3) True
如果您指定
abs
但未指定rel
,則比較將完全不考慮相對容差。 換句話說,如果兩個數字在1e-6
的預設相對容差範圍內,但超過指定的絕對容差,則仍將被視為不相等。 如果您同時指定abs
和rel
,則如果滿足任一容差,則數字將被視為相等>>> 1 + 1e-8 == approx(1) True >>> 1 + 1e-8 == approx(1, abs=1e-12) False >>> 1 + 1e-8 == approx(1, rel=1e-6, abs=1e-12) True
您也可以使用
approx
來比較非數值類型,或包含非數值類型的字典和序列,在這種情況下,它會回退到嚴格相等。 這對於比較可以包含可選值的字典和序列非常有用>>> {"required": 1.0000005, "optional": None} == approx({"required": 1, "optional": None}) True >>> [None, 1.0000005] == approx([None,1]) True >>> ["foo", 1.0000005] == approx([None,1]) False
如果您正在考慮使用
approx
,那麼您可能想知道它與其他比較浮點數的好方法相比如何。 所有這些演算法都基於相對容差和絕對容差,並且在大多數情況下應該一致,但它們確實有意義的差異math.isclose(a, b, rel_tol=1e-9, abs_tol=0.0)
:如果相對於a
或b
滿足相對容差,或者滿足絕對容差,則為 True。 因為相對容差是相對於a
和b
計算的,所以這個測試是對稱的(即a
和b
都不是「參考值」)。 如果您要與0.0
進行比較,則必須指定絕對容差,因為預設情況下沒有容差。 更多資訊:math.isclose()
。numpy.isclose(a, b, rtol=1e-5, atol=1e-8)
:如果a
和b
之間的差異小於相對於b
的相對容差和絕對容差之和,則為 True。 因為相對容差僅相對於b
計算,所以這個測試是不對稱的,您可以將b
視為參考值。 比較序列的支援由numpy.allclose()
提供。 更多資訊:numpy.isclose。unittest.TestCase.assertAlmostEqual(a, b)
:如果a
和b
在1e-7
的絕對容差範圍內,則為 True。 不考慮相對容差,因此此函數不適用於非常大或非常小的數字。 此外,它僅在unittest.TestCase
的子類別中可用,並且由於它不遵循 PEP8 而顯得很難看。 更多資訊:unittest.TestCase.assertAlmostEqual()
。a == pytest.approx(b, rel=1e-6, abs=1e-12)
:如果相對於b
滿足相對容差,或者滿足絕對容差,則為 True。 因為相對容差僅相對於b
計算,所以這個測試是不對稱的,您可以將b
視為參考值。 在您明確指定絕對容差但不指定相對容差的特殊情況下,僅考慮絕對容差。
注意
approx
可以處理 numpy 陣列,但如果您需要支援比較、NaN 或基於 ULP 的容差,我們建議使用 測試支援 (numpy.testing) 中的專用測試輔助程式。若要使用正則表達式匹配字串,您可以使用 Matches,來自 re_assert 套件。
警告
在版本 3.2 中變更。
為了避免不一致的行為,對於
>
、>=
、<
和<=
比較,會引發TypeError
。 下面的範例說明了問題assert approx(0.1) > 0.1 + 1e-10 # calls approx(0.1).__gt__(0.1 + 1e-10) assert 0.1 + 1e-10 > approx(0.1) # calls approx(0.1).__lt__(0.1 + 1e-10)
在第二個範例中,人們期望調用
approx(0.1).__le__(0.1 + 1e-10)
。 但實際上,approx(0.1).__lt__(0.1 + 1e-10)
用於比較。 這是因為豐富比較的調用層次結構遵循固定的行為。 更多資訊:object.__ge__()
在版本 3.7.1 中變更:當
approx
遇到非數值類型的字典值或序列元素時,會引發TypeError
。在版本 6.1.0 中變更:
approx
對於非數值類型,會回退到嚴格相等,而不是引發TypeError
。
pytest.fail¶
教學:如何使用 skip 和 xfail 來處理無法成功的測試
- fail(reason[, pytrace=True])[source]¶
使用給定的訊息明確地讓正在執行的測試失敗。
- 參數:
- 引發:
pytest.fail.Exception – 引發的例外狀況。
- class pytest.fail.Exception¶
pytest.fail()
引發的例外狀況。
pytest.skip¶
- skip(reason[, allow_module_level=False])[source]¶
使用給定的訊息跳過正在執行的測試。
此函數應僅在測試期間(setup、call 或 teardown)或在收集期間使用
allow_module_level
標誌調用。 此函數也可以在 doctests 中調用。- 參數:
- 引發:
pytest.skip.Exception – 引發的例外狀況。
注意
當可能時,最好使用 pytest.mark.skipif 標記來聲明在某些條件下(例如平台或依賴項不匹配)要跳過的測試。 同樣地,使用
# doctest: +SKIP
指令(請參閱doctest.SKIP
)以靜態方式跳過 doctest。
- class pytest.skip.Exception¶
pytest.skip()
引發的例外狀況。
pytest.importorskip¶
- importorskip(modname, minversion=None, reason=None, *, exc_type=None)[source]¶
匯入並傳回請求的模組
modname
,如果無法匯入模組,則跳過當前測試。- 參數:
modname (str) – 要匯入的模組名稱。
minversion (str | None) – 如果給定,則匯入模組的
__version__
屬性必須至少為此最小版本,否則測試仍會跳過。reason (str | None) – 如果給定,則當無法匯入模組時,此原因會顯示為訊息。
exc_type (type[ImportError] | None) –
為了跳過模組而應捕獲的例外狀況。 必須是
ImportError
或子類別。如果可以匯入模組但引發
ImportError
,pytest 將向使用者發出警告,因為使用者通常希望找不到該模組(這將引發ModuleNotFoundError
)。可以透過明確傳遞
exc_type=ImportError
來抑制此警告。有關詳細資訊,請參閱 關於 ImportError 的 pytest.importorskip 預設行為。
- 傳回:
匯入的模組。 這應該分配給其規範名稱。
- 引發:
pytest.skip.Exception – 如果無法匯入模組。
- 傳回類型:
範例
docutils = pytest.importorskip("docutils")
在版本 8.2 中新增:
exc_type
參數。
pytest.xfail¶
- xfail(reason='')[source]¶
使用給定的原因以命令方式 xfail 正在執行的測試或 setup 函數。
此函數應僅在測試期間(setup、call 或 teardown)調用。
在使用
xfail()
之後,不會執行其他任何程式碼(它在內部透過引發例外狀況來實現)。- 參數:
reason (str) – 向使用者顯示作為 xfail 原因的訊息。
注意
當可能時,最好使用 pytest.mark.xfail 標記來聲明在某些條件下(例如已知錯誤或缺少功能)要 xfailed 的測試。
- 引發:
pytest.xfail.Exception – 引發的例外狀況。
- class pytest.xfail.Exception¶
pytest.xfail()
引發的例外狀況。
pytest.exit¶
- exit(reason[, returncode=None])[source]¶
退出測試程序。
- 參數:
reason (str) – 顯示為退出 pytest 原因的訊息。 reason 具有預設值只是因為
msg
已棄用。returncode (int | None) – 退出 pytest 時要使用的傳回代碼。 None 與
0
(無錯誤)相同,與sys.exit()
相同。
- 引發:
pytest.exit.Exception – 引發的例外狀況。
- class pytest.exit.Exception¶
pytest.exit()
引發的例外狀況。
pytest.main¶
pytest.param¶
- param(*values[, id][, marks])[source]¶
在 pytest.mark.parametrize 調用或 參數化 fixtures 中指定參數。
@pytest.mark.parametrize( "test_input,expected", [ ("3+5", 8), pytest.param("6*9", 42, marks=pytest.mark.xfail), ], ) def test_eval(test_input, expected): assert eval(test_input) == expected
- 參數:
values (object) – 參數集值的變數 args,依序排列。
marks (MarkDecorator | Collection[MarkDecorator | Mark]) – 要應用於此參數集的單個標記或標記列表。
id (str | None) – 要歸因於此參數集的 ID。
pytest.raises¶
教學:關於預期例外狀況的斷言
- with raises(expected_exception: type[E] | tuple[type[E], ...], *, match: str | Pattern[str] | None = ...) RaisesContext[E] as excinfo[source]¶
- with raises(expected_exception: type[E] | tuple[type[E], ...], func: Callable[[...], Any], *args: Any, **kwargs: Any) ExceptionInfo[E] as excinfo
斷言程式碼區塊/函式呼叫會引發例外類型,或是其子類別之一。
- 參數:
expected_exception – 預期的例外類型,或是在預期多種可能例外類型時的元組。請注意,傳入例外項目的子類別也會符合。
match (str | re.Pattern[str] | None) –
如果指定,則為包含正規表示式的字串,或是正規表示式物件,會針對例外及其 PEP 678
__notes__
的字串表示形式,使用re.search()
進行測試。若要比對可能包含 特殊字元 的文字字串,可以先使用
re.escape()
跳脫模式。(這僅在
pytest.raises
作為上下文管理器使用時使用,否則會傳遞至函式。當使用pytest.raises
作為函式時,您可以使用:pytest.raises(Exc, func, match="passed on").match("my pattern")
。)
將
pytest.raises
作為上下文管理器使用,這將會捕獲給定類型或其任何子類別的例外>>> import pytest >>> with pytest.raises(ZeroDivisionError): ... 1/0
如果程式碼區塊未引發預期的例外 (
ZeroDivisionError
在以上範例中),或是完全沒有例外,則檢查會改為失敗。您也可以使用關鍵字引數
match
來斷言例外是否符合文字或正規表示式>>> with pytest.raises(ValueError, match='must be 0 or None'): ... raise ValueError("value must be 0 or None") >>> with pytest.raises(ValueError, match=r'must be \d+$'): ... raise ValueError("value must be 42")
match
引數會搜尋格式化的例外字串,其中包含任何 PEP-678__notes__
>>> with pytest.raises(ValueError, match=r"had a note added"): ... e = ValueError("value must be 42") ... e.add_note("had a note added") ... raise e
上下文管理器會產生
ExceptionInfo
物件,可用於檢查捕獲的例外詳細資訊>>> with pytest.raises(ValueError) as exc_info: ... raise ValueError("value must be 42") >>> assert exc_info.type is ValueError >>> assert exc_info.value.args[0] == "value must be 42"
警告
鑑於
pytest.raises
會比對子類別,請謹慎使用它來比對Exception
,如下所示with pytest.raises(Exception): # Careful, this will catch ANY exception raised. some_function()
因為
Exception
幾乎是所有例外的基底類別,因此很容易隱藏真正的錯誤,使用者撰寫此程式碼時預期會發生特定的例外,但由於重構期間引入的錯誤而引發了其他例外。除非確定您真的想要捕獲任何引發的例外,否則請避免使用
pytest.raises
來捕獲Exception
。注意
當使用
pytest.raises
作為上下文管理器時,值得注意的是,一般的上下文管理器規則適用,且引發的例外必須是上下文管理器範圍中的最後一行。在上下文管理器範圍內,在此之後的程式碼行將不會執行。例如>>> value = 15 >>> with pytest.raises(ValueError) as exc_info: ... if value > 10: ... raise ValueError("value must be <= 10") ... assert exc_info.type is ValueError # This will not execute.
相反地,必須採取以下方法 (請注意範圍的差異)
>>> with pytest.raises(ValueError) as exc_info: ... if value > 10: ... raise ValueError("value must be <= 10") ... >>> assert exc_info.type is ValueError
使用 with
pytest.mark.parametrize
當使用 pytest.mark.parametrize 時,可以參數化測試,使某些執行引發例外,而另一些則不引發。
請參閱 參數化條件式引發 以取得範例。
另請參閱
關於預期例外的斷言 以取得更多範例和詳細討論。
舊版形式
可以透過傳遞要呼叫的 lambda 來指定可呼叫物件
>>> raises(ZeroDivisionError, lambda: 1/0) <ExceptionInfo ...>
或者您可以指定具有引數的任意可呼叫物件
>>> def f(x): return 1/x ... >>> raises(ZeroDivisionError, f, 0) <ExceptionInfo ...> >>> raises(ZeroDivisionError, f, x=0) <ExceptionInfo ...>
以上形式完全支援,但不建議用於新程式碼,因為上下文管理器形式被認為更具可讀性且更不易出錯。
注意
與 Python 中捕獲的例外物件類似,明確清除對傳回的
ExceptionInfo
物件的本機參照,可以協助 Python 直譯器加速其垃圾回收。清除這些參照會中斷參照循環 (
ExceptionInfo
–> 捕獲的例外 –> 引發例外的框架堆疊 –> 目前框架堆疊 –> 本機變數 –>ExceptionInfo
),這會使 Python 保留從該循環參照的所有物件 (包括目前框架中的所有本機變數) 處於活動狀態,直到下一次循環垃圾回收執行。更多詳細資訊可以在 Python 官方文件中找到 try 陳述式。
pytest.deprecated_call¶
教學課程:確保程式碼觸發棄用警告
- with deprecated_call(*, match: str | Pattern[str] | None = ...) WarningsRecorder [source]¶
- with deprecated_call(func: Callable[[...], T], *args: Any, **kwargs: Any) T
斷言程式碼產生
DeprecationWarning
或PendingDeprecationWarning
或FutureWarning
。此函式可以用作上下文管理器
>>> import warnings >>> def api_call_v2(): ... warnings.warn('use v3 of this api', DeprecationWarning) ... return 200 >>> import pytest >>> with pytest.deprecated_call(): ... assert api_call_v2() == 200
也可以透過傳遞函式和
*args
和**kwargs
來使用,在這種情況下,它將確保呼叫func(*args, **kwargs)
產生上述警告類型之一。傳回值是函式的傳回值。在上下文管理器形式中,您可以使用關鍵字引數
match
來斷言警告是否符合文字或正規表示式。上下文管理器會產生
warnings.WarningMessage
物件的清單,每個引發的警告各一個。
pytest.register_assert_rewrite¶
教學課程:斷言重寫
pytest.warns¶
教學課程:使用 warns 函式斷言警告
- with warns(expected_warning: type[Warning] | tuple[type[Warning], ...] = <class 'Warning'>, *, match: str | ~typing.Pattern[str] | None = None) WarningsChecker [source]¶
- with warns(expected_warning: type[Warning] | tuple[type[Warning], ...], func: Callable[[...], T], *args: Any, **kwargs: Any) T
斷言程式碼引發特定類別的警告。
具體來說,參數
expected_warning
可以是警告類別或警告類別的元組,並且with
區塊內的程式碼必須發出至少一個該類別或類別的警告。此輔助程式會產生
warnings.WarningMessage
物件的清單,每個發出的警告各一個 (無論它是否為expected_warning
)。從 pytest 8.0 開始,不符的警告也會在上下文關閉時重新發出。此函式可以用作上下文管理器
>>> import pytest >>> with pytest.warns(RuntimeWarning): ... warnings.warn("my warning", RuntimeWarning)
在上下文管理器形式中,您可以使用關鍵字引數
match
來斷言警告是否符合文字或正規表示式。>>> with pytest.warns(UserWarning, match='must be 0 or None'): ... warnings.warn("value must be 0 or None", UserWarning) >>> with pytest.warns(UserWarning, match=r'must be \d+$'): ... warnings.warn("value must be 42", UserWarning) >>> with pytest.warns(UserWarning): # catch re-emitted warning ... with pytest.warns(UserWarning, match=r'must be \d+$'): ... warnings.warn("this is not here", UserWarning) Traceback (most recent call last): ... Failed: DID NOT WARN. No warnings of type ...UserWarning... were emitted...
使用 with
pytest.mark.parametrize
當使用 pytest.mark.parametrize 時,可以參數化測試,使某些執行引發警告,而另一些則不引發。
這可以透過與例外相同的方式達成,請參閱 參數化條件式引發 以取得範例。
pytest.freeze_includes¶
教學課程:凍結 pytest
標記¶
標記可用於將元資料套用至測試函式 (但不能用於夾具),然後可以由夾具或外掛程式存取。
pytest.mark.filterwarnings¶
教學課程:@pytest.mark.filterwarnings
將警告篩選器新增至標記的測試項目。
pytest.mark.parametrize¶
教學課程:如何參數化夾具和測試函式
此標記具有與 pytest.Metafunc.parametrize()
相同的簽名;請參閱該處。
pytest.mark.skip¶
教學課程:跳過測試函式
無條件跳過測試函式。
pytest.mark.skipif¶
教學課程:跳過測試函式
如果條件為 True
,則跳過測試函式。
pytest.mark.usefixtures¶
教學課程:在類別和模組中使用 usefixtures 的夾具
將測試函式標記為使用給定的夾具名稱。
- pytest.mark.usefixtures(*names)¶
- 參數:
args – 要使用的夾具名稱,以字串表示。
注意
當在 Hook 中使用 usefixtures
時,它只能在套用至測試設定之前的測試函式時載入夾具 (例如在 pytest_collection_modifyitems
Hook 中)。
另請注意,此標記套用至夾具時無效。
pytest.mark.xfail¶
教學課程:XFail:將測試函式標記為預期會失敗
將測試函式標記為預期會失敗。
- pytest.mark.xfail(condition=False, *, reason=None, raises=None, run=True, strict=xfail_strict)¶
- 參數:
condition (Union[bool, str]) – 將測試函式標記為 xfail 的條件 (
True/False
或 條件字串)。如果為bool
,您也必須指定reason
(請參閱 條件字串)。reason (str) – 測試函式標記為 xfail 的原因。
raises (Type[
Exception
]) – 預期由測試函式引發的例外類別 (或類別元組);其他例外會使測試失敗。請注意,傳遞類別的子類別也會導致符合 (類似於except
陳述式的運作方式)。run (bool) – 測試函式是否應實際執行。如果為
False
,則函式將始終 xfail 且不會執行 (如果函式發生區段錯誤,則很有用)。strict (bool) –
如果為
False
,則函式在終端輸出中會顯示為xfailed
(如果失敗) 和xpass
(如果通過)。在這兩種情況下,這都不會導致測試套件整體失敗。這對於標記不穩定測試 (隨機失敗的測試) 以便稍後處理特別有用。如果為
True
,則函式在終端輸出中會顯示為xfailed
(如果失敗),但如果意外通過,則會使測試套件失敗。這對於標記始終失敗的函式特別有用,如果它們意外開始通過,則應有明確的指示 (例如,新版本的程式庫修正了已知的錯誤)。
預設為
xfail_strict
,預設為False
。
自訂標記¶
標記是使用 factory 物件 pytest.mark
動態建立的,並作為裝飾器套用。
例如
@pytest.mark.timeout(10, "slow", method="thread")
def test_function(): ...
將建立 Mark
物件並將其附加到收集的 Item
,然後可以使用 Node.iter_markers
,透過夾具或 Hook 存取。 mark
物件將具有以下屬性
mark.args == (10, "slow")
mark.kwargs == {"method": "thread"}
使用多個自訂標記的範例
@pytest.mark.timeout(10, "slow", method="thread")
@pytest.mark.slow
def test_function(): ...
當 Node.iter_markers
或 Node.iter_markers_with_node
與多個標記一起使用時,最靠近函式的標記將首先被迭代。以上範例將產生 @pytest.mark.slow
,然後是 @pytest.mark.timeout(...)
。
夾具¶
教學課程:夾具參考
夾具由測試函式或其他夾具透過將其宣告為引數名稱來請求。
需要夾具的測試範例
def test_output(capsys):
print("hello")
out, err = capsys.readouterr()
assert out == "hello\n"
需要另一個夾具的夾具範例
@pytest.fixture
def db_session(tmp_path):
fn = tmp_path / "db.file"
return connect(fn)
如需更多詳細資訊,請參閱完整的 夾具文件。
@pytest.fixture¶
- @fixture(fixture_function: FixtureFunction, *, scope: Literal['session', 'package', 'module', 'class', 'function'] | Callable[[str, Config], Literal['session', 'package', 'module', 'class', 'function']] = 'function', params: Iterable[object] | None = None, autouse: bool = False, ids: Sequence[object | None] | Callable[[Any], object | None] | None = None, name: str | None = None) FixtureFunction [source]¶
- @fixture(fixture_function: None = None, *, scope: Literal['session', 'package', 'module', 'class', 'function'] | Callable[[str, Config], Literal['session', 'package', 'module', 'class', 'function']] = 'function', params: Iterable[object] | None = None, autouse: bool = False, ids: Sequence[object | None] | Callable[[Any], object | None] | None = None, name: str | None = None) FixtureFunctionMarker
用來標記 fixture 工廠函數的裝飾器。
此裝飾器可以帶參數或不帶參數使用,以定義 fixture 函數。
fixture 函數的名稱稍後可以被引用,以使其在執行測試之前被調用:測試模組或類別可以使用
pytest.mark.usefixtures(fixturename)
標記。測試函數可以直接使用 fixture 名稱作為輸入參數,在這種情況下,將注入從 fixture 函數返回的 fixture 實例。
Fixture 可以使用
return
或yield
語句將其值提供給測試函數。當使用yield
時,yield
語句之後的程式碼區塊將作為 teardown 程式碼執行,無論測試結果如何,並且必須只 yield 一次。- 參數:
scope –
此 fixture 共用的範圍;可以是
"function"
(預設值)、"class"
、"module"
、"package"
或"session"
其中之一。此參數也可以是一個可調用物件,它接收
(fixture_name, config)
作為參數,並且必須返回一個str
,其值為上述值之一。有關更多資訊,請參閱文件中的 動態範圍。
params – 參數的可選列表,它將導致 fixture 函數及其所有使用它的測試被多次調用。目前的參數在
request.param
中可用。autouse – 如果為 True,則 fixture func 會針對所有可以看到它的測試啟動。如果為 False (預設值),則需要顯式引用才能啟動 fixture。
ids – IDs 的序列,每個 ID 對應於 params,以便它們成為測試 ID 的一部分。如果未提供 IDs,它們將從 params 自動生成。
name – fixture 的名稱。預設為裝飾函數的名稱。如果 fixture 在定義它的同一個模組中使用,則 fixture 的函數名稱將被請求 fixture 的函數參數遮蔽;一種解決此問題的方法是將裝飾函數命名為
fixture_<fixturename>
,然後使用@pytest.fixture(name='<fixturename>')
。
capfd¶
- capfd()[source]¶
啟用對檔案描述器
1
和2
寫入的文字捕捉。捕捉到的輸出可通過
capfd.readouterr()
方法呼叫取得,該方法呼叫返回一個(out, err)
具名元組。out
和err
將會是text
物件。返回
CaptureFixture[str]
的實例。範例
def test_system_echo(capfd): os.system('echo "hello"') captured = capfd.readouterr() assert captured.out == "hello\n"
capfdbinary¶
- capfdbinary()[source]¶
啟用對檔案描述器
1
和2
寫入的位元組捕捉。捕捉到的輸出可通過
capfd.readouterr()
方法呼叫取得,該方法呼叫返回一個(out, err)
具名元組。out
和err
將會是byte
物件。返回
CaptureFixture[bytes]
的實例。範例
def test_system_echo(capfdbinary): os.system('echo "hello"') captured = capfdbinary.readouterr() assert captured.out == b"hello\n"
caplog¶
教學: 如何管理日誌記錄
- caplog()[source]¶
存取和控制日誌捕捉。
捕捉到的日誌可通過以下屬性/方法取得
* caplog.messages -> list of format-interpolated log messages * caplog.text -> string containing formatted log output * caplog.records -> list of logging.LogRecord instances * caplog.record_tuples -> list of (logger_name, level, message) tuples * caplog.clear() -> clear captured records and formatted log output string
返回
pytest.LogCaptureFixture
實例。
- final class LogCaptureFixture[source]¶
提供日誌捕捉的存取和控制。
- property handler: LogCaptureHandler¶
取得 fixture 使用的日誌處理器。
- get_records(when)[source]¶
取得可能測試階段之一的日誌記錄。
- 參數:
when (Literal['setup', 'call', 'teardown']) – 要從哪個測試階段取得記錄。有效值為:「setup」、「call」和「teardown」。
- 傳回:
在給定階段捕捉到的記錄列表。
- 傳回類型:
在 3.4 版本中新增。
- property record_tuples: list[tuple[str, int, str]]¶
為用於斷言比較而設計的精簡版日誌記錄列表。
元組的格式為
(logger_name, log_level, message)
- property messages: list[str]¶
格式插值後的日誌訊息列表。
與 ‘records’ 不同,後者包含格式字串和用於插值的參數,此列表中的日誌訊息都是經過插值處理的。
與 ‘text’ 不同,後者包含來自處理器的輸出,此列表中的日誌訊息沒有修飾層級、時間戳記等,使得精確比較更可靠。
請注意,追溯或堆疊資訊 (來自
logging.exception()
或日誌函數的exc_info
或stack_info
參數) 不包含在內,因為這是由處理器中的格式器添加的。在 3.7 版本中新增。
- set_level(level, logger=None)[source]¶
為測試期間設定 logger 的閾值層級。
嚴重性低於此層級的日誌訊息將不會被捕捉。
在 3.4 版本中變更:由此函數變更的 logger 層級將在測試結束時還原為其初始值。
如果請求的日誌記錄層級已通過
logging.disable()
停用,則將啟用該層級。
- with at_level(level, logger=None)[source]¶
設定日誌捕捉層級的上下文管理器。在 ‘with’ 語句結束後,層級將還原為其原始值。
如果請求的日誌記錄層級已通過
logging.disable()
停用,則將啟用該層級。
- with filtering(filter_)[source]¶
上下文管理器,用於在 ‘with’ 語句區塊中暫時將給定的篩選器添加到 caplog 的
handler()
,並在區塊結束時移除該篩選器。- 參數:
filter – 自訂
logging.Filter
物件。
在 7.5 版本中新增。
capsys¶
- capsys()[source]¶
啟用對
sys.stdout
和sys.stderr
寫入的文字捕捉。捕捉到的輸出可通過
capsys.readouterr()
方法呼叫取得,該方法呼叫返回一個(out, err)
具名元組。out
和err
將會是text
物件。返回
CaptureFixture[str]
的實例。範例
def test_output(capsys): print("hello") captured = capsys.readouterr() assert captured.out == "hello\n"
- class CaptureFixture[source]¶
由
capsys
、capsysbinary
、capfd
和capfdbinary
fixture 返回的物件。
capsysbinary¶
- capsysbinary()[source]¶
啟用對
sys.stdout
和sys.stderr
寫入的位元組捕捉。擷取的輸出可透過
capsysbinary.readouterr()
方法呼叫取得,此方法呼叫會回傳一個(out, err)
具名元組。out
和err
將會是bytes
物件。返回
CaptureFixture[bytes]
的實例。範例
def test_output(capsysbinary): print("hello") captured = capsysbinary.readouterr() assert captured.out == b"hello\n"
config.cache¶
config.cache
物件允許其他外掛程式和 fixture 跨測試執行儲存和檢索值。若要從 fixture 存取它,請在您的 fixture 中請求 pytestconfig
,並使用 pytestconfig.cache
取得它。
在底層,快取外掛程式使用 json
stdlib 模組的簡單 dumps
/loads
API。
config.cache
是 pytest.Cache
的實例。
- final class Cache[source]¶
cache
fixture 的實例。- mkdir(name)[source]¶
傳回具有指定名稱的目錄路徑物件。
如果目錄尚不存在,將會建立它。您可以使用它來管理檔案,例如在測試階段之間儲存/檢索資料庫傾印。
在版本 7.0 中新增。
- 參數:
name (str) – 必須是不包含
/
分隔符號的字串。請確保名稱包含您的外掛程式或應用程式識別符,以防止與其他快取使用者發生衝突。
doctest_namespace¶
教學:如何執行 doctest
- doctest_namespace()[source]¶
Fixture,傳回一個
dict
,將會注入到 doctest 的命名空間中。通常此 fixture 會與另一個
autouse
fixture 一起使用@pytest.fixture(autouse=True) def add_np(doctest_namespace): doctest_namespace["np"] = numpy
如需更多詳細資訊:‘doctest_namespace’ fixture。
monkeypatch¶
- monkeypatch()[source]¶
用於 monkey-patching 的便利 fixture。
此 fixture 提供以下方法來修改物件、字典或
os.environ
所有修改將在請求測試函式或 fixture 完成後還原。
raising
參數決定如果設定/刪除操作沒有指定的目標,是否會引發KeyError
或AttributeError
。若要在包含的範圍內還原 fixture 所做的修改,請使用
context()
。傳回
MonkeyPatch
實例。
- final class MonkeyPatch[source]¶
方便地 monkeypatch 屬性/項目/環境變數/syspath 的輔助程式。
由
monkeypatch
fixture 傳回。在 6.2 版本變更: 現在也可以直接作為
pytest.MonkeyPatch()
使用,用於 fixture 無法使用的情況。在這種情況下,請使用with MonkeyPatch.context() as mp:
或記得明確呼叫undo()
。- classmethod with context()[source]¶
情境管理器,傳回一個新的
MonkeyPatch
物件,該物件會在退出時還原在with
區塊內完成的任何修補。範例
import functools def test_partial(monkeypatch): with monkeypatch.context() as m: m.setattr(functools, "partial", 3)
在需要在測試結束前還原某些修補程式的情況下很有用,例如 mock 可能會破壞 pytest 本身的
stdlib
函式(有關範例,請參閱 #3290)。
- setattr(target: str, name: object, value: ~_pytest.monkeypatch.Notset = <notset>, raising: bool = True) None [source]¶
- setattr(target: object, name: str, value: object, raising: bool = True) None
在目標上設定屬性值,並記住舊值。
例如
import os monkeypatch.setattr(os, "getcwd", lambda: "/")
上面的程式碼將
os.getcwd()
函式替換為始終傳回"/"
的lambda
。為了方便起見,您可以將字串指定為
target
,它將被解讀為虛線匯入路徑,最後一部分是屬性名稱monkeypatch.setattr("os.getcwd", lambda: "/")
如果屬性不存在,則引發
AttributeError
,除非將raising
設定為 False。修補的位置
monkeypatch.setattr
的運作方式是(暫時)將名稱指向的物件替換為另一個物件。可能有許多名稱指向任何單一物件,因此為了使修補生效,您必須確保修補測試系統使用的名稱。請參閱 Where to patch 章節,在
unittest.mock
文件中,以獲得完整的說明,該說明是針對unittest.mock.patch()
而設計的,但也適用於monkeypatch.setattr
。
- delattr(target, name=<notset>, raising=True)[source]¶
從
target
刪除屬性name
。如果未指定
name
且target
是字串,它將被解讀為虛線匯入路徑,最後一部分是屬性名稱。如果屬性不存在,則引發 AttributeError,除非將
raising
設定為 False。
- delitem(dic, name, raising=True)[source]¶
從 dict 刪除
name
。如果它不存在,則引發
KeyError
,除非將raising
設定為 False。
pytestconfig¶
- pytestconfig()[source]¶
Session 範圍的 fixture,傳回 session 的
pytest.Config
物件。範例
def test_foo(pytestconfig): if pytestconfig.get_verbosity() > 0: ...
pytester¶
在 6.2 版本中新增。
提供 Pytester
實例,可用於執行和測試 pytest 本身。
它提供一個空的目錄,pytest 可以在其中隔離執行,並包含用於寫入測試、組態檔以及比對預期輸出的工具。
若要使用它,請包含在最上層的 conftest.py
檔案中
pytest_plugins = "pytester"
- final class Pytester[source]¶
用於寫入測試/組態檔、隔離執行 pytest 以及比對預期輸出的工具,非常適合 pytest 外掛程式的黑箱測試。
它嘗試盡可能地將測試執行與外部因素隔離,在初始化期間將目前的工作目錄修改為
path
和環境變數。- plugins: list[str | object]¶
要與
parseconfig()
和runpytest()
一起使用的外掛程式清單。最初這是一個空清單,但可以將外掛程式新增至清單。要新增至清單的項目類型取決於使用它們的方法,因此請參閱它們以獲取詳細資訊。
- make_hook_recorder(pluginmanager)[source]¶
為
PytestPluginManager
建立新的HookRecorder
。
- makefile(ext, *args, **kwargs)[source]¶
在測試目錄中建立新的文字檔。
- 參數:
- 傳回:
第一個建立的檔案。
- 傳回類型:
範例
pytester.makefile(".txt", "line1", "line2") pytester.makefile(".ini", pytest="[pytest]\naddopts=-rs\n")
若要建立二進位檔案,請直接使用
pathlib.Path.write_bytes()
filename = pytester.path.joinpath("foo.bin") filename.write_bytes(b"...")
- makepyfile(*args, **kwargs)[source]¶
使用 .py 副檔名的 .makefile() 捷徑。
預設為具有 ‘.py’ 副檔名的測試名稱,例如 test_foobar.py,覆寫現有檔案。
範例
def test_something(pytester): # Initial file is created test_something.py. pytester.makepyfile("foobar") # To create multiple files, pass kwargs accordingly. pytester.makepyfile(custom="foobar") # At this point, both 'test_something.py' & 'custom.py' exist in the test directory.
- maketxtfile(*args, **kwargs)[source]¶
使用 .txt 副檔名的 .makefile() 捷徑。
預設為具有 ‘.txt’ 副檔名的測試名稱,例如 test_foobar.txt,覆寫現有檔案。
範例
def test_something(pytester): # Initial file is created test_something.txt. pytester.maketxtfile("foobar") # To create multiple files, pass kwargs accordingly. pytester.maketxtfile(custom="foobar") # At this point, both 'test_something.txt' & 'custom.txt' exist in the test directory.
- copy_example(name=None)[source]¶
從專案目錄複製檔案到測試目錄中。
- 參數:
name (str | None) – 要複製的檔案名稱。
- 傳回:
已複製目錄的路徑(在
self.path
內)。- 傳回類型:
- getnode(config, arg)[source]¶
取得檔案的集合節點。
- 參數:
config (Config) – pytest config。請參閱
parseconfig()
和parseconfigure()
以建立它。
- 傳回:
節點。
- 傳回類型:
- getpathnode(path)[source]¶
傳回檔案的集合節點。
這類似於
getnode()
,但使用parseconfigure()
來建立(已設定的)pytest Config 實例。
- runitem(source)[source]¶
執行 “test_func” 項目。
呼叫的測試實例(包含測試方法的類別)必須提供一個
.getrunner()
方法,該方法應傳回一個執行器,可以為單個項目執行測試協定,例如_pytest.runner.runtestprotocol
。
- inline_runsource(source, *cmdlineargs)[source]¶
使用
pytest.main()
在進程中執行測試模組。此執行會將 “source” 寫入臨時檔案,並對其執行
pytest.main()
,傳回結果的HookRecorder
實例。- 參數:
source (str) – 測試模組的原始碼。
cmdlineargs – 要使用的任何額外命令列引數。
- inline_genitems(*args)[source]¶
在進程中執行
pytest.main(['--collect-only'])
。執行
pytest.main()
函數,以在測試進程本身內部執行所有 pytest,類似於inline_run()
,但傳回已收集的項目和HookRecorder
實例的元組。
- inline_run(*args, plugins=(), no_reraise_ctrlc=False)[source]¶
在進程中執行
pytest.main()
,傳回 HookRecorder。執行
pytest.main()
函數,以在測試進程本身內部執行所有 pytest。這表示它可以傳回一個HookRecorder
實例,該實例提供比從runpytest()
比對 stdout/stderr 更詳細的結果。- 參數:
args (str | PathLike[str]) – 要傳遞給
pytest.main()
的命令列引數。plugins –
pytest.main()
實例應使用的額外外掛程式實例。no_reraise_ctrlc (bool) – 通常我們會從子執行重新引發鍵盤中斷。如果為 True,則會捕獲 KeyboardInterrupt 例外。
- parseconfig(*args)[source]¶
從給定的命令列引數傳回新的 pytest
pytest.Config
實例。這會在 _pytest.config 中調用 pytest 引導程式碼,以建立新的
pytest.PytestPluginManager
並呼叫pytest_cmdline_parse
hook 以建立新的pytest.Config
實例。如果
plugins
已填入,它們應該是外掛程式模組,以便向外掛程式管理器註冊。
- parseconfigure(*args)[source]¶
傳回新的 pytest 已設定的 Config 實例。
傳回新的
pytest.Config
實例,類似於parseconfig()
,但也呼叫pytest_configure
hook。
- getitem(source, funcname='test_func')[source]¶
傳回測試函數的測試項目。
將原始碼寫入 Python 檔案,並對產生的模組執行 pytest 的集合,傳回請求的函數名稱的測試項目。
- getmodulecol(source, configargs=(), *, withinit=False)[source]¶
傳回
source
的模組集合節點。使用
makepyfile()
將source
寫入檔案,然後對其執行 pytest 集合,傳回測試模組的集合節點。- 參數:
configargs – 要傳遞給
parseconfigure()
的任何額外引數。withinit (bool) – 是否也將
__init__.py
檔案寫入同一目錄,以確保它是套件。
- collect_by_name(modcol, name)[source]¶
從模組集合傳回名稱的集合節點。
在模組集合節點中搜尋符合給定名稱的集合節點。
- 參數:
modcol (Collector) – 模組集合節點;請參閱
getmodulecol()
。name (str) – 要傳回的節點名稱。
- popen(cmdargs, stdout=-1, stderr=-1, stdin=NotSetType.token, **kw)[source]¶
調用
subprocess.Popen
。呼叫
subprocess.Popen
,確保目前的工作目錄在PYTHONPATH
中。您可能想要改用
run()
。
- run(*cmdargs, timeout=None, stdin=NotSetType.token)[source]¶
執行帶有引數的命令。
使用
subprocess.Popen
執行進程,並儲存 stdout 和 stderr。- 參數:
cmdargs (str | PathLike[str]) – 要傳遞給
subprocess.Popen
的引數序列,其中路徑類物件會自動轉換為str
。timeout (float | None) – 超時的時間段(以秒為單位),超過此時間段後會超時並引發
Pytester.TimeoutExpired
。stdin (_pytest.compat.NotSetType | bytes | IO[Any] | int) –
可選的標準輸入。
如果它是
CLOSE_STDIN
(預設值),則此方法會使用stdin=subprocess.PIPE
呼叫subprocess.Popen
,並且在啟動新命令後立即關閉標準輸入。如果它是
bytes
類型,則這些位元組會傳送到命令的標準輸入。否則,它會傳遞到
subprocess.Popen
。在這種情況下,如需更多資訊,請查閱subprocess.Popen
中stdin
參數的文件。
- 傳回:
結果。
- 傳回類型:
- runpytest_subprocess(*args, timeout=None)[source]¶
以子進程方式使用給定引數執行 pytest。
使用
-p
命令列選項新增至plugins
清單的任何外掛程式。此外,--basetemp
用於將任何臨時檔案和目錄放在以 “runpytest-” 為字首的編號目錄中,以避免與臨時檔案和目錄的正常編號 pytest 位置衝突。
- final class RunResult[source]¶
從
Pytester
執行命令的結果。- outlines¶
從 stdout 捕獲的行列表。
- errlines¶
從 stderr 捕獲的行列表。
- stdout¶
stdout 的
LineMatcher
。例如,使用
str(stdout)
來重建 stdout,或常用的stdout.fnmatch_lines()
方法。
- stderr¶
stderr 的
LineMatcher
。
- duration¶
持續時間(以秒為單位)。
- parseoutcomes()[source]¶
從剖析測試進程產生的終端輸出中,傳回結果名詞 -> 計數的字典。
傳回的名詞將始終為複數形式
======= 1 failed, 1 passed, 1 warning, 1 error in 0.13s ====
將傳回
{"failed": 1, "passed": 1, "warnings": 1, "errors": 1}
。
- class LineMatcher[source]¶
彈性的文字比對。
這是一個方便的類別,用於測試大型文字,例如命令的輸出。
建構子採用不帶尾隨換行符的行列表,即
text.splitlines()
。- fnmatch_lines_random(lines2)[source]¶
檢查行是否以任何順序存在於輸出中(使用
fnmatch.fnmatch()
)。
- re_match_lines_random(lines2)[source]¶
檢查行是否以任何順序存在於輸出中(使用
re.match()
)。
- fnmatch_lines(lines2, *, consecutive=False)[原始碼]¶
檢查行是否存在於輸出中 (使用
fnmatch.fnmatch()
)。此引數是要比對且可以使用 glob 萬用字元的行列表。如果它們不匹配,則會呼叫 pytest.fail()。匹配和不匹配的項目也會顯示為錯誤訊息的一部分。
- re_match_lines(lines2, *, consecutive=False)[原始碼]¶
檢查行是否存在於輸出中 (使用
re.match()
)。此引數是要使用
re.match
比對的行列表。如果它們不匹配,則會呼叫 pytest.fail()。匹配和不匹配的項目也會顯示為錯誤訊息的一部分。
record_property¶
教學課程: record_property
record_testsuite_property¶
教學課程: record_testsuite_property
- record_testsuite_property()[原始碼]¶
記錄新的
<property>
標籤作為根<testsuite>
的子項。這適用於寫入關於整個測試套件的全域資訊,並且與
xunit2
JUnit 系列相容。這是
session
範圍的 fixture,使用(name, value)
呼叫。範例def test_foo(record_testsuite_property): record_testsuite_property("ARCH", "PPC") record_testsuite_property("STORAGE_TYPE", "CEPH")
- 參數:
name – 屬性名稱。
value – 屬性值。將轉換為字串。
警告
目前此 fixture 不適用於 pytest-xdist 外掛程式。請參閱 #7767 以取得詳細資訊。
recwarn¶
教學課程: 記錄警告
- recwarn()[原始碼]¶
傳回
WarningsRecorder
實例,該實例會記錄測試函式發出的所有警告。請參閱 如何捕獲警告 以取得關於警告類別的資訊。
- class WarningsRecorder[原始碼]¶
用於記錄引發警告的情境管理器。
每個記錄的警告都是
warnings.WarningMessage
的實例。改編自
warnings.catch_warnings
。注意
DeprecationWarning
和PendingDeprecationWarning
的處理方式不同;請參閱 確保程式碼觸發棄用警告。
request¶
request
fixture 是一個特殊的 fixture,提供請求測試函式的相關資訊。
- class FixtureRequest[原始碼]¶
request
fixture 的類型。request 物件可讓您存取請求測試情境,並且在 fixture 已參數化的情況下,具有
param
屬性。- property scope: Literal['session', 'package', 'module', 'class', 'function']¶
範圍字串,為 “function”、“class”、“module”、“package”、“session” 之一。
- abstract property node¶
底層集合節點 (取決於目前的請求範圍)。
- property function¶
如果請求具有每個函式範圍,則為測試函式物件。
- property cls¶
收集測試函式的類別 (可以為 None)。
- property instance¶
收集測試函式的實例 (可以為 None)。
- property module¶
收集測試函式的 Python 模組物件。
- property keywords: MutableMapping[str, Any]¶
底層節點的關鍵字/標記字典。
- applymarker(marker)[原始碼]¶
將標記套用至單個測試函式調用。
如果您不想在所有函式調用上都有關鍵字/標記,則此方法很有用。
- 參數:
marker (str | MarkDecorator) – 由呼叫
pytest.mark.NAME(...)
建立的物件。
- getfixturevalue(argname)[原始碼]¶
動態執行具名 fixture 函式。
建議盡可能透過函式引數宣告 fixture。但是,如果您只能在測試設定時間決定是否要使用另一個 fixture,則可以使用此函式在 fixture 或測試函式主體內檢索它。
此方法可用於測試設定階段或測試執行階段,但在測試拆解階段,fixture 的值可能不可用。
- 參數:
argname (str) – fixture 名稱。
- 引發:
pytest.FixtureLookupError – 如果找不到給定的 fixture。
testdir¶
與 pytester
相同,但提供的實例的方法在適用時會傳回舊版 py.path.local
物件。
新程式碼應避免使用 testdir
,而改用 pytester
。
- final class Testdir[原始碼]
與
Pytester
類似,但此類別適用於舊版 legacy_path 物件。所有方法都只是轉發到內部
Pytester
實例,並在必要時將結果轉換為legacy_path
物件。- exception TimeoutExpired
- property tmpdir: LocalPath
執行測試的臨時目錄。
- make_hook_recorder(pluginmanager)[原始碼]
請參閱
Pytester.make_hook_recorder()
。
- chdir()[原始碼]
請參閱
Pytester.chdir()
。
- makefile(ext, *args, **kwargs)[原始碼]
請參閱
Pytester.makefile()
。
- makeconftest(source)[原始碼]
-
- makeini(source)[原始碼]
請參閱
Pytester.makeini()
。
- getinicfg(source)[原始碼]
請參閱
Pytester.getinicfg()
。
- makepyprojecttoml(source)[原始碼]
請參閱
Pytester.makepyprojecttoml()
。
- makepyfile(*args, **kwargs)[原始碼]
-
- maketxtfile(*args, **kwargs)[原始碼]
-
- syspathinsert(path=None)[原始碼]
-
- mkdir(name)[原始碼]
請參閱
Pytester.mkdir()
。
- mkpydir(name)[原始碼]
請參閱
Pytester.mkpydir()
。
- copy_example(name=None)[原始碼]
-
- getnode(config, arg)[原始碼]
請參閱
Pytester.getnode()
。
- getpathnode(path)[原始碼]
- genitems(colitems)[原始碼]
請參閱
Pytester.genitems()
。
- runitem(source)[原始碼]
- inline_runsource(source, *cmdlineargs)[source]
- inline_genitems(*args)[source]
- inline_run(*args, plugins=(), no_reraise_ctrlc=False)[source]
-
- runpytest_inprocess(*args, **kwargs)[source]
請參閱
Pytester.runpytest_inprocess()
。
- runpytest(*args, **kwargs)[source]
-
- parseconfig(*args)[source]
-
- parseconfigure(*args)[source]
-
- getitem(source, funcname='test_func')[source]
- getitems(source)[source]
- getmodulecol(source, configargs=(), withinit=False)[source]
- collect_by_name(modcol, name)[source]
請參閱
Pytester.collect_by_name()
。
- popen(cmdargs, stdout=-1, stderr=-1, stdin=NotSetType.token, **kw)[source]
請參閱
Pytester.popen()
。
- run(*cmdargs, timeout=None, stdin=NotSetType.token)[source]
請參閱
Pytester.run()
。
- runpython(script)[source]
-
- runpython_c(command)[source]
- runpytest_subprocess(*args, timeout=None)[source]
請參閱
Pytester.runpytest_subprocess()
。
- spawn_pytest(string, expect_timeout=10.0)[source]
-
- spawn(cmd, expect_timeout=10.0)[source]
請參閱
Pytester.spawn()
。
tmp_path¶
教學: 如何在測試中使用暫存目錄和檔案
- tmp_path()[source]¶
傳回一個暫存目錄(作為
pathlib.Path
物件),該目錄對於每個測試函數調用都是唯一的。暫存目錄會被建立為基礎暫存目錄的子目錄,並具有可設定的保留期限,如暫存目錄位置和保留期限中所討論的。
tmp_path_factory¶
tmp_path_factory
是 TempPathFactory
的一個實例
- final class TempPathFactory[source]¶
用於在通用基礎暫存目錄下建立暫存目錄的工廠,如暫存目錄位置和保留期限中所討論的。
tmpdir¶
教學: tmpdir 和 tmpdir_factory 夾具
- tmpdir()¶
傳回一個暫存目錄(作為 legacy_path 物件),該目錄對於每個測試函數調用都是唯一的。暫存目錄會被建立為基礎暫存目錄的子目錄,並具有可設定的保留期限,如暫存目錄位置和保留期限中所討論的。
tmpdir_factory¶
教學: tmpdir 和 tmpdir_factory 夾具
tmpdir_factory
是 TempdirFactory
的一個實例
- final class TempdirFactory[source]¶
實現
py.path.local
以用於TempPathFactory
的向後相容性包裝器。- mktemp(basename, numbered=True)[source]¶
與
TempPathFactory.mktemp()
相同,但傳回py.path.local
物件。
- getbasetemp()[source]¶
與
TempPathFactory.getbasetemp()
相同,但傳回py.path.local
物件。
Hook¶
教學: 編寫外掛程式
參考所有可由 conftest.py 檔案 和 外掛程式 實作的 hook。
@pytest.hookimpl¶
- @pytest.hookimpl¶
pytest 的裝飾器,用於將函數標記為 hook 實作。
@pytest.hookspec¶
- @pytest.hookspec¶
pytest 的裝飾器,用於將函數標記為 hook 規格。
請參閱 宣告新 hook 和
pluggy.HookspecMarker()
。
啟動引導 hook¶
為夠早註冊的外掛程式(內部和第三方外掛程式)呼叫的啟動引導 hook。
- pytest_load_initial_conftests(early_config, parser, args)[source]¶
呼叫以實作在命令列選項解析之前載入 初始 conftest 檔案。
- 參數:
在 conftest 外掛程式中使用¶
此 hook 不會為 conftest 檔案呼叫。
- pytest_cmdline_parse(pluginmanager, args)[source]¶
傳回初始化的
Config
,解析指定的 args。在第一個非 None 結果處停止,請參閱 firstresult:在第一個非 None 結果處停止。
注意
此 hook 僅為傳遞給
plugins
參數的外掛程式類別呼叫,當使用 pytest.main 執行進程內測試執行時。- 參數:
pluginmanager (PytestPluginManager) – pytest 外掛程式管理器。
- 傳回:
pytest config 物件。
- 傳回類型:
Config | None
在 conftest 外掛程式中使用¶
此 hook 不會為 conftest 檔案呼叫。
- pytest_cmdline_main(config)[source]¶
呼叫以執行主要的命令列動作。
預設實作將調用 configure hook 和
pytest_runtestloop
。在第一個非 None 結果處停止,請參閱 firstresult:在第一個非 None 結果處停止。
在 conftest 外掛程式中使用¶
此 hook 僅為 初始 conftest 呼叫。
初始化 hook¶
為外掛程式和 conftest.py
檔案呼叫的初始化 hook。
- pytest_addoption(parser, pluginmanager)[source]¶
註冊 argparse 樣式的選項和 ini 樣式的 config 值,在測試執行開始時呼叫一次。
- 參數:
parser (Parser) – 若要新增命令列選項,請呼叫
parser.addoption(...)
。若要新增 ini 檔案值,請呼叫parser.addini(...)
。pluginmanager (PytestPluginManager) – pytest 外掛程式管理器,可用於安裝
hookspec()
或hookimpl()
,並允許一個外掛程式呼叫另一個外掛程式的 hook,以變更新增命令列選項的方式。
選項稍後可分別透過
config
物件存取config.getoption(name)
以檢索命令列選項的值。config.getini(name)
以檢索從 ini 樣式檔案讀取的值。
config 物件透過
.config
屬性在許多內部物件上傳遞,或者可以作為pytestconfig
夾具檢索。注意
此 hook 與 hook 包裝器不相容。
在 conftest 外掛程式中使用¶
如果 conftest 外掛程式實作此 hook,則會在註冊 conftest 時立即呼叫它。
此 hook 僅為 初始 conftest 呼叫。
- pytest_addhooks(pluginmanager)[source]¶
在外掛程式註冊時呼叫,以允許透過呼叫
pluginmanager.add_hookspecs(module_or_class, prefix)
來新增新 hook。- 參數:
pluginmanager (PytestPluginManager) – pytest 外掛程式管理器。
注意
此 hook 與 hook 包裝器不相容。
在 conftest 外掛程式中使用¶
如果 conftest 外掛程式實作此 hook,則會在註冊 conftest 時立即呼叫它。
- pytest_configure(config)[source]¶
允許外掛程式和 conftest 檔案執行初始設定。
注意
此 hook 與 hook 包裝器不相容。
- 參數:
config (Config) – pytest config 物件。
在 conftest 外掛程式中使用¶
在命令列選項解析後,會為每個初始 conftest 檔案呼叫此 hook。之後,當註冊其他 conftest 檔案時,會為它們呼叫此 hook。
- pytest_unconfigure(config)[source]¶
在測試程序結束之前呼叫。
- 參數:
config (Config) – pytest config 物件。
在 conftest 外掛程式中使用¶
任何 conftest 檔案都可以實作此 hook。
- pytest_sessionstart(session)[source]¶
在建立
Session
物件之後,以及在執行收集和進入執行測試迴圈之前呼叫。- 參數:
session (Session) – pytest session 物件。
在 conftest 外掛程式中使用¶
此 hook 僅為 初始 conftest 呼叫。
- pytest_sessionfinish(session, exitstatus)[source]¶
在整個測試執行完成後呼叫,就在將退出狀態傳回系統之前。
在 conftest 外掛程式中使用¶
任何 conftest 檔案都可以實作此 hook。
- pytest_plugin_registered(plugin, plugin_name, manager)[原始碼]¶
新的 pytest 外掛程式已註冊。
- 參數:
plugin (_PluggyPlugin) – 外掛程式模組或實例。
plugin_name (str) – 外掛程式註冊時使用的名稱。
manager (PytestPluginManager) – pytest 外掛程式管理器。
注意
此 hook 與 hook 包裝器不相容。
在 conftest 外掛程式中使用¶
如果 conftest 外掛程式實作了此 hook,當 conftest 註冊時會立即呼叫它,對於到目前為止已註冊的每個外掛程式(包括它自己!)呼叫一次,並且對於之後註冊的所有外掛程式也會在它們註冊時呼叫。
收集 hooks¶
pytest
呼叫以下 hooks 以收集檔案和目錄
- pytest_collection(session)[原始碼]¶
為給定的 session 執行收集階段。
在第一個非 None 結果處停止,請參閱 firstresult:在第一個非 None 結果處停止。傳回值未使用,但僅停止進一步處理。
預設的收集階段如下(完整詳細資訊請參閱個別 hooks)
從
session
作為初始收集器開始
pytest_collectstart(collector)
report = pytest_make_collect_report(collector)
pytest_exception_interact(collector, call, report)
如果發生互動式例外對於每個收集到的節點
如果是一個 item,
pytest_itemcollected(item)
如果是一個收集器,遞迴進入它。
pytest_collectreport(report)
pytest_collection_modifyitems(session, config, items)
pytest_deselected(items)
用於任何取消選擇的 items(可能會呼叫多次)
pytest_collection_finish(session)
將
session.items
設定為收集到的 items 列表將
session.testscollected
設定為收集到的 items 數量
您可以實作此 hook 以僅在收集之前執行某些動作,例如終端外掛程式使用它來開始顯示收集計數器(並傳回
None
)。- 參數:
session (Session) – pytest session 物件。
在 conftest 外掛程式中使用¶
此 hook 僅為 初始 conftest 呼叫。
- pytest_ignore_collect(collection_path, path, config)[原始碼]¶
傳回
True
以忽略此路徑進行收集。傳回
None
以讓其他外掛程式忽略此路徑進行收集。傳回
False
將強制不忽略此路徑進行收集,而不給予其他外掛程式忽略此路徑的機會。在呼叫更具體的 hooks 之前,會針對所有檔案和目錄諮詢此 hook。
在第一個非 None 結果處停止,請參閱 firstresult:在第一個非 None 結果處停止。
- 參數:
collection_path (pathlib.Path) – 要分析的路徑。
path (LEGACY_PATH) – 要分析的路徑(已棄用)。
config (Config) – pytest config 物件。
變更於 7.0.0 版本:
collection_path
參數已新增為pathlib.Path
,相當於path
參數。path
參數已被棄用。在 conftest 外掛程式中使用¶
任何 conftest 檔案都可以實作此 hook。對於給定的收集路徑,僅諮詢收集路徑的父目錄中的 conftest 檔案(如果路徑是目錄,則不諮詢其自身的 conftest 檔案 - 目錄不能忽略自身!)。
- pytest_collect_directory(path, parent)[原始碼]¶
為給定的目錄建立
Collector
,如果無關則傳回 None。新增於 8.0 版本。
為了獲得最佳結果,傳回的收集器應為
Directory
的子類別,但這不是必需的。新的節點需要將指定的
parent
作為父節點。在第一個非 None 結果處停止,請參閱 firstresult:在第一個非 None 結果處停止。
- 參數:
path (pathlib.Path) – 要分析的路徑。
有關此 hook 的簡單使用範例,請參閱 使用自訂目錄收集器。
在 conftest 外掛程式中使用¶
任何 conftest 檔案都可以實作此 hook。對於給定的收集路徑,僅諮詢收集路徑的父目錄中的 conftest 檔案(如果路徑是目錄,則不諮詢其自身的 conftest 檔案 - 目錄不能收集自身!)。
- pytest_collect_file(file_path, path, parent)[原始碼]¶
為給定的路徑建立
Collector
,如果無關則傳回 None。為了獲得最佳結果,傳回的收集器應為
File
的子類別,但這不是必需的。新的節點需要將指定的
parent
作為父節點。- 參數:
file_path (pathlib.Path) – 要分析的路徑。
path (LEGACY_PATH) – 要收集的路徑(已棄用)。
變更於 7.0.0 版本:
file_path
參數已新增為pathlib.Path
,相當於path
參數。path
參數已被棄用。在 conftest 外掛程式中使用¶
任何 conftest 檔案都可以實作此 hook。對於給定的檔案路徑,僅諮詢檔案路徑的父目錄中的 conftest 檔案。
- pytest_pycollect_makemodule(module_path, path, parent)[原始碼]¶
傳回給定路徑的
pytest.Module
收集器,如果無關則傳回 None。將針對每個符合的測試模組路徑呼叫此 hook。如果您想為不符合測試模組的檔案建立測試模組,則需要使用
pytest_collect_file
hook。在第一個非 None 結果處停止,請參閱 firstresult:在第一個非 None 結果處停止。
- 參數:
module_path (pathlib.Path) – 要收集的模組路徑。
path (LEGACY_PATH) – 要收集的模組路徑(已棄用)。
變更於 7.0.0 版本:
module_path
參數已新增為pathlib.Path
,相當於path
參數。path
參數已被棄用,建議使用fspath
。在 conftest 外掛程式中使用¶
任何 conftest 檔案都可以實作此 hook。對於給定的父收集器,僅諮詢收集器的目錄及其父目錄中的 conftest 檔案。
若要影響 Python 模組中物件的收集,您可以使用以下 hook
- pytest_pycollect_makeitem(collector, name, obj)[原始碼]¶
傳回模組中 Python 物件的自訂 item/收集器,或 None。
在第一個非 None 結果處停止,請參閱 firstresult:在第一個非 None 結果處停止。
- 參數:
- 傳回:
已建立的 items/收集器。
- 傳回類型:
在 conftest 外掛程式中使用¶
任何 conftest 檔案都可以實作此 hook。對於給定的收集器,僅諮詢收集器的目錄及其父目錄中的 conftest 檔案。
- pytest_generate_tests(metafunc)[原始碼]¶
為測試函數產生(多個)參數化呼叫。
在 conftest 外掛程式中使用¶
任何 conftest 檔案都可以實作此 hook。對於給定的函數定義,僅諮詢函數目錄及其父目錄中的 conftest 檔案。
- pytest_make_parametrize_id(config, val, argname)[原始碼]¶
傳回給定
val
的使用者友善字串表示形式,該表示形式將由 @pytest.mark.parametrize 呼叫使用,如果 hook 不知道val
則傳回 None。如果需要,參數名稱可用作
argname
。在第一個非 None 結果處停止,請參閱 firstresult:在第一個非 None 結果處停止。
在 conftest 外掛程式中使用¶
任何 conftest 檔案都可以實作此 hook。
影響測試跳過的 Hooks
- pytest_markeval_namespace(config)[原始碼]¶
在建構用於評估 xfail/skipif 標記中字串條件的全域字典時呼叫。
當標記的條件需要昂貴或在收集時無法取得的物件時,此功能很有用,而正常的布林條件則需要這些物件。
在 6.2 版本中新增。
在 conftest 外掛程式中使用¶
任何 conftest 檔案都可以實作此 hook。對於給定的 item,僅諮詢 item 父目錄中的 conftest 檔案。
收集完成後,您可以修改 items 的順序、刪除或以其他方式修改測試 items
- pytest_collection_modifyitems(session, config, items)[原始碼]¶
在執行收集後呼叫。可能會就地篩選或重新排序 items。
當 items 被取消選擇(從
items
中篩選掉)時,必須使用取消選擇的 items 顯式呼叫 hookpytest_deselected
,以正確通知其他外掛程式,例如使用config.hook.pytest_deselected(items=deselected_items)
。- 參數:
在 conftest 外掛程式中使用¶
任何 conftest 外掛程式都可以實作此 hook。
注意
如果此 hook 在 conftest.py
檔案中實作,它始終接收所有收集到的 items,而不僅僅是實作它的 conftest.py
下的 items。
測試執行 (runtest) hooks¶
所有 runtest 相關的 hooks 都會接收 pytest.Item
物件。
- pytest_runtestloop(session)[原始碼]¶
執行主要的 runtest 迴圈(在收集完成後)。
預設的 hook 實作會針對 session 中收集的所有 items (
session.items
) 執行 runtest 協定,除非收集失敗或設定了collectonly
pytest 選項。如果在任何時候呼叫了
pytest.exit()
,則迴圈會立即終止。如果在任何時候設定了
session.shouldfail
或session.shouldstop
,則在目前 item 的 runtest 協定完成後,迴圈會終止。- 參數:
session (Session) – pytest session 物件。
在第一個非 None 結果處停止,請參閱 firstresult:在第一個非 None 結果處停止。傳回值未使用,但僅停止進一步處理。
在 conftest 外掛程式中使用¶
任何 conftest 檔案都可以實作此 hook。
- pytest_runtest_protocol(item, nextitem)[原始碼]¶
為單個測試 item 執行 runtest 協定。
預設的 runtest 協定如下(完整詳細資訊請參閱個別 hooks)
pytest_runtest_logstart(nodeid, location)
- 設定階段
call = pytest_runtest_setup(item)
(包裝在CallInfo(when="setup")
中)report = pytest_runtest_makereport(item, call)
pytest_runtest_logreport(report)
pytest_exception_interact(call, report)
如果發生互動式例外
- 呼叫階段,如果設定通過且未設定
setuponly
pytest 選項 call = pytest_runtest_call(item)
(包裝在CallInfo(when="call")
中)report = pytest_runtest_makereport(item, call)
pytest_runtest_logreport(report)
pytest_exception_interact(call, report)
如果發生互動式例外
- 呼叫階段,如果設定通過且未設定
- 拆解階段
call = pytest_runtest_teardown(item, nextitem)
(包裝在CallInfo(when="teardown")
中)report = pytest_runtest_makereport(item, call)
pytest_runtest_logreport(report)
pytest_exception_interact(call, report)
如果發生互動式例外
pytest_runtest_logfinish(nodeid, location)
- 參數:
在第一個非 None 結果處停止,請參閱 firstresult:在第一個非 None 結果處停止。傳回值未使用,但僅停止進一步處理。
在 conftest 外掛程式中使用¶
任何 conftest 檔案都可以實作此 hook。
- pytest_runtest_logstart(nodeid, location)[原始碼]¶
在開始為單個 item 執行 runtest 協定時呼叫。
有關 runtest 協定的說明,請參閱
pytest_runtest_protocol
。- 參數:
在 conftest 外掛程式中使用¶
任何 conftest 檔案都可以實作此 hook。對於給定的 item,僅諮詢 item 目錄及其父目錄中的 conftest 檔案。
- pytest_runtest_logfinish(nodeid, location)[原始碼]¶
在為單個 item 執行 runtest 協定結束時呼叫。
有關 runtest 協定的說明,請參閱
pytest_runtest_protocol
。- 參數:
在 conftest 外掛程式中使用¶
任何 conftest 檔案都可以實作此 hook。對於給定的 item,僅諮詢 item 目錄及其父目錄中的 conftest 檔案。
- pytest_runtest_setup(item)[原始碼]¶
呼叫以執行測試 item 的設定階段。
預設實作在
item
及其所有父項(尚未設定)上執行setup()
。這包括取得 item 所需的 fixtures 的值(尚未取得)。- 參數:
item (Item) – item。
在 conftest 外掛程式中使用¶
任何 conftest 檔案都可以實作此 hook。對於給定的 item,僅諮詢 item 目錄及其父目錄中的 conftest 檔案。
- pytest_runtest_call(item)[原始碼]¶
呼叫以執行測試 item 的測試(呼叫階段)。
預設實作呼叫
item.runtest()
。- 參數:
item (Item) – item。
在 conftest 外掛程式中使用¶
任何 conftest 檔案都可以實作此 hook。對於給定的 item,僅諮詢 item 目錄及其父目錄中的 conftest 檔案。
- pytest_runtest_teardown(item, nextitem)[原始碼]¶
呼叫以執行測試 item 的拆解階段。
預設實作執行 finalizers 並在
item
及其所有父項(需要拆解)上呼叫teardown()
。這包括執行 item 所需的 fixtures 的拆解階段(如果它們超出範圍)。- 參數:
在 conftest 外掛程式中使用¶
任何 conftest 檔案都可以實作此 hook。對於給定的 item,僅諮詢 item 目錄及其父目錄中的 conftest 檔案。
- pytest_runtest_makereport(item, call)[原始碼]¶
呼叫以針對測試 item 的設定、呼叫和拆解 runtest 階段的每個階段建立
TestReport
。有關 runtest 協定的說明,請參閱
pytest_runtest_protocol
。在第一個非 None 結果處停止,請參閱 firstresult:在第一個非 None 結果處停止。
在 conftest 外掛程式中使用¶
任何 conftest 檔案都可以實作此 hook。對於給定的 item,僅諮詢 item 目錄及其父目錄中的 conftest 檔案。
為了更深入的理解,您可以查看 _pytest.runner
中的這些 hooks 的預設實作,也可能查看與 _pytest.capture
及其輸入/輸出捕獲互動的 _pytest.pdb
,以便在發生測試失敗時立即進入互動式除錯。
- pytest_pyfunc_call(pyfuncitem)[原始碼]¶
呼叫底層測試函數。
在第一個非 None 結果處停止,請參閱 firstresult:在第一個非 None 結果處停止。
- 參數:
pyfuncitem (Function) – 函數 item。
在 conftest 外掛程式中使用¶
任何 conftest 檔案都可以實作此 hook。對於給定的 item,僅諮詢 item 目錄及其父目錄中的 conftest 檔案。
報告 hooks¶
Session 相關的報告 hooks
- pytest_collectstart(collector)[原始碼]¶
收集器開始收集。
- 參數:
collector (Collector) – 收集器。
在 conftest 外掛程式中使用¶
任何 conftest 檔案都可以實作此 hook。對於給定的收集器,僅諮詢收集器的目錄及其父目錄中的 conftest 檔案。
- pytest_make_collect_report(collector)[原始碼]¶
執行
collector.collect()
並傳回CollectReport
。在第一個非 None 結果處停止,請參閱 firstresult:在第一個非 None 結果處停止。
- 參數:
collector (Collector) – 收集器。
在 conftest 外掛程式中使用¶
任何 conftest 檔案都可以實作此 hook。對於給定的收集器,僅諮詢收集器的目錄及其父目錄中的 conftest 檔案。
- pytest_itemcollected(item)[原始碼]¶
我們剛剛收集了一個測試 item。
- 參數:
item (Item) – item。
在 conftest 外掛程式中使用¶
任何 conftest 檔案都可以實作此 hook。對於給定的 item,僅諮詢 item 目錄及其父目錄中的 conftest 檔案。
- pytest_collectreport(report)[原始碼]¶
收集器完成收集。
- 參數:
report (CollectReport) – 收集報告。
在 conftest 外掛程式中使用¶
任何 conftest 檔案都可以實作此 hook。對於給定的收集器,僅諮詢收集器的目錄及其父目錄中的 conftest 檔案。
- pytest_deselected(items)[原始碼]¶
針對取消選擇的測試 items 呼叫,例如依關鍵字。
請注意,此 hook 對於外掛程式有兩個整合面向
它可以被實作以接收取消選擇的 items 的通知
當 items 被取消選擇時,必須從
pytest_collection_modifyitems
實作中呼叫它(以正確通知其他外掛程式)。
可能會呼叫多次。
- 參數:
items (Sequence[Item]) – items。
在 conftest 外掛程式中使用¶
任何 conftest 檔案都可以實作此 hook。
- pytest_report_header(config, start_path, startdir)[原始碼]¶
傳回字串或字串列表,以顯示為終端報告的標頭資訊。
- 參數:
config (Config) – pytest config 物件。
start_path (pathlib.Path) – 起始目錄。
startdir (LEGACY_PATH) – 起始目錄(已棄用)。
注意
外掛程式傳回的行會顯示在在其之前運行的外掛程式的行之前。如果您希望您的行顯示在最前面,請使用 trylast=True。
變更於 7.0.0 版本:
start_path
參數已新增為pathlib.Path
,相當於startdir
參數。startdir
參數已被棄用。在 conftest 外掛程式中使用¶
此 hook 僅為 初始 conftest 呼叫。
- pytest_report_collectionfinish(config, start_path, startdir, items)[source]¶
傳回一個字串或字串列表,以便在集合成功完成後顯示。
這些字串將在標準的「已收集 X 個項目」訊息後顯示。
在版本 3.2 中新增。
- 參數:
config (Config) – pytest config 物件。
start_path (pathlib.Path) – 起始目錄。
startdir (LEGACY_PATH) – 起始目錄(已棄用)。
items (Sequence[Item]) – 即將執行的 pytest 項目列表;此列表不應被修改。
注意
外掛程式傳回的行會顯示在在其之前運行的外掛程式的行之前。如果您希望您的行顯示在最前面,請使用 trylast=True。
變更於 7.0.0 版本:
start_path
參數已新增為pathlib.Path
,相當於startdir
參數。startdir
參數已被棄用。在 conftest 插件中使用¶
任何 conftest 外掛程式都可以實作此 hook。
- pytest_report_teststatus(report, config)[source]¶
傳回狀態報告的結果類別、簡短字母和詳細文字。
結果類別是用於計算結果的類別,例如「通過」、「跳過」、「錯誤」或空字串。
簡短字母在測試進行時顯示,例如「.」、「s」、「E」或空字串。
詳細文字在詳細模式下測試進行時顯示,例如「PASSED」、「SKIPPED」、「ERROR」或空字串。
pytest 可以根據報告結果隱式地設定這些樣式。若要提供明確的樣式,請傳回詳細文字的元組,例如
"rerun", "R", ("RERUN", {"yellow": True})
。- 參數:
report (CollectReport | TestReport) – 要傳回其狀態的報告物件。
config (Config) – pytest config 物件。
- 傳回:
測試狀態。
- 傳回類型:
TestShortLogReport | tuple[str, str, str | tuple[str, Mapping[str, bool]]]
在第一個非 None 結果處停止,請參閱 firstresult:在第一個非 None 結果處停止。
在 conftest 插件中使用¶
任何 conftest 外掛程式都可以實作此 hook。
- pytest_report_to_serializable(config, report)[source]¶
將給定的報告物件序列化為適合透過網路傳輸的資料結構,例如轉換為 JSON。
- 參數:
config (Config) – pytest config 物件。
report (CollectReport | TestReport) – 報告。
在 conftest 插件中使用¶
任何 conftest 檔案都可以實作此 hook。確切的細節可能取決於呼叫此 hook 的插件。
- pytest_report_from_serializable(config, data)[source]¶
還原先前使用
pytest_report_to_serializable
序列化的報告物件。- 參數:
config (Config) – pytest config 物件。
在 conftest 插件中使用¶
任何 conftest 檔案都可以實作此 hook。確切的細節可能取決於呼叫此 hook 的插件。
- pytest_terminal_summary(terminalreporter, exitstatus, config)[source]¶
在終端摘要報告中新增一個區段。
- 參數:
Added in version 4.2:
config
參數。在 conftest 插件中使用¶
任何 conftest 外掛程式都可以實作此 hook。
- pytest_fixture_setup(fixturedef, request)[source]¶
執行 fixture 設定。
- 參數:
fixturedef (FixtureDef[Any]) – fixture 定義物件。
request (SubRequest) – fixture 請求物件。
- 傳回:
呼叫 fixture 函數的回傳值。
- 傳回類型:
object | None
在第一個非 None 結果處停止,請參閱 firstresult:在第一個非 None 結果處停止。
注意
如果 fixture 函數傳回 None,則會繼續呼叫此 hook 函數的其他實作,根據 firstresult:在第一個非 None 結果時停止 選項的行為。
在 conftest 插件中使用¶
任何 conftest 檔案都可以實作此 hook。對於給定的 fixture,只會諮詢 fixture 作用域目錄及其父目錄中的 conftest 檔案。
- pytest_fixture_post_finalizer(fixturedef, request)[source]¶
在 fixture 拆解之後,但在清除快取之前呼叫,因此 fixture 結果
fixturedef.cached_result
仍然可用(非None
)。- 參數:
fixturedef (FixtureDef[Any]) – fixture 定義物件。
request (SubRequest) – fixture 請求物件。
在 conftest 插件中使用¶
任何 conftest 檔案都可以實作此 hook。對於給定的 fixture,只會諮詢 fixture 作用域目錄及其父目錄中的 conftest 檔案。
- pytest_warning_recorded(warning_message, when, nodeid, location)[source]¶
處理由內部 pytest 警告插件捕獲的警告。
- 參數:
warning_message (warnings.WarningMessage) – 捕獲的警告。這與
warnings.catch_warnings
產生的物件相同,並且包含與warnings.showwarning()
參數相同的屬性。when (Literal['config', 'collect', 'runtest']) –
指示警告被捕獲的時間。可能的值
"config"
:在 pytest 配置/初始化階段。"collect"
:在測試集合期間。"runtest"
:在測試執行期間。
nodeid (str) – 項目的完整 ID。對於非特定於特定節點的警告,則為空字串。
location (tuple[str, int, str] | None) – 如果可用,則包含有關捕獲警告的執行上下文的資訊(檔案名稱、行號、函數)。當執行上下文位於模組層級時,
function
的評估結果為 <module>。
在 6.0 版本中新增。
在 conftest 插件中使用¶
任何 conftest 檔案都可以實作此 hook。如果警告特定於特定節點,則只會諮詢節點父目錄中的 conftest 檔案。
用於報告測試執行的中心 hook
- pytest_runtest_logreport(report)[source]¶
處理為項目的每個 setup、call 和 teardown 執行測試階段產生的
TestReport
。有關 runtest 協定的說明,請參閱
pytest_runtest_protocol
。在 conftest 插件中使用¶
任何 conftest 檔案都可以實作此 hook。對於給定的 item,僅諮詢 item 目錄及其父目錄中的 conftest 檔案。
斷言相關的 hooks
- pytest_assertrepr_compare(config, op, left, right)[source]¶
傳回斷言表達式失敗時比較的解釋。
如果沒有自訂解釋,則傳回 None,否則傳回字串列表。這些字串將以換行符號連接,但字串中的任何換行符號都將被跳脫。請注意,除了第一行之外的所有行都將稍微縮排,第一行的目的是作為摘要。
- 參數:
在 conftest 插件中使用¶
任何 conftest 檔案都可以實作此 hook。對於給定的 item,僅諮詢 item 目錄及其父目錄中的 conftest 檔案。
- pytest_assertion_pass(item, lineno, orig, expl)[source]¶
每當斷言通過時呼叫。
在版本 5.0 中新增。
使用此 hook 在斷言通過後執行一些處理。原始斷言資訊可在
orig
字串中取得,而 pytest 內省的斷言資訊可在expl
字串中取得。此 hook 必須由
enable_assertion_pass_hook
ini 檔案選項明確啟用[pytest] enable_assertion_pass_hook=true
當啟用此選項時,您需要清除專案目錄和直譯器程式庫中的 .pyc 檔案,因為斷言將需要重新編寫。
- 參數:
在 conftest 插件中使用¶
任何 conftest 檔案都可以實作此 hook。對於給定的 item,僅諮詢 item 目錄及其父目錄中的 conftest 檔案。
除錯/互動 hooks¶
有一些 hooks 可用於特殊報告或與異常互動
- pytest_internalerror(excrepr, excinfo)[source]¶
為內部錯誤呼叫。
傳回 True 以抑制直接將 INTERNALERROR 訊息列印到 sys.stderr 的後備處理。
- 參數:
excrepr (ExceptionRepr) – 異常 repr 物件。
excinfo (ExceptionInfo[BaseException]) – 異常資訊。
在 conftest 插件中使用¶
任何 conftest 外掛程式都可以實作此 hook。
- pytest_keyboard_interrupt(excinfo)[source]¶
為鍵盤中斷呼叫。
- 參數:
excinfo (ExceptionInfo[KeyboardInterrupt | Exit]) – 異常資訊。
在 conftest 插件中使用¶
任何 conftest 外掛程式都可以實作此 hook。
- pytest_exception_interact(node, call, report)[source]¶
當引發可能以互動方式處理的異常時呼叫。
可能在集合期間呼叫(請參閱
pytest_make_collect_report
),在這種情況下,report
是CollectReport
。可能在項目的 runtest 期間呼叫(請參閱
pytest_runtest_protocol
),在這種情況下,report
是TestReport
。如果引發的異常是內部異常,例如
skip.Exception
,則不會呼叫此 hook。- 參數:
call (CallInfo[Any]) – 呼叫資訊。包含異常。
report (CollectReport | TestReport) – 集合或測試報告。
在 conftest 插件中使用¶
任何 conftest 檔案都可以實作此 hook。對於給定的節點,只會諮詢節點父目錄中的 conftest 檔案。
集合樹物件¶
這些是組成集合樹的收集器和項目類別(統稱為「節點」)。
節點¶
- class Node[source]¶
基底類別:
ABC
Collector
和Item
的基底類別,測試集合樹的組件。Collector
是樹的內部節點,而Item
是葉節點。- fspath: LEGACY_PATH¶
path
屬性的LEGACY_PATH
副本。適用於尚未遷移到pathlib.Path
的方法,例如Item.reportinfo
。將在未來版本中棄用,建議改用path
。
- parent¶
父收集器節點。
- path: pathlib.Path¶
從中收集此節點的檔案系統路徑(可以為 None)。
- classmethod from_parent(parent, **kw)[source]¶
節點的公共建構子。
引入此間接層是為了能夠從節點建構子中移除脆弱的邏輯。
子類別可以在覆寫建構時使用
super().from_parent(...)
。- 參數:
parent (Node) – 此節點的父節點。
- warn(warning)[source]¶
為此節點發出警告。
警告將在測試會期後顯示,除非明確抑制。
- 參數:
warning (Warning) – 要發出的警告實例。
- 引發:
ValueError – 如果
warning
實例不是 Warning 的子類別。
使用範例
node.warn(PytestWarning("some message")) node.warn(UserWarning("some message"))
Changed in version 6.2:
Warning
的任何子類別現在都被接受,而不僅僅是PytestWarning
子類別。
- add_marker(marker, append=True)[source]¶
動態地新增一個標記物件到節點。
- 參數:
marker (str | MarkDecorator) – 標記。
append (bool) – 是否附加標記,或預先加入標記。
- get_closest_marker(name: str) Mark | None [source]¶
- get_closest_marker(name: str, default: Mark) Mark
返回與名稱匹配的第一個標記,從最接近的層級(例如函式)到更遠的層級(例如模組層級)。
- 參數:
default – 如果找不到標記時的回退返回值。
name – 要依其過濾的名稱。
- getparent(cls)[source]¶
取得最接近的父層節點(包含自身),該節點是給定類別的實例。
- 參數:
cls (type[_NodeType]) – 要搜尋的節點類別。
- 傳回:
如果找到,則返回該節點。
- 傳回類型:
_NodeType | None
- repr_failure(excinfo, style=None)[source]¶
返回集合或測試失敗的表示形式。
另請參閱
- 參數:
excinfo (ExceptionInfo[BaseException]) – 失敗的例外資訊。
Collector¶
- class Collector[source]¶
-
所有收集器的基底類別。
收集器透過
collect()
建立子項目,並以此迭代地建構集合樹狀結構。- repr_failure(excinfo)[source]¶
返回集合失敗的表示形式。
- 參數:
excinfo (ExceptionInfo[BaseException]) – 失敗的例外資訊。
- parent¶
父收集器節點。
- path: pathlib.Path¶
從中收集此節點的檔案系統路徑(可以為 None)。
Item¶
- class Item[source]¶
-
所有測試調用項目的基底類別。
請注意,對於單個函式,可能有多個測試調用項目。
- parent¶
父收集器節點。
- path: pathlib.Path¶
從中收集此節點的檔案系統路徑(可以為 None)。
- add_report_section(when, key, content)[source]¶
新增一個新的報告章節,類似於內部新增 stdout 和 stderr 捕獲輸出的方式
item.add_report_section("call", "stdout", "report section contents")
File¶
- class File[source]¶
基底類別:
FSCollector
,ABC
用於從檔案收集測試的基底類別。
- parent¶
父收集器節點。
- path: pathlib.Path¶
從中收集此節點的檔案系統路徑(可以為 None)。
FSCollector¶
Session¶
- final class Session[source]¶
基底類別:
Collector
集合樹狀結構的根目錄。
Session
收集作為參數提供給 pytest 的初始路徑。- exception Interrupted¶
基底類別:
KeyboardInterrupt
表示測試執行被中斷。
- isinitpath(path, *, with_parents=False)[source]¶
路徑是否為初始路徑?
初始路徑是在命令列上明確提供給 pytest 的路徑。
- 參數:
with_parents (bool) – 如果設定,當路徑是初始路徑的父層路徑時,也返回 True。
變更於版本 8.0: 新增了
with_parents
參數。
- perform_collect(args: Sequence[str] | None = None, genitems: Literal[True] = True) Sequence[Item] [source]¶
- perform_collect(args: Sequence[str] | None = None, genitems: bool = True) Sequence[Item | Collector]
為此會話執行收集階段。
這由預設的
pytest_collection
hook 實作呼叫;有關更多詳細資訊,請參閱此 hook 的文件。為了測試目的,也可以直接在新的Session
上呼叫它。此函式通常會遞迴展開從會話收集的任何收集器到其項目,並且僅返回項目。為了測試目的,可以透過傳遞
genitems=False
來抑制此行為,在這種情況下,返回值包含這些未展開的收集器,並且session.items
為空。
- parent¶
父收集器節點。
套件¶
模組¶
類別¶
- class Class[原始碼]¶
基底類別:
PyCollector
Python 類別中測試方法 (和巢狀類別) 的收集器。
-
parent
¶ 父收集器節點。
-
path
: pathlib.Path¶ 從中收集此節點的檔案系統路徑(可以為 None)。
-
函式¶
- class Function[原始碼]¶
基底類別:
PyobjMixin
,Item
負責設定和執行 Python 測試函式的項目。
- 參數:
name – 完整的函式名稱,包含任何裝飾,例如由參數化新增的裝飾 (
my_func[my_param]
)。parent – 父節點。
config – pytest Config 物件。
callspec – 如果已給定,則此函式已參數化,且 callspec 包含關於參數化的元資訊。
callobj – 如果已給定,則為呼叫 Function 時將呼叫的物件,否則 callobj 將使用
originalname
從parent
取得。keywords – 繫結至函式物件的關鍵字,用於 “-k” 比對。
session – pytest Session 物件。
fixtureinfo – 已在此 fixture 節點解析的 Fixture 資訊。
originalname – 用於存取底層函式物件的屬性名稱。預設為
name
。如果 name 與原始名稱不同,例如當它包含由參數化新增的裝飾時 (my_func[my_param]
),請設定此項。
-
originalname
¶ 原始函式名稱,不含任何裝飾 (例如,參數化會將
"[...]"
後綴新增至函式名稱),用於從parent
存取底層函式物件 (在未明確給定callobj
的情況下)。在版本 3.0 中新增。
-
property
function
¶ 底層 python ‘function’ 物件。
-
property
instance
¶ 函式繫結到的 Python 執行個體物件。
如果不是測試方法,則傳回 None,例如,對於獨立測試函式、類別或模組。
-
repr_failure
(excinfo
)[原始碼]¶ 返回集合或測試失敗的表示形式。
另請參閱
- 參數:
excinfo (ExceptionInfo[BaseException]) – 失敗的例外資訊。
-
parent
¶ 父收集器節點。
-
path
: pathlib.Path¶ 從中收集此節點的檔案系統路徑(可以為 None)。
FunctionDefinition¶
物件¶
可從 fixtures 或 hooks 存取,或可從 pytest
匯入的物件。
CallInfo¶
-
final class
CallInfo
[原始碼]¶ 函式調用結果/例外資訊。
-
excinfo
: ExceptionInfo[BaseException] | None¶ 如果呼叫引發例外,則為已捕獲的例外。
-
property
result
:TResult
¶ 如果呼叫未引發例外,則為呼叫的傳回值。
只有在 excinfo 為 None 時才能存取。
-
classmethod
from_call
(func
,when
,reraise
=None
)[原始碼]¶ 呼叫 func,將結果包裝在 CallInfo 中。
- 參數:
func (Callable[[], _pytest.runner.TResult]) – 要呼叫的函式。不帶引數呼叫。
when (
Literal
['collect'
,'setup'
,'call'
,'teardown'
]) – 函式被呼叫的階段。reraise (
type
[BaseException
] |tuple
[type
[BaseException
], ...] |None
) – 如果函式引發例外,則應傳播的例外或例外,而不是包裝在 CallInfo 中。
-
CollectReport¶
-
final class
CollectReport
[原始碼]¶ 基底類別:
BaseReport
收集報告物件。
報告可以包含任意的額外屬性。
-
longrepr
: None | ExceptionInfo[BaseException] | tuple[str, int, str] | str |TerminalRepr
¶ None 或失敗表示法。
-
result
¶ 收集到的項目和收集節點。
-
sections
: list[tuple[str, str]]¶ str
(heading, content)
的元組,其中包含測試報告的額外資訊。pytest 使用它來新增從stdout
、stderr
捕獲的文字,以及攔截的記錄事件。其他外掛程式可以使用它將任意資訊新增至報告。
-
property
count_towards_summary
: bool¶ 實驗性質 此報告是否應計入測試階段結束時顯示的總計:「1 個通過、1 個失敗等等」。
注意
此函式被視為實驗性質,因此請注意,即使在修補程式版本中也可能會變更。
-
Config¶
- final class Config[source]¶
存取組態值、外掛程式管理器和外掛程式鉤點。
- 參數:
pluginmanager (PytestPluginManager) – 一個 pytest PluginManager。
invocation_params (InvocationParams) – 包含關於
pytest.main()
呼叫的參數物件。
- final class InvocationParams(*, args, plugins, dir)[source]¶
保存
pytest.main()
期間傳遞的參數。物件屬性為唯讀。
在 5.1 版本中新增。
注意
請注意,環境變數
PYTEST_ADDOPTS
和addopts
ini 選項是由 pytest 處理,並未包含在args
屬性中。存取
InvocationParams
的外掛程式必須注意這一點。- args: tuple[str, ...]¶
傳遞給
pytest.main()
的命令列引數。
- dir: Path¶
呼叫
pytest.main()
的目錄。 :type: pathlib.Path
- class ArgsSource(*values)[source]¶
指示測試引數的來源。
在 7.2 版本中新增。
- ARGS = 1¶
命令列引數。
- INVOCATION_DIR = 2¶
呼叫目錄。
- TESTPATHS = 3¶
‘testpaths’ 組態值。
- option¶
以屬性形式存取命令列選項。
- invocation_params¶
pytest 被呼叫時使用的參數。
- 類型:
- pluginmanager¶
外掛程式管理器處理外掛程式註冊和鉤點呼叫。
- property inipath: Path | None¶
指向 configfile 的路徑。
在 6.1 版本中新增。
- issue_config_time_warning(warning, stacklevel)[source]¶
在 “configure” 階段發出並處理警告。
在
pytest_configure
期間,我們無法使用catch_warnings_for_item
函數捕獲警告,因為無法在pytest_configure
周圍設置 hook wrappers。此函數主要用於需要在
pytest_configure
(或類似階段)期間發出警告的外掛程式。
- getini(name)[source]¶
從 ini 檔案 回傳組態值。
如果組態值未在 ini 檔案 中定義,則會回傳透過
parser.addini
註冊組態時提供的default
值。請注意,您甚至可以提供None
作為有效的預設值。如果在使用
parser.addini
註冊時未提供default
,則會根據傳遞給parser.addini
的type
參數回傳預設值。基於type
的預設值為:paths
、pathlist
、args
和linelist
:空列表[]
;bool
:False
;string
:空字串""
。如果在透過
parser.addini
註冊組態時,既未傳遞default
也未傳遞type
參數,則組態會被視為字串,並回傳預設空字串 ‘’。如果指定的名稱尚未透過先前的
parser.addini
呼叫(通常來自外掛程式)註冊,則會引發 ValueError。
- getoption(name, default=<NOTSET>, skip=False)[source]¶
回傳命令列選項值。
- 參數:
name (str) – 選項的名稱。您也可以指定文字
--OPT
選項,而不是 “dest” 選項名稱。default – 如果沒有透過
pytest_addoption
宣告該名稱的選項,則為後備值。請注意,即使選項的值為None
,當選項被宣告時,此參數將被忽略。skip (bool) – 如果為
True
,則當選項未宣告或具有None
值時,引發pytest.skip()
。請注意,即使為True
,如果指定了預設值,則會回傳該預設值而不是 skip。
- VERBOSITY_ASSERTIONS: Final = 'assertions'¶
失敗斷言的詳細程度類型 (請參閱
verbosity_assertions
)。
- VERBOSITY_TEST_CASES: Final = 'test_cases'¶
測試案例執行的詳細程度類型 (請參閱
verbosity_test_cases
)。
- get_verbosity(verbosity_type=None)[source]¶
檢索細粒度詳細程度類型的詳細程度層級。
- 參數:
verbosity_type (str | None) – 要取得層級的詳細程度類型。如果為給定類型配置了層級,則會回傳該值。如果給定類型不是已知的詳細程度類型,則會回傳全域詳細程度層級。如果給定類型為 None (預設值),則會回傳全域詳細程度層級。
若要為細粒度詳細程度類型配置層級,組態檔應具有組態名稱的設定以及詳細程度層級的數值。特殊值 “auto” 可用於明確使用全域詳細程度層級。
範例
# content of pytest.ini [pytest] verbosity_assertions = 2
pytest -v
print(config.get_verbosity()) # 1 print(config.get_verbosity(Config.VERBOSITY_ASSERTIONS)) # 2
Dir¶
- final class Dir[source]¶
檔案系統目錄中檔案的收集器。
新增於 8.0 版本。
- classmethod from_parent(parent, *, path)[source]¶
公開建構子。
- 參數:
parent (nodes.Collector) – 此 Dir 的父收集器。
path (pathlib.Path) – 目錄的路徑。
- parent¶
父收集器節點。
- path: pathlib.Path¶
從中收集此節點的檔案系統路徑(可以為 None)。
Directory¶
- class Directory[source]¶
用於從目錄收集檔案的基礎類別。
基本的目錄收集器會執行以下操作:遍歷目錄中的檔案和子目錄,並透過呼叫鉤點
pytest_collect_directory
和pytest_collect_file
為它們建立收集器,在檢查它們是否未使用pytest_ignore_collect
忽略之後。新增於 8.0 版本。
- parent¶
父收集器節點。
- path: pathlib.Path¶
從中收集此節點的檔案系統路徑(可以為 None)。
ExceptionInfo¶
- final class ExceptionInfo[source]¶
封裝 sys.exc_info() 物件,並為導航回溯提供協助。
- classmethod from_exception(exception, exprinfo=None)[source]¶
為現有的例外狀況回傳 ExceptionInfo。
例外狀況必須具有非
None
的__traceback__
屬性,否則此函數會因斷言錯誤而失敗。這表示例外狀況必須已引發,或使用with_traceback()
方法新增了回溯。- 參數:
exprinfo (str | None) – 一個文字字串,有助於判斷我們是否應從輸出中移除
AssertionError
。預設為例外狀況訊息/__str__()
。
在 7.4 版本中新增。
- classmethod from_exc_info(exc_info, exprinfo=None)[source]¶
類似於
from_exception()
,但使用舊式的 exc_info tuple。
- classmethod from_current(exprinfo=None)[source]¶
回傳與目前回溯相符的 ExceptionInfo。
警告
實驗性 API
- 參數:
exprinfo (str | None) – 一個文字字串,有助於判斷我們是否應從輸出中移除
AssertionError
。預設為例外狀況訊息/__str__()
。
- property value: E¶
例外值。
- property tb: TracebackType¶
原始的例外回溯 (traceback)。
- property traceback: Traceback¶
回溯 (traceback)。
- exconly(tryshort=False)[source]¶
以字串形式傳回例外。
當 ‘tryshort’ 解析為 True,且例外為 AssertionError 時,只會傳回例外表示法的實際例外部分(因此 ‘AssertionError: ’ 會從開頭移除)。
- getrepr(showlocals=False, style='long', abspath=False, tbfilter=True, funcargs=False, truncate_locals=True, truncate_args=True, chain=True)[source]¶
傳回此例外資訊的可字串化 (str()able) 表示形式。
- 參數:
showlocals (bool) – 顯示每個回溯條目的區域變數。如果
style=="native"
則忽略。style (str) – 回溯樣式:long|short|line|no|native|value。
abspath (bool) – 路徑是否應變更為絕對路徑或保持不變。
tbfilter (bool | Callable[[ExceptionInfo[BaseException]], Traceback]) –
回溯條目的篩選器。
如果為 false,則不隱藏任何條目。
如果為 true,則隱藏內部條目和包含區域變數
__tracebackhide__ = True
的條目。如果是可呼叫物件,則將篩選委派給可呼叫物件。
如果
style
為"native"
,則忽略。funcargs (bool) – 顯示每個回溯條目的夾具(為了舊版目的而稱為 “funcargs”)。
truncate_locals (bool) – 在
showlocals==True
的情況下,確保區域變數可以安全地表示為字串。truncate_args (bool) – 在
showargs==True
的情況下,確保引數可以安全地表示為字串。chain (bool) – 是否應顯示 Python 3 中的鏈式例外。
變更於 3.9 版本: 新增了
chain
參數。
- match(regexp)[source]¶
檢查正規表示式
regexp
是否使用re.search()
比對例外的字串表示形式。如果比對成功,則傳回
True
,否則會引發AssertionError
。
- group_contains(expected_exception, *, match=None, depth=None)[source]¶
檢查捕獲的例外群組是否包含相符的例外。
- 參數:
expected_exception (Type[BaseException] | Tuple[Type[BaseException]]) – 預期的例外類型,或如果預期有多個可能的例外類型,則為元組。
match (str | Pattern[str] | None) –
如果指定,則為包含正規表示式的字串,或正規表示式物件,將針對例外的字串表示形式及其
PEP-678 <https://peps.python.org/pep-0678/>
__notes__
使用re.search()
進行測試。若要比對可能包含 特殊字元 的文字字串,可以先使用
re.escape()
跳脫模式。depth (Optional[int]) – 如果
None
,將在任何巢狀深度搜尋相符的例外。如果 >= 1,則僅在例外位於指定的深度時比對例外(深度 = 1 是最上層例外群組中包含的例外)。
新增於 8.0 版本。
ExitCode¶
FixtureDef¶
MarkDecorator¶
- class MarkDecorator[source]¶
用於在測試函數和類別上套用標記的裝飾器。
MarkDecorators
是使用pytest.mark
建立的mark1 = pytest.mark.NAME # Simple MarkDecorator mark2 = pytest.mark.NAME(name1=value) # Parametrized MarkDecorator
然後可以作為裝飾器套用至測試函數
@mark2 def test_function(): pass
當呼叫
MarkDecorator
時,它會執行以下操作如果呼叫時僅以單一類別作為其唯一的位置引數,且沒有其他關鍵字引數,則它會將標記附加到該類別,以便自動套用至在該類別中找到的所有測試案例。
如果呼叫時僅以單一函數作為其唯一的位置引數,且沒有其他關鍵字引數,則它會將標記附加到該函數,其中包含已在內部儲存在
MarkDecorator
中的所有引數。在任何其他情況下呼叫時,它會傳回新的
MarkDecorator
實例,其中原始MarkDecorator
的內容已使用傳遞給此呼叫的引數更新。
注意:上述規則防止
MarkDecorator
僅儲存單一函數或類別參考作為其位置引數,而沒有其他關鍵字或位置引數。您可以使用with_args()
來解決此問題。
MarkGenerator¶
- final class MarkGenerator[source]¶
用於
MarkDecorator
物件的工廠 - 以pytest.mark
單例實例公開。範例
import pytest @pytest.mark.slowtest def test_function(): pass
在
test_function
上套用 ‘slowtest’Mark
。
Mark¶
Metafunc¶
- final class Metafunc[source]¶
傳遞給
pytest_generate_tests
Hook 的物件。它們有助於檢查測試函數,並根據測試組態或在定義測試函數的類別或模組中指定的值來產生測試。
- definition¶
- config¶
存取測試階段的
pytest.Config
物件。
- module¶
在其中定義測試函數的模組物件。
- function¶
底層的 Python 測試函數。
- fixturenames¶
測試函數所需的夾具名稱集合。
- cls¶
在其中定義測試函數的類別物件,或
None
。
- parametrize(argnames, argvalues, indirect=False, ids=None, scope=None, *, _param_mark=None)[source]¶
使用給定 argnames 的 argvalues 列表,將新的調用新增至底層測試函數。參數化是在收集階段執行。如果您需要設定昂貴的資源,請考慮將 indirect 設定為執行此操作,而不是在測試設定時間執行。
每個測試函數可以多次呼叫(但只能針對不同的引數名稱),在這種情況下,每次呼叫都會參數化所有先前的參數化,例如:
unparametrized: t parametrize ["x", "y"]: t[x], t[y] parametrize [1, 2]: t[x-1], t[x-2], t[y-1], t[y-2]
- 參數:
argnames (str | Sequence[str]) – 以逗號分隔的字串,表示一個或多個引數名稱,或引數字串的列表/元組。
argvalues (Iterable[_pytest.mark.structures.ParameterSet | Sequence[object] | object]) –
argvalues 列表決定了使用不同引數值調用測試的頻率。
如果僅指定一個 argname,則 argvalues 是值列表。如果指定了 N 個 argnames,則 argvalues 必須是 N 元組的列表,其中每個元組元素都指定其各自 argname 的值。
indirect (bool | Sequence[str]) – 引數名稱列表(argnames 的子集)或布林值。如果為 True,則列表包含 argnames 中的所有名稱。與此列表中的 argname 對應的每個 argvalue 將作為 request.param 傳遞給其各自的 argname 夾具函數,以便它可以在測試的設定階段而不是在收集時間執行更昂貴的設定。
ids (Iterable[object | None] | Callable[[Any], object | None] | None) –
用於
argvalues
的 id 序列(或產生器),或用於傳回每個 argvalue 的部分 id 的可呼叫物件。使用序列(和產生器,如
itertools.count()
),傳回的 id 應為string
、int
、float
、bool
或None
類型。它們會對應到argvalues
中的對應索引。None
表示使用自動產生的 id。如果它是可呼叫物件,則會針對
argvalues
中的每個條目呼叫它,並且傳回值會用作整個集合的自動產生 id 的一部分(其中各部分以破折號 (“-”) 連接)。這對於為特定項目(例如日期)提供更具體的 id 非常有用。傳回None
將使用自動產生的 id。如果未提供任何 id,則會從 argvalues 自動產生它們。
scope (Literal['session', 'package', 'module', 'class', 'function'] | None) – 如果指定,則表示參數的範圍。範圍用於按參數實例分組測試。它也將覆寫任何夾具函數定義的範圍,允許使用測試內容或組態設定動態範圍。
Parser¶
- final class Parser[source]¶
用於命令列引數和 ini 檔案值的剖析器。
- 變數:
extra_info – 通用參數 -> 值的字典,用於在處理命令列引數時發生錯誤的情況下顯示。
- getgroup(name, description='', after=None)[source]¶
取得(或建立)具名的選項群組。
- 參數:
- 傳回:
選項群組。
- 傳回類型:
傳回的群組物件有一個
addoption
方法,其簽名與parser.addoption
相同,但會顯示在pytest --help
輸出的對應群組中。
- addoption(*opts, **attrs)[原始碼]¶
註冊一個命令列選項。
- 參數:
opts (str) – 選項名稱,可以是短選項或長選項。
attrs (Any) – 與 argparse 函式庫的
add_argument()
函數接受的屬性相同。
在命令列解析之後,選項可透過 pytest config 物件上的
config.option.NAME
取得,其中NAME
通常透過傳遞dest
屬性來設定,例如addoption("--long", dest="NAME", ...)
。
- addini(name, help, type=None, default=<notset>)[原始碼]¶
註冊一個 ini 檔選項。
- 參數:
name (str) – ini 變數的名稱。
type (Literal['string', 'paths', 'pathlist', 'args', 'linelist', 'bool'] | None) –
變數的類型。可以是
string
: 字串bool
: 布林值args
: 字串列表,以 shell 方式分隔linelist
: 字串列表,以換行符號分隔paths
:pathlib.Path
列表,以 shell 方式分隔pathlist
:py.path
列表,以 shell 方式分隔
對於
paths
和pathlist
類型,它們被視為相對於 ini 檔。如果執行時未定義 ini 檔,它們將被視為相對於目前工作目錄 (例如使用--override-ini
)。7.0 版本新增:
paths
變數類型。8.1 版本新增: 在沒有 ini 檔的情況下,使用目前工作目錄來解析
paths
和pathlist
。如果
None
或未傳遞,則預設為string
。default (Any) – 如果沒有 ini 檔選項存在但被查詢時的預設值。
ini 變數的值可以透過呼叫
config.getini(name)
來檢索。
OptionGroup¶
- class OptionGroup[原始碼]¶
一組選項,顯示在自己的區段中。
- addoption(*opts, **attrs)[原始碼]¶
將一個選項新增到此群組。
如果指定了長選項的縮短版本,它將在說明中被抑制。
addoption('--twowords', '--two-words')
會導致說明僅顯示--two-words
,但--twowords
會被接受**且**自動目的地在args.twowords
中。- 參數:
opts (str) – 選項名稱,可以是短選項或長選項。
attrs (Any) – 與 argparse 函式庫的
add_argument()
函數接受的屬性相同。
PytestPluginManager¶
- final class PytestPluginManager[原始碼]¶
基底類別:
PluginManager
一個
pluggy.PluginManager
,具有額外的 pytest 特定功能從命令列、
PYTEST_PLUGINS
環境變數和pytest_plugins
全域變數載入外掛程式,這些變數在外掛程式載入時被找到。啟動期間載入
conftest.py
。
- register(plugin, name=None)[原始碼]¶
註冊一個外掛程式並傳回其名稱。
- 參數:
name (str | None) – 註冊外掛程式所使用的名稱。如果未指定,則會使用
get_canonical_name()
產生名稱。- 傳回:
外掛程式名稱。如果名稱被阻止註冊,則傳回
None
。- 傳回類型:
str | None
如果外掛程式已註冊,則引發
ValueError
。
- import_plugin(modname, consider_entry_points=False)[原始碼]¶
匯入具有
modname
的外掛程式。如果
consider_entry_points
為 True,則也會考慮 entry point 名稱以尋找外掛程式。
- add_hookcall_monitoring(before, after)¶
為所有 hook 新增 before/after 追蹤函數。
傳回一個 undo 函數,呼叫時會移除新增的追蹤器。
before(hook_name, hook_impls, kwargs)
將在所有 hook 呼叫之前被呼叫,並接收一個 hookcaller 實例、HookImpl 實例列表以及 hook 呼叫的關鍵字引數。after(outcome, hook_name, hook_impls, kwargs)
接收與before
相同的引數,但也接收一個Result
物件,代表整體 hook 呼叫的結果。
- add_hookspecs(module_or_class)¶
新增給定的
module_or_class
中定義的新 hook 規格。如果函數已使用相符的
HookspecMarker
裝飾器裝飾,則會被識別為 hook 規格。
- check_pending()¶
驗證所有尚未針對 hook 規格驗證的 hook 都是可選的,否則引發
PluginValidationError
。
- enable_tracing()¶
啟用 hook 呼叫的追蹤。
傳回一個 undo 函數,呼叫時會移除新增的追蹤。
- get_canonical_name(plugin)¶
傳回外掛程式物件的標準名稱。
請注意,外掛程式可能會以不同的名稱註冊,該名稱由
register(plugin, name)
的呼叫者指定。若要取得已註冊外掛程式的名稱,請改用get_name(plugin)
。
- get_hookcallers(plugin)¶
取得指定外掛程式的所有 hook 呼叫器。
- 傳回:
hook 呼叫器,如果
plugin
未在此外掛程式管理器中註冊,則為None
。- 傳回類型:
list[HookCaller] | None
- get_name(plugin)¶
傳回外掛程式註冊時使用的名稱,如果沒有註冊則傳回
None
。
- get_plugin(name)¶
傳回以給定名稱註冊的外掛程式 (如果有的話)。
- get_plugins()¶
傳回所有已註冊外掛程式物件的集合。
- has_plugin(name)¶
傳回是否已註冊具有給定名稱的外掛程式。
- is_blocked(name)¶
傳回給定的外掛程式名稱是否被封鎖。
- is_registered(plugin)¶
傳回外掛程式是否已註冊。
- list_name_plugin()¶
傳回所有已註冊外掛程式的 (名稱, 外掛程式) 配對列表。
- list_plugin_distinfo()¶
傳回所有 setuptools 註冊外掛程式的 (外掛程式, distinfo) 配對列表。
- load_setuptools_entrypoints(group, name=None)¶
從查詢指定的 setuptools
group
載入模組。
- set_blocked(name)¶
封鎖給定名稱的註冊,如果已註冊則取消註冊。
- subset_hook_caller(name, remove_plugins)¶
傳回具名方法的 proxy
HookCaller
實例,該實例管理對所有已註冊外掛程式的呼叫,但排除來自 remove_plugins 的外掛程式。
- unblock(name)¶
解除封鎖名稱。
傳回名稱是否實際上被封鎖。
- unregister(plugin=None, name=None)¶
取消註冊外掛程式及其所有 hook 實作。
外掛程式可以透過外掛程式物件或外掛程式名稱指定。如果兩者都指定,則它們必須一致。
傳回已取消註冊的外掛程式,如果找不到則傳回
None
。
- project_name: Final¶
專案名稱。
TestReport¶
- final class TestReport[原始碼]¶
基底類別:
BaseReport
基本測試報告物件 (也用於 setup 和 teardown 呼叫,如果它們失敗)。
報告可以包含任意的額外屬性。
- location: tuple[str, int | None, str]¶
一個 (檔案系統路徑, 行號, 網域資訊) 元組,指示測試項目的實際位置 - 它可能與收集到的位置不同,例如,如果方法是從不同的模組繼承的。檔案系統路徑可能是相對於
config.rootdir
的相對路徑。行號從 0 開始。
- longrepr: None | ExceptionInfo[BaseException] | tuple[str, int, str] | str | TerminalRepr¶
None 或失敗表示法。
- user_properties¶
使用者屬性是 (名稱, 值) 元組的列表,其中包含使用者定義的測試屬性。
- sections: list[tuple[str, str]]¶
str
(heading, content)
的元組,其中包含測試報告的額外資訊。pytest 使用它來新增從stdout
、stderr
捕獲的文字,以及攔截的記錄事件。其他外掛程式可以使用它將任意資訊新增至報告。
- property count_towards_summary: bool¶
實驗性質 此報告是否應計入測試階段結束時顯示的總計:「1 個通過、1 個失敗等等」。
注意
此函式被視為實驗性質,因此請注意,即使在修補程式版本中也可能會變更。
TestShortLogReport¶
Result¶
在 hook wrappers 中使用的結果物件,請參閱 pluggy 文件中的 Result
以取得更多資訊。
Stash¶
- 類別 Stash[source]¶
Stash
是一個型別安全、異質的可變對應,允許金鑰和值型別與其建立位置(Stash
)分開定義。通常你會獲得一個具有
Stash
的物件,例如Config
或Node
stash: Stash = some_object.stash
如果模組或外掛想要在此
Stash
中儲存資料,它會為其金鑰建立StashKey
(在模組層級)# At the top-level of the module some_str_key = StashKey[str]() some_bool_key = StashKey[bool]()
儲存資訊
# Value type must match the key. stash[some_str_key] = "value" stash[some_bool_key] = True
擷取資訊
# The static type of some_str is str. some_str = stash[some_str_key] # The static type of some_bool is bool. some_bool = stash[some_bool_key]
在版本 7.0 中新增。
全域變數¶
當在測試模組或 conftest.py
檔案中定義時,pytest 會以特殊方式處理某些全域變數。
- collect_ignore¶
教學: 自訂測試收集
可以在 conftest.py 檔案 中宣告以排除測試目錄或模組。需要是路徑列表(str
、 pathlib.Path
或任何 os.PathLike
)。
collect_ignore = ["setup.py"]
- collect_ignore_glob¶
教學: 自訂測試收集
可以在 conftest.py 檔案 中宣告,以使用 Unix shell 樣式的萬用字元排除測試目錄或模組。需要是 list[str]
,其中 str
可以包含 glob 模式。
collect_ignore_glob = ["*_ignore.py"]
- pytest_plugins¶
教學: 在測試模組或 conftest 檔案中要求/載入外掛
可以在測試模組和 conftest.py 檔案的全域層級宣告,以註冊額外的外掛。可以是 str
或 Sequence[str]
。
pytest_plugins = "myapp.testsupport.myplugin"
pytest_plugins = ("myapp.testsupport.tools", "myapp.testsupport.regression")
- pytestmark¶
教學: 標記整個類別或模組
可以在測試模組的全域層級宣告,以將一個或多個 標記 應用於所有測試函數和方法。可以是單個標記或標記列表(依從左到右的順序應用)。
import pytest
pytestmark = pytest.mark.webtest
import pytest
pytestmark = [pytest.mark.integration, pytest.mark.slow]
環境變數¶
可用於變更 pytest 行為的環境變數。
- CI¶
當設定時(無論值為何),pytest 會確認它正在 CI 流程中執行。是 BUILD_NUMBER
變數的替代方案。另請參閱 CI Pipelines。
- BUILD_NUMBER¶
當設定時(無論值為何),pytest 會確認它正在 CI 流程中執行。是 CI 變數的替代方案。另請參閱 CI Pipelines。
- PYTEST_ADDOPTS¶
這包含一個命令列(由 py:mod:shlex
模組解析),它將前置到使用者給定的命令列,請參閱 內建設定檔選項 以取得更多資訊。
- PYTEST_VERSION¶
此環境變數在 pytest 會話開始時定義,之後會取消定義。它包含 pytest.__version__
的值,除其他外,可用於輕鬆檢查程式碼是否從 pytest 執行中執行。
- PYTEST_CURRENT_TEST¶
這並非供使用者設定,而是由 pytest 內部設定,其中包含當前測試的名稱,以便其他流程可以檢查它,請參閱 PYTEST_CURRENT_TEST 環境變數 以取得更多資訊。
- PYTEST_DEBUG¶
當設定時,pytest 將印出追蹤和偵錯資訊。
- PYTEST_DEBUG_TEMPROOT¶
由諸如 tmp_path
之類的 fixtures 產生的暫存目錄的根目錄,如 暫存目錄位置和保留 中所述。
- PYTEST_DISABLE_PLUGIN_AUTOLOAD¶
設定後,會透過 entry point packaging metadata 停用外掛自動載入。僅會載入明確指定的外掛。
- PYTEST_PLUGINS¶
包含應載入為外掛的模組的逗號分隔清單
export PYTEST_PLUGINS=mymodule.plugin,xdist
- PYTEST_THEME¶
設定用於程式碼輸出的 pygment 風格。
- PYTEST_THEME_MODE¶
將 PYTEST_THEME
設定為 dark 或 light。
- PY_COLORS¶
當設定為 1
時,pytest 將在終端機輸出中使用顏色。當設定為 0
時,pytest 將不會使用顏色。PY_COLORS
優先於 NO_COLOR
和 FORCE_COLOR
。
- NO_COLOR¶
當設定為非空字串時(無論值為何),pytest 將不會在終端機輸出中使用顏色。PY_COLORS
優先於 NO_COLOR
,而 NO_COLOR
又優先於 FORCE_COLOR
。有關其他支援此社群標準的程式庫,請參閱 no-color.org。
- FORCE_COLOR¶
當設定為非空字串時(無論值為何),pytest 將在終端機輸出中使用顏色。PY_COLORS
和 NO_COLOR
優先於 FORCE_COLOR
。
例外¶
- final exception FixtureLookupError[source]¶
基底類別:
LookupError
無法傳回請求的 fixture(遺失或無效)。
警告¶
在某些情況下產生的自訂警告,例如不當使用或已棄用的功能。
- 類別 PytestWarning¶
基底類別:
UserWarning
pytest 發出的所有警告的基底類別。
- 類別 PytestAssertRewriteWarning¶
基底類別:
PytestWarning
pytest assert rewrite 模組發出的警告。
- 類別 PytestCacheWarning¶
基底類別:
PytestWarning
cache 外掛在各種情況下發出的警告。
- 類別 PytestCollectionWarning¶
基底類別:
PytestWarning
當 pytest 無法收集模組中的檔案或符號時發出的警告。
- 類別 PytestConfigWarning¶
基底類別:
PytestWarning
針對設定問題發出的警告。
- 類別 PytestDeprecationWarning¶
基底類別:
PytestWarning
、DeprecationWarning
用於未來版本中將移除的功能的警告類別。
- 類別 PytestExperimentalApiWarning¶
基底類別:
PytestWarning
、FutureWarning
用於表示 pytest 中實驗的警告類別。
請謹慎使用,因為 API 可能會在未來版本中變更甚至完全移除。
- 類別 PytestReturnNotNoneWarning¶
基底類別:
PytestWarning
當測試函數傳回 None 以外的值時發出的警告。
- 類別 PytestRemovedIn9Warning¶
基底類別:
PytestDeprecationWarning
用於 pytest 9 中將移除的功能的警告類別。
- 類別 PytestUnhandledCoroutineWarning¶
基底類別:
PytestReturnNotNoneWarning
針對未處理的協程發出的警告。
在收集測試函數時遇到協程,但未被任何非同步感知外掛處理。原生不支援協程測試函數。
- 類別 PytestUnknownMarkWarning¶
基底類別:
PytestWarning
在使用不明標記時發出的警告。
有關詳細資訊,請參閱 如何使用屬性標記測試函數 。
- 類別 PytestUnraisableExceptionWarning¶
基底類別:
PytestWarning
報告了一個無法引發的例外。
無法引發的例外是在
__del__
實作和類似情況下引發的例外,在這些情況下,例外無法像正常情況一樣引發。
- 類別 PytestUnhandledThreadExceptionWarning¶
基底類別:
PytestWarning
在
Thread
中發生未處理的例外。此類例外通常不會傳播。
有關更多資訊,請參閱文件中的 內部 pytest 警告 章節。
設定選項¶
以下是可以寫入 pytest.ini
(或 .pytest.ini
)、 pyproject.toml
、 tox.ini
或 setup.cfg
檔案(通常位於儲存庫的根目錄)中的內建設定選項列表。
若要查看每個檔案格式的詳細資訊,請參閱 設定檔格式。
警告
除了非常簡單的用例外,不建議使用 setup.cfg
。 .cfg
檔案使用與 pytest.ini
和 tox.ini
不同的解析器,這可能會導致難以追蹤的問題。如果可能,建議使用後者檔案或 pyproject.toml
來保存您的 pytest 設定。
設定選項可以在命令列中使用 -o/--override-ini
覆寫,也可以多次傳遞。預期的格式為 name=value
。例如
pytest -o console_output_style=classic -o cache_dir=/tmp/mycache
- addopts¶
將指定的
OPTS
新增至命令列引數集合,就像使用者已指定它們一樣。範例:如果您有此 ini 檔案內容# content of pytest.ini [pytest] addopts = --maxfail=2 -rf # exit after 2 failures, report fail info
發出
pytest test_hello.py
實際上表示pytest --maxfail=2 -rf test_hello.py
預設為不新增任何選項。
- cache_dir¶
設定儲存 cache 外掛內容的目錄。預設目錄為
.pytest_cache
,它在 rootdir 中建立。目錄可以是相對或絕對路徑。如果設定相對路徑,則目錄是相對於 rootdir 建立的。此外,路徑可能包含將展開的環境變數。有關 cache 外掛的更多資訊,請參閱 如何重新執行失敗的測試並在測試執行之間維護狀態。
- consider_namespace_packages¶
控制 pytest 是否應在收集 Python 模組時嘗試識別 命名空間套件 。預設值為
False
。如果您正在測試的套件是命名空間套件的一部分,請設定為
True
。僅支援 原生命名空間套件 ,並且沒有計劃支援 舊式命名空間套件 。
在版本 8.1 中新增。
- console_output_style¶
設定執行測試時的控制台輸出樣式
classic
:經典 pytest 輸出。progress
:類似經典 pytest 輸出,但帶有進度指示器。progress-even-when-capture-no
:即使在capture=no
的情況下,也允許使用進度指示器。count
:類似於 progress,但以已完成的測試計數而非百分比來顯示進度。
預設值為
progress
,但如果您偏好classic
,或者新的模式導致意外問題,您可以回退到classic
。# content of pytest.ini [pytest] console_output_style = classic
- doctest_encoding¶
用於解碼包含 docstring 的文字檔的預設編碼。請參閱 pytest 如何處理 doctest。
- doctest_optionflags¶
來自標準
doctest
模組的一個或多個 doctest 旗標名稱。請參閱 pytest 如何處理 doctest。
- empty_parameter_set_mark¶
允許選擇參數化中空參數集的動作
skip
跳過具有空參數集的測試(預設值)xfail
將具有空參數集的測試標記為 xfail(run=False)fail_at_collect
如果參數化收集到空參數集,則引發例外
# content of pytest.ini [pytest] empty_parameter_set_mark = xfail
注意
此選項的預設值計劃在未來版本中更改為
xfail
,因為這被認為更不容易出錯,詳情請參閱 #3155。
- faulthandler_timeout¶
如果測試執行時間超過
X
秒(包括 fixture 設定和拆卸),則傾印所有執行緒的回溯 (traceback)。使用faulthandler.dump_traceback_later()
函式實作,因此所有注意事項都適用。# content of pytest.ini [pytest] faulthandler_timeout=5
有關更多資訊,請參閱 Fault Handler。
- filterwarnings¶
設定應針對匹配的警告採取的篩選器和動作列表。預設情況下,測試會話期間發出的所有警告將顯示在測試會話結束時的摘要中。
# content of pytest.ini [pytest] filterwarnings = error ignore::DeprecationWarning
這告訴 pytest 忽略棄用警告,並將所有其他警告轉換為錯誤。有關更多資訊,請參閱 如何捕獲警告。
- junit_duration_report¶
版本 4.1 新增。
設定如何將持續時間記錄到 JUnit XML 報告中
total
(預設值):報告的持續時間包括設定、呼叫和拆卸時間。call
:報告的持續時間僅包括呼叫時間,不包括設定和拆卸。
[pytest] junit_duration_report = call
- junit_family¶
版本 4.2 新增。
版本 6.1 變更:預設值變更為
xunit2
。設定產生的 JUnit XML 檔案的格式。可能的選項有
xunit1
(或legacy
):產生舊式輸出,與 xunit 1.0 格式相容。xunit2
:產生 xunit 2.0 樣式輸出,應更相容於最新的 Jenkins 版本。這是預設值。
[pytest] junit_family = xunit2
- junit_logging¶
在版本 3.5 中新增。
版本 5.4 變更:新增
log
、all
、out-err
選項。設定是否應將捕獲的輸出寫入 JUnit XML 檔案。有效值為
log
:僅寫入logging
捕獲的輸出。system-out
:寫入捕獲的stdout
內容。system-err
:寫入捕獲的stderr
內容。out-err
:同時寫入捕獲的stdout
和stderr
內容。all
:寫入捕獲的logging
、stdout
和stderr
內容。no
(預設值):不寫入捕獲的輸出。
[pytest] junit_logging = system-out
- junit_log_passing_tests¶
版本 4.6 新增。
如果
junit_logging != "no"
,則設定是否應將捕獲的輸出寫入 通過 測試的 JUnit XML 檔案。預設值為True
。[pytest] junit_log_passing_tests = False
- junit_suite_name¶
若要設定根測試套件 xml 項目的名稱,您可以在設定檔中設定
junit_suite_name
選項[pytest] junit_suite_name = my_suite
- log_auto_indent¶
允許選擇性自動縮排多行日誌訊息。
支援命令列選項
--log-auto-indent [value]
和設定選項log_auto_indent = [value]
,以設定所有日誌記錄的自動縮排行為。[value]
可以是True 或 “On” - 動態自動縮排多行日誌訊息
False 或 “Off” 或 0 - 不自動縮排多行日誌訊息 (預設行為)
[正整數] - 將多行日誌訊息自動縮排 [value] 個空格
[pytest] log_auto_indent = False
支援將 kwarg
extra={"auto_indent": [value]}
傳遞給logging.log()
的呼叫,以指定日誌中特定條目的自動縮排行為。extra
kwarg 會覆寫在命令列或設定中指定的值。
- log_cli_date_format¶
設定與
time.strftime()
相容的字串,該字串將用於格式化即時日誌記錄的日期。[pytest] log_cli_date_format = %Y-%m-%d %H:%M:%S
有關更多資訊,請參閱 即時日誌。
- log_cli_format¶
設定與
logging
相容的字串,用於格式化即時日誌記錄訊息。[pytest] log_cli_format = %(asctime)s %(levelname)s %(message)s
有關更多資訊,請參閱 即時日誌。
- log_date_format¶
設定與
time.strftime()
相容的字串,該字串將用於格式化日誌捕獲的日期。[pytest] log_date_format = %Y-%m-%d %H:%M:%S
有關更多資訊,請參閱 如何管理日誌記錄。
- log_file¶
設定相對於目前工作目錄的檔案名稱,日誌訊息應寫入該檔案,以及其他活動的日誌記錄設施。
[pytest] log_file = logs/pytest-logs.txt
有關更多資訊,請參閱 如何管理日誌記錄。
- log_file_date_format¶
設定與
time.strftime()
相容的字串,該字串將用於格式化日誌檔案的日期。[pytest] log_file_date_format = %Y-%m-%d %H:%M:%S
有關更多資訊,請參閱 如何管理日誌記錄。
- log_file_format¶
設定與
logging
相容的字串,用於格式化重新導向到日誌檔案的日誌記錄訊息。[pytest] log_file_format = %(asctime)s %(levelname)s %(message)s
有關更多資訊,請參閱 如何管理日誌記錄。
- log_file_level¶
設定應為日誌檔案捕獲的最低日誌訊息層級。可以使用整數值或層級名稱。
[pytest] log_file_level = INFO
有關更多資訊,請參閱 如何管理日誌記錄。
- log_format¶
設定與
logging
相容的字串,用於格式化捕獲的日誌記錄訊息。[pytest] log_format = %(asctime)s %(levelname)s %(message)s
有關更多資訊,請參閱 如何管理日誌記錄。
- markers¶
當使用
--strict-markers
或--strict
命令列引數時,僅允許已知的標記 (marker) - 由核心 pytest 或某些外掛程式在程式碼中定義的標記。您可以在此設定中列出其他標記,以將其新增到白名單,在這種情況下,您可能需要將
--strict-markers
新增到addopts
,以避免未來發生回歸。[pytest] addopts = --strict-markers markers = slow serial
注意
強烈建議使用
--strict-markers
。--strict
僅為了向後相容性而保留,並且可能會讓其他人感到困惑,因為它僅適用於標記,而不適用於其他選項。
- minversion¶
指定執行測試所需的最低 pytest 版本。
# content of pytest.ini [pytest] minversion = 3.0 # will fail if we run with pytest-2.8
- norecursedirs¶
設定在遞迴搜尋測試時要避免的目錄基本名稱模式。個別的 (fnmatch 樣式) 模式會套用至目錄的基本名稱,以決定是否遞迴進入其中。模式匹配字元
* matches everything ? matches any single character [seq] matches any character in seq [!seq] matches any char not in seq
預設模式為
'*.egg'
、'.*'
、'_darcs'
、'build'
、'CVS'
、'dist'
、'node_modules'
、'venv'
、'{arch}'
。設定norecursedirs
會取代預設值。以下是如何避免特定目錄的範例[pytest] norecursedirs = .svn _build tmp*
這會告訴
pytest
不要查找典型的 subversion 或 sphinx-build 目錄,或任何以tmp
為字首的目錄。此外,
pytest
將嘗試智慧型地識別並忽略 virtualenv。任何被視為虛擬環境根目錄的目錄將不會在測試收集期間被考慮,除非給定--collect-in-virtualenv
。另請注意,norecursedirs
優先於--collect-in-virtualenv
;例如,如果您打算在基本目錄與'.*'
匹配的虛擬環境中執行測試,您除了使用--collect-in-virtualenv
旗標外,必須 覆寫norecursedirs
。
- python_classes¶
一個或多個名稱字首或 glob 樣式模式,用於決定哪些類別被視為測試收集。透過在模式之間新增空格來搜尋多個 glob 模式。預設情況下,pytest 會將任何以
Test
為字首的類別視為測試收集。以下是如何從以Suite
結尾的類別收集測試的範例[pytest] python_classes = *Suite
請注意,無論此選項為何,都會始終收集
unittest.TestCase
衍生類別,因為unittest
自己的收集框架用於收集這些測試。
- python_files¶
一個或多個 Glob 樣式檔案模式,用於決定哪些 python 檔案被視為測試模組。透過在模式之間新增空格來搜尋多個 glob 模式
[pytest] python_files = test_*.py check_*.py example_*.py
或每行一個
[pytest] python_files = test_*.py check_*.py example_*.py
預設情況下,符合
test_*.py
和*_test.py
的檔案將被視為測試模組。
- python_functions¶
一個或多個名稱字首或 glob 模式,用於決定哪些測試函式和方法被視為測試。透過在模式之間新增空格來搜尋多個 glob 模式。預設情況下,pytest 會將任何以
test
為字首的函式視為測試。以下是如何收集以_test
結尾的測試函式和方法的範例[pytest] python_functions = *_test
請注意,這對位於
unittest.TestCase
衍生類別上的方法沒有影響,因為unittest
自己的收集框架用於收集這些測試。請參閱 變更命名慣例 以取得更詳細的範例。
- pythonpath¶
設定應新增至 python 搜尋路徑的目錄列表。目錄將新增至
sys.path
的開頭。類似於PYTHONPATH
環境變數,目錄將包含在 Python 尋找匯入模組的位置中。路徑相對於 rootdir 目錄。目錄在測試會話期間保留在路徑中。[pytest] pythonpath = src1 src2
注意
pythonpath
不會影響某些很早就發生的匯入,最值得注意的是使用-p
命令列選項載入的外掛程式。
- required_plugins¶
pytest 執行時必須存在的以空格分隔的外掛程式列表。外掛程式可以直接在其名稱後列出,帶或不帶版本規範。不允許在不同版本規範之間留有空格。如果找不到任何一個外掛程式,則發出錯誤。
[pytest] required_plugins = pytest-django>=3.0.0,<4.0.0 pytest-html pytest-xdist>=1.0.0
- testpaths¶
設定應在 rootdir 目錄執行 pytest 時,在命令列中未給定特定目錄、檔案或測試 ID 的情況下,應搜尋測試的目錄列表。檔案系統路徑可以使用 shell 樣式的萬用字元,包括遞迴
**
模式。當所有專案測試都位於已知位置時,這很有用,可以加速測試收集並避免意外拾取不需要的測試。
[pytest] testpaths = testing doc
此設定表示執行
pytest
與執行以下命令具有相同的實際效果
pytest testing doc
- tmp_path_retention_count¶
根據
tmp_path_retention_policy
,我們應該保留tmp_path
目錄多少個會期。[pytest] tmp_path_retention_count = 3
預設值:
3
- tmp_path_retention_policy¶
控制
tmp_path
fixture 建立的哪些目錄會根據測試結果保留。all
:保留所有測試的目錄,無論結果如何。failed
:僅保留結果為error
或failed
的測試目錄。none
:目錄始終在每個測試結束後移除,無論結果如何。
[pytest] tmp_path_retention_policy = all
預設值:
all
- usefixtures¶
將套用於所有測試函式的 fixture 列表;這在語義上與將
@pytest.mark.usefixtures
標記套用於所有測試函式相同。[pytest] usefixtures = clean_db
- verbosity_assertions¶
專門為斷言相關輸出設定詳細程度層級,覆寫應用程式範圍的層級。
[pytest] verbosity_assertions = 2
預設為應用程式範圍的詳細程度層級 (透過
-v
命令列選項)。可以使用特殊值 “auto” 來明確使用全域詳細程度層級。
- verbosity_test_cases¶
專門為測試案例執行相關輸出設定詳細程度層級,覆寫應用程式範圍的層級。
[pytest] verbosity_test_cases = 2
預設為應用程式範圍的詳細程度層級 (透過
-v
命令列選項)。可以使用特殊值 “auto” 來明確使用全域詳細程度層級。
命令列旗標¶
所有命令列旗標都可以透過執行 pytest --help
取得
$ pytest --help
usage: pytest [options] [file_or_dir] [file_or_dir] [...]
positional arguments:
file_or_dir
general:
-k EXPRESSION Only run tests which match the given substring
expression. An expression is a Python evaluable
expression where all names are substring-matched
against test names and their parent classes.
Example: -k 'test_method or test_other' matches all
test functions and classes whose name contains
'test_method' or 'test_other', while -k 'not
test_method' matches those that don't contain
'test_method' in their names. -k 'not test_method
and not test_other' will eliminate the matches.
Additionally keywords are matched to classes and
functions containing extra names in their
'extra_keyword_matches' set, as well as functions
which have names assigned directly to them. The
matching is case-insensitive.
-m MARKEXPR Only run tests matching given mark expression. For
example: -m 'mark1 and not mark2'.
--markers show markers (builtin, plugin and per-project ones).
-x, --exitfirst Exit instantly on first error or failed test
--fixtures, --funcargs
Show available fixtures, sorted by plugin appearance
(fixtures with leading '_' are only shown with '-v')
--fixtures-per-test Show fixtures per test
--pdb Start the interactive Python debugger on errors or
KeyboardInterrupt
--pdbcls=modulename:classname
Specify a custom interactive Python debugger for use
with --pdb.For example:
--pdbcls=IPython.terminal.debugger:TerminalPdb
--trace Immediately break when running each test
--capture=method Per-test capturing method: one of fd|sys|no|tee-sys
-s Shortcut for --capture=no
--runxfail Report the results of xfail tests as if they were
not marked
--lf, --last-failed Rerun only the tests that failed at the last run (or
all if none failed)
--ff, --failed-first Run all tests, but run the last failures first. This
may re-order tests and thus lead to repeated fixture
setup/teardown.
--nf, --new-first Run tests from new files first, then the rest of the
tests sorted by file mtime
--cache-show=[CACHESHOW]
Show cache contents, don't perform collection or
tests. Optional argument: glob (default: '*').
--cache-clear Remove all cache contents at start of test run
--lfnf, --last-failed-no-failures={all,none}
With ``--lf``, determines whether to execute tests
when there are no previously (known) failures or
when no cached ``lastfailed`` data was found.
``all`` (the default) runs the full test suite
again. ``none`` just emits a message about no known
failures and exits successfully.
--sw, --stepwise Exit on test failure and continue from last failing
test next time
--sw-skip, --stepwise-skip
Ignore the first failing test but stop on the next
failing test. Implicitly enables --stepwise.
Reporting:
--durations=N Show N slowest setup/test durations (N=0 for all)
--durations-min=N Minimal duration in seconds for inclusion in slowest
list. Default: 0.005.
-v, --verbose Increase verbosity
--no-header Disable header
--no-summary Disable summary
--no-fold-skipped Do not fold skipped tests in short summary.
-q, --quiet Decrease verbosity
--verbosity=VERBOSE Set verbosity. Default: 0.
-r chars Show extra test summary info as specified by chars:
(f)ailed, (E)rror, (s)kipped, (x)failed, (X)passed,
(p)assed, (P)assed with output, (a)ll except passed
(p/P), or (A)ll. (w)arnings are enabled by default
(see --disable-warnings), 'N' can be used to reset
the list. (default: 'fE').
--disable-warnings, --disable-pytest-warnings
Disable warnings summary
-l, --showlocals Show locals in tracebacks (disabled by default)
--no-showlocals Hide locals in tracebacks (negate --showlocals
passed through addopts)
--tb=style Traceback print mode
(auto/long/short/line/native/no)
--xfail-tb Show tracebacks for xfail (as long as --tb != no)
--show-capture={no,stdout,stderr,log,all}
Controls how captured stdout/stderr/log is shown on
failed tests. Default: all.
--full-trace Don't cut any tracebacks (default is to cut)
--color=color Color terminal output (yes/no/auto)
--code-highlight={yes,no}
Whether code should be highlighted (only if --color
is also enabled). Default: yes.
--pastebin=mode Send failed|all info to bpaste.net pastebin service
--junitxml, --junit-xml=path
Create junit-xml style report file at given path
--junitprefix, --junit-prefix=str
Prepend prefix to classnames in junit-xml output
pytest-warnings:
-W, --pythonwarnings PYTHONWARNINGS
Set which warnings to report, see -W option of
Python itself
--maxfail=num Exit after first num failures or errors
--strict-config Any warnings encountered while parsing the `pytest`
section of the configuration file raise errors
--strict-markers Markers not registered in the `markers` section of
the configuration file raise errors
--strict (Deprecated) alias to --strict-markers
-c, --config-file FILE
Load configuration from `FILE` instead of trying to
locate one of the implicit configuration files.
--continue-on-collection-errors
Force test execution even if collection errors occur
--rootdir=ROOTDIR Define root directory for tests. Can be relative
path: 'root_dir', './root_dir',
'root_dir/another_dir/'; absolute path:
'/home/user/root_dir'; path with variables:
'$HOME/root_dir'.
collection:
--collect-only, --co Only collect tests, don't execute them
--pyargs Try to interpret all arguments as Python packages
--ignore=path Ignore path during collection (multi-allowed)
--ignore-glob=path Ignore path pattern during collection (multi-
allowed)
--deselect=nodeid_prefix
Deselect item (via node id prefix) during collection
(multi-allowed)
--confcutdir=dir Only load conftest.py's relative to specified dir
--noconftest Don't load any conftest.py files
--keep-duplicates Keep duplicate tests
--collect-in-virtualenv
Don't ignore tests in a local virtualenv directory
--import-mode={prepend,append,importlib}
Prepend/append to sys.path when importing test
modules and conftest files. Default: prepend.
--doctest-modules Run doctests in all .py modules
--doctest-report={none,cdiff,ndiff,udiff,only_first_failure}
Choose another output format for diffs on doctest
failure
--doctest-glob=pat Doctests file matching pattern, default: test*.txt
--doctest-ignore-import-errors
Ignore doctest collection errors
--doctest-continue-on-failure
For a given doctest, continue to run after the first
failure
test session debugging and configuration:
--basetemp=dir Base temporary directory for this test run.
(Warning: this directory is removed if it exists.)
-V, --version Display pytest version and information about
plugins. When given twice, also display information
about plugins.
-h, --help Show help message and configuration info
-p name Early-load given plugin module name or entry point
(multi-allowed). To avoid loading of plugins, use
the `no:` prefix, e.g. `no:doctest`.
--trace-config Trace considerations of conftest.py files
--debug=[DEBUG_FILE_NAME]
Store internal tracing debug information in this log
file. This file is opened with 'w' and truncated as
a result, care advised. Default: pytestdebug.log.
-o, --override-ini OVERRIDE_INI
Override ini option with "option=value" style, e.g.
`-o xfail_strict=True -o cache_dir=cache`.
--assert=MODE Control assertion debugging tools.
'plain' performs no assertion debugging.
'rewrite' (the default) rewrites assert statements
in test modules on import to provide assert
expression information.
--setup-only Only setup fixtures, do not execute tests
--setup-show Show setup of fixtures while executing tests
--setup-plan Show what fixtures and tests would be executed but
don't execute anything
logging:
--log-level=LEVEL Level of messages to catch/display. Not set by
default, so it depends on the root/parent log
handler's effective level, where it is "WARNING" by
default.
--log-format=LOG_FORMAT
Log format used by the logging module
--log-date-format=LOG_DATE_FORMAT
Log date format used by the logging module
--log-cli-level=LOG_CLI_LEVEL
CLI logging level
--log-cli-format=LOG_CLI_FORMAT
Log format used by the logging module
--log-cli-date-format=LOG_CLI_DATE_FORMAT
Log date format used by the logging module
--log-file=LOG_FILE Path to a file when logging will be written to
--log-file-mode={w,a}
Log file open mode
--log-file-level=LOG_FILE_LEVEL
Log file logging level
--log-file-format=LOG_FILE_FORMAT
Log format used by the logging module
--log-file-date-format=LOG_FILE_DATE_FORMAT
Log date format used by the logging module
--log-auto-indent=LOG_AUTO_INDENT
Auto-indent multiline messages passed to the logging
module. Accepts true|on, false|off or an integer.
--log-disable=LOGGER_DISABLE
Disable a logger by name. Can be passed multiple
times.
[pytest] ini-options in the first pytest.ini|tox.ini|setup.cfg|pyproject.toml file found:
markers (linelist): Register new markers for test functions
empty_parameter_set_mark (string):
Default marker for empty parametersets
norecursedirs (args): Directory patterns to avoid for recursion
testpaths (args): Directories to search for tests when no files or
directories are given on the command line
filterwarnings (linelist):
Each line specifies a pattern for
warnings.filterwarnings. Processed after
-W/--pythonwarnings.
consider_namespace_packages (bool):
Consider namespace packages when resolving module
names during import
usefixtures (args): List of default fixtures to be used with this
project
python_files (args): Glob-style file patterns for Python test module
discovery
python_classes (args):
Prefixes or glob names for Python test class
discovery
python_functions (args):
Prefixes or glob names for Python test function and
method discovery
disable_test_id_escaping_and_forfeit_all_rights_to_community_support (bool):
Disable string escape non-ASCII characters, might
cause unwanted side effects(use at your own risk)
console_output_style (string):
Console output: "classic", or with additional
progress information ("progress" (percentage) |
"count" | "progress-even-when-capture-no" (forces
progress even when capture=no)
verbosity_test_cases (string):
Specify a verbosity level for test case execution,
overriding the main level. Higher levels will
provide more detailed information about each test
case executed.
xfail_strict (bool): Default for the strict parameter of xfail markers
when not given explicitly (default: False)
tmp_path_retention_count (string):
How many sessions should we keep the `tmp_path`
directories, according to
`tmp_path_retention_policy`.
tmp_path_retention_policy (string):
Controls which directories created by the `tmp_path`
fixture are kept around, based on test outcome.
(all/failed/none)
enable_assertion_pass_hook (bool):
Enables the pytest_assertion_pass hook. Make sure to
delete any previously generated pyc cache files.
verbosity_assertions (string):
Specify a verbosity level for assertions, overriding
the main level. Higher levels will provide more
detailed explanation when an assertion fails.
junit_suite_name (string):
Test suite name for JUnit report
junit_logging (string):
Write captured log messages to JUnit report: one of
no|log|system-out|system-err|out-err|all
junit_log_passing_tests (bool):
Capture log information for passing tests to JUnit
report:
junit_duration_report (string):
Duration time to report: one of total|call
junit_family (string):
Emit XML for schema: one of legacy|xunit1|xunit2
doctest_optionflags (args):
Option flags for doctests
doctest_encoding (string):
Encoding used for doctest files
cache_dir (string): Cache directory path
log_level (string): Default value for --log-level
log_format (string): Default value for --log-format
log_date_format (string):
Default value for --log-date-format
log_cli (bool): Enable log display during test run (also known as
"live logging")
log_cli_level (string):
Default value for --log-cli-level
log_cli_format (string):
Default value for --log-cli-format
log_cli_date_format (string):
Default value for --log-cli-date-format
log_file (string): Default value for --log-file
log_file_mode (string):
Default value for --log-file-mode
log_file_level (string):
Default value for --log-file-level
log_file_format (string):
Default value for --log-file-format
log_file_date_format (string):
Default value for --log-file-date-format
log_auto_indent (string):
Default value for --log-auto-indent
pythonpath (paths): Add paths to sys.path
faulthandler_timeout (string):
Dump the traceback of all threads if a test takes
more than TIMEOUT seconds to finish
addopts (args): Extra command line options
minversion (string): Minimally required pytest version
required_plugins (args):
Plugins that must be present for pytest to run
Environment variables:
CI When set (regardless of value), pytest knows it is running in a CI process and does not truncate summary info
BUILD_NUMBER Equivalent to CI
PYTEST_ADDOPTS Extra command line options
PYTEST_PLUGINS Comma-separated plugins to load during startup
PYTEST_DISABLE_PLUGIN_AUTOLOAD Set to disable plugin auto-loading
PYTEST_DEBUG Set to enable debug tracing of pytest's internals
to see available markers type: pytest --markers
to see available fixtures type: pytest --fixtures
(shown according to specified file_or_dir or current dir if not specified; fixtures with leading '_' are only shown with the '-v' option