Python unittest 模块,defaultTestLoader() 实例源码

我们从Python开源项目中,提取了以下20个代码示例,用于说明如何使用unittest.defaultTestLoader()

项目:datatest    作者:shawnbrown    | 项目源码 | 文件源码
def __init__(self, module='__main__', defaultTest=None, argv=None,
                   testRunner=DataTestRunner, testLoader=_defaultTestLoader,
                   exit=True, verbosity=1, failfast=None, catchbreak=None,
                   buffer=None, ignore=False):
        self.ignore = ignore
        _TestProgram.__init__(self,
                              module=module,
                              defaultTest=defaultTest,
                              argv=argv,
                              testRunner=testRunner,
                              testLoader=testLoader,
                              exit=exit,
                              verbosity=verbosity,
                              failfast=failfast,
                              catchbreak=catchbreak,
                              buffer=buffer)
项目:eos-data-distribution    作者:endlessm    | 项目源码 | 文件源码
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
    test_runner.run(test_suite)
项目:protoc-gen-lua-bin    作者:u0u0    | 项目源码 | 文件源码
def MakeTestSuite():
  # Test C++ implementation
  import unittest
  import google.protobuf.pyext.descriptor_cpp2_test as descriptor_cpp2_test
  import google.protobuf.pyext.message_factory_cpp2_test \
      as message_factory_cpp2_test
  import google.protobuf.pyext.reflection_cpp2_generated_test \
      as reflection_cpp2_generated_test

  loader = unittest.defaultTestLoader
  suite = unittest.TestSuite()
  for test in [  descriptor_cpp2_test,
                 message_factory_cpp2_test,
                 reflection_cpp2_generated_test]:
    suite.addTest(loader.loadTestsFromModule(test))
  return suite
项目:protoc-gen-lua-bin    作者:u0u0    | 项目源码 | 文件源码
def MakeTestSuite():
  # Test C++ implementation
  import unittest
  import google.protobuf.pyext.descriptor_cpp2_test as descriptor_cpp2_test
  import google.protobuf.pyext.message_factory_cpp2_test \
      as message_factory_cpp2_test
  import google.protobuf.pyext.reflection_cpp2_generated_test \
      as reflection_cpp2_generated_test

  loader = unittest.defaultTestLoader
  suite = unittest.TestSuite()
  for test in [  descriptor_cpp2_test,
                 message_factory_cpp2_test,
                 reflection_cpp2_generated_test]:
    suite.addTest(loader.loadTestsFromModule(test))
  return suite
项目:deb-oslotest    作者:openstack    | 项目源码 | 文件源码
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)
项目:deb-python-gabbi    作者:openstack    | 项目源码 | 文件源码
def test_suite_catches_fixture_fail(self):
        """When a fixture fails in start_fixture it should fail
        the first test in the suite and skip the others.
        """
        loader = unittest.defaultTestLoader
        result = unittest.TestResult()
        test_data = {'fixtures': ['FakeFixture'],
                     'tests': [{'name': 'alpha', 'GET': '/'},
                               {'name': 'beta', 'GET': '/'}]}
        test_suite = suitemaker.test_suite_from_dict(
            loader, 'foo', test_data, '.', 'localhost',
            80, sys.modules[__name__], None)

        test_suite.run(result)

        self.assertEqual(2, len(result.skipped))
        self.assertEqual(1, len(result.errors))

        errored_test, trace = result.errors[0]

        self.assertIn('foo_alpha', str(errored_test))
        self.assertIn(VALUE_ERROR, trace)
项目:deb-python-gabbi    作者:openstack    | 项目源码 | 文件源码
def run_suite(handle, handler_objects, host, port, prefix, force_ssl=False,
              failfast=False, data_dir='.', verbosity=False, name='input'):
    """Run the tests from the YAML in handle."""
    data = utils.load_yaml(handle)
    if force_ssl:
        if 'defaults' in data:
            data['defaults']['ssl'] = True
        else:
            data['defaults'] = {'ssl': True}
    if verbosity:
        if 'defaults' in data:
            data['defaults']['verbose'] = verbosity
        else:
            data['defaults'] = {'verbose': verbosity}

    loader = unittest.defaultTestLoader
    test_suite = suitemaker.test_suite_from_dict(
        loader, name, data, data_dir, host, port, None, None, prefix=prefix,
        handlers=handler_objects, test_loader_name='gabbi-runner')

    result = ConciseTestRunner(
        verbosity=2, failfast=failfast).run(test_suite)
    return result.wasSuccessful()
项目:core-framework    作者:RedhawkSDR    | 项目源码 | 文件源码
def main(spd_file=None, module='__main__', defaultTest=None, argv=None, testRunner=None,
         testLoader=unittest.defaultTestLoader, impl=None):
    if spd_file is None:
        return rhunittest.RHTestProgram(module, defaultTest, argv, testRunner, impl)
    else:
        return ScaComponentTestProgram(spd_file, module, defaultTest, argv, testRunner, testLoader, impl)
项目:datatest    作者:shawnbrown    | 项目源码 | 文件源码
def __init__(self, module='__main__', defaultTest=None, argv=None,
                   testRunner=DataTestRunner, testLoader=_defaultTestLoader,
                   exit=True, ignore=False):
        self.ignore = ignore
        _TestProgram.__init__(self,
                              module=module,
                              defaultTest=defaultTest,
                              argv=argv,
                              testRunner=testRunner,
                              testLoader=testLoader,
                              exit=exit)
项目:datatest    作者:shawnbrown    | 项目源码 | 文件源码
def __init__(self, module='__main__', defaultTest=None, argv=None,
                   testRunner=DataTestRunner, testLoader=_defaultTestLoader,
                   exit=True, ignore=False):
        self.exit = exit  # <- 2.6 does not handle exit argument.
        self.ignore = ignore
        _TestProgram.__init__(self,
                              module=module,
                              defaultTest=defaultTest,
                              argv=argv,
                              testRunner=testRunner,
                              testLoader=testLoader)
项目:super_simple_siem    作者:elucidant    | 项目源码 | 文件源码
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:
        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
项目:packaging    作者:blockstack    | 项目源码 | 文件源码
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)
项目:deb-python-gabbi    作者:openstack    | 项目源码 | 文件源码
def setUp(self):
        super(DriverTest, self).setUp()
        self.loader = unittest.defaultTestLoader
        self.test_dir = os.path.join(os.path.dirname(__file__), TESTS_DIR)
项目:deb-python-gabbi    作者:openstack    | 项目源码 | 文件源码
def setUp(self):
        super(DriverTest, self).setUp()
        self.loader = unittest.defaultTestLoader
        self.test_dir = os.path.join(os.path.dirname(__file__), TESTS_DIR)
项目:greedypacker    作者:ssbothwell    | 项目源码 | 文件源码
def load_tests(loader, standard_tests, pattern):
    if pattern == __name__:
        pattern = None
    suite = unittest.TestSuite()
    for test_module in [
        test_api,
        test_shelf,
        test_guillotine,
        test_maximalrectangles,
        test_skyline,
    ]:
        tests = (unittest.defaultTestLoader
                 .loadTestsFromModule(test_module, pattern=pattern))
        suite.addTests(tests)
    return suite
项目:gmc    作者:kapilgarg1996    | 项目源码 | 文件源码
def build_suite(test_labels=None):
    suite = unittest.TestSuite()
    test_loader = unittest.defaultTestLoader
    test_labels = test_labels or ['.']
    discover_kwargs = {}
    for label in test_labels:
        kwargs = discover_kwargs.copy()
        tests = None

        label_as_path = os.path.abspath(label)
        # if a module, or "module.ClassName[.method_name]", just run those
        if not os.path.exists(label_as_path):
            tests = test_loader.loadTestsFromName(label)
        elif os.path.isdir(label_as_path):
            top_level = label_as_path
            while True:
                init_py = os.path.join(top_level, '__init__.py')
                if os.path.exists(init_py):
                    try_next = os.path.dirname(top_level)
                    if try_next == top_level:
                        # __init__.py all the way down? give up.
                        break
                    top_level = try_next
                    continue
                break
            kwargs['top_level_dir'] = top_level

        if not (tests and tests.countTestCases()) and is_discoverable(label):
            # Try discovery if path is a package or directory
            tests = test_loader.discover(start_dir=label, **kwargs)

            # Make unittest forget the top-level dir it calculated from this
            # run, to support running tests from two different top-levels.
            test_loader._top_level_dir = None

        suite.addTests(tests)

    return suite
项目:inventwithpython_pysdl2    作者:rswinkle    | 项目源码 | 文件源码
def list_tags(option, opt, value, parser, *args, **kwargs):
    alltags = []
    testsuites = []
    testdir, testfiles = gettestfiles(os.path.join
                                      (os.path.dirname(__file__), ".."))
    testloader = unittest.defaultTestLoader

    for test in testfiles:
        try:
            testmod = os.path.splitext(test)[0]
            fp, pathname, descr = imp.find_module(testmod, [testdir, ])
            package = imp.load_module(testmod, fp, pathname, descr)
            try:
                testsuites.append(loadtests_frompkg(package, testloader))
            except:
                printerror()
        except:
            pass
    for suite in testsuites:
        for test in suite:
            if hasattr(test, "__tags__"):
                tags = getattr(test, "__tags__")
                for tag in tags:
                    if tag not in alltags:
                        alltags.append(tag)
    print(alltags)
    sys.exit()
项目:stencil    作者:funkybob    | 项目源码 | 文件源码
def test_suite():
    """Return tests suite."""
    test_loader = unittest.defaultTestLoader
    return test_loader.discover('tests', pattern='test*.py')
项目:gnocchi    作者:gnocchixyz    | 项目源码 | 文件源码
def _do_test(self, filename):
        token = self.os_admin.auth_provider.get_token()
        url = self.os_admin.auth_provider.base_url(
            {'service':  CONF.metric.catalog_type,
             'endpoint_type': CONF.metric.endpoint_type})

        parsed_url = urlparse.urlsplit(url)
        prefix = parsed_url.path.rstrip('/')  # turn it into a prefix
        if parsed_url.scheme == 'https':
            port = 443
            require_ssl = True
        else:
            port = 80
            require_ssl = False
        host = parsed_url.hostname
        if parsed_url.port:
            port = parsed_url.port

        os.environ["GNOCCHI_SERVICE_TOKEN"] = token
        os.environ["GNOCCHI_AUTHORIZATION"] = "not used"

        with open(os.path.join(TEST_DIR, filename)) as f:
            suite_dict = utils.load_yaml(f)
            suite_dict.setdefault('defaults', {})['ssl'] = require_ssl
            test_suite = suitemaker.test_suite_from_dict(
                loader=unittest.defaultTestLoader,
                test_base_name="gabbi",
                suite_dict=suite_dict,
                test_directory=TEST_DIR,
                host=host, port=port,
                fixture_module=None,
                intercept=None,
                prefix=prefix,
                handlers=runner.initialize_handlers([]),
                test_loader_name="tempest")

            # NOTE(sileht): We hide stdout/stderr and reraise the failure
            # manually, tempest will print it itself.
            with open(os.devnull, 'w') as stream:
                result = unittest.TextTestRunner(
                    stream=stream, verbosity=0, failfast=True,
                ).run(test_suite)

            if not result.wasSuccessful():
                failures = (result.errors + result.failures +
                            result.unexpectedSuccesses)
                if failures:
                    test, bt = failures[0]
                    name = test.test_data.get('name', test.id())
                    msg = 'From test "%s" :\n%s' % (name, bt)
                    self.fail(msg)

            self.assertTrue(result.wasSuccessful())
项目:auto_appium    作者:feixiangingk    | 项目源码 | 文件源码
def get_cases(case_ini='testcase'):
        testSuite=unittest.TestSuite()
        loader=unittest.defaultTestLoader
        # info=Initialization()
        inital=appium_init.inital

        cases_info=inital.get_cases_info(case_ini)
        # print cases_info.get('case_discover')
        if cases_info=={}:
            inital.logger.info('get_cases | plz check appium_config.ini')
            return None

        #?????????????
        elif cases_info.get('load_all') in ['Y','y','*']:
            cases_list=loader.discover(cases_info.get('cases_path'),pattern='case_*.py')
            for module in cases_list:
                testSuite.addTests(module)

            inital.logger.info("get_cases | load all cases!")
            return  testSuite


        elif cases_info.get('case_module')==None and cases_info.get('case_discover')==None:
            print('cases_list is null,plz input cases in appium_config.ini')
            return None

        elif cases_info.get('case_module')!=None:
            modules=cases_info.get('case_module').split(',')
            for module in modules:
                if module.startswith('#')==False:
                    module='test_cases.'+module
                    cases_list=loader.loadTestsFromModule(__import__(module,fromlist=True))

                    testSuite.addTests(cases_list)

        if cases_info.get('case_discover')!=None:
            if  ',' not in cases_info.get('case_discover'):
                discover_list=[]
                discover_list.append(cases_info.get('case_discover'))
            else:
                discover_list=cases_info.get('case_discover').split(',')
            for discover in discover_list:
                if discover.startswith('#')==False:
                    cases_list = loader.discover(cases_info.get('cases_path'), pattern=discover)
                    for module in cases_list:
                        testSuite.addTests(module)

        cases=testSuite.countTestCases()
        inital.logger.info('get_cases | load case number is %d' %cases)
        return testSuite