Skip to main content

结构化日志记录断言

项目描述

行动 皮皮 版本 哇

pytest 结构日志

结构化的日志记录断言。 pytest + structlog = pytest-structlog

pytest 结构日志

安装:

$ pip install pytest-structlog

用法:

夹具名称是log。它有两个有趣的属性:log.events是来自捕获的日志调用的事件列表,而log.has是一个辅助函数,用于断言在预期上下文中记录了单个事件。

假设您有一些使用structlog的库模块your_lib

# your_lib.py
from structlog import get_logger

logger = get_logger()

def spline_reticulator():
    logger.info("reticulating splines")
    for i in range(3):
        logger.debug("processing", spline=i)
    logger.info("reticulated splines", n_splines=3)

然后您的测试套件可能会使用如下所示的断言:

# test_your_lib.py
from your_lib import spline_reticulator

def test_spline_reticulator(log):
    assert len(log.events) == 0
    spline_reticulator()
    assert len(log.events) == 5

    # can assert on the event only
    assert log.has("reticulating splines")

    # can assert with subcontext
    assert log.has("reticulated splines")
    assert log.has("reticulated splines", n_splines=3)
    assert log.has("reticulated splines", n_splines=3, level="info")

    # but not incorrect context
    assert not log.has("reticulated splines", n_splines=42)
    assert not log.has("reticulated splines", key="bogus")

    # can assert with the event dicts directly
    assert log.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 data
    assert {"event": "reticulating splines", "level": "info"} in log.events

    # can use >= to specify only the events you're interested in
    assert log.events >= [
        {"event": "processing", "level": "debug", "spline": 0},
        {"event": "processing", "level": "debug", "spline": 2},
    ]

    # or put the comparison the other way around if you prefer
    assert [
        {"event": "processing", "level": "debug", "spline": 0},
        {"event": "processing", "level": "debug", "spline": 2},
    ] <= log.events

    # note: comparisons are order sensitive!
    assert not [
        {"event": "processing", "level": "debug", "spline": 2},
        {"event": "processing", "level": "debug", "spline": 0},
    ] <= log.events

项目详情


下载文件

下载适用于您平台的文件。如果您不确定要选择哪个,请了解有关安装包的更多信息。

源分布

pytest-structlog-0.5.tar.gz (5.6 kB 查看哈希)

已上传 source

内置分布

pytest_structlog-0.5-py2.py3-none-any.whl (4.9 kB 查看哈希

已上传 py2 py3