Python pkg_resources._namespace_packages() Examples

The following are 22 code examples of pkg_resources._namespace_packages(). 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 pkg_resources , or try the search function .
Example #1
Source File: test.py    From Flask with Apache License 2.0 6 votes vote down vote up
def run_tests(self):
        import unittest

        # Purge modules under test from sys.modules. The test loader will
        # re-import them from the build location. Required when 2to3 is used
        # with namespace packages.
        if sys.version_info >= (3,) and getattr(self.distribution, 'use_2to3', False):
            module = self.test_args[-1].split('.')[0]
            if module in _namespace_packages:
                del_modules = []
                if module in sys.modules:
                    del_modules.append(module)
                module += '.'
                for name in sys.modules:
                    if name.startswith(module):
                        del_modules.append(name)
                list(map(sys.modules.__delitem__, del_modules))

        loader_ep = EntryPoint.parse("x="+self.test_loader)
        loader_class = loader_ep.load(require=False)
        cks = loader_class()
        unittest.main(
            None, None, [unittest.__file__]+self.test_args,
            testLoader = cks
        ) 
Example #2
Source File: test.py    From Flask with Apache License 2.0 6 votes vote down vote up
def run_tests(self):
        import unittest

        # Purge modules under test from sys.modules. The test loader will
        # re-import them from the build location. Required when 2to3 is used
        # with namespace packages.
        if sys.version_info >= (3,) and getattr(self.distribution, 'use_2to3', False):
            module = self.test_args[-1].split('.')[0]
            if module in _namespace_packages:
                del_modules = []
                if module in sys.modules:
                    del_modules.append(module)
                module += '.'
                for name in sys.modules:
                    if name.startswith(module):
                        del_modules.append(name)
                list(map(sys.modules.__delitem__, del_modules))

        loader_ep = EntryPoint.parse("x="+self.test_loader)
        loader_class = loader_ep.load(require=False)
        cks = loader_class()
        unittest.main(
            None, None, [unittest.__file__]+self.test_args,
            testLoader = cks
        ) 
Example #3
Source File: test_resources.py    From datafari with Apache License 2.0 5 votes vote down vote up
def test_two_levels_deep(self):
        """
        Test nested namespace packages
        Create namespace packages in the following tree :
            site-packages-1/pkg1/pkg2
            site-packages-2/pkg1/pkg2
        Check both are in the _namespace_packages dict and that their __path__
        is correct
        """
        sys.path.append(os.path.join(self._tmpdir, "site-pkgs2"))
        os.makedirs(os.path.join(self._tmpdir, "site-pkgs", "pkg1", "pkg2"))
        os.makedirs(os.path.join(self._tmpdir, "site-pkgs2", "pkg1", "pkg2"))
        ns_str = "__import__('pkg_resources').declare_namespace(__name__)\n"
        for site in ["site-pkgs", "site-pkgs2"]:
            pkg1_init = open(os.path.join(self._tmpdir, site,
                             "pkg1", "__init__.py"), "w")
            pkg1_init.write(ns_str)
            pkg1_init.close()
            pkg2_init = open(os.path.join(self._tmpdir, site,
                             "pkg1", "pkg2", "__init__.py"), "w")
            pkg2_init.write(ns_str)
            pkg2_init.close()
        import pkg1
        assert "pkg1" in pkg_resources._namespace_packages
        # attempt to import pkg2 from site-pkgs2
        import pkg1.pkg2
        # check the _namespace_packages dict
        assert "pkg1.pkg2" in pkg_resources._namespace_packages
        assert pkg_resources._namespace_packages["pkg1"] == ["pkg1.pkg2"]
        # check the __path__ attribute contains both paths
        expected = [
            os.path.join(self._tmpdir, "site-pkgs", "pkg1", "pkg2"),
            os.path.join(self._tmpdir, "site-pkgs2", "pkg1", "pkg2"),
        ]
        assert pkg1.pkg2.__path__ == expected 
Example #4
Source File: test_resources.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_two_levels_deep(self):
        """
        Test nested namespace packages
        Create namespace packages in the following tree :
            site-packages-1/pkg1/pkg2
            site-packages-2/pkg1/pkg2
        Check both are in the _namespace_packages dict and that their __path__
        is correct
        """
        sys.path.append(os.path.join(self._tmpdir, "site-pkgs2"))
        os.makedirs(os.path.join(self._tmpdir, "site-pkgs", "pkg1", "pkg2"))
        os.makedirs(os.path.join(self._tmpdir, "site-pkgs2", "pkg1", "pkg2"))
        ns_str = "__import__('pkg_resources').declare_namespace(__name__)\n"
        for site in ["site-pkgs", "site-pkgs2"]:
            pkg1_init = open(os.path.join(self._tmpdir, site,
                             "pkg1", "__init__.py"), "w")
            pkg1_init.write(ns_str)
            pkg1_init.close()
            pkg2_init = open(os.path.join(self._tmpdir, site,
                             "pkg1", "pkg2", "__init__.py"), "w")
            pkg2_init.write(ns_str)
            pkg2_init.close()
        import pkg1
        self._assertIn("pkg1", pkg_resources._namespace_packages.keys())
        try:
            import pkg1.pkg2
        except ImportError:
            self.fail("Setuptools tried to import the parent namespace package")
        # check the _namespace_packages dict
        self._assertIn("pkg1.pkg2", pkg_resources._namespace_packages.keys())
        self.assertEqual(pkg_resources._namespace_packages["pkg1"], ["pkg1.pkg2"])
        # check the __path__ attribute contains both paths
        self.assertEqual(pkg1.pkg2.__path__, [
            os.path.join(self._tmpdir, "site-pkgs", "pkg1", "pkg2"),
            os.path.join(self._tmpdir, "site-pkgs2", "pkg1", "pkg2")]) 
Example #5
Source File: test_resources.py    From Flask with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self._ns_pkgs = pkg_resources._namespace_packages.copy()
        self._tmpdir = tempfile.mkdtemp(prefix="tests-setuptools-")
        os.makedirs(os.path.join(self._tmpdir, "site-pkgs"))
        self._prev_sys_path = sys.path[:]
        sys.path.append(os.path.join(self._tmpdir, "site-pkgs")) 
Example #6
Source File: test_resources.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_two_levels_deep(self):
        """
        Test nested namespace packages
        Create namespace packages in the following tree :
            site-packages-1/pkg1/pkg2
            site-packages-2/pkg1/pkg2
        Check both are in the _namespace_packages dict and that their __path__
        is correct
        """
        sys.path.append(os.path.join(self._tmpdir, "site-pkgs2"))
        os.makedirs(os.path.join(self._tmpdir, "site-pkgs", "pkg1", "pkg2"))
        os.makedirs(os.path.join(self._tmpdir, "site-pkgs2", "pkg1", "pkg2"))
        ns_str = "__import__('pkg_resources').declare_namespace(__name__)\n"
        for site in ["site-pkgs", "site-pkgs2"]:
            pkg1_init = open(os.path.join(self._tmpdir, site,
                             "pkg1", "__init__.py"), "w")
            pkg1_init.write(ns_str)
            pkg1_init.close()
            pkg2_init = open(os.path.join(self._tmpdir, site,
                             "pkg1", "pkg2", "__init__.py"), "w")
            pkg2_init.write(ns_str)
            pkg2_init.close()
        import pkg1
        self._assertIn("pkg1", pkg_resources._namespace_packages.keys())
        try:
            import pkg1.pkg2
        except ImportError:
            self.fail("Setuptools tried to import the parent namespace package")
        # check the _namespace_packages dict
        self._assertIn("pkg1.pkg2", pkg_resources._namespace_packages.keys())
        self.assertEqual(pkg_resources._namespace_packages["pkg1"], ["pkg1.pkg2"])
        # check the __path__ attribute contains both paths
        self.assertEqual(pkg1.pkg2.__path__, [
            os.path.join(self._tmpdir, "site-pkgs", "pkg1", "pkg2"),
            os.path.join(self._tmpdir, "site-pkgs2", "pkg1", "pkg2")]) 
Example #7
Source File: test_resources.py    From Flask with Apache License 2.0 5 votes vote down vote up
def tearDown(self):
        shutil.rmtree(self._tmpdir)
        pkg_resources._namespace_packages = self._ns_pkgs.copy()
        sys.path = self._prev_sys_path[:] 
Example #8
Source File: test_resources.py    From Flask with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self._ns_pkgs = pkg_resources._namespace_packages.copy()
        self._tmpdir = tempfile.mkdtemp(prefix="tests-setuptools-")
        os.makedirs(os.path.join(self._tmpdir, "site-pkgs"))
        self._prev_sys_path = sys.path[:]
        sys.path.append(os.path.join(self._tmpdir, "site-pkgs")) 
Example #9
Source File: test_resources.py    From setuptools with MIT License 5 votes vote down vote up
def test_two_levels_deep(self, symlinked_tmpdir):
        """
        Test nested namespace packages
        Create namespace packages in the following tree :
            site-packages-1/pkg1/pkg2
            site-packages-2/pkg1/pkg2
        Check both are in the _namespace_packages dict and that their __path__
        is correct
        """
        real_tmpdir = symlinked_tmpdir.realpath()
        tmpdir = symlinked_tmpdir
        sys.path.append(str(tmpdir / 'site-pkgs2'))
        site_dirs = tmpdir / 'site-pkgs', tmpdir / 'site-pkgs2'
        for site in site_dirs:
            pkg1 = site / 'pkg1'
            pkg2 = pkg1 / 'pkg2'
            pkg2.ensure_dir()
            (pkg1 / '__init__.py').write_text(self.ns_str, encoding='utf-8')
            (pkg2 / '__init__.py').write_text(self.ns_str, encoding='utf-8')
        import pkg1
        assert "pkg1" in pkg_resources._namespace_packages
        # attempt to import pkg2 from site-pkgs2
        import pkg1.pkg2
        # check the _namespace_packages dict
        assert "pkg1.pkg2" in pkg_resources._namespace_packages
        assert pkg_resources._namespace_packages["pkg1"] == ["pkg1.pkg2"]
        # check the __path__ attribute contains both paths
        expected = [
            str(real_tmpdir / "site-pkgs" / "pkg1" / "pkg2"),
            str(real_tmpdir / "site-pkgs2" / "pkg1" / "pkg2"),
        ]
        assert pkg1.pkg2.__path__ == expected 
Example #10
Source File: test_resources.py    From setuptools with MIT License 5 votes vote down vote up
def patched_path(self, tmpdir):
        """
        Patch sys.path to include the 'site-pkgs' dir. Also
        restore pkg_resources._namespace_packages to its
        former state.
        """
        saved_ns_pkgs = pkg_resources._namespace_packages.copy()
        saved_sys_path = sys.path[:]
        site_pkgs = tmpdir.mkdir('site-pkgs')
        sys.path.append(str(site_pkgs))
        try:
            yield
        finally:
            pkg_resources._namespace_packages = saved_ns_pkgs
            sys.path = saved_sys_path 
Example #11
Source File: util.py    From linter-pylama with MIT License 5 votes vote down vote up
def is_namespace(modname):
    # pylint: disable=no-member; astroid issue #290, modifying globals at runtime.
    return (pkg_resources is not None
            and modname in pkg_resources._namespace_packages) 
Example #12
Source File: test_resources.py    From datafari with Apache License 2.0 5 votes vote down vote up
def teardown_method(self, method):
        shutil.rmtree(self._tmpdir)
        pkg_resources._namespace_packages = self._ns_pkgs.copy()
        sys.path = self._prev_sys_path[:] 
Example #13
Source File: test_resources.py    From datafari with Apache License 2.0 5 votes vote down vote up
def setup_method(self, method):
        self._ns_pkgs = pkg_resources._namespace_packages.copy()
        self._tmpdir = tempfile.mkdtemp(prefix="tests-setuptools-")
        os.makedirs(os.path.join(self._tmpdir, "site-pkgs"))
        self._prev_sys_path = sys.path[:]
        sys.path.append(os.path.join(self._tmpdir, "site-pkgs")) 
Example #14
Source File: test_resources.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_two_levels_deep(self):
        """
        Test nested namespace packages
        Create namespace packages in the following tree :
            site-packages-1/pkg1/pkg2
            site-packages-2/pkg1/pkg2
        Check both are in the _namespace_packages dict and that their __path__
        is correct
        """
        sys.path.append(os.path.join(self._tmpdir, "site-pkgs2"))
        os.makedirs(os.path.join(self._tmpdir, "site-pkgs", "pkg1", "pkg2"))
        os.makedirs(os.path.join(self._tmpdir, "site-pkgs2", "pkg1", "pkg2"))
        ns_str = "__import__('pkg_resources').declare_namespace(__name__)\n"
        for site in ["site-pkgs", "site-pkgs2"]:
            pkg1_init = open(os.path.join(self._tmpdir, site,
                             "pkg1", "__init__.py"), "w")
            pkg1_init.write(ns_str)
            pkg1_init.close()
            pkg2_init = open(os.path.join(self._tmpdir, site,
                             "pkg1", "pkg2", "__init__.py"), "w")
            pkg2_init.write(ns_str)
            pkg2_init.close()
        import pkg1
        assert "pkg1" in pkg_resources._namespace_packages
        try:
            import pkg1.pkg2
        except ImportError:
            self.fail("Setuptools tried to import the parent namespace package")
        # check the _namespace_packages dict
        assert "pkg1.pkg2" in pkg_resources._namespace_packages
        assert pkg_resources._namespace_packages["pkg1"] == ["pkg1.pkg2"]
        # check the __path__ attribute contains both paths
        expected = [
            os.path.join(self._tmpdir, "site-pkgs", "pkg1", "pkg2"),
            os.path.join(self._tmpdir, "site-pkgs2", "pkg1", "pkg2"),
        ]
        assert pkg1.pkg2.__path__ == expected 
Example #15
Source File: test_resources.py    From oss-ftp with MIT License 5 votes vote down vote up
def tearDown(self):
        shutil.rmtree(self._tmpdir)
        pkg_resources._namespace_packages = self._ns_pkgs.copy()
        sys.path = self._prev_sys_path[:] 
Example #16
Source File: test_resources.py    From oss-ftp with MIT License 5 votes vote down vote up
def setUp(self):
        self._ns_pkgs = pkg_resources._namespace_packages.copy()
        self._tmpdir = tempfile.mkdtemp(prefix="tests-setuptools-")
        os.makedirs(os.path.join(self._tmpdir, "site-pkgs"))
        self._prev_sys_path = sys.path[:]
        sys.path.append(os.path.join(self._tmpdir, "site-pkgs")) 
Example #17
Source File: test_resources.py    From pkg_resources with MIT License 5 votes vote down vote up
def test_two_levels_deep(self, symlinked_tmpdir):
        """
        Test nested namespace packages
        Create namespace packages in the following tree :
            site-packages-1/pkg1/pkg2
            site-packages-2/pkg1/pkg2
        Check both are in the _namespace_packages dict and that their __path__
        is correct
        """
        real_tmpdir = symlinked_tmpdir.realpath()
        tmpdir = symlinked_tmpdir
        sys.path.append(str(tmpdir / 'site-pkgs2'))
        site_dirs = tmpdir / 'site-pkgs', tmpdir / 'site-pkgs2'
        for site in site_dirs:
            pkg1 = site / 'pkg1'
            pkg2 = pkg1 / 'pkg2'
            pkg2.ensure_dir()
            (pkg1 / '__init__.py').write_text(self.ns_str, encoding='utf-8')
            (pkg2 / '__init__.py').write_text(self.ns_str, encoding='utf-8')
        import pkg1
        assert "pkg1" in pkg_resources._namespace_packages
        # attempt to import pkg2 from site-pkgs2
        import pkg1.pkg2
        # check the _namespace_packages dict
        assert "pkg1.pkg2" in pkg_resources._namespace_packages
        assert pkg_resources._namespace_packages["pkg1"] == ["pkg1.pkg2"]
        # check the __path__ attribute contains both paths
        expected = [
            str(real_tmpdir / "site-pkgs" / "pkg1" / "pkg2"),
            str(real_tmpdir / "site-pkgs2" / "pkg1" / "pkg2"),
        ]
        assert pkg1.pkg2.__path__ == expected 
Example #18
Source File: test_resources.py    From pkg_resources with MIT License 5 votes vote down vote up
def patched_path(self, tmpdir):
        """
        Patch sys.path to include the 'site-pkgs' dir. Also
        restore pkg_resources._namespace_packages to its
        former state.
        """
        saved_ns_pkgs = pkg_resources._namespace_packages.copy()
        saved_sys_path = sys.path[:]
        site_pkgs = tmpdir.mkdir('site-pkgs')
        sys.path.append(str(site_pkgs))
        try:
            yield
        finally:
            pkg_resources._namespace_packages = saved_ns_pkgs
            sys.path = saved_sys_path 
Example #19
Source File: test_resources.py    From pledgeservice with Apache License 2.0 5 votes vote down vote up
def test_two_levels_deep(self):
        """
        Test nested namespace packages
        Create namespace packages in the following tree :
            site-packages-1/pkg1/pkg2
            site-packages-2/pkg1/pkg2
        Check both are in the _namespace_packages dict and that their __path__
        is correct
        """
        sys.path.append(os.path.join(self._tmpdir, "site-pkgs2"))
        os.makedirs(os.path.join(self._tmpdir, "site-pkgs", "pkg1", "pkg2"))
        os.makedirs(os.path.join(self._tmpdir, "site-pkgs2", "pkg1", "pkg2"))
        ns_str = "__import__('pkg_resources').declare_namespace(__name__)\n"
        for site in ["site-pkgs", "site-pkgs2"]:
            pkg1_init = open(os.path.join(self._tmpdir, site,
                             "pkg1", "__init__.py"), "w")
            pkg1_init.write(ns_str)
            pkg1_init.close()
            pkg2_init = open(os.path.join(self._tmpdir, site,
                             "pkg1", "pkg2", "__init__.py"), "w")
            pkg2_init.write(ns_str)
            pkg2_init.close()
        import pkg1
        self._assertIn("pkg1", pkg_resources._namespace_packages.keys())
        try:
            import pkg1.pkg2
        except ImportError:
            self.fail("Setuptools tried to import the parent namespace package")
        # check the _namespace_packages dict
        self._assertIn("pkg1.pkg2", pkg_resources._namespace_packages.keys())
        self.assertEqual(pkg_resources._namespace_packages["pkg1"], ["pkg1.pkg2"])
        # check the __path__ attribute contains both paths
        self.assertEqual(pkg1.pkg2.__path__, [
            os.path.join(self._tmpdir, "site-pkgs", "pkg1", "pkg2"),
            os.path.join(self._tmpdir, "site-pkgs2", "pkg1", "pkg2")]) 
Example #20
Source File: test_resources.py    From pledgeservice with Apache License 2.0 5 votes vote down vote up
def tearDown(self):
        shutil.rmtree(self._tmpdir)
        pkg_resources._namespace_packages = self._ns_pkgs.copy()
        sys.path = self._prev_sys_path[:] 
Example #21
Source File: test_resources.py    From pledgeservice with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self._ns_pkgs = pkg_resources._namespace_packages.copy()
        self._tmpdir = tempfile.mkdtemp(prefix="tests-setuptools-")
        os.makedirs(os.path.join(self._tmpdir, "site-pkgs"))
        self._prev_sys_path = sys.path[:]
        sys.path.append(os.path.join(self._tmpdir, "site-pkgs")) 
Example #22
Source File: localimport.py    From c4ddev with MIT License 4 votes vote down vote up
def __enter__(self):
    # pkg_resources comes with setuptools.
    try:
      import pkg_resources
      nsdict = copy.deepcopy(pkg_resources._namespace_packages)
      declare_namespace = pkg_resources.declare_namespace
      pkg_resources.declare_namespace = self._declare_namespace
    except ImportError:
      nsdict = None
      declare_namespace = None

    # Save the global importer state.
    self.state = {
      'nsdict': nsdict,
      'declare_namespace': declare_namespace,
      'nspaths': {},
      'path': sys.path[:],
      'meta_path': sys.meta_path[:],
      'disables': {},
      'pkgutil.extend_path': pkgutil.extend_path,
    }

    # Update the systems meta path and apply function mocks.
    sys.path[:] = self.path
    sys.meta_path[:] = self.meta_path + sys.meta_path
    pkgutil.extend_path = extend_path

    # If this function is called not the first time, we need to
    # restore the modules that have been imported with it and
    # temporarily disable the ones that would be shadowed.
    for key, mod in items(self.modules):
      try: self.state['disables'][key] = sys.modules.pop(key)
      except KeyError: pass
      sys.modules[key] = mod

    # Evaluate imports from the .pth files, if any.
    for fn, lineno, stmt in self.pth_imports:
      exec_pth_import(fn, lineno, stmt)

    # Add the original path to sys.path.
    sys.path += self.state['path']

    # Update the __path__ of all namespace modules.
    for key, mod in items(sys.modules):
      if mod is None:
        # Relative imports could have lead to None-entries in
        # sys.modules. Get rid of them so they can be re-evaluated.
        prefix = key.rpartition('.')[0]
        if hasattr(sys.modules.get(prefix), '__path__'):
          del sys.modules[key]
      elif hasattr(mod, '__path__'):
        self.state['nspaths'][key] = copy.copy(mod.__path__)
        mod.__path__ = pkgutil.extend_path(mod.__path__, mod.__name__)

    self.in_context = True
    if self.do_autodisable:
      self.autodisable()
    return self