Skip to content

Commit

Permalink
Fix handling empty values of NO_COLOR and FORCE_COLOR
Browse files Browse the repository at this point in the history
Fix handling NO_COLOR and FORCE_COLOR environment variables to correctly
be ignored when they are set to an empty value, as defined
in the specification:

> Command-line software which adds ANSI color to its output by default
> should check for a NO_COLOR environment variable that, when present
> *and not an empty string* (regardless of its value), prevents
> the addition of ANSI color.

(emphasis mine, https://no-color.org/)

The same is true of FORCE_COLOR, https://force-color.org/.
  • Loading branch information
mgorny committed Dec 16, 2023
1 parent 047ba83 commit ac007d3
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 4 deletions.
4 changes: 2 additions & 2 deletions doc/en/reference/reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1146,13 +1146,13 @@ When set to ``0``, pytest will not use color.

.. envvar:: NO_COLOR

When set (regardless of value), pytest will not use color in terminal output.
When set to a non-empty string (regardless of value), pytest will not use color in terminal output.
``PY_COLORS`` takes precedence over ``NO_COLOR``, which takes precedence over ``FORCE_COLOR``.
See `no-color.org <https://no-color.org/>`__ for other libraries supporting this community standard.

.. envvar:: FORCE_COLOR

When set (regardless of value), pytest will use color in terminal output.
When set to a non-empty string (regardless of value), pytest will use color in terminal output.
``PY_COLORS`` and ``NO_COLOR`` take precedence over ``FORCE_COLOR``.

Exceptions
Expand Down
4 changes: 2 additions & 2 deletions src/_pytest/_io/terminalwriter.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ def should_do_markup(file: TextIO) -> bool:
return True
if os.environ.get("PY_COLORS") == "0":
return False
if "NO_COLOR" in os.environ:
if os.environ.get("NO_COLOR"):
return False
if "FORCE_COLOR" in os.environ:
if os.environ.get("FORCE_COLOR"):
return True
return (
hasattr(file, "isatty") and file.isatty() and os.environ.get("TERM") != "dumb"
Expand Down
6 changes: 6 additions & 0 deletions testing/io/test_terminalwriter.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,12 @@ def test_should_not_do_markup_NO_COLOR_and_FORCE_COLOR(
assert_color_not_set()


def test_empty_NO_COLOR_ignored(monkeypatch: MonkeyPatch) -> None:
monkeypatch.setitem(os.environ, "NO_COLOR", "")
monkeypatch.setitem(os.environ, "FORCE_COLOR", "1")
assert_color_set()


class TestTerminalWriterLineWidth:
def test_init(self) -> None:
tw = terminalwriter.TerminalWriter()
Expand Down

0 comments on commit ac007d3

Please sign in to comment.