wimglenn / pytest-structlog

Structured logging assertions
MIT License
54 stars 6 forks source link

Add factory method for log events to assert on for better readability #23

Closed logi closed 1 year ago

logi commented 1 year ago

I have made a number of additions to pytest-structlog locally and this is the lowest-hanging fruit of that to submit. It makes the lists of log events to assert on more terse and more readable.

logi commented 1 year ago

FYI, I have 2 other branches that I'll submit PRs from, each building on the last. You can see them here:

logi commented 1 year ago

PS If you're at PyCon I'll be happy to talk about this at Squatters.

logi commented 1 year ago

Any further thoughts about this PR?

Since I've got it open, here is code lifted directly from one of our unit tests. I especially like the last line but that's for another PR...

assert log.events >= [
    log.info(
        "Processing started for calibration",
        calibration_id=2,
    ),
    log.info(
        "Request measurement data",
        auth_user="test_mms_user",
        end_time=fix_time("2018-09-03T18:30"),
        response_code=200,
        sensor_ids=["07000997:DE:0"],
        start_time=fix_time("2018-09-02T18:00"),
    ),
    log.info(
        "Request measurement data",
        auth_user="test_mms_user",
        end_time=fix_time("2018-09-03T18:30"),
        response_code=200,
        sensor_ids=["10000994:DE:0"],
        start_time=fix_time("2018-09-02T18:00"),
    ),
    log.info(
        "Found stable range for setpoint in period",
        end_time=fix_time("2018-09-02T18:40"),
        reference_sensor_id="07000997:DE:0",
        setpoint=25.0,
        setpoint_average=Decimal("25.1"),
        setpoint_id=5,
        start_time=fix_time("2018-09-02T18:00"),
    ),
    log.debug(
        "Setpoint passed",
        average=Decimal("25.6"),
        average_temperature_error=Decimal("0.5"),
        end_time=fix_time("2018-09-02T18:40"),
        passed=True,
        reference_sensor_id="07000997:DE:0",
        start_time=fix_time("2018-09-02T18:00"),
        sensor_id="10000994:DE:0",
        setpoint=25.0,
        setpoint_average=Decimal("25.1"),
        setpoint_id=5,
        tolerance=Decimal("0.5000"),
    ),
    log.info(
        "Processing of calibration completed successfully",
        calibration_id=2,
    ),
]
assert not log.events.warnings()
wimglenn commented 1 year ago

@logi This looks OK to me! My only concern is that pytest-structlog was, previously, blissfully unaware of stdlib logging. It was "pure structlog" so to speak. However, there's not really any huge gain from that, and anyway structlog already imports stdlib logging these days regardless.

Note that the trick you've used here has been called despicable by Guido van Rossum.