Skip to content
Merged
3 changes: 1 addition & 2 deletions Lib/_colorize.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import io
import os
import sys

Expand Down Expand Up @@ -330,7 +329,7 @@ def _safe_getenv(k: str, fallback: str | None = None) -> str | None:

try:
return os.isatty(file.fileno())
except io.UnsupportedOperation:
except OSError:
return hasattr(file, "isatty") and file.isatty()


Expand Down
11 changes: 11 additions & 0 deletions Lib/test/test__colorize.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,17 @@ def test_colorized_detection_checks_for_file(self):
file.isatty.return_value = False
self.assertEqual(_colorize.can_colorize(file=file), False)

# The documentation for file.fileno says:
# > An OSError is raised if the IO object does not use a file descriptor.
# See https://github.com/python/cpython/issues/141570
Comment thread
hroncok marked this conversation as resolved.
Outdated
with unittest.mock.patch("os.isatty", side_effect=ZeroDivisionError):
Comment thread
hroncok marked this conversation as resolved.
file = unittest.mock.MagicMock()
file.fileno.side_effect = OSError
file.isatty.return_value = True
self.assertEqual(_colorize.can_colorize(file=file), True)
file.isatty.return_value = False
self.assertEqual(_colorize.can_colorize(file=file), False)


if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
In ``_colorize.can_colorize``, support file objects rising
:exc:`OSError` from the :meth:`~io.IOBase.fileno` method, as docuemtned. An
example of such an object is a ``mod_wsgi`` logger.
Comment thread
hroncok marked this conversation as resolved.
Outdated
Loading