结构化日志断言
pytest-structlog的Python项目详细描述
pytest结构日志
结构化日志断言。pytest+structlog=pytest-structlog。
安装:
$ pip install pytest-structlog
用法:
设备名是log。它有两个感兴趣的属性:log.events是捕获的日志调用的事件列表,log.has是一个帮助函数,用于断言在预期上下文中记录了单个事件。
假设您有一个库模块your_lib,它使用structlog:
# your_lib.pyfromstructlogimportget_loggerlogger=get_logger(__name__)defspline_reticulator():logger.info("reticulating splines")foriinrange(3):logger.debug("processing",spline=i)logger.info("reticulated splines",n_splines=3)
那么您的测试套件可能会使用如下所示的断言:
# test_your_lib.pyfromyour_libimportspline_reticulatordeftest_spline_reticulator(log):assertlen(log.events)==0spline_reticulator()assertlen(log.events)==5# can assert on the event onlyassertlog.has("reticulating splines")# can assert with subcontextassertlog.has("reticulated splines")assertlog.has("reticulated splines",n_splines=3)assertlog.has("reticulated splines",n_splines=3,level="info")# but not incorrect contextassertnotlog.has("reticulated splines",n_splines=42)assertnotlog.has("reticulated splines",key="bogus")# can assert with the event dicts directlyassertlog.events==[{"event":"reticulating splines","level":"info"},{"event":"processing","level":"debug","spline":0},{"event":"processing","level":"debug","spline":1},{"event":"processing","level":"debug","spline":2},{"event":"reticulated splines","level":"info","n_splines":3},]# can use membership to check for a single event's dataassert{"event":"reticulating splines","level":"info"}inlog.events# can use >= to specify only the events you're interested inassertlog.events>=[{"event":"processing","level":"debug","spline":0},{"event":"processing","level":"debug","spline":2},]# or put the comparison the other way around if you preferassert[{"event":"processing","level":"debug","spline":0},{"event":"processing","level":"debug","spline":2},]<=log.events# note: comparisons are order sensitive!assertnot[{"event":"processing","level":"debug","spline":2},{"event":"processing","level":"debug","spline":0},]<=log.events