Green is a clean, colorful, fast python test runner.
—
Green's output formatting system provides color-coded terminal output with hierarchical display, multiple verbosity levels, and customizable formatting options for enhanced test result readability.
Enhanced output stream wrapper that provides Green's signature clean, colorful formatting with proper handling of multi-line output and hierarchical test display.
class GreenStream:
"""
Enhanced output stream wrapper for Green's formatted output.
Wraps standard output streams to provide Green's clean, hierarchical
test output with color coding and proper formatting.
"""
def __init__(self, stream, override_appveyor=False, disable_windows=False, disable_unidecode=False):
"""
Initialize enhanced output stream.
Args:
stream: Base output stream (typically sys.stdout or sys.stderr)
override_appveyor (bool): Override AppVeyor-specific behavior
disable_windows (bool): Disable Windows-specific formatting
disable_unidecode (bool): Disable Unicode to ASCII conversion
Example:
import sys
from green.output import GreenStream
stream = GreenStream(sys.stdout)
stream.writeln("Test output with Green formatting")
"""
def write(self, text):
"""
Write text to the stream with Green formatting.
Args:
text (str): Text to write, may contain color codes and formatting
Handles color codes, Unicode characters, and Windows compatibility.
"""
def writeln(self, text=''):
"""
Write a line of text with newline.
Args:
text (str): Text to write, defaults to empty string for blank line
Example:
stream.writeln("Test: test_example")
stream.writeln() # Blank line
"""
def writelines(self, lines):
"""
Write multiple lines of text.
Args:
lines (iterable): Iterable of strings to write as separate lines
"""
def formatText(self, text, indent=0, outcome_char=''):
"""
Format multi-line text with Green's hierarchical styling.
Args:
text (str): Text to format (may contain multiple lines)
indent (int): Indentation level for hierarchical display
outcome_char (str): Character indicating test outcome ('.', 'F', 'E', etc.)
Returns:
str: Formatted text with proper indentation and outcome indicators
Example:
formatted = stream.formatText("Multi-line\\ntest output", indent=2, outcome_char='.')
stream.write(formatted)
"""
def formatLine(self, line, indent=0, outcome_char=''):
"""
Format a single line with outcome character and indentation.
Args:
line (str): Single line of text to format
indent (int): Indentation level
outcome_char (str): Test outcome character
Returns:
str: Formatted line with proper alignment
Example:
formatted = stream.formatLine("test_example", indent=1, outcome_char='.')
# Returns: ". test_example"
"""
def flush(self):
"""Flush the underlying stream."""
def isatty(self):
"""
Check if stream is connected to a terminal.
Returns:
bool: True if stream is a TTY (supports colors)
"""Terminal color formatting system that provides both basic colors and semantic color methods for different test outcomes.
class Colors:
"""
Terminal color formatting for Green's output.
Provides color methods for different test outcomes and general formatting,
with automatic terminal capability detection.
"""
def __init__(self, termcolor=None):
"""
Initialize color formatter.
Args:
termcolor (bool, optional): Force color on/off. If None, auto-detects
terminal color support.
Example:
# Auto-detect color support
colors = Colors()
# Force colors on
colors = Colors(termcolor=True)
# Force colors off
colors = Colors(termcolor=False)
"""
# Basic color methods
def green(self, text):
"""
Format text in green color.
Args:
text (str): Text to color
Returns:
str: Text with green color codes (if terminal supports colors)
"""
def red(self, text):
"""Format text in red color."""
def blue(self, text):
"""Format text in blue color."""
def yellow(self, text):
"""Format text in yellow color."""
def bold(self, text):
"""Format text in bold."""
# Semantic color methods for test outcomes
def passing(self, text):
"""
Format text for passing tests (typically green).
Args:
text (str): Text to format
Returns:
str: Formatted text indicating success
Example:
colors = Colors()
print(colors.passing("✓ test_login_success"))
"""
def failing(self, text):
"""Format text for failing tests (typically red)."""
def error(self, text):
"""Format text for test errors (typically red/bold)."""
def skipped(self, text):
"""Format text for skipped tests (typically yellow)."""
def unexpectedSuccess(self, text):
"""Format text for unexpected successes (typically cyan)."""
def expectedFailure(self, text):
"""Format text for expected failures (typically yellow)."""
def moduleName(self, text):
"""Format text for test module names (typically bold)."""
def className(self, text):
"""Format text for test class names (typically bold)."""Debug output function for development and troubleshooting purposes.
def debug(message, level=1):
"""
Output debug message if debug level is sufficient.
Args:
message (str): Debug message to output
level (int): Debug level required for this message (default: 1)
The global debug_level variable controls which messages are shown.
Only messages with level <= debug_level are displayed.
Example:
import green.output
green.output.debug_level = 2
debug("Basic debug info", level=1) # Will be shown
debug("Detailed debug info", level=2) # Will be shown
debug("Verbose debug info", level=3) # Will NOT be shown
"""from green.output import GreenStream, Colors
import sys
# Create enhanced stream
stream = GreenStream(sys.stdout)
colors = Colors()
# Write formatted output
stream.writeln(colors.moduleName("test_module"))
stream.writeln(colors.className(" TestClass"))
stream.writeln(colors.passing(". test_method_passes"))
stream.writeln(colors.failing("F test_method_fails"))
stream.writeln(colors.error("E test_method_error"))
stream.writeln(colors.skipped("s test_method_skipped"))from green.output import GreenStream
stream = GreenStream(sys.stdout)
# Format hierarchical test output
module_text = "test_authentication"
class_text = "AuthenticationTest"
test_text = "test_login_with_valid_credentials"
# Format with different indentation levels
formatted_module = stream.formatLine(module_text, indent=0)
formatted_class = stream.formatLine(class_text, indent=1)
formatted_test = stream.formatLine(test_text, indent=2, outcome_char='.')
stream.write(formatted_module)
stream.write(formatted_class)
stream.write(formatted_test)from green.output import GreenStream
stream = GreenStream(sys.stdout)
# Handle multi-line error messages
error_message = """Traceback (most recent call last):
File "test_module.py", line 25, in test_example
self.assertEqual(expected, actual)
AssertionError: 'expected' != 'actual'"""
# Format with proper indentation
formatted_error = stream.formatText(error_message, indent=3, outcome_char='F')
stream.write(formatted_error)from green.output import Colors
# Force colors on for non-TTY output (e.g., file redirection)
colors = Colors(termcolor=True)
# Create custom color combinations
def custom_warning(text):
return colors.yellow(colors.bold(text))
def custom_success(text):
return colors.green(colors.bold(text))
def custom_critical(text):
return colors.red(colors.bold(text))
# Use custom colors
print(custom_warning("Warning: deprecated test method"))
print(custom_success("All integration tests passed"))
print(custom_critical("Critical test failure detected"))import green.output
# Set debug level
green.output.debug_level = 2
# Different levels of debug output
green.output.debug("Loading test configuration", level=1)
green.output.debug("Found 25 test files", level=1)
green.output.debug("Parsing test file: test_auth.py", level=2)
green.output.debug("Internal parser state: {...}", level=3) # Won't showfrom green.output import GreenStream, Colors
from green.result import GreenTestResult
class ColoredTestResult(GreenTestResult):
"""Test result with custom colored output."""
def __init__(self, args, stream):
# Ensure we have a GreenStream
if not isinstance(stream, GreenStream):
stream = GreenStream(stream)
super().__init__(args, stream)
self.colors = Colors()
def addSuccess(self, test, test_time=None):
super().addSuccess(test, test_time)
# Custom success output
if test_time:
self.stream.writeln(self.colors.passing(
f". {test} ({test_time:.3f}s)"
))
else:
self.stream.writeln(self.colors.passing(f". {test}"))
def addFailure(self, test, err, test_time=None):
super().addFailure(test, err, test_time)
# Custom failure output
self.stream.writeln(self.colors.failing(f"F {test}"))
formatted_error = self.stream.formatText(str(err[1]), indent=4)
self.stream.write(self.colors.failing(formatted_error))from green.output import GreenStream
import sys
import os
# Configure for different platforms
if os.name == 'nt': # Windows
stream = GreenStream(sys.stdout, disable_windows=False)
elif sys.platform == 'win32' and 'APPVEYOR' in os.environ: # AppVeyor CI
stream = GreenStream(sys.stdout, override_appveyor=True)
else: # Unix-like systems
stream = GreenStream(sys.stdout)
# Stream automatically handles platform differences
stream.writeln("Test output formatted for current platform")from green.output import GreenStream, Colors
class VerboseFormatter:
"""Custom formatter for verbose test output."""
def __init__(self, stream):
self.stream = GreenStream(stream) if not isinstance(stream, GreenStream) else stream
self.colors = Colors()
def format_test_start(self, test):
"""Format test start message."""
timestamp = time.strftime("%H:%M:%S")
formatted = f"[{timestamp}] Starting: {test}"
self.stream.writeln(self.colors.blue(formatted))
def format_test_success(self, test, duration):
"""Format successful test completion."""
formatted = f"✓ {test} ({duration:.3f}s)"
self.stream.writeln(self.colors.passing(formatted))
def format_test_failure(self, test, error, duration):
"""Format test failure."""
formatted = f"✗ {test} ({duration:.3f}s)"
self.stream.writeln(self.colors.failing(formatted))
# Format error details
error_text = self.stream.formatText(str(error), indent=2)
self.stream.writeln(self.colors.failing(error_text))
def format_summary(self, total, passed, failed, errors, skipped):
"""Format test run summary."""
self.stream.writeln()
self.stream.writeln(self.colors.bold("Test Summary:"))
self.stream.writeln(f" Total: {total}")
self.stream.writeln(self.colors.passing(f" Passed: {passed}"))
if failed:
self.stream.writeln(self.colors.failing(f" Failed: {failed}"))
if errors:
self.stream.writeln(self.colors.error(f" Errors: {errors}"))
if skipped:
self.stream.writeln(self.colors.skipped(f" Skipped: {skipped}"))
# Usage
formatter = VerboseFormatter(sys.stdout)
formatter.format_test_start("test_example")
formatter.format_test_success("test_example", 0.025)Green supports multiple verbosity levels that affect output formatting:
Green automatically detects terminal color support and adjusts output accordingly:
Install with Tessl CLI
npx tessl i tessl/pypi-green