python类SkipTest()的实例源码

common_io_test.py 文件源码 项目:NeoAnalysis 作者: neoanalysis 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def download_test_files_if_not_present(self):
        '''
        Download %s file at G-node for testing
        url_for_tests is global at beginning of this file.

        ''' % self.ioclass.__name__
        if not self.use_network:
            raise unittest.SkipTest("Requires download of data from the web")

        url = url_for_tests+self.shortname
        try:
            make_all_directories(self.files_to_download, self.local_test_dir)
            download_test_file(self.files_to_download,
                               self.local_test_dir, url)
        except IOError as exc:
            raise unittest.SkipTest(exc)
test_failure_types.py 文件源码 项目:deb-python-cassandra-driver 作者: openstack 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def setUp(self):
        """
        Test is skipped if run with native protocol version <4
        """
        self.support_v5 = True
        if PROTOCOL_VERSION < 4:
            raise unittest.SkipTest(
                "Native protocol 4,0+ is required for custom payloads, currently using %r"
                % (PROTOCOL_VERSION,))
        try:
            self.cluster = Cluster(protocol_version=ProtocolVersion.MAX_SUPPORTED, allow_beta_protocol_version=True)
            self.session = self.cluster.connect()
        except NoHostAvailable:
            log.info("Protocol Version 5 not supported,")
            self.cluster = Cluster(protocol_version=PROTOCOL_VERSION)
            self.session = self.cluster.connect()
            self.support_v5 = False

        self.nodes_currently_failing = []
        self.node1, self.node2, self.node3 = get_cluster().nodes.values()
testcases.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def _deferredSkip(condition, reason):
    def decorator(test_func):
        if not (isinstance(test_func, type) and
                issubclass(test_func, unittest.TestCase)):
            @wraps(test_func)
            def skip_wrapper(*args, **kwargs):
                if condition():
                    raise unittest.SkipTest(reason)
                return test_func(*args, **kwargs)
            test_item = skip_wrapper
        else:
            # Assume a class is decorated
            test_item = test_func
            test_item.__unittest_skip__ = CheckCondition(condition)
        test_item.__unittest_skip_why__ = reason
        return test_item
    return decorator
test_cuda.py 文件源码 项目:pytorch-dist 作者: apaszke 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
def compare_cpu_gpu(tensor_constructor, arg_constructor, fn, t, precision=1e-5):
    def tmp(self):
        cpu_tensor = tensor_constructor(t)
        gpu_tensor = to_gpu(cpu_tensor)
        cpu_args = arg_constructor(t)
        gpu_args = [to_gpu(arg) for arg in cpu_args]
        cpu_result = getattr(cpu_tensor, fn)(*cpu_args)
        try:
            gpu_result = getattr(gpu_tensor, fn)(*gpu_args)
        except RuntimeError as e:
            reason = e.args[0]
            if 'unimplemented data type' in reason:
                raise unittest.SkipTest('unimplemented data type')
            raise
        except AttributeError as e:
            reason = e.args[0]
            if 'object has no attribute' in reason:
                raise unittest.SkipTest('unimplemented data type')
            raise
        # If one changes, another should change as well
        self.assertEqual(cpu_tensor, gpu_tensor, precision)
        self.assertEqual(cpu_args, gpu_args, precision)
        # Compare results
        self.assertEqual(cpu_result, gpu_result, precision)
    return tmp
common_nn.py 文件源码 项目:pytorch-dist 作者: apaszke 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def test_cuda(self, test_case):
        if not TEST_CUDA or not self.should_test_cuda:
            raise unittest.SkipTest('Excluded from CUDA tests')
        try:
            cpu_input = self._get_input()
            type_map = {
                torch.DoubleTensor: torch.cuda.FloatTensor,
            }
            gpu_input = to_gpu(cpu_input, type_map=type_map)

            cpu_target = self.target
            gpu_target = to_gpu(self.target, type_map=type_map)

            cpu_module = self.constructor(*self.constructor_args)
            gpu_module = self.constructor(*self.constructor_args).float().cuda()

            cpu_output = test_case._forward_criterion(cpu_module, cpu_input, cpu_target)
            gpu_output = test_case._forward_criterion(gpu_module, gpu_input, gpu_target)
            test_case.assertEqual(cpu_output, gpu_output, 2e-4)

            cpu_gradInput = test_case._backward_criterion(cpu_module, cpu_input, cpu_target)
            gpu_gradInput = test_case._backward_criterion(gpu_module, gpu_input, gpu_target)
            test_case.assertEqual(cpu_gradInput, gpu_gradInput, 2e-4)
        except NotImplementedError:
            pass
test_setups.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def test_skiptest_in_setupclass(self):
        class Test(unittest.TestCase):
            @classmethod
            def setUpClass(cls):
                raise unittest.SkipTest('foo')
            def test_one(self):
                pass
            def test_two(self):
                pass

        result = self.runTests(Test)
        self.assertEqual(result.testsRun, 0)
        self.assertEqual(len(result.errors), 0)
        self.assertEqual(len(result.skipped), 1)
        skipped = result.skipped[0][0]
        self.assertEqual(str(skipped), 'setUpClass (%s.Test)' % __name__)
test_setups.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def test_skiptest_in_setupmodule(self):
        class Test(unittest.TestCase):
            def test_one(self):
                pass
            def test_two(self):
                pass

        class Module(object):
            @staticmethod
            def setUpModule():
                raise unittest.SkipTest('foo')

        Test.__module__ = 'Module'
        sys.modules['Module'] = Module

        result = self.runTests(Test)
        self.assertEqual(result.testsRun, 0)
        self.assertEqual(len(result.errors), 0)
        self.assertEqual(len(result.skipped), 1)
        skipped = result.skipped[0][0]
        self.assertEqual(str(skipped), 'setUpModule (Module)')
support.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def copy_xxmodule_c(directory):
    """Helper for tests that need the xxmodule.c source file.

    Example use:

        def test_compile(self):
            copy_xxmodule_c(self.tmpdir)
            self.assertIn('xxmodule.c', os.listdir(self.tmpdir))

    If the source file can be found, it will be copied to *directory*.  If not,
    the test will be skipped.  Errors during copy are not caught.
    """
    filename = _get_xxmodule_path()
    if filename is None:
        raise unittest.SkipTest('cannot find xxmodule.c (test must run in '
                                'the python build dir)')
    shutil.copy(filename, directory)
__init__.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 472 收藏 0 点赞 0 评论 0
def get_tests(package, mask, verbosity, exclude=()):
    """Return a list of skipped test modules, and a list of test cases."""
    tests = []
    skipped = []
    for modname in find_package_modules(package, mask):
        if modname.split(".")[-1] in exclude:
            skipped.append(modname)
            if verbosity > 1:
                print >> sys.stderr, "Skipped %s: excluded" % modname
            continue
        try:
            mod = __import__(modname, globals(), locals(), ['*'])
        except (ResourceDenied, unittest.SkipTest) as detail:
            skipped.append(modname)
            if verbosity > 1:
                print >> sys.stderr, "Skipped %s: %s" % (modname, detail)
            continue
        for name in dir(mod):
            if name.startswith("_"):
                continue
            o = getattr(mod, name)
            if type(o) is type(unittest.TestCase) and issubclass(o, unittest.TestCase):
                tests.append(o)
    return skipped, tests
test_functools32.py 文件源码 项目:deb-python-functools32 作者: openstack 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_attributes(self):
        p = self.thetype(capture, 1, 2, a=10, b=20)
        # attributes should be readable
        self.assertEqual(p.func, capture)
        self.assertEqual(p.args, (1, 2))
        self.assertEqual(p.keywords, dict(a=10, b=20))
        # attributes should not be writable
        if not isinstance(self.thetype, type):
            return
        if "__pypy__" in sys.modules:
            raise unittest.SkipTest("In the PyPy execution environment")
        self.assertRaises(TypeError, setattr, p, 'func', map)
        self.assertRaises(TypeError, setattr, p, 'args', (1, 2))
        self.assertRaises(TypeError, setattr, p, 'keywords', dict(a=1, b=2))

        p = self.thetype(hex)
        try:
            del p.__dict__
        except TypeError:
            pass
        else:
            self.fail('partial object allowed __dict__ to be deleted')
test_stats.py 文件源码 项目:empyrical 作者: quantopian 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def __getattr__(self, item):
        if self._pandas_only:
            raise SkipTest("empyrical.%s expects pandas-only inputs that have "
                           "dt indices/labels" % item)

        func = super(ConvertPandasEmpyricalProxy, self).__getattr__(item)

        @wraps(func)
        def convert_args(*args, **kwargs):
            args = [self._convert(arg) if isinstance(arg, NDFrame) else arg
                    for arg in args]
            kwargs = {
                k: self._convert(v) if isinstance(v, NDFrame) else v
                for k, v in iteritems(kwargs)
            }
            return func(*args, **kwargs)

        return convert_args
base.py 文件源码 项目:client-python 作者: kubernetes-incubator 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def get_e2e_configuration():
    config = Configuration()
    config.host = None
    if os.path.exists(
            os.path.expanduser(kube_config.KUBE_CONFIG_DEFAULT_LOCATION)):
        kube_config.load_kube_config(client_configuration=config)
    else:
        print('Unable to load config from %s' %
              kube_config.KUBE_CONFIG_DEFAULT_LOCATION)
        for url in ['https://%s:8443' % DEFAULT_E2E_HOST,
                    'http://%s:8080' % DEFAULT_E2E_HOST]:
            try:
                urllib3.PoolManager().request('GET', url)
                config.host = url
                config.verify_ssl = False
                urllib3.disable_warnings()
                break
            except urllib3.exceptions.HTTPError:
                pass
    if config.host is None:
        raise unittest.SkipTest('Unable to find a running Kubernetes instance')
    print('Running test against : %s' % config.host)
    config.assert_hostname = False
    return config
test_shell.py 文件源码 项目:simLAB 作者: kamwar 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_08_create_adf(self):
        # Get number of EF_DIR records
        status, data = self.shell.read("/2F00")
        self.shell.assertOk(status, data)
        numOfRecords = len(data.split(';')) - 1
        # Use the next free Id
        dirPath = "/ADF%d/" % numOfRecords
        try:
            self.shell.delete(dirPath)
        except:
            pass
        status, out = self.shell.create(dirPath)
        if status == "status NOK":
            raise unittest.SkipTest(
                """Known issue: ADF creation doesn't work for some SIM cards
                 (INCORRECT_PARAMETER_IN_DATA_FIELD is returned)""")
        #self.shell.assertOk(status, out)
        status, out = self.shell.delete(dirPath)
        self.shell.assertOk(status, out)
__init__.py 文件源码 项目:pyspotify-connect 作者: chukysoria 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def gc_collect():
    """Run enough GC collections to make object finalizers run."""

    # XXX Tests of GC and cleanup behavior are generally flaky and icky,
    # especially when you target all of Python 2.7, 3.3+ and PyPy. Their result
    # quickly depends on other tests, the arguments to the test runner and the
    # computer running the tests. This skips them all for now.
    raise unittest.SkipTest

    if platform.python_implementation() == 'PyPy':
        # Since PyPy use garbage collection instead of reference counting
        # objects are not finalized before the next major GC collection.
        # Currently, the best way we have to ensure a major GC collection has
        # run is to call gc.collect() a number of times.
        [gc.collect() for _ in range(10)]
    else:
        gc.collect()
base.py 文件源码 项目:napalm-base 作者: napalm-automation 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def test_get_environment(self):
        try:
            environment = self.device.get_environment()
        except NotImplementedError:
            raise SkipTest()
        result = len(environment) > 0

        for fan, fan_data in environment['fans'].items():
            result = result and self._test_model(models.fan, fan_data)

        for power, power_data in environment['power'].items():
            result = result and self._test_model(models.power, power_data)

        for temperature, temperature_data in environment['temperature'].items():
            result = result and self._test_model(models.temperature, temperature_data)

        for cpu, cpu_data in environment['cpu'].items():
            result = result and self._test_model(models.cpu, cpu_data)

        result = result and self._test_model(models.memory, environment['memory'])

        self.assertTrue(result)
base.py 文件源码 项目:napalm-base 作者: napalm-automation 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def test_get_bgp_neighbors(self):
        try:
            get_bgp_neighbors = self.device.get_bgp_neighbors()
        except NotImplementedError:
            raise SkipTest()
        result = 'global' in get_bgp_neighbors.keys()

        if not result:
            print('global is not part of the returned vrfs')
        else:
            for vrf, vrf_data in get_bgp_neighbors.items():
                result = result and isinstance(vrf_data['router_id'], text_type)
                if not result:
                    print('router_id is not {}'.format(text_type))

                for peer, peer_data in vrf_data['peers'].items():
                    result = result and self._test_model(models.peer, peer_data)

                    for af, af_data in peer_data['address_family'].items():
                        result = result and self._test_model(models.af, af_data)

            self.assertTrue(result)
base.py 文件源码 项目:napalm-base 作者: napalm-automation 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def test_get_bgp_neighbors_detail(self):
        try:
            get_bgp_neighbors_detail = self.device.get_bgp_neighbors_detail()
        except NotImplementedError:
            raise SkipTest()

        result = len(get_bgp_neighbors_detail) > 0

        for vrf, vrf_ases in get_bgp_neighbors_detail.items():
            result = result and isinstance(vrf, text_type)
            for remote_as, neighbor_list in vrf_ases.items():
                result = result and isinstance(remote_as, int)
                for neighbor in neighbor_list:
                    result = result and self._test_model(models.peer_details, neighbor)

        self.assertTrue(result)
base.py 文件源码 项目:napalm-base 作者: napalm-automation 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def test_get_optics(self):

        try:
            get_optics = self.device.get_optics()
        except NotImplementedError:
            raise SkipTest()

        assert isinstance(get_optics, dict)

        for iface, iface_data in get_optics.items():
            assert isinstance(iface, text_type)
            for channel in iface_data['physical_channels']['channel']:
                assert len(channel) == 2
                assert isinstance(channel['index'], int)
                for field in ['input_power', 'output_power',
                              'laser_bias_current']:

                    assert len(channel['state'][field]) == 4
                    assert isinstance(channel['state'][field]['instant'],
                                      float)
                    assert isinstance(channel['state'][field]['avg'], float)
                    assert isinstance(channel['state'][field]['min'], float)
                    assert isinstance(channel['state'][field]['max'], float)
test_filefinder2_importlib_import.py 文件源码 项目:filefinder2 作者: asmodehn 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_importlib_import_relative_pkg(self):
            """Verify that package is importable relatively"""
            print_importers()
            assert __package__
            # need globals to handle relative imports
            # __import__ checks sys.modules by itself
            # but the test is not reflecting anything if we use the already loaded module.
            if sys.modules.get(__package__ + '.pkg'):
                raise unittest.SkipTest("module previously loaded".format(__package__ + '.pkg'))
            else:
                pkg = importlib.__import__('pkg', globals=globals(), level=1)
                test_pkg = pkg

                self.assertTrue(test_pkg is not None)
                self.assertTrue(test_pkg.TestClassInSubPkg is not None)
                self.assertTrue(callable(test_pkg.TestClassInSubPkg))

                # TODO : implement some differences and check we get them...
                if hasattr(importlib, 'reload'):  # recent version of importlib
                    # attempting to reload
                    importlib.reload(test_pkg)
                else:
                    pass
test_filefinder2_importlib_import.py 文件源码 项目:filefinder2 作者: asmodehn 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def test_importlib_import_relative_pkg_submodule(self):
            """Verify that package is importable relatively"""
            print_importers()
            assert __package__
            # need globals to handle relative imports
            # __import__ checks sys.modules by itself
            # but the test is not reflecting anything if we use the already loaded module.
            if sys.modules.get(__package__ + '.pkg.submodule'):
                raise unittest.SkipTest("module previously loaded".format(__package__ + '.pkg.submodule'))
            else:
                pkg = importlib.__import__('pkg.submodule', globals=globals(), level=1)
                test_mod = pkg.submodule

                self.assertTrue(test_mod is not None)
                self.assertTrue(test_mod.TestClassInSubModule is not None)
                self.assertTrue(callable(test_mod.TestClassInSubModule))

                # TODO : implement some differences and check we get them...
                if hasattr(importlib, 'reload'):  # recent version of importlib
                    # attempting to reload
                    importlib.reload(test_mod)
                else:
                    pass
test_filefinder2_importlib_import.py 文件源码 项目:filefinder2 作者: asmodehn 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_importlib_import_relative_pkg_bytecode(self):
            """Verify that package is importable relatively"""
            print_importers()
            assert __package__
            # need globals to handle relative imports
            # __import__ checks sys.modules by itself
            # but the test is not reflecting anything if we use the already loaded module.
            if sys.modules.get(__package__ + '.pkg.bytecode'):
                raise unittest.SkipTest("module previously loaded".format(__package__ + '.pkg.bytecode'))
            else:
                pkg = importlib.__import__('pkg.bytecode', globals=globals(), level=1)
                test_mod = pkg.bytecode

                self.assertTrue(test_mod is not None)
                self.assertTrue(test_mod.TestClassInBytecode is not None)
                self.assertTrue(callable(test_mod.TestClassInBytecode))

                # TODO : implement some differences and check we get them...
                if hasattr(importlib, 'reload'):  # recent version of importlib
                    # attempting to reload
                    importlib.reload(test_mod)
                else:
                    pass
test_filefinder2_importlib_import.py 文件源码 项目:filefinder2 作者: asmodehn 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def test_importlib_import_class_from_relative_pkg(self):
            """Verify that message class is importable relatively"""
            print_importers()
            assert __package__
            # need globals to handle relative imports
            # __import__ checks sys.modules by itself
            # but the test is not reflecting anything if we use the already loaded module.
            if sys.modules.get(__package__ + '.pkg'):
                raise unittest.SkipTest("module previously loaded".format(__package__ + '.pkg'))
            else:
                pkg = importlib.__import__('pkg', globals=globals(), level=1)
                test_class_in_subpkg = pkg.TestClassInSubPkg

                self.assertTrue(test_class_in_subpkg is not None)
                self.assertTrue(callable(test_class_in_subpkg))

                # TODO : implement some differences and check we get them...
                if hasattr(importlib, 'reload'):  # recent version of importlib
                    # attempting to reload
                    importlib.reload(pkg)
                else:
                    pass
test_filefinder2_importlib_import.py 文件源码 项目:filefinder2 作者: asmodehn 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_importlib_import_class_from_relative_pkg_submodule(self):
            """Verify that package is importable relatively"""
            print_importers()
            assert __package__
            # need globals to handle relative imports
            # __import__ checks sys.modules by itself
            # but the test is not reflecting anything if we use the already loaded module.
            if sys.modules.get(__package__ + '.pkg.submodule'):
                raise unittest.SkipTest("module previously loaded".format(__package__ + '.pkg.submodule'))
            else:
                pkg = importlib.__import__('pkg.submodule', globals=globals(), level=1)
                test_class_in_submodule = pkg.submodule.TestClassInSubModule

                self.assertTrue(test_class_in_submodule is not None)
                self.assertTrue(callable(test_class_in_submodule))

                # TODO : implement some differences and check we get them...
                if hasattr(importlib, 'reload'):  # recent version of importlib
                    # attempting to reload
                    importlib.reload(pkg)
                else:
                    pass
test_filefinder2_importlib_import.py 文件源码 项目:filefinder2 作者: asmodehn 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_importlib_import_relative_ns_subpkg(self):
            """Verify that package is importable relatively"""
            print_importers()
            assert __package__

            # __import__ checks sys.modules by itself
            # but the test is not reflecting anything if we use the already loaded module.
            if sys.modules.get(__package__ + '.nspkg.subpkg'):
                raise unittest.SkipTest("module previously loaded".format(__package__ + '.nspkg.subpkg'))
            else:
                nspkg = importlib.__import__('nspkg.subpkg', globals=globals(),
                                             level=1)  # need globals to handle relative imports
                test_pkg = nspkg.subpkg

                self.assertTrue(test_pkg is not None)
                self.assertTrue(test_pkg.TestClassInSubPkg is not None)
                self.assertTrue(callable(test_pkg.TestClassInSubPkg))

                # TODO : implement some differences and check we get them...
                if hasattr(importlib, 'reload'):  # recent version of importlib
                    # attempting to reload
                    importlib.reload(test_pkg)
                else:
                    pass
test_filefinder2_importlib_import.py 文件源码 项目:filefinder2 作者: asmodehn 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def test_importlib_import_relative_ns_subpkg_submodule(self):
            """Verify that package is importable relatively"""
            print_importers()
            assert __package__

            # __import__ checks sys.modules by itself
            # but the test is not reflecting anything if we use the already loaded module.
            if sys.modules.get(__package__ + '.nspkg.subpkg.submodule'):
                raise unittest.SkipTest("module previously loaded".format(__package__ + '.nspkg.subpkg.submodule'))
            else:
                nspkg = importlib.__import__('nspkg.subpkg.submodule', globals=globals(),
                                             level=1)  # need globals to handle relative imports
                test_mod = nspkg.subpkg.submodule

                self.assertTrue(test_mod is not None)
                self.assertTrue(test_mod.TestClassInSubModule is not None)
                self.assertTrue(callable(test_mod.TestClassInSubModule))

                # TODO : implement some differences and check we get them...
                if hasattr(importlib, 'reload'):  # recent version of importlib
                    # attempting to reload
                    importlib.reload(test_mod)
                else:
                    pass
test_filefinder2_importlib_import.py 文件源码 项目:filefinder2 作者: asmodehn 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_importlib_import_relative_ns_subpkg_bytecode(self):
            """Verify that package is importable relatively"""
            print_importers()
            assert __package__

            # __import__ checks sys.modules by itself
            # but the test is not reflecting anything if we use the already loaded module.
            if sys.modules.get(__package__ + '.nspkg.subpkg.bytecode'):
                raise unittest.SkipTest("module previously loaded".format(__package__ + '.nspkg.subpkg.bytecode'))
            else:
                nspkg = importlib.__import__('nspkg.subpkg.bytecode', globals=globals(),
                                             level=1)  # need globals to handle relative imports
                test_mod = nspkg.subpkg.bytecode

                self.assertTrue(test_mod is not None)
                self.assertTrue(test_mod.TestClassInBytecode is not None)
                self.assertTrue(callable(test_mod.TestClassInBytecode))

                # TODO : implement some differences and check we get them...
                if hasattr(importlib, 'reload'):  # recent version of importlib
                    # attempting to reload
                    importlib.reload(test_mod)
                else:
                    pass
test_filefinder2_importlib_import.py 文件源码 项目:filefinder2 作者: asmodehn 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_importlib_import_class_from_relative_ns_subpkg(self):
            """Verify that message class is importable relatively"""
            print_importers()
            assert __package__

            # __import__ checks sys.modules by itself
            # but the test is not reflecting anything if we use the already loaded module.
            if sys.modules.get(__package__ + '.nspkg.subpkg'):
                raise unittest.SkipTest("module previously loaded".format(__package__ + '.nspkg.subpkg'))
            else:
                nspkg = importlib.__import__('nspkg.subpkg', globals=globals(),
                                             level=1)  # need globals to handle relative imports
                test_class_in_subpkg = nspkg.subpkg.TestClassInSubPkg

                self.assertTrue(test_class_in_subpkg is not None)
                self.assertTrue(callable(test_class_in_subpkg))

                # TODO : implement some differences and check we get them...
                if hasattr(importlib, 'reload'):  # recent version of importlib
                    # attempting to reload
                    importlib.reload(nspkg)
                else:
                    pass
test_filefinder2_importlib_import.py 文件源码 项目:filefinder2 作者: asmodehn 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_importlib_import_class_from_relative_ns_subpkg_bytecode(self):
            """Verify that package is importable relatively"""
            print_importers()
            assert __package__

            # __import__ checks sys.modules by itself
            # but the test is not reflecting anything if we use the already loaded module.
            if sys.modules.get(__package__ + '.nspkg.subpkg.bytecode'):
                raise unittest.SkipTest("module previously loaded".format(__package__ + '.nspkg.subpkg.bytecode'))
            else:
                nspkg = importlib.__import__('nspkg.subpkg.bytecode', globals=globals(),
                                             level=1)  # need globals to handle relative imports
                test_class_in_bytecode = nspkg.subpkg.bytecode.TestClassInBytecode

                self.assertTrue(test_class_in_bytecode is not None)
                self.assertTrue(callable(test_class_in_bytecode))

                # TODO : implement some differences and check we get them...
                if hasattr(importlib, 'reload'):  # recent version of importlib
                    # attempting to reload
                    importlib.reload(nspkg)
                else:
                    pass
test_filefinder2_importlib_loadmodule.py 文件源码 项目:filefinder2 作者: asmodehn 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def test_importlib_loadmodule_relative_pkg(self):
            """Verify that package is importable relatively"""
            print_importers()
            assert __package__
            if sys.modules.get(__package__ + '.pkg'):
                raise unittest.SkipTest("module previously loaded".format(__package__ + '.pkg'))
            else:
                # load_module returns existing modules from sys.modules by specification
                # see https://docs.python.org/3.3/library/importlib.html#importlib.abc.Loader)
                pkg_loader = importlib.find_loader(__package__ + '.pkg', [os.path.dirname(__file__)])
                pkg = pkg_loader.load_module(__package__ + '.pkg')
                # safely adding to sysmodules to be able to perform relative imports in there
                #sys.modules.setdefault(nspkg.__name__, nspkg)

            self.assertTrue(pkg is not None)
            self.assertTrue(pkg.TestClassInSubPkg is not None)
            self.assertTrue(callable(pkg.TestClassInSubPkg))

            # Note : apparently reload is broken with find_loader (at least on python 3.5)
            # _find_spec in reload() apparently returns None...
            #
            # => not testing reload in that case (this API is obsolete anyway)
test_filefinder2_importlib_loadmodule.py 文件源码 项目:filefinder2 作者: asmodehn 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_importlib_loadmodule_relative_pkg_submodule(self):
            """Verify that package is importable relatively"""
            print_importers()
            assert __package__
            if sys.modules.get(__package__ + '.pkg'):
                raise unittest.SkipTest("module previously loaded".format(__package__ + '.pkg'))
            else:
                # load_module returns existing modules from sys.modules by specification
                # see https://docs.python.org/3.3/library/importlib.html#importlib.abc.Loader)
                pkg_loader = importlib.find_loader(__package__ + '.pkg', [os.path.dirname(__file__)])
                pkg = pkg_loader.load_module(__package__ + '.pkg')
                # safely adding to sysmodules to be able to perform relative imports in there
                #sys.modules.setdefault(nspkg.__name__, nspkg)

            # here we should get the module that has already be loaded while executing subpkg
            submodule = sys.modules.get(__package__ + '.pkg.submodule')

            self.assertTrue(submodule is not None)
            self.assertTrue(submodule.TestClassInSubModule is not None)
            self.assertTrue(callable(submodule.TestClassInSubModule))

            # Note : apparently reload is broken with find_loader (at least on python 3.5)
            # _find_spec in reload() apparently returns None...
            #
            # => not testing reload in that case (this API is obsolete anyway)


问题


面经


文章

微信
公众号

扫码关注公众号