From ef053193b5f726c20a875b0bbc9a3d46e7c03a60 Mon Sep 17 00:00:00 2001 From: Thomas Hisch Date: Wed, 29 May 2019 23:15:34 +0200 Subject: [PATCH] logging: Extend LEVELNAME_FMT_REGEX --- changelog/5335.bugfix.rst | 2 ++ src/_pytest/logging.py | 2 +- testing/logging/test_formatter.py | 25 +++++++++++++++++++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 changelog/5335.bugfix.rst diff --git a/changelog/5335.bugfix.rst b/changelog/5335.bugfix.rst new file mode 100644 index 000000000..0a2e99dc9 --- /dev/null +++ b/changelog/5335.bugfix.rst @@ -0,0 +1,2 @@ +Colorize level names when the level in the logging format is formatted using +'%(levelname).Xs' (truncated fixed width alignment), where X is an integer. diff --git a/src/_pytest/logging.py b/src/_pytest/logging.py index a5f41173a..ee143cb41 100644 --- a/src/_pytest/logging.py +++ b/src/_pytest/logging.py @@ -39,7 +39,7 @@ class ColoredLevelFormatter(logging.Formatter): logging.DEBUG: {"purple"}, logging.NOTSET: set(), } - LEVELNAME_FMT_REGEX = re.compile(r"%\(levelname\)([+-]?\d*s)") + LEVELNAME_FMT_REGEX = re.compile(r"%\(levelname\)([+-.]?\d*s)") def __init__(self, terminalwriter, *args, **kwargs): super(ColoredLevelFormatter, self).__init__(*args, **kwargs) diff --git a/testing/logging/test_formatter.py b/testing/logging/test_formatter.py index c851c34d7..7a63ab47e 100644 --- a/testing/logging/test_formatter.py +++ b/testing/logging/test_formatter.py @@ -65,3 +65,28 @@ def test_multiline_message(): "dummypath 10 INFO Test Message line1\n" " line2" ) + + +def test_colored_short_level(): + logfmt = "%(levelname).1s %(message)s" + + record = logging.LogRecord( + name="dummy", + level=logging.INFO, + pathname="dummypath", + lineno=10, + msg="Test Message", + args=(), + exc_info=False, + ) + + class ColorConfig(object): + class option(object): + pass + + tw = py.io.TerminalWriter() + tw.hasmarkup = True + formatter = ColoredLevelFormatter(tw, logfmt) + output = formatter.format(record) + # the I (of INFO) is colored + assert output == ("\x1b[32mI\x1b[0m Test Message")