8000 Bug: Cannot use Pytest's caplog fixture with non-preconfigured Logger · Issue #6753 · aws-powertools/powertools-lambda-python · GitHub
[go: up one dir, main page]

Skip to content
Bug: Cannot use Pytest's caplog fixture with non-preconfigured Logger #6753
Open
@amin-farjadi

Description

@amin-farjadi

Expected Behaviour

Log records must appear in Pytest's caplog fixture since caplog is recommended for testing the logs in documentation.

Current Behaviour

When using a new Logger (non-preconfigured), the log record does not appear in caplog. However, messages logged by a child logger is captured by caplog.

Code snippet

The following tests must pass

import random
import string

import pytest
from _pytest.logging import LogCaptureHandler

from aws_lambda_powertools.logging.logger import Logger


@pytest.fixture
def service_name():
    chars = string.ascii_letters + string.digits
    return "".join(random.SystemRandom().choice(chars) for _ in range(15))


def test_non_preconfigured_logger_with_caplog(caplog, service_name):
    caplog.set_level("INFO")
    logger = Logger(service=service_name)
    logger.info("testing, testing...")
    pytest_handler_existence = any(isinstance(item, LogCaptureHandler) for item in logger._logger.parent.handlers)

    assert pytest_handler_existence is True
    assert len(caplog.records) == 1
    assert caplog.records[0].message == "testing, testing..."


def test_child_logger_with_caplog(caplog):
    caplog.set_level("INFO")
    logger = Logger(child=True)
    logger.info("testing, testing...")

    assert len(caplog.records) == 1

But, test_non_preconfigured_logger_with_caplog fails with:

>       assert len(caplog.records) == 1
E       assert 0 == 1
E        +  where 0 = len([])
E        +    where [] = <_pytest.logging.LogCaptureFixture object at 0x104e7c560>.records

Possible Solution

Add the following guard clause the _init_logger method of the Logger class (before checking if self.child:)

        if os.environ.get("PYTEST_CURRENT_TEST"):
            return

Steps to Reproduce

Copy and paste the above tests in tests/functional/logger/required_dependencies/test_logger.py file and run.

Powertools for AWS Lambda (Python) version

latest

AWS Lambda function runtime

3.12

Packaging format used

PyPi

Debugging logs

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingtriagePending triage from maintainers

    Type

    No type

    Projects

    Status

    Triage

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0