Skip to main content

DiscoverRunner

A Django test runner that uses unittest2 test discovery.

Attributes

AttributeTypeDescription
test_suitetype = unittest.TestSuiteThe class used to instantiate the main test suite container for collected tests.
parallel_test_suitetype = ParallelTestSuiteThe class used to wrap and manage the test suite when running tests across multiple processes.
test_runnertype = unittest.TextTestRunnerThe class used to execute the test suite and produce output results.
test_loaderunittest.TestLoader = unittest.defaultTestLoaderThe instance responsible for discovering and loading tests from modules and directories.
reorder_bytuple = (TestCase, SimpleTestCase)A tuple of test case classes used to determine the execution order of discovered tests.

Constructor

Signature

def DiscoverRunner(
pattern: string = None,
top_level: string = None,
verbosity: int = 1,
interactive: boolean = True,
failfast: boolean = False,
keepdb: boolean = False,
reverse: boolean = False,
debug_mode: boolean = False,
debug_sql: boolean = False,
parallel: int = 0,
tags: list = None,
exclude_tags: list = None,
test_name_patterns: list = None,
pdb: boolean = False,
buffer: boolean = False,
enable_faulthandler: boolean = True,
timing: boolean = False,
shuffle: int = False,
logger: logging.Logger = None,
durations: int = None,
kwargs: dict = null
) - > null

Parameters

NameTypeDescription
patternstring = NoneThe test matching pattern.
top_levelstring = NoneTop level of project for unittest discovery.
verbosityint = 1Verbosity level: 0, 1, 2, or 3.
interactiveboolean = TrueWhether to allow interactive prompts.
failfastboolean = FalseWhether to stop the test suite after the first failure.
keepdbboolean = FalseWhether to preserve the test database between runs.
reverseboolean = FalseWhether to reverse test case order.
debug_modeboolean = FalseWhether to set settings.DEBUG to True.
debug_sqlboolean = FalseWhether to print logged SQL queries on failure.
parallelint = 0Number of parallel processes to use.
tagslist = NoneList of tags to include.
exclude_tagslist = NoneList of tags to exclude.
test_name_patternslist = NoneList of patterns to match test names.
pdbboolean = FalseWhether to drop into the debugger on failure.
bufferboolean = FalseWhether to discard output from passing tests.
enable_faulthandlerboolean = TrueWhether to enable the Python faulthandler module.
timingboolean = FalseWhether to output timing information.
shuffleint = FalseSeed for shuffling test case order.
loggerlogging.Logger = NoneCustom logger instance.
durationsint = NoneShow the N slowest test cases.
kwargsdict = nullAdditional keyword arguments.

Methods


add_arguments()

@classmethod
def add_arguments(
parser: ArgumentParser
)

Configures the argument parser with test runner options such as failfast, parallel execution, and database persistence.

Parameters

NameTypeDescription
parserArgumentParserThe argument parser instance to which test runner command-line arguments will be added.

shuffle_seed()

@classmethod
def shuffle_seed() - > int

Retrieves the seed value used by the shuffler to randomize test execution order.

Returns

TypeDescription
intThe integer seed value if shuffling is enabled, otherwise None.

log()

@classmethod
def log(
msg: str,
level: int = None
)

Log the message at the given logging level (the default is INFO).

Parameters

NameTypeDescription
msgstrThe text message to be logged or printed to the console.
levelint = NoneThe logging level (e.g., logging.DEBUG); defaults to logging.INFO if not provided.

setup_test_environment()

@classmethod
def setup_test_environment(
**kwargs: dict
)

Initializes the global Django test environment and installs the unittest signal handler.

Parameters

NameTypeDescription
**kwargsdictAdditional keyword arguments for environment configuration.

setup_shuffler()

@classmethod
def setup_shuffler()

Initializes the Shuffler instance if test randomization is enabled and logs the seed used.


load_with_patterns()

@classmethod
def load_with_patterns() - > contextmanager

A context manager that temporarily applies test name filtering patterns to the test loader.

Returns

TypeDescription
contextmanagerA context manager that restores original test name patterns upon exit.

load_tests_for_label()

@classmethod
def load_tests_for_label(
label: str,
discover_kwargs: dict
) - > TestSuite

Loads test cases from a specific label, which can be a dotted module path or a directory path.

Parameters

NameTypeDescription
labelstrThe dotted path or file system path identifying the tests to load.
discover_kwargsdictKeyword arguments passed to the unittest discovery process.

Returns

TypeDescription
TestSuiteA suite containing the tests discovered for the provided label.

build_suite()

@classmethod
def build_suite(
test_labels: list = None,
**kwargs: dict
) - > TestSuite

Constructs a complete test suite by discovering tests from labels, filtering by tags, and applying ordering or parallelism.

Parameters

NameTypeDescription
test_labelslist = NoneA list of strings representing the modules or directories to search for tests.
**kwargsdictAdditional arguments used to customize suite construction.

Returns

TypeDescription
TestSuiteThe final test suite ready for execution, potentially wrapped for parallel processing.

setup_databases()

@classmethod
def setup_databases(
**kwargs: dict
) - > list

Creates and initializes the test databases required for the test run.

Parameters

NameTypeDescription
**kwargsdictAdditional parameters passed to the underlying database setup utility.

Returns

TypeDescription
listA list of configuration data used to restore the database state during teardown.

get_resultclass()

@classmethod
def get_resultclass() - > type

Determines the appropriate test result class based on debugging settings like SQL logging or PDB integration.

Returns

TypeDescription
typeThe class used to instantiate the test result object, or None for the default.

get_test_runner_kwargs()

@classmethod
def get_test_runner_kwargs() - > dict

Builds the dictionary of keyword arguments required to initialize the underlying unittest runner.

Returns

TypeDescription
dictA dictionary containing failfast, resultclass, verbosity, buffer, and durations settings.

run_checks()

@classmethod
def run_checks(
databases: dict
)

Executes Django system checks to ensure the project configuration is valid before running tests.

Parameters

NameTypeDescription
databasesdictThe set of database aliases to include in the system check.

run_suite()

@classmethod
def run_suite(
suite: TestSuite,
**kwargs: dict
) - > TestResult

Executes the provided test suite using the configured test runner and logs shuffle information if applicable.

Parameters

NameTypeDescription
suiteTestSuiteThe suite of tests to be executed.
**kwargsdictAdditional arguments for the test runner.

Returns

TypeDescription
TestResultThe result object containing details about the completed test run.

teardown_databases()

@classmethod
def teardown_databases(
old_config: list,
**kwargs: dict
)

Destroy all the non-mirror databases.

Parameters

NameTypeDescription
old_configlistThe database configuration data returned by setup_databases used to restore state.
**kwargsdictAdditional arguments for database destruction.

teardown_test_environment()

@classmethod
def teardown_test_environment(
**kwargs: dict
)

Cleans up the global Django test environment and removes the unittest signal handler.

Parameters

NameTypeDescription
**kwargsdictAdditional keyword arguments for environment teardown.

suite_result()

@classmethod
def suite_result(
suite: TestSuite,
result: TestResult,
**kwargs: dict
) - > int

Calculates the total number of test failures, errors, and unexpected successes from the test result.

Parameters

NameTypeDescription
suiteTestSuiteThe suite that was executed.
resultTestResultThe result object containing the outcome of the test run.
**kwargsdictAdditional arguments for result calculation.

Returns

TypeDescription
intThe aggregate count of failed or erroneous test outcomes.

get_databases()

@classmethod
def get_databases(
suite: TestSuite
) - > dict

Identifies the databases required by the suite and logs any configured databases that will be skipped.

Parameters

NameTypeDescription
suiteTestSuiteThe suite used to determine database requirements.

Returns

TypeDescription
dictThe filtered mapping of database aliases required for the current test suite.

run_tests()

@classmethod
def run_tests(
test_labels: list,
**kwargs: dict
) - > int

Run the unit tests for all the test labels in the provided list.

Parameters

NameTypeDescription
test_labelslistDotted Python paths to test modules, test classes, or test methods.
**kwargsdictAdditional arguments for the test execution process.

Returns

TypeDescription
intThe number of tests that failed.