用法:
test.support.warnings_helper.check_warnings(*filters, quiet=True)
warnings.catch_warnings()
的便捷包裝器,可以更輕鬆地測試是否正確引發了警告。它大約相當於調用warnings.catch_warnings(record=True)
並將warnings.simplefilter()
設置為always
並帶有自動驗證記錄的結果的選項。check_warnings
接受("message regexp", WarningCategory)
形式的 2 元組作為位置參數。如果提供了一個或多個filters
,或者如果可選的關鍵字參數quiet
是False
,它會檢查以確保警告與預期的一樣:每個指定的過濾器必須至少匹配隨附的警告中的一個代碼或測試失敗,並且如果引發與任何指定過濾器不匹配的任何警告,則測試失敗。要禁用這些檢查中的第一個,請將quiet
設置為True
。如果未指定參數,則默認為:
check_warnings(("", Warning), quiet=True)
在這種情況下,所有警告都會被捕獲,並且不會引發任何錯誤。
在進入上下文管理器時,會返回一個
WarningRecorder
實例。catch_warnings()
中的基礎警告列表可通過記錄器對象的warnings
屬性獲得。為方便起見,表示最近警告的對象的屬性也可以通過記錄器對象直接訪問(參見下麵的示例)。如果未引發任何警告,則表示警告的對象上預期的任何屬性都將返回None
。記錄器對象還有一個
reset()
方法,用於清除警告列表。上下文管理器被設計成這樣使用:
with check_warnings(("assertion is always true", SyntaxWarning), ("", UserWarning)): exec('assert(False, "Hey!")') warnings.warn(UserWarning("Hide me!"))
在這種情況下,如果沒有引發任何警告,或者引發了其他警告,
check_warnings()
將引發錯誤。當測試需要更深入地查看警告,而不僅僅是檢查它們是否發生時,可以使用如下代碼:
with check_warnings(quiet=True) as w: warnings.warn("foo") assert str(w.args[0]) == "foo" warnings.warn("bar") assert str(w.args[0]) == "bar" assert str(w.warnings[0].args[0]) == "foo" assert str(w.warnings[1].args[0]) == "bar" w.reset() assert len(w.warnings) == 0
這裏所有的警告都會被捕獲,測試代碼直接測試捕獲的警告。
在 3.2 版中更改:新的可選參數
filters
和quiet
.
相關用法
- Python test.support.catch_unraisable_exception用法及代碼示例
- Python test.support.load_package_tests用法及代碼示例
- Python test.support.check_impl_detail用法及代碼示例
- Python test.support.captured_stdin用法及代碼示例
- Python test.support.import_helper.import_fresh_module用法及代碼示例
- Python test.support.check__all__用法及代碼示例
- Python test.support.threading_helper.catch_threading_exception用法及代碼示例
- Python numpy testing.decorators.slow用法及代碼示例
- Python numpy testing.decorators.setastest用法及代碼示例
- Python tesnsorflow.grad_pass_through()用法及代碼示例
- Python textwrap.indent用法及代碼示例
- Python tensorflow.eye()用法及代碼示例
- Python tensorflow.fill()用法及代碼示例
- Python tensorflow.math.special.dawsn()用法及代碼示例
- Python tensorflow.ensure_shape()用法及代碼示例
- Python tensorflow.math.special.fresnel_cos()用法及代碼示例
- Python tensorflow.raw_ops.Cos()用法及代碼示例
- Python tensorflow.get_logger()用法及代碼示例
- Python tensorflow.math.sqrt()用法及代碼示例
- Python tensorflow.math.atanh()用法及代碼示例
注:本文由純淨天空篩選整理自python.org大神的英文原創作品 test.support.warnings_helper.check_warnings。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。