true color and 256 terminal formatters added and use PYTEST_THEME env variable for style

This commit is contained in:
pandula12 2024-05-13 14:53:47 +09:30
parent eea04c2891
commit a1591f8aaf
3 changed files with 65 additions and 50 deletions

View File

@ -308,6 +308,7 @@ Omar Kohl
Omer Hadari
Ondřej Súkup
Oscar Benjamin
Pandula Gajadeera
Parth Patel
Patrick Hayes
Patrick Lannigan

View File

@ -0,0 +1,5 @@
Improved the terminal writer to be able to use Terminal256Formatter and TerminalTrueColorFormatter.
These are newer versions of TerminalFormmater from the pygments library that is currently in use.
These style of these formatters are set by the users through the environmental variable PYTEST_THEME.

View File

@ -194,9 +194,9 @@ class TerminalWriter:
for indent, new_line in zip(indents, new_lines):
self.line(indent + new_line)
def _highlight(
def _highlight(
self, source: str, lexer: Literal["diff", "python"] = "python"
) -> str:
) -> str:
"""Highlight the given source if we have markup support."""
from _pytest.config.exceptions import UsageError
@ -212,8 +212,20 @@ class TerminalWriter:
from pygments.lexers.diff import DiffLexer as Lexer
else:
assert_never(lexer)
from pygments import highlight
import pygments.util
if os.getenv("COLORTERM", "") in ("truecolor", "24bit"):
from pygments.formatters.terminal256 import TerminalTrueColorFormatter
terminal_formatter = TerminalTrueColorFormatter(style=os.getenv("PYTEST_THEME", "default"))
elif "256" in os.getenv("TERM", ""):
from pygments.formatters.terminal256 import Terminal256Formatter
terminal_formatter = Terminal256Formatter(style=os.getenv("PYTEST_THEME", "default"))
else:
terminal_formatter = TerminalFormatter(bg=os.getenv("PYTEST_THEME_MODE", "dark"),
style=os.getenv("PYTEST_THEME", "default"))
except ImportError:
return source
else:
@ -221,10 +233,7 @@ class TerminalWriter:
highlighted: str = highlight(
source,
Lexer(),
TerminalFormatter(
bg=os.getenv("PYTEST_THEME_MODE", "dark"),
style=os.getenv("PYTEST_THEME"),
),
terminal_formatter,
)
# pygments terminal formatter may add a newline when there wasn't one.
# We don't want this, remove.