問題描述
我正在嘗試編寫一個簡單的單元測試,以驗證在特定條件下,我的應用程序中的類將通過標準日志記錄 API 記錄錯誤.我不知道測試這種情況的最干凈的方法是什么.
I'm trying to write a simple unit test that will verify that, under a certain condition, a class in my application will log an error via the standard logging API. I can't work out what the cleanest way to test this situation is.
我知道鼻子已經(jīng)通過它的日志插件捕獲日志輸出,但這似乎是為了作為失敗測試的報告和調(diào)試幫助.
I know that nose already captures logging output through it's logging plugin, but this seems to be intended as a reporting and debugging aid for failed tests.
我可以看到的兩種方法是:
The two ways to do this I can see are:
- 以零碎的方式 (mymodule.logging = mockloggingmodule) 或使用適當?shù)哪M庫來模擬日志模塊.
- 編寫或使用現(xiàn)有的鼻子插件來捕獲輸出并進行驗證.
如果我采用前一種方法,我想知道將全局狀態(tài)重置為模擬日志模塊之前的狀態(tài)的最簡潔方法.
If I go for the former approach, I'd like to know what the cleanest way to reset the global state to what it was before I mocked out the logging module.
期待您對此的提示和技巧...
Looking forward to your hints and tips on this one...
推薦答案
我曾經(jīng)模擬記錄器,但是在這種情況下我發(fā)現(xiàn)最好使用記錄處理程序,所以我基于 jkp 建議的文件(現(xiàn)在已經(jīng)死了,但緩存在 互聯(lián)網(wǎng)檔案)
I used to mock loggers, but in this situation I found best to use logging handlers, so I wrote this one based on the document suggested by jkp(now dead, but cached on Internet Archive)
class MockLoggingHandler(logging.Handler):
"""Mock logging handler to check for expected logs."""
def __init__(self, *args, **kwargs):
self.reset()
logging.Handler.__init__(self, *args, **kwargs)
def emit(self, record):
self.messages[record.levelname.lower()].append(record.getMessage())
def reset(self):
self.messages = {
'debug': [],
'info': [],
'warning': [],
'error': [],
'critical': [],
}
這篇關于在鼻子下測試 Python 代碼時,我應該如何驗證日志消息?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!