Python unittest.defaultTestLoader() Examples

The following are 30 code examples for showing how to use unittest.defaultTestLoader(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module unittest , or try the search function .

Example 1
Project: throttle   Author: rbarrois   File: setup.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def run(self):
        """Run the test suite."""
        try:
            import unittest2 as unittest
        except ImportError:
            import unittest

        if self.verbose:
            verbosity=1
        else:
            verbosity=0

        loader = unittest.defaultTestLoader
        suite = unittest.TestSuite()

        if self.test_suite == self.DEFAULT_TEST_SUITE:
            for test_module in loader.discover('.'):
                suite.addTest(test_module)
        else:
            suite.addTest(loader.loadTestsFromName(self.test_suite))

        result = unittest.TextTestRunner(verbosity=verbosity).run(suite)

        if not result.wasSuccessful():
            sys.exit(1) 
Example 2
Project: dragonfly   Author: t4ngo   File: suites.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def build_suite(suite, names):
    # Determine the root directory of the source code files.  This is
    #  used for finding doctest files specified relative to that root.
    project_root = os.path.join(os.path.dirname(__file__), "..", "..")
    project_root = os.path.abspath(project_root)

    # Load test cases from specified names.
    loader = unittest.defaultTestLoader
    for name in names:
        if name.startswith("."):
            name = "dragonfly.test" + name
            suite.addTests(loader.loadTestsFromName(name))
        elif name.startswith("doc:"):
            path = name[4:]
            path = os.path.join(project_root, *path.split("/"))
            path = os.path.abspath(path)
            suite.addTests(doctest.DocFileSuite(path))
        else:
            raise Exception("Invalid test name: %r." % (name,))
    return suite 
Example 3
Project: python-isc-dhcp-leases   Author: MartijnBraam   File: setup.py    License: MIT License 6 votes vote down vote up
def discover_and_run_tests():
    import os
    import sys
    import unittest

    # get setup.py directory
    setup_file = sys.modules['__main__'].__file__
    setup_dir = os.path.abspath(os.path.dirname(setup_file))

    # use the default shared TestLoader instance
    test_loader = unittest.defaultTestLoader

    # use the basic test runner that outputs to sys.stderr
    test_runner = unittest.TextTestRunner()

    # automatically discover all tests
    # NOTE: only works for python 2.7 and later
    test_suite = test_loader.discover(setup_dir)

    # run the test suite
    result = test_runner.run(test_suite)
    if len(result.failures) + len(result.errors) > 0:
        exit(1) 
Example 4
Project: oslotest   Author: openstack   File: test_base.py    License: Apache License 2.0 6 votes vote down vote up
def test_mock_patch_cleanup_on_teardown(self):
        # create an object and save its reference
        class Sub(object):
            pass

        obj = Sub()
        obj.value = obj.backup = object()

        # patch the object
        mock.patch.object(obj, 'value').start()
        self.assertNotEqual(obj.backup, obj.value)

        # run a test case
        loader = unittest.defaultTestLoader
        suite = loader.loadTestsFromTestCase(self.FakeTestCase)
        suite.run(unittest.TestResult())

        # check that mock patches are cleaned up
        self.assertEqual(obj.backup, obj.value) 
Example 5
Project: browserscope   Author: elsigh   File: gaeunit.py    License: Apache License 2.0 5 votes vote down vote up
def django_json_test_runner(request):
    from django.http import HttpResponse
    response = HttpResponse()
    response["Content-Type"] = "text/javascript"
    test_name = request.REQUEST.get("name")
    _load_default_test_modules(_LOCAL_DJANGO_TEST_DIR)
    suite = unittest.defaultTestLoader.loadTestsFromName(test_name)
    runner = JsonTestRunner()
    _run_test_suite(runner, suite)
    runner.result.render_to(response)
    return response

######################################################## 
Example 6
Project: browserscope   Author: elsigh   File: gaeunit.py    License: Apache License 2.0 5 votes vote down vote up
def get(self):
        self.response.headers["Content-Type"] = "text/javascript"
        test_name = self.request.get("name")
        _load_default_test_modules(_LOCAL_TEST_DIR)
        suite = unittest.defaultTestLoader.loadTestsFromName(test_name)
        runner = JsonTestRunner()
        _run_test_suite(runner, suite)
        runner.result.render_to(self.response.out)


# This is not used by the HTML page, but it may be useful for other client test runners. 
Example 7
Project: browserscope   Author: elsigh   File: gaeunit.py    License: Apache License 2.0 5 votes vote down vote up
def _create_suite(package_name, test_name, test_dir):
    loader = unittest.defaultTestLoader
    suite = unittest.TestSuite()

    error = None

    try:
        if not package_name and not test_name:
                modules = _load_default_test_modules(test_dir)
                for module in modules:
                    suite.addTest(loader.loadTestsFromModule(module))
        elif test_name:
                _load_default_test_modules(test_dir)
                suite.addTest(loader.loadTestsFromName(test_name))
        elif package_name:
                package = reload(__import__(package_name))
                module_names = package.__all__
                for module_name in module_names:
                    suite.addTest(loader.loadTestsFromName('%s.%s' % (package_name, module_name)))

        if suite.countTestCases() == 0:
            raise Exception("'%s' is not found or does not contain any tests." %  \
                            (test_name or package_name or 'local directory: \"%s\"' % _LOCAL_TEST_DIR))
    except Exception:
        import traceback
        error = traceback.format_exc()
        print error
        _log_error(error)

    return (suite, error) 
Example 8
Project: pyrser   Author: LionelAuroux   File: __main__.py    License: GNU General Public License v3.0 5 votes vote down vote up
def load_tests(loader, standard_tests, pattern):
    loader = unittest.defaultTestLoader
    if test_unit:
        suite = loader.discover(parent_dir)
    else:
        suite = unittest.TestSuite()

    if test_integration:
        for test_case in test_cases:
            tests = loader.loadTestsFromTestCase(test_case)
            suite.addTests(tests)
    return suite 
Example 9
Project: modred   Author: belson17   File: alltests.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run():
    test_loader = unittest.defaultTestLoader
    test_suites = test_loader.discover(os.path.dirname(__file__))
    unittest.TextTestRunner(buffer=True).run(test_suites)
    #parallel.barrier() 
Example 10
Project: mybatis-mapper2sql   Author: hhyo   File: setup.py    License: Apache License 2.0 5 votes vote down vote up
def run_tests(self):
        import unittest

        test_loader = unittest.defaultTestLoader
        test_runner = unittest.TextTestRunner()
        test_suite = test_loader.discover(setup_dir)
        test_runner.run(test_suite) 
Example 11
def run_tests():
    loader = unittest.defaultTestLoader
    suite = _make_test_suite(loader)
    exit_code = _run_test_suite(suite)
    return exit_code 
Example 12
Project: kgsgo-dataset-preprocessor   Author: hughperkins   File: discover_tests.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def additional_tests():
    setup_file = sys.modules['__main__'].__file__
    setup_dir = os.path.abspath(os.path.dirname(setup_file))
    test_dir = os.path.join(setup_dir, 'tests')
    test_suite = unittest.defaultTestLoader.discover(test_dir)
    blacklist = []
    if '/home/travis' in __file__:
        # Skip some tests that fail on travis-ci
        blacklist.append('test_command')
    return exclude_tests(test_suite, blacklist) 
Example 13
Project: pdb-tools   Author: haddocking   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def test_all():
    mpath = os.path.abspath(os.path.join(test_dir, '..'))
    sys.path.insert(0, mpath)  # so we load dev files before  any installation

    loader = unittest.defaultTestLoader

    tpath = os.path.join(mpath, 'tests')
    suite = loader.discover(tpath)

    return suite 
Example 14
Project: tor_access   Author: comger   File: setup.py    License: MIT License 5 votes vote down vote up
def run(self):
        import os, sys, unittest
        setup_file = sys.modules['__main__'].__file__
        setup_dir = os.path.abspath(os.path.dirname(setup_file))
        test_loader = unittest.defaultTestLoader
        test_runner = unittest.TextTestRunner()
        test_suite = test_loader.discover(setup_dir)
        test_runner.run(test_suite) 
Example 15
Project: python-blowfish   Author: jashandeep-sohi   File: dist.py    License: GNU General Public License v3.0 5 votes vote down vote up
def run(self):    
    build = self.get_finalized_command("build")
    build.run()
    
    if self.catch:
      unittest.installHandler()
    
    sys.path.insert(0, str(Path(build.build_lib).resolve()))
    
    test_loader = unittest.defaultTestLoader
    
    if self.test_name:
      tests = test_loader.loadTestsFromName(self.test_name, None)
    else:
      tests = test_loader.discover(self.start_dir, self.pattern)
    
    test_runner = unittest.TextTestRunner(
      verbosity = self.verbose,
      failfast = self.failfast,
      buffer = self.buffer
    )
    
    test_results = test_runner.run(tests)
      
    del sys.path[0]
    
    if self.exit and not test_results.wasSuccessful():
      raise SystemExit() 
Example 16
Project: scalyr-agent-2   Author: scalyr   File: all_tests.py    License: Apache License 2.0 5 votes vote down vote up
def run_all_tests():
    """Runs all the tests containing this this directory and its children (where tests are
    contained in files ending in '_test.py'.
    """
    print("Current python version: %s" % sys.version)

    test_loader = unittest.defaultTestLoader
    suites = []
    error = False

    test_modules = find_all_tests(UNIT_TESTS_DIRECTORY, UNIT_TESTS_DIRECTORY)
    # Remove all modules which are to be ignored
    ignored_test_modules = [
        get_module_fqdn_for_path(module_path) for module_path in collect_ignore
    ]
    test_modules = list(set(test_modules) - set(ignored_test_modules))

    for test_case in test_modules:
        try:
            suites.append(test_loader.loadTestsFromName(test_case))
        except Exception as e:
            error = True
            print(
                "Error loading test_case '%s'.  %s, %s"
                % (test_case, str(e), traceback.format_exc())
            )

    test_suite = unittest.TestSuite(suites)
    if sys.version_info[:2] < (2, 7):
        # 2.6 and below to do not support capturing test output
        text_runner = unittest.TextTestRunner().run(test_suite)
    else:
        text_runner = unittest.TextTestRunner(buffer=True).run(test_suite)
    if not text_runner.wasSuccessful():
        error = True
    sys.exit(error) 
Example 17
Project: btcrecover   Author: gurnec   File: test_passwords.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __init__(self):
        super(GPUTests, self).__init__()
        self.addTest(unittest.defaultTestLoader.loadTestsFromNames(("Test08KeyDecryption." + method_name
            for method_name in (
                "test_bitcoincore_cl",
                "test_bitcoincore_cl_unicode",
                "test_bitcoincore_cl_no_interrupts",
                "test_bitcoincore_cl_sli",
                "test_armory_cl",
                "test_armory_cl_mem_factor",
                "test_armory_cl_no_interrupts",
                "test_armory_cl_sli")),
            module=sys.modules[__name__]
        )) 
Example 18
Project: MultiPlanarUNet   Author: perslev   File: test_all.py    License: MIT License 5 votes vote down vote up
def get_test_suite(test_class):
    suite = unittest.TestSuite()
    loader = unittest.defaultTestLoader
    suite.addTests(loader.loadTestsFromTestCase(test_class))
    return suite 
Example 19
Project: DataPlotly   Author: ghtmtt   File: test_suite.py    License: GNU General Public License v2.0 5 votes vote down vote up
def test_package(package='DataPlotly'):
    """Test package.
    This function is called by travis without arguments.

    :param package: The package to test.
    :type package: str
    """
    test_loader = unittest.defaultTestLoader
    try:
        test_suite = test_loader.discover(package)
    except ImportError:
        test_suite = unittest.TestSuite()
    _run_tests(test_suite, package) 
Example 20
Project: DataPlotly   Author: ghtmtt   File: test_suite.py    License: GNU General Public License v2.0 5 votes vote down vote up
def test_environment():
    """Test package with an environment variable."""
    package = os.environ.get('TESTING_PACKAGE', 'DataPlotly')
    test_loader = unittest.defaultTestLoader
    test_suite = test_loader.discover(package)
    _run_tests(test_suite, package) 
Example 21
Project: parsec.py   Author: sighingnow   File: __init__.py    License: MIT License 5 votes vote down vote up
def additional_tests():
    suite = unittest.TestSuite()
    '''Accumulate all unit test cases.'''
    loader = unittest.defaultTestLoader
    ## some test cases use the syntax that Python 2 doesn't support.
    additional_names = []
    if sys.version_info[0] >= 3 and sys.version_info[1] >= 3:
        additional_names.append('examples')
        from tests.python_3_only.test_generator import ParserGeneratorWithReturnTest
        suite.addTest(loader.loadTestsFromTestCase(ParserGeneratorWithReturnTest))
    for name in additional_names:
        suite.addTests(loader.discover(name))
    return suite 
Example 22
Project: ok   Author: okpy   File: manage.py    License: Apache License 2.0 5 votes vote down vote up
def run(self):
        test_loader = unittest.defaultTestLoader
        test_runner = unittest.TextTestRunner()
        test_suite = test_loader.discover('tests/')
        test_runner.run(test_suite) 
Example 23
Project: dlcookbook-dlbs   Author: HewlettPackard   File: run_tests.py    License: Apache License 2.0 5 votes vote down vote up
def main(_):
  loader = unittest.defaultTestLoader
  if FLAGS.full_tests:
    suite = unittest.TestSuite([
        loader.loadTestsFromModule(allreduce_test),
        loader.loadTestsFromModule(cnn_util_test),
        loader.loadTestsFromModule(variable_mgr_util_test),
        loader.loadTestsFromModule(benchmark_cnn_test),
    ])
    dist_suite = unittest.TestSuite([
        loader.loadTestsFromModule(benchmark_cnn_distributed_test),
    ])
  else:
    suite = unittest.TestSuite([
        loader.loadTestsFromModule(allreduce_test),
        loader.loadTestsFromModule(cnn_util_test),
        loader.loadTestsFromModule(variable_mgr_util_test),
        loader.loadTestsFromTestCase(benchmark_cnn_test.TestAlexnetModel),
        loader.loadTestsFromTestCase(benchmark_cnn_test.TfCnnBenchmarksTest),
        loader.loadTestsFromTestCase(benchmark_cnn_test.VariableUpdateTest),
    ])
    dist_suite = unittest.TestSuite([
        loader.loadTestsFromNames([
            'benchmark_cnn_distributed_test.DistributedVariableUpdateTest'
            '.testVarUpdateDefault',

            'benchmark_cnn_distributed_test.TfCnnBenchmarksDistributedTest'
            '.testParameterServer',
        ]),
    ])

  if FLAGS.run_distributed_tests:
    print('Running distributed tests')
    result = unittest.TextTestRunner(verbosity=2).run(dist_suite)
  else:
    print('Running non-distributed tests')
    result = unittest.TextTestRunner(verbosity=2).run(suite)
  sys.exit(not result.wasSuccessful()) 
Example 24
Project: qgis-processing-r   Author: north-road   File: test_suite.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_package(package='processing_r'):
    """Test package.
    This function is called by travis without arguments.

    :param package: The package to test.
    :type package: str
    """
    test_loader = unittest.defaultTestLoader
    try:
        test_suite = test_loader.discover(package)
    except ImportError:
        test_suite = unittest.TestSuite()
    _run_tests(test_suite, package) 
Example 25
Project: qgis-processing-r   Author: north-road   File: test_suite.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_environment():
    """Test package with an environment variable."""
    package = os.environ.get('TESTING_PACKAGE', 'processing_r')
    test_loader = unittest.defaultTestLoader
    test_suite = test_loader.discover(package)
    _run_tests(test_suite, package) 
Example 26
Project: tdda   Author: tdda   File: referencetestcase.py    License: MIT License 5 votes vote down vote up
def _run_tests(module=None, argv=None, tagged=False, check=False):
    """
    Run tests
    """
    if argv is None:
        argv = sys.argv
    loader = (TaggedTestLoader(check) if tagged or check
              else unittest.defaultTestLoader)
    if module is None:
        unittest.main(argv=argv, testLoader=loader)
    else:
        unittest.main(module=module, argv=argv, testLoader=loader) 
Example 27
Project: djongo   Author: nesdis   File: test_discover_runner.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_overridable_test_loader(self):
        self.assertEqual(DiscoverRunner().test_loader, defaultTestLoader) 
Example 28
Project: djongo   Author: nesdis   File: test_discover_runner.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_overridable_test_loader(self):
        self.assertEqual(DiscoverRunner().test_loader, defaultTestLoader) 
Example 29
Project: benchmarks   Author: tensorflow   File: run_tests.py    License: Apache License 2.0 4 votes vote down vote up
def main(_):
  loader = unittest.defaultTestLoader
  if FLAGS.full_tests:
    suite = unittest.TestSuite([
        loader.loadTestsFromModule(allreduce_test),
        loader.loadTestsFromModule(cnn_util_test),
        loader.loadTestsFromModule(variable_mgr_util_test),
        loader.loadTestsFromModule(benchmark_cnn_test),
        loader.loadTestsFromModule(all_reduce_benchmark_test),
    ])
    if model_config.can_import_contrib:
      from models.tf1_only import nasnet_test  # pylint: disable=g-import-not-at-top
      suite.addTest(loader.loadTestsFromModule(nasnet_test))
    dist_suite = unittest.TestSuite([
        loader.loadTestsFromModule(benchmark_cnn_distributed_test),
    ])
  else:
    suite = unittest.TestSuite([
        loader.loadTestsFromModule(allreduce_test),
        loader.loadTestsFromModule(cnn_util_test),
        loader.loadTestsFromModule(all_reduce_benchmark_test),
        loader.loadTestsFromModule(variable_mgr_util_test),
        loader.loadTestsFromTestCase(benchmark_cnn_test.TestAlexnetModel),
        loader.loadTestsFromTestCase(benchmark_cnn_test.TfCnnBenchmarksTest),
        loader.loadTestsFromTestCase(benchmark_cnn_test.VariableUpdateTest),
        loader.loadTestsFromTestCase(
            benchmark_cnn_test.VariableMgrLocalReplicatedTest),
    ])
    dist_suite = unittest.TestSuite([
        loader.loadTestsFromNames([
            'benchmark_cnn_distributed_test.DistributedVariableUpdateTest'
            '.testVarUpdateDefault',

            'benchmark_cnn_distributed_test.TfCnnBenchmarksDistributedTest'
            '.testParameterServer',
        ]),
    ])

  if FLAGS.run_distributed_tests:
    print('Running distributed tests')
    result = unittest.TextTestRunner(verbosity=2).run(dist_suite)
  else:
    print('Running non-distributed tests')
    result = unittest.TextTestRunner(verbosity=2).run(suite)
  sys.exit(not result.wasSuccessful()) 
Example 30
Project: pth-toolkit   Author: byt3bl33d3r   File: run.py    License: BSD 2-Clause "Simplified" License 4 votes vote down vote up
def __init__(self, module=__name__, defaultTest=None, argv=None,
                    testRunner=None, testLoader=defaultTestLoader,
                    exit=True, verbosity=1, failfast=None, catchbreak=None,
                    buffer=None, stdout=None):
        if module == __name__:
            self.module = None
        elif istext(module):
            self.module = __import__(module)
            for part in module.split('.')[1:]:
                self.module = getattr(self.module, part)
        else:
            self.module = module
        if argv is None:
            argv = sys.argv
        if stdout is None:
            stdout = sys.stdout

        self.exit = exit
        self.failfast = failfast
        self.catchbreak = catchbreak
        self.verbosity = verbosity
        self.buffer = buffer
        self.defaultTest = defaultTest
        self.listtests = False
        self.load_list = None
        self.testRunner = testRunner
        self.testLoader = testLoader
        progName = argv[0]
        if progName.endswith('%srun.py' % os.path.sep):
            elements = progName.split(os.path.sep)
            progName = '%s.run' % elements[-2]
        else:
            progName = os.path.basename(argv[0])
        self.progName = progName
        self.parseArgs(argv)
        if self.load_list:
            # TODO: preserve existing suites (like testresources does in
            # OptimisingTestSuite.add, but with a standard protocol).
            # This is needed because the load_tests hook allows arbitrary
            # suites, even if that is rarely used.
            source = open(self.load_list, 'rb')
            try:
                lines = source.readlines()
            finally:
                source.close()
            test_ids = set(line.strip().decode('utf-8') for line in lines)
            filtered = unittest.TestSuite()
            for test in iterate_tests(self.test):
                if test.id() in test_ids:
                    filtered.addTest(test)
            self.test = filtered
        if not self.listtests:
            self.runTests()
        else:
            for test in iterate_tests(self.test):
                stdout.write('%s\n' % test.id())