diff --git a/AUTHORS b/AUTHORS index 0560caf72..398db4b7b 100644 --- a/AUTHORS +++ b/AUTHORS @@ -311,6 +311,7 @@ Omar Kohl Omer Hadari Ondřej Súkup Oscar Benjamin +Pandula Gajadeera Parth Patel Patrick Hayes Patrick Lannigan diff --git a/changelog/11666.improvement.rst b/changelog/11666.improvement.rst new file mode 100644 index 000000000..9cb3a3b7f --- /dev/null +++ b/changelog/11666.improvement.rst @@ -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. diff --git a/src/_pytest/_io/terminalwriter.py b/src/_pytest/_io/terminalwriter.py index 5bcd05927..f21a38059 100644 --- a/src/_pytest/_io/terminalwriter.py +++ b/src/_pytest/_io/terminalwriter.py @@ -218,13 +218,28 @@ class TerminalWriter: return source else: try: + # Import new more rich color formatters from the pygments library + from pygments.formatters.terminal256 import Terminal256Formatter + from pygments.formatters.terminal256 import TerminalTrueColorFormatter + + # Use terminal formatters depending on user environment variables + if os.environ.get("COLORTERM", "") in ("truecolor", "24bit"): + # Style determined by user set environment variable, if none then use default style + terminal_formatter = TerminalTrueColorFormatter( + style=os.getenv("PYTEST_THEME", "default") + ) + elif "256" in os.environ.get("TERM", ""): + 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"), + ) highlighted: str = highlight( source, Lexer(), - TerminalFormatter( - bg=os.getenv("PYTEST_THEME_MODE", "dark"), - style=os.getenv("PYTEST_THEME"), - ), ) # pygments terminal formatter may add a newline when there wasn't one. # We don't want this, remove.