Green is a clean, colorful, fast python test runner.
—
Green's enhanced test discovery system provides comprehensive test loading capabilities with pattern matching, module loading, and Green-specific test suite creation with filtering and customization.
Enhanced test loader that extends unittest.TestLoader with Green-specific functionality for parallel execution and advanced test discovery.
class GreenTestLoader(unittest.TestLoader):
"""
Enhanced test loader with Green-specific features.
Extends unittest.TestLoader to provide:
- Parallel-friendly test loading
- Custom test suite creation
- Enhanced discovery patterns
- Integration with Green's configuration system
"""
def loadTargets(self, targets, file_pattern='test*.py'):
"""
Load tests from multiple target specifications.
Args:
targets (list): List of test targets. Can be:
- Directory paths: 'tests/', 'src/tests'
- Module names: 'tests.test_module'
- Class names: 'tests.test_module.TestClass'
- Method names: 'tests.test_module.TestClass.test_method'
- File paths: 'tests/test_file.py'
file_pattern (str): Pattern for test files (default: 'test*.py')
Returns:
GreenTestSuite or None: Test suite containing all loaded tests,
or None if no tests found
Example:
loader = GreenTestLoader()
suite = loader.loadTargets(['tests/', 'integration/'])
if suite:
print(f"Loaded {suite.countTestCases()} tests")
"""
def loadTarget(self, target, file_pattern='test*.py'):
"""
Load tests from a single target specification.
Args:
target (str): Single test target (directory, module, class, or method)
file_pattern (str): Pattern for test files
Returns:
GreenTestSuite or None: Test suite for the target
Example:
loader = GreenTestLoader()
suite = loader.loadTarget('tests.test_auth.TestLogin.test_valid_credentials')
"""
def discover(self, current_path, file_pattern='test*.py', top_level_dir=None):
"""
Discover tests in a directory structure.
Args:
current_path (str): Directory to search for tests
file_pattern (str): Pattern to match test files (default: 'test*.py')
top_level_dir (str, optional): Top-level directory for imports
Returns:
GreenTestSuite or None: Discovered tests
Example:
loader = GreenTestLoader()
suite = loader.discover('tests', file_pattern='*_test.py')
"""
def loadTestsFromTestCase(self, testCaseClass):
"""
Load tests from a test case class.
Args:
testCaseClass: unittest.TestCase subclass
Returns:
GreenTestSuite: Test suite containing tests from the class
"""
def loadFromModuleFilename(self, filename):
"""
Load tests from a module filename.
Args:
filename (str): Path to Python module file
Returns:
TestSuite: Loaded tests from the module
"""
def loadTestsFromModule(self, module, pattern=None):
"""
Load tests from a Python module.
Args:
module: Python module object
pattern (str, optional): Pattern to filter test methods
Returns:
GreenTestSuite: Tests loaded from the module
"""
def loadTestsFromName(self, name, module=None):
"""
Load tests from a dotted name specification.
Args:
name (str): Dotted name (e.g., 'tests.test_module.TestClass.test_method')
module (optional): Module to use as context for relative names
Returns:
GreenTestSuite: Loaded tests
"""def toProtoTestList(suite, test_list=None, doing_completions=False):
"""
Convert test suite to list of ProtoTest objects for multiprocessing.
Args:
suite: Test suite to convert
test_list (list, optional): Existing list to append to
doing_completions (bool): Whether this is for shell completions
Returns:
list: List of ProtoTest objects
"""
def toParallelTargets(suite, targets):
"""
Convert test suite to parallel-execution-friendly target list.
Args:
suite: Test suite to convert
targets: Original target specifications
Returns:
list: List of target strings suitable for parallel execution
"""
def flattenTestSuite(test_suite, module=None):
"""
Flatten nested test suites into a single GreenTestSuite.
Args:
test_suite: Test suite to flatten
module (optional): Module context
Returns:
GreenTestSuite: Flattened test suite
"""def getCompletions(target):
"""
Get shell completion suggestions for a test target.
Args:
target (str): Partial test target for completion
Returns:
str: Newline-separated completion suggestions
Example:
completions = getCompletions('tests.test_')
# Returns possible completions like:
# tests.test_auth
# tests.test_models
# tests.test_views
"""def findDottedModuleAndParentDir(file_path):
"""
Find the dotted module name and parent directory for a file path.
Args:
file_path (str): Path to Python file
Returns:
tuple: (dotted_module_name, parent_directory)
Example:
module, parent = findDottedModuleAndParentDir('/project/tests/test_auth.py')
# Returns: ('tests.test_auth', '/project')
"""
def isPackage(file_path):
"""
Check if a file path represents a Python package.
Args:
file_path (str): Path to check
Returns:
bool: True if path is a package (directory with __init__.py)
"""
def isTestCaseDisabled(test_case_class, method_name):
"""
Check if a test case method is disabled.
Args:
test_case_class: TestCase class
method_name (str): Name of test method
Returns:
bool: True if test method is disabled
"""from green.loader import GreenTestLoader
# Create loader
loader = GreenTestLoader()
# Load from directory
suite = loader.loadTargets(['tests/'])
print(f"Found {suite.countTestCases()} tests")
# Load specific module
suite = loader.loadTarget('tests.test_authentication')
# Load specific test class
suite = loader.loadTarget('tests.test_models.UserModelTest')
# Load specific test method
suite = loader.loadTarget('tests.test_views.LoginViewTest.test_valid_login')from green.loader import GreenTestLoader
loader = GreenTestLoader()
# Custom file patterns
suite = loader.discover('tests', file_pattern='*_test.py')
suite = loader.discover('tests', file_pattern='test_*.py')
# Multiple targets with different patterns
targets = ['unit_tests/', 'integration_tests/', 'tests/test_specific.py']
suite = loader.loadTargets(targets, file_pattern='*.py')from green.config import parseArguments, mergeConfig
from green.loader import GreenTestLoader
# Use configuration-driven loading
args = parseArguments(['tests/', '--file-pattern', '*_test.py'])
config = mergeConfig(args)
loader = GreenTestLoader()
suite = loader.loadTargets(config.targets, config.file_pattern)from green.loader import GreenTestLoader, toProtoTestList, flattenTestSuite
loader = GreenTestLoader()
suite = loader.loadTargets(['tests/'])
# Convert to proto tests for multiprocessing
proto_tests = toProtoTestList(suite)
print(f"Proto tests: {len(proto_tests)}")
# Flatten nested suites
flat_suite = flattenTestSuite(suite)
print(f"Flattened: {flat_suite.countTestCases()} tests")from green.loader import getCompletions
# Get completions for partial target
completions = getCompletions('tests.test_')
print("Available completions:")
for completion in completions.split('\n'):
if completion.strip():
print(f" {completion}")from green.loader import GreenTestLoader, findDottedModuleAndParentDir, isPackage
loader = GreenTestLoader()
# Load tests from specific file paths
test_files = ['/project/tests/test_auth.py', '/project/tests/test_models.py']
suites = []
for file_path in test_files:
if file_path.endswith('.py'):
# Convert file path to module name
module_name, parent_dir = findDottedModuleAndParentDir(file_path)
suite = loader.loadTarget(module_name)
if suite:
suites.append(suite)
# Combine all suites
if suites:
main_suite = suites[0]
for suite in suites[1:]:
main_suite.addTest(suite)from green.loader import GreenTestLoader
loader = GreenTestLoader()
try:
suite = loader.loadTargets(['nonexistent_tests/'])
if suite is None:
print("No tests found in specified targets")
elif suite.countTestCases() == 0:
print("Test suite is empty")
else:
print(f"Successfully loaded {suite.countTestCases()} tests")
except ImportError as e:
print(f"Failed to import test module: {e}")
except Exception as e:
print(f"Error loading tests: {e}")Green supports various test discovery patterns:
test*.py - Files starting with "test"*test.py - Files ending with "test"*_test.py - Files ending with "_test"test_*.py - Files starting with "test_"tests/, src/tests/tests.test_auth, mypackage.tests.test_modelstests.test_auth.AuthenticationTesttests.test_auth.AuthenticationTest.test_logintests/test_auth.py, /absolute/path/to/test.py# In test modules, specify doctests to run
doctest_modules = ['mypackage.utils', 'mypackage.helpers']
# Green will automatically discover and run doctests from these modulesInstall with Tessl CLI
npx tessl i tessl/pypi-green