如何管理記錄¶
pytest 會自動擷取等級為 WARNING
或更高的記錄訊息,並在每個失敗的測試中顯示在自己的區段,方式與擷取的 stdout 和 stderr 相同。
不使用選項執行
pytest
顯示失敗的測試如下
----------------------- Captured stdlog call ----------------------
test_reporting.py 26 WARNING text going to logger
----------------------- Captured stdout call ----------------------
text going to stdout
----------------------- Captured stderr call ----------------------
text going to stderr
==================== 2 failed in 0.02 seconds =====================
預設每個擷取的記錄訊息會顯示模組、行號、記錄等級和訊息。
如果需要,可以透過傳遞特定格式化選項,將記錄和日期格式指定為記錄模組支援的任何格式
pytest --log-format="%(asctime)s %(levelname)s %(message)s" \
--log-date-format="%Y-%m-%d %H:%M:%S"
顯示失敗的測試如下
----------------------- Captured stdlog call ----------------------
2010-04-10 14:48:44 WARNING text going to logger
----------------------- Captured stdout call ----------------------
text going to stdout
----------------------- Captured stderr call ----------------------
text going to stderr
==================== 2 failed in 0.02 seconds =====================
這些選項也可以透過 pytest.ini
檔案自訂
[pytest]
log_format = %(asctime)s %(levelname)s %(message)s
log_date_format = %Y-%m-%d %H:%M:%S
可以透過 --log-disable={logger_name}
停用特定記錄器。此引數可以傳遞多次
pytest --log-disable=main --log-disable=testing
此外,可以使用下列方式在失敗的測試中完全停用擷取內容(stdout、stderr 和記錄)的報告
pytest --show-capture=no
caplog 固定裝置¶
在測試中,可以變更擷取記錄訊息的記錄等級。這是由 caplog
固定裝置支援
def test_foo(caplog):
caplog.set_level(logging.INFO)
預設在根記錄器上設定等級,但為了方便,也可以設定任何記錄器的記錄等級
def test_foo(caplog):
caplog.set_level(logging.CRITICAL, logger="root.baz")
設定的記錄等級會在測試結束時自動還原。
也可以使用內容管理員在 with
區塊中暫時變更記錄等級
def test_bar(caplog):
with caplog.at_level(logging.INFO):
pass
同樣地,預設會影響根記錄器的等級,但也可以使用下列方式變更任何記錄器的等級
def test_bar(caplog):
with caplog.at_level(logging.CRITICAL, logger="root.baz"):
pass
最後,測試執行期間傳送到記錄器的所有記錄會以 logging.LogRecord
實例和最後的記錄文字兩種形式提供給固定裝置。這對於當你想要針對訊息內容進行斷言時很有用
def test_baz(caplog):
func_under_test()
for record in caplog.records:
assert record.levelname != "CRITICAL"
assert "wally" not in caplog.text
對於記錄記錄的所有可用屬性,請參閱 logging.LogRecord
類別。
如果你只想確保已在特定記錄器名稱下使用特定嚴重性等級和訊息記錄某些訊息,也可以使用 record_tuples
def test_foo(caplog):
logging.getLogger().info("boo %s", "arg")
assert caplog.record_tuples == [("root", logging.INFO, "boo arg")]
你可以呼叫 caplog.clear()
來重設測試中擷取的記錄記錄
def test_something_with_clearing_records(caplog):
some_method_that_creates_log_records()
caplog.clear()
your_test_method()
assert ["Foo"] == [rec.message for rec in caplog.records]
caplog.records
屬性僅包含來自目前階段的記錄,因此在 setup
階段中,它只包含設定記錄,call
和 teardown
階段也是如此。
若要存取其他階段的記錄,請使用 caplog.get_records(when)
方法。舉例來說,如果你想要確保使用特定固定裝置的測試永遠不會記錄任何警告,你可以像這樣在中斷期間檢查 setup
和 call
階段的記錄
@pytest.fixture
def window(caplog):
window = create_window()
yield window
for when in ("setup", "call"):
messages = [
x.message for x in caplog.get_records(when) if x.levelno == logging.WARNING
]
if messages:
pytest.fail(f"warning messages encountered during testing: {messages}")
完整的 API 可在 pytest.LogCaptureFixture
取得。
警告
caplog
固定裝置會將處理常式新增至根記錄器以擷取記錄。如果根記錄器在測試期間被修改,例如使用 logging.config.dictConfig
,這個處理常式可能會被移除,並導致無法擷取任何記錄。若要避免這種情況,請確保任何根記錄器組態只會新增至現有的處理常式。
即時記錄¶
透過將 log_cli
組態選項設定為 true
,pytest 會在記錄發出時將其直接輸出到主控台。
您可以透過傳遞 --log-cli-level
來指定要將哪個層級或更高層級的記錄列印至主控台。此設定接受記錄層級名稱或數值,如 記錄文件 中所示。
此外,您也可以指定 --log-cli-format
和 --log-cli-date-format
,它們會反映並預設為 --log-format
和 --log-date-format
(如果未提供),但僅套用於主控台記錄處理常式。
所有 CLI 記錄選項也可以在組態 INI 檔案中設定。選項名稱為
log_cli_level
log_cli_format
log_cli_date_format
如果您需要將整個測試套件的記錄呼叫記錄到檔案,您可以傳遞 --log-file=/path/to/log/file
。此記錄檔案預設以寫入模式開啟,表示它會在每次執行測試階段時覆寫。如果您希望檔案以附加模式開啟,則可以傳遞 --log-file-mode=a
。請注意,記錄檔案位置的相對路徑(無論是在 CLI 中傳遞或在組態檔案中宣告)總是相對於目前工作目錄解析。
您也可以透過傳遞 --log-file-level
來指定記錄檔案的記錄層級。此設定接受記錄層級名稱或數值,如 記錄文件 中所示。
此外,您也可以指定 --log-file-format
和 --log-file-date-format
,它們等於 --log-format
和 --log-date-format
,但套用於記錄檔案記錄處理常式。
所有記錄檔案選項也可以在組態 INI 檔案中設定。選項名稱為
log_file
log_file_mode
log_file_level
log_file_format
log_file_date_format
您可以呼叫 set_log_path()
來動態自訂 log_file 路徑。此功能被視為實驗性。請注意,set_log_path()
會尊重 log_file_mode
選項。
自訂色彩¶
如果啟用彩色終端機輸出,則記錄等級會以彩色顯示。透過 add_color_level()
支援變更預設顏色或在自訂記錄等級上加上顏色。範例
@pytest.hookimpl(trylast=True)
def pytest_configure(config):
logging_plugin = config.pluginmanager.get_plugin("logging-plugin")
# Change color on existing log level
logging_plugin.log_cli_handler.formatter.add_color_level(logging.INFO, "cyan")
# Add color to a custom log level (a custom log level `SPAM` is already set up)
logging_plugin.log_cli_handler.formatter.add_color_level(logging.SPAM, "blue")
警告
此功能及其 API 被視為實驗性質,且可能在版本之間變更,而不會發出不建議使用的通知。
版本說明¶
此功能作為 pytest-catchlog 外掛程式的替代方案,而它們會互相衝突。當此功能推出時,已移除與 pytest-capturelog
的舊版相容性 API,因此如果您仍需要 pytest-catchlog
,可以將下列內容新增至 pytest.ini
中,以停用內部功能
[pytest]
addopts=-p no:logging
pytest 3.4 中的不相容變更¶
此功能在 3.3
中推出,在收到社群回饋後,已在 3.4
中進行一些不相容變更
除非明確要求
log_level
組態或--log-level
命令列選項,否則不再變更記錄等級。這允許使用者自行組態記錄器物件。設定log_level
會設定全球擷取的等級,因此如果特定測試需要較低的等級,請使用caplog.set_level()
功能,否則該測試容易失敗。即時記錄 現在預設停用,且可以設定
log_cli
組態選項為true
來啟用。啟用後,詳細程度會提高,因此每個測試的記錄都可見。即時記錄 現在傳送至
sys.stdout
,不再需要-s
命令列選項才能運作。
如果您想要部分還原 3.3
版本的記錄行為,可以將這些選項新增至 ini
檔案
[pytest]
log_cli=true
log_level=NOTSET
有關導致這些變更的討論,可參閱 問題 #3013 中的詳細資訊。