or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

cli.mdconfiguration.mddjango-integration.mdindex.mdjunit-xml.mdoutput-formatting.mdsetuptools-integration.mdtest-execution.mdtest-loading.mdtest-results.md
tile.json

tessl/pypi-green

Green is a clean, colorful, fast python test runner.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/green@4.0.x

To install, run

npx @tessl/cli install tessl/pypi-green@4.0.0

index.mddocs/

Green

Green 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.

Package Information

  • Package Name: green
  • Language: Python
  • Installation: pip install green
  • Python Requirements: 3.8+ (except 3.12.1)

Core Imports

import green

Command-line usage:

from green.cmdline import main

For 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

Basic Usage

Command Line

# 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/

Programmatic Usage

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)

Custom Test Runner

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}")

Architecture

Green is built around several key components that work together to provide enhanced test running:

  • Configuration System: Hierarchical configuration merging from files and command-line
  • Test Discovery: Enhanced unittest-compatible test loading with pattern matching
  • Parallel Execution: Multi-process test running for improved performance
  • Result Aggregation: Comprehensive test result collection and reporting
  • Output Formatting: Color-coded, hierarchical test output with multiple verbosity levels
  • Integration Points: Django test runner, setuptools command, JUnit XML export

Capabilities

Command Line Interface

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)
    """

Command Line Interface

Configuration Management

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."""

Configuration

Test Discovery and Loading

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."""

Test Loading

Test Execution

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
    """

Test Execution

Test Results and Reporting

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): ...

Test Results

Output Formatting

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): ...

Output Formatting

Django Integration

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): ...

Django Integration

JUnit XML Reporting

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): ...

JUnit XML Reporting

Setuptools Integration

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."""

Setuptools Integration

Types

# 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."""