Green is a clean, colorful, fast python test runner.
npx @tessl/cli install tessl/pypi-green@4.0.0Green is a comprehensive Python test runner that provides clean, colorful terminal output with multi-process parallel test execution for improved performance. It serves as an enhanced alternative to unittest, offering hierarchical test result display, built-in coverage integration, configurable verbosity levels, and support for multiple output formats including JUnit XML.
pip install greenimport greenCommand-line usage:
from green.cmdline import mainFor programmatic test running:
from green.config import parseArguments, mergeConfig
from green.loader import GreenTestLoader
from green.runner import run
from green.suite import GreenTestSuite
from green.output import GreenStream
from green.result import GreenTestResult
from typing import Sequence, Iterable, TextIO
import argparse
import unittest# Run tests in current directory
green
# Run specific test module
green tests/test_module.py
# Run with verbose output and coverage
green --verbose 2 --run-coverage tests/
# Generate JUnit XML report
green --junit-report junit.xml tests/from green.cmdline import main
import sys
# Run tests programmatically with command-line interface
exit_code = main(['tests/', '--verbose', '2', '--run-coverage'])
sys.exit(exit_code)from green.config import parseArguments, mergeConfig
from green.loader import GreenTestLoader
from green.runner import run
from green.output import GreenStream
import sys
# Parse arguments and configuration
args = parseArguments(['--verbose', '2', 'tests/'])
args = mergeConfig(args)
# Load tests
loader = GreenTestLoader()
suite = loader.loadTargets(args.targets)
# Run tests with custom stream
stream = GreenStream(sys.stdout)
result = run(suite, stream, args)
# Check if all tests passed
success = result.wasSuccessful()
print(f"Tests passed: {success}")Green is built around several key components that work together to provide enhanced test running:
Main entry point for running Green as a command-line tool with full argument parsing, configuration file merging, and comprehensive options.
def main(argv: Sequence[str] | None = None, testing: bool = False) -> int:
"""
Main entry point for Green command-line interface.
Args:
argv (Sequence[str] | None, optional): Command-line arguments. Defaults to sys.argv.
testing (bool): Enable testing mode. Defaults to False.
Returns:
int: Exit code (0 for success, non-zero for failure)
"""Hierarchical configuration system supporting multiple config file formats, environment variables, and command-line arguments with precedence rules.
def parseArguments(argv: Sequence[str] | None = None) -> argparse.Namespace:
"""Parse command-line arguments."""
def mergeConfig(args: argparse.Namespace, testing: bool = False) -> argparse.Namespace:
"""Merge configuration from files and environment."""
def getConfig(filepath=None):
"""Load configuration from files."""Enhanced test discovery with pattern matching, module loading, and Green-specific test suite creation with filtering and customization capabilities.
class GreenTestLoader(unittest.TestLoader):
def loadTargets(self, targets: Iterable[str] | str, file_pattern: str = "test*.py") -> GreenTestSuite | None:
"""Load tests from target specifications."""
def loadTarget(self, target, file_pattern='test*.py'):
"""Load tests from a single target."""
def discover(self, current_path: str, file_pattern: str = "test*.py", top_level_dir: str | None = None) -> GreenTestSuite | None:
"""Discover tests in directory structure."""Multi-process test execution with process pool management, worker initialization, and parallel test running for improved performance.
def run(suite, stream: TextIO | GreenStream, args: argparse.Namespace, testing: bool = False) -> GreenTestResult:
"""
Run tests with Green's enhanced features.
Args:
suite: Test suite to run
stream: Output stream (wrapped in GreenStream)
args: Configuration namespace
testing (bool): Testing mode flag
Returns:
GreenTestResult: Test execution results
"""Comprehensive test result collection, aggregation from multiple processes, and support for various output formats including JUnit XML.
class GreenTestResult:
def __init__(self, args, stream): ...
def addProtoTestResult(self, proto_test_result): ...
def wasSuccessful(self): ...
def startTestRun(self): ...
def stopTestRun(self): ...Color-coded terminal output with hierarchical display, multiple verbosity levels, and customizable formatting options.
class GreenStream:
def __init__(self, stream, override_appveyor=False, disable_windows=False, disable_unidecode=False): ...
def write(self, text): ...
def formatText(self, text, indent=0, outcome_char=''): ...
def formatLine(self, line, indent=0, outcome_char=''): ...
class Colors:
def __init__(self, termcolor=None): ...
def green(self, text): ...
def red(self, text): ...
def passing(self, text): ...
def failing(self, text): ...Native Django test runner integration allowing Green to be used as the test runner in Django projects with full Django-specific features.
class DjangoRunner(DiscoverRunner):
def __init__(self, verbose=-1, **kwargs): ...
def add_arguments(self, parser): ...
def run_tests(self, test_labels, extra_tests=None, **kwargs): ...JUnit XML report generation for CI/CD integration with comprehensive test result metadata and proper XML formatting.
class JUnitXML:
def save_as(self, test_results, destination): ...Integration with setuptools allowing Green to be used as a setup.py command for test execution in Python packages.
class green(setuptools.Command):
"""Setuptools command for running Green tests."""# Type aliases used throughout Green
from typing import Union
from unittest import TestCase, TestSuite
from doctest import DocTestCase
TestCaseT = Union["ProtoTest", TestCase, DocTestCase]
RunnableTestT = Union[TestCaseT, TestSuite]
class GreenTestSuite(unittest.TestSuite):
def __init__(self, tests=(), args=None): ...
def addTest(self, test): ...
def customize(self, args): ...
def run(self, result, debug=False): ...
class ProtoTest:
"""Serializable test representation for multiprocessing."""
# Attributes (not properties)
module: str
class_name: str
method_name: str
docstr_part: str
subtest_part: str
test_time: str
description: str
is_doctest: bool
filename: str | None
name: str
is_class_or_module_teardown_error: bool
failureException: type[Exception]
def __init__(self, test: TestCase | DocTestCase | TestSuite | None = None) -> None: ...
def getDescription(self, verbose: int) -> str: ...
# Properties
@property
def dotted_name(self) -> str: ...
class ProtoTestResult:
"""Test result for individual subprocess runs."""
def __init__(self, start_callback=None, finalize_callback=None): ...
def reinitialize(self): ...
def finalize(self): ...
class ProtoError:
"""Serializable error representation."""
def __init__(self, err): ...
class InitializerOrFinalizerError(Exception):
"""Errors in worker process setup/teardown."""