or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

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

0

# Green

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: green

7

- **Language**: Python

8

- **Installation**: `pip install green`

9

- **Python Requirements**: 3.8+ (except 3.12.1)

10

11

## Core Imports

12

13

```python

14

import green

15

```

16

17

Command-line usage:

18

```python

19

from green.cmdline import main

20

```

21

22

For programmatic test running:

23

```python

24

from green.config import parseArguments, mergeConfig

25

from green.loader import GreenTestLoader

26

from green.runner import run

27

from green.suite import GreenTestSuite

28

from green.output import GreenStream

29

from green.result import GreenTestResult

30

from typing import Sequence, Iterable, TextIO

31

import argparse

32

import unittest

33

```

34

35

## Basic Usage

36

37

### Command Line

38

39

```bash

40

# Run tests in current directory

41

green

42

43

# Run specific test module

44

green tests/test_module.py

45

46

# Run with verbose output and coverage

47

green --verbose 2 --run-coverage tests/

48

49

# Generate JUnit XML report

50

green --junit-report junit.xml tests/

51

```

52

53

### Programmatic Usage

54

55

```python

56

from green.cmdline import main

57

import sys

58

59

# Run tests programmatically with command-line interface

60

exit_code = main(['tests/', '--verbose', '2', '--run-coverage'])

61

sys.exit(exit_code)

62

```

63

64

### Custom Test Runner

65

66

```python

67

from green.config import parseArguments, mergeConfig

68

from green.loader import GreenTestLoader

69

from green.runner import run

70

from green.output import GreenStream

71

import sys

72

73

# Parse arguments and configuration

74

args = parseArguments(['--verbose', '2', 'tests/'])

75

args = mergeConfig(args)

76

77

# Load tests

78

loader = GreenTestLoader()

79

suite = loader.loadTargets(args.targets)

80

81

# Run tests with custom stream

82

stream = GreenStream(sys.stdout)

83

result = run(suite, stream, args)

84

85

# Check if all tests passed

86

success = result.wasSuccessful()

87

print(f"Tests passed: {success}")

88

```

89

90

## Architecture

91

92

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

93

94

- **Configuration System**: Hierarchical configuration merging from files and command-line

95

- **Test Discovery**: Enhanced unittest-compatible test loading with pattern matching

96

- **Parallel Execution**: Multi-process test running for improved performance

97

- **Result Aggregation**: Comprehensive test result collection and reporting

98

- **Output Formatting**: Color-coded, hierarchical test output with multiple verbosity levels

99

- **Integration Points**: Django test runner, setuptools command, JUnit XML export

100

101

## Capabilities

102

103

### Command Line Interface

104

105

Main entry point for running Green as a command-line tool with full argument parsing, configuration file merging, and comprehensive options.

106

107

```python { .api }

108

def main(argv: Sequence[str] | None = None, testing: bool = False) -> int:

109

"""

110

Main entry point for Green command-line interface.

111

112

Args:

113

argv (Sequence[str] | None, optional): Command-line arguments. Defaults to sys.argv.

114

testing (bool): Enable testing mode. Defaults to False.

115

116

Returns:

117

int: Exit code (0 for success, non-zero for failure)

118

"""

119

```

120

121

[Command Line Interface](./cli.md)

122

123

### Configuration Management

124

125

Hierarchical configuration system supporting multiple config file formats, environment variables, and command-line arguments with precedence rules.

126

127

```python { .api }

128

def parseArguments(argv: Sequence[str] | None = None) -> argparse.Namespace:

129

"""Parse command-line arguments."""

130

131

def mergeConfig(args: argparse.Namespace, testing: bool = False) -> argparse.Namespace:

132

"""Merge configuration from files and environment."""

133

134

def getConfig(filepath=None):

135

"""Load configuration from files."""

136

```

137

138

[Configuration](./configuration.md)

139

140

### Test Discovery and Loading

141

142

Enhanced test discovery with pattern matching, module loading, and Green-specific test suite creation with filtering and customization capabilities.

143

144

```python { .api }

145

class GreenTestLoader(unittest.TestLoader):

146

def loadTargets(self, targets: Iterable[str] | str, file_pattern: str = "test*.py") -> GreenTestSuite | None:

147

"""Load tests from target specifications."""

148

149

def loadTarget(self, target, file_pattern='test*.py'):

150

"""Load tests from a single target."""

151

152

def discover(self, current_path: str, file_pattern: str = "test*.py", top_level_dir: str | None = None) -> GreenTestSuite | None:

153

"""Discover tests in directory structure."""

154

```

155

156

[Test Loading](./test-loading.md)

157

158

### Test Execution

159

160

Multi-process test execution with process pool management, worker initialization, and parallel test running for improved performance.

161

162

```python { .api }

163

def run(suite, stream: TextIO | GreenStream, args: argparse.Namespace, testing: bool = False) -> GreenTestResult:

164

"""

165

Run tests with Green's enhanced features.

166

167

Args:

168

suite: Test suite to run

169

stream: Output stream (wrapped in GreenStream)

170

args: Configuration namespace

171

testing (bool): Testing mode flag

172

173

Returns:

174

GreenTestResult: Test execution results

175

"""

176

```

177

178

[Test Execution](./test-execution.md)

179

180

### Test Results and Reporting

181

182

Comprehensive test result collection, aggregation from multiple processes, and support for various output formats including JUnit XML.

183

184

```python { .api }

185

class GreenTestResult:

186

def __init__(self, args, stream): ...

187

def addProtoTestResult(self, proto_test_result): ...

188

def wasSuccessful(self): ...

189

def startTestRun(self): ...

190

def stopTestRun(self): ...

191

```

192

193

[Test Results](./test-results.md)

194

195

### Output Formatting

196

197

Color-coded terminal output with hierarchical display, multiple verbosity levels, and customizable formatting options.

198

199

```python { .api }

200

class GreenStream:

201

def __init__(self, stream, override_appveyor=False, disable_windows=False, disable_unidecode=False): ...

202

def write(self, text): ...

203

def formatText(self, text, indent=0, outcome_char=''): ...

204

def formatLine(self, line, indent=0, outcome_char=''): ...

205

206

class Colors:

207

def __init__(self, termcolor=None): ...

208

def green(self, text): ...

209

def red(self, text): ...

210

def passing(self, text): ...

211

def failing(self, text): ...

212

```

213

214

[Output Formatting](./output-formatting.md)

215

216

### Django Integration

217

218

Native Django test runner integration allowing Green to be used as the test runner in Django projects with full Django-specific features.

219

220

```python { .api }

221

class DjangoRunner(DiscoverRunner):

222

def __init__(self, verbose=-1, **kwargs): ...

223

def add_arguments(self, parser): ...

224

def run_tests(self, test_labels, extra_tests=None, **kwargs): ...

225

```

226

227

[Django Integration](./django-integration.md)

228

229

### JUnit XML Reporting

230

231

JUnit XML report generation for CI/CD integration with comprehensive test result metadata and proper XML formatting.

232

233

```python { .api }

234

class JUnitXML:

235

def save_as(self, test_results, destination): ...

236

```

237

238

[JUnit XML Reporting](./junit-xml.md)

239

240

### Setuptools Integration

241

242

Integration with setuptools allowing Green to be used as a setup.py command for test execution in Python packages.

243

244

```python { .api }

245

class green(setuptools.Command):

246

"""Setuptools command for running Green tests."""

247

```

248

249

[Setuptools Integration](./setuptools-integration.md)

250

251

## Types

252

253

```python { .api }

254

# Type aliases used throughout Green

255

from typing import Union

256

from unittest import TestCase, TestSuite

257

from doctest import DocTestCase

258

259

TestCaseT = Union["ProtoTest", TestCase, DocTestCase]

260

RunnableTestT = Union[TestCaseT, TestSuite]

261

class GreenTestSuite(unittest.TestSuite):

262

def __init__(self, tests=(), args=None): ...

263

def addTest(self, test): ...

264

def customize(self, args): ...

265

def run(self, result, debug=False): ...

266

267

class ProtoTest:

268

"""Serializable test representation for multiprocessing."""

269

# Attributes (not properties)

270

module: str

271

class_name: str

272

method_name: str

273

docstr_part: str

274

subtest_part: str

275

test_time: str

276

description: str

277

is_doctest: bool

278

filename: str | None

279

name: str

280

is_class_or_module_teardown_error: bool

281

failureException: type[Exception]

282

283

def __init__(self, test: TestCase | DocTestCase | TestSuite | None = None) -> None: ...

284

def getDescription(self, verbose: int) -> str: ...

285

286

# Properties

287

@property

288

def dotted_name(self) -> str: ...

289

290

class ProtoTestResult:

291

"""Test result for individual subprocess runs."""

292

def __init__(self, start_callback=None, finalize_callback=None): ...

293

def reinitialize(self): ...

294

def finalize(self): ...

295

296

class ProtoError:

297

"""Serializable error representation."""

298

def __init__(self, err): ...

299

300

class InitializerOrFinalizerError(Exception):

301

"""Errors in worker process setup/teardown."""

302

```