A testing framework that extends unittest with plugins and enhanced discovery capabilities
—
Core functionality for discovering, loading, and running tests with extensive customization options through command-line arguments, configuration files, and plugin integration.
Primary functions for running tests and test discovery.
def main(*args, **kwargs):
"""
Main entry point for running tests.
Parameters:
- module: Module in which to run tests (default: __main__)
- defaultTest: Default test name (default: None)
- argv: Command line args (default: sys.argv)
- exit: Exit after running tests (default: True)
- verbosity: Base verbosity level
- plugins: List of additional plugin modules to load
- excludePlugins: List of plugin modules to exclude
- extraHooks: List of (hook name, plugin instance) tuples
Returns:
PluggableTestProgram instance
"""
def discover(*args, **kwargs):
"""
Main entry point for test discovery.
Runs PluggableTestProgram with module=None to force test discovery.
All arguments are passed through except module.
Returns:
PluggableTestProgram instance
"""Main test program that coordinates the entire test execution process.
class PluggableTestProgram:
"""
TestProgram that enables plugins.
Accepts the same parameters as unittest.TestProgram but most are ignored
as their functions are handled by plugins.
"""
sessionClass = Session
loaderClass = PluggableTestLoader
runnerClass = PluggableTestRunner
defaultPlugins: tuple
excludePlugins: tuple
def __init__(self, **kwargs):
"""
Initialize test program.
Parameters:
- module: Module in which to run tests
- defaultTest: Default test name
- argv: Command line args
- exit: Exit after running tests
- verbosity: Base verbosity
- plugins: Additional plugin modules
- excludePlugins: Plugin modules to exclude
- extraHooks: (hook name, plugin instance) pairs
"""
def parseArgs(self, argv):
"""
Parse command line args and create configuration session.
Parameters:
- argv: Command line arguments
"""
def loadPlugins(self):
"""
Load available plugins.
Uses defaultPlugins and excludePlugins to alter plugin list.
Also registers extraHooks plugin pairs.
"""
def createTests(self):
"""Create top-level test suite."""
def runTests(self):
"""Run tests using configured runner."""
@classmethod
def getCurrentSession(cls):
"""
Get the current session.
Returns:
Current Session instance or None if no session running
"""Pluggable test loader that defers all loading operations to plugins.
class PluggableTestLoader:
"""
Test loader that defers all loading to plugins.
Parameters:
- session: Test run session
"""
suiteClass = unittest.TestSuite
def __init__(self, session):
"""Initialize with test session."""
def loadTestsFromModule(self, module):
"""
Load tests from module.
Fires loadTestsFromModule hook.
Parameters:
- module: Python module to load tests from
Returns:
TestSuite containing loaded tests
"""
def loadTestsFromNames(self, testNames, module=None):
"""
Load tests from test names.
Fires loadTestsFromNames hook.
Parameters:
- testNames: List of test names to load
- module: Optional module context
Returns:
TestSuite containing loaded tests
"""
def loadTestsFromName(self, name, module=None):
"""
Load tests from test name.
Fires loadTestsFromName hook.
Parameters:
- name: Test name to load
- module: Optional module context
Returns:
TestSuite containing loaded tests
"""
def discover(self, start_dir=None, pattern=None):
"""
Compatibility shim for load_tests protocol.
Parameters:
- start_dir: Directory to start discovery
- pattern: Pattern to match test files
Returns:
TestSuite containing discovered tests
"""
def failedImport(self, name):
"""
Make test case representing a failed import.
Parameters:
- name: Name of module that failed to import
Returns:
TestCase representing the import failure
"""
def failedLoadTests(self, name, exception):
"""
Make test case representing a failed test load.
Parameters:
- name: Name of test that failed to load
- exception: Exception that occurred during loading
Returns:
TestCase representing the load failure
"""Pluggable test result that defers all outcome recording to plugins.
class PluggableTestResult:
"""
Test result that defers to plugins.
All test outcome recording and reporting is deferred to plugins,
which implement startTest, stopTest, testOutcome, and wasSuccessful.
Parameters:
- session: Test run session
"""
shouldStop: bool # When True, test run should stop
failfast: bool # TestCase.subTest expects this attribute
def __init__(self, session):
"""Initialize with test session."""
def startTest(self, test):
"""
Start a test case.
Fires startTest hook.
Parameters:
- test: Test case being started
"""
def stopTest(self, test):
"""
Stop a test case.
Fires stopTest hook.
Parameters:
- test: Test case being stopped
"""
def addError(self, test, err):
"""
Test case resulted in error.
Fires setTestOutcome and testOutcome hooks.
Parameters:
- test: Test case
- err: Error tuple (type, value, traceback)
"""
def addFailure(self, test, err):
"""
Test case resulted in failure.
Fires setTestOutcome and testOutcome hooks.
Parameters:
- test: Test case
- err: Failure tuple (type, value, traceback)
"""
def addSuccess(self, test):
"""
Test case resulted in success.
Fires setTestOutcome and testOutcome hooks.
Parameters:
- test: Test case
"""
def addSkip(self, test, reason):
"""
Test case was skipped.
Fires setTestOutcome and testOutcome hooks.
Parameters:
- test: Test case
- reason: Skip reason string
"""
def addSubTest(self, test, subtest, err):
"""
Called at the end of a subtest.
Fires setTestOutcome and testOutcome hooks.
Parameters:
- test: Parent test case
- subtest: Subtest case
- err: Error tuple or None for success
"""import nose2
# Discover and run all tests in current directory
nose2.discover()
# Discover tests with custom start directory
nose2.discover(argv=['nose2', '--start-dir', 'tests'])from nose2.main import PluggableTestProgram
# Create custom test program
program = PluggableTestProgram(
module=None, # Force discovery
argv=['test', '--verbose', '--start-dir', 'tests'],
exit=False, # Don't exit after running
plugins=['nose2.plugins.coverage', 'nose2.plugins.junitxml']
)from nose2.session import Session
from nose2.loader import PluggableTestLoader
# Create session and loader
session = Session()
loader = PluggableTestLoader(session)
# Load tests from specific module
import my_test_module
suite = loader.loadTestsFromModule(my_test_module)
# Load tests by name
suite = loader.loadTestsFromNames(['test_module.TestClass.test_method'])Install with Tessl CLI
npx tessl i tessl/pypi-nose2