diff --git a/changelog/8548.bugfix.rst b/changelog/8548.bugfix.rst new file mode 100644 index 000000000..9201169fc --- /dev/null +++ b/changelog/8548.bugfix.rst @@ -0,0 +1 @@ +Introduce fix to handle precision width in ``log-cli-format`` in turn to fix output coloring for certain formats. diff --git a/src/_pytest/logging.py b/src/_pytest/logging.py index 642000831..da1de013d 100644 --- a/src/_pytest/logging.py +++ b/src/_pytest/logging.py @@ -59,7 +59,7 @@ class ColoredLevelFormatter(logging.Formatter): logging.DEBUG: {"purple"}, logging.NOTSET: set(), } - LEVELNAME_FMT_REGEX = re.compile(r"%\(levelname\)([+-.]?\d*[.]?\d*s)") + LEVELNAME_FMT_REGEX = re.compile(r"%\(levelname\)([+-.]?\d*(?:\.\d+)?s)") def __init__(self, terminalwriter: TerminalWriter, *args, **kwargs) -> None: super().__init__(*args, **kwargs) diff --git a/testing/logging/test_formatter.py b/testing/logging/test_formatter.py index 335166caa..ccc7bfbeb 100644 --- a/testing/logging/test_formatter.py +++ b/testing/logging/test_formatter.py @@ -36,6 +36,37 @@ def test_coloredlogformatter() -> None: assert output == ("dummypath 10 INFO Test Message") +def test_coloredlogformatter_with_width_precision() -> None: + logfmt = "%(filename)-25s %(lineno)4d %(levelname)-8.2s %(message)s" + + record = logging.LogRecord( + name="dummy", + level=logging.INFO, + pathname="dummypath", + lineno=10, + msg="Test Message", + args=(), + exc_info=None, + ) + + class ColorConfig: + class option: + pass + + tw = TerminalWriter() + tw.hasmarkup = True + formatter = ColoredLevelFormatter(tw, logfmt) + output = formatter.format(record) + assert output == ( + "dummypath 10 \x1b[32mINFO \x1b[0m Test Message" + ) + + tw.hasmarkup = False + formatter = ColoredLevelFormatter(tw, logfmt) + output = formatter.format(record) + assert output == ("dummypath 10 INFO Test Message") + + def test_multiline_message() -> None: from _pytest.logging import PercentStyleMultiline