我正在使用日志(log)格式化程序来编辑密码.我想编写一个测试,以确认日志(log)编校程序是有效的.在本例中,我简化了代码以编辑"foo".
在My my_logger.py
模块中使用此编校程序代码(特定单词的简化编校):
class RedactFoo:
def __init__(self, base_formatter):
self.base_formatter = base_formatter
def format(self, record):
msg = self.base_formatter.format(record)
return msg.replace("foo", "<<REDACTED>>")
def __getattr__(self, attr):
return getattr(self.orig_formatter, attr)
然后配置我的记录器并包装每个处理程序的格式化程序:
logging.config.dictConfig(logging_config)
# Set the formatter on all handlers
for h in logging.root.handlers:
h.setFormatter(RedactFoo(h.formatter))
def get_logger(name):
return logging.getLogger(name)
如果我参选:
logger = my_logger.get_logger("Test")
logger.error(f"This message has foo.")
记录器会对消息进行编辑.
然而,在PYTEST test_my_logger.py
中:
import my_logger
def test_logging_redactor(caplog):
logger = my_logger.get_logger("test")
logger.error(f"This message has foo.")
assert ""This message has <<REDACTED>>." in caplog.text
此测试未通过,因为Pytest日志(log)记录配置覆盖了我的自定义配置.如何使用PYTEST和caplog
fixture 来执行此测试?
我在这里看到了unittest
的解决方案:How to test specific logging formatting in Python (using `pytest` and `unittest`),但我对用PYTEST做这个很感兴趣.