Skip to content

Commit a1a36e4

Browse files
committed
Test colored tracebacks
1 parent f4c0980 commit a1a36e4

File tree

2 files changed

+37
-20
lines changed

2 files changed

+37
-20
lines changed

colorlog/formatter.py

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -140,28 +140,28 @@ def _escape_code_map(self, item: str) -> EscapeCodes:
140140
"""
141141
Build a map of keys to escape codes for use in message formatting.
142142
143-
If _blank_escape_codes() returns True, all values will be an empty string.
143+
If _color() returns False, all values will be an empty string.
144144
"""
145145
codes = {**colorlog.escape_codes.escape_codes}
146146
codes.setdefault("log_color", self._get_escape_code(self.log_colors, item))
147147
for name, colors in self.secondary_log_colors.items():
148148
codes.setdefault("%s_log_color" % name, self._get_escape_code(colors, item))
149-
if self._blank_escape_codes():
149+
if not self._colorize():
150150
codes = {key: "" for key in codes.keys()}
151151
return codes
152152

153-
def _blank_escape_codes(self):
154-
"""Return True if we should be prevented from printing escape codes."""
153+
def _colorize(self):
154+
"""Return False if we should be prevented from printing escape codes."""
155155
if self.force_color or "FORCE_COLOR" in os.environ:
156-
return False
156+
return True
157157

158158
if self.no_color or "NO_COLOR" in os.environ:
159-
return True
159+
return False
160160

161161
if self.stream is not None and not self.stream.isatty():
162-
return True
162+
return False
163163

164-
return False
164+
return True
165165

166166
@staticmethod
167167
def _get_escape_code(log_colors: LogColors, item: str) -> str:
@@ -179,21 +179,18 @@ def _append_reset(self, message: str, escapes: EscapeCodes) -> str:
179179

180180
if sys.version_info >= (3, 13):
181181

182-
def formatException(self, ei):
183-
"""Format and return the specified exception information as a string."""
184-
# This is a copy of logging.Formatter.formatException that passes in
185-
# an appropriate value for colorize to print_exception.
182+
def formatException(self, ei) -> str:
183+
"""
184+
Format and return the specified exception information as a string.
185+
186+
This is a copy of logging.Formatter.formatException that passes in
187+
an appropriate value for colorize to print_exception.
188+
"""
189+
kwargs = dict(colorize=self._colorize())
186190

187191
sio = io.StringIO()
188192
tb = ei[2]
189-
traceback.print_exception(
190-
ei[0],
191-
ei[1],
192-
tb,
193-
limit=None,
194-
file=sio,
195-
colorize=not self._blank_escape_codes(),
196-
)
193+
traceback.print_exception(ei[0], ei[1], tb, limit=None, file=sio, **kwargs)
197194
s = sio.getvalue()
198195
sio.close()
199196
if s[-1:] == "\n":

colorlog/tests/test_colorlog.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
"""Test the colorlog.colorlog module."""
22

33
import sys
4+
import unittest.mock
5+
6+
import pytest
47

58
import colorlog
69

@@ -114,3 +117,20 @@ def test_ttycolorlog_notty(create_and_test_logger, monkeypatch):
114117
validator=lambda line: "\x1b[" not in line,
115118
stream=sys.stderr,
116119
)
120+
121+
122+
if sys.version_info >= (3, 13):
123+
124+
@pytest.mark.parametrize("tty", [True, False])
125+
def test_formatException(tty: bool, monkeypatch):
126+
stream = unittest.mock.Mock()
127+
stream.isatty = unittest.mock.Mock(return_value=tty)
128+
129+
formatter = colorlog.ColoredFormatter(stream=stream)
130+
try:
131+
raise KeyError("test")
132+
except KeyError:
133+
ei = sys.exc_info()
134+
text = formatter.formatException(ei)
135+
136+
assert ("\x1b[" in text) == tty

0 commit comments

Comments
 (0)