Python unittest.defaultTestLoader() Examples

The following are 30 code examples of unittest.defaultTestLoader(). 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 also want to check out all available functions/classes of the module unittest , or try the search function .
Example #1
Source File: setup.py    From python-isc-dhcp-leases with 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 #2
Source File: test_base.py    From oslotest with 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 #3
Source File: suites.py    From dragonfly with 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 #4
Source File: setup.py    From throttle with 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 #5
Source File: test_all.py    From MultiPlanarUNet with 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 #6
Source File: gaeunit.py    From browserscope with 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
Source File: test_discover_runner.py    From djongo with 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 #8
Source File: test_discover_runner.py    From djongo with 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 #9
Source File: referencetestcase.py    From tdda with 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 #10
Source File: test_suite.py    From qgis-processing-r with 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 #11
Source File: test_suite.py    From qgis-processing-r with 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 #12
Source File: run_tests.py    From dlcookbook-dlbs with 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 #13
Source File: manage.py    From ok with 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 #14
Source File: __init__.py    From parsec.py with 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 #15
Source File: test_suite.py    From DataPlotly with 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 #16
Source File: test_suite.py    From DataPlotly with 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 #17
Source File: test_passwords.py    From btcrecover with 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
Source File: gaeunit.py    From browserscope with 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 #19
Source File: all_tests.py    From scalyr-agent-2 with 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 #20
Source File: gaeunit.py    From browserscope with 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 #21
Source File: dist.py    From python-blowfish with 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 #22
Source File: setup.py    From tor_access with 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 #23
Source File: __init__.py    From pdb-tools with 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 #24
Source File: discover_tests.py    From kgsgo-dataset-preprocessor with 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 #25
Source File: auth_api_with_ldap_api_replacement_quicktest.py    From n6 with GNU Affero General Public License v3.0 5 votes vote down vote up
def run_tests():
    loader = unittest.defaultTestLoader
    suite = _make_test_suite(loader)
    exit_code = _run_test_suite(suite)
    return exit_code 
Example #26
Source File: setup.py    From mybatis-mapper2sql with 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 #27
Source File: alltests.py    From modred with 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 #28
Source File: __main__.py    From pyrser with 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 #29
Source File: run_tests.py    From benchmarks with 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
Source File: run.py    From pth-toolkit with 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())