示例#1
0
    def test_discovery_from_dotted_namespace_packages(self):
        loader = unittest.TestLoader()

        package = types.ModuleType('package')
        package.__path__ = ['/a', '/b']
        package.__spec__ = types.SimpleNamespace(
            loader=None, submodule_search_locations=['/a', '/b'])

        def _import(packagename, *args, **kwargs):
            sys.modules[packagename] = package
            return package

        _find_tests_args = []

        def _find_tests(start_dir, pattern, namespace=None):
            _find_tests_args.append((start_dir, pattern))
            return ['%s/tests' % start_dir]

        loader._find_tests = _find_tests
        loader.suiteClass = list

        with unittest.mock.patch('builtins.__import__', _import):
            # Since loader.discover() can modify sys.path, restore it when done.
            with support.DirsOnSysPath():
                # Make sure to remove 'package' from sys.modules when done.
                with test.test_importlib.util.uncache('package'):
                    suite = loader.discover('package')

        self.assertEqual(suite, ['/a/tests', '/b/tests'])
    def test_reload_namespace_changed(self):
        name = 'spam'
        with support.temp_cwd(None) as cwd:
            with test_util.uncache('spam'):
                with support.DirsOnSysPath(cwd):
                    # Start as a namespace package.
                    self.init.invalidate_caches()
                    bad_path = os.path.join(cwd, name, '__init.py')
                    cached = self.util.cache_from_source(bad_path)
                    expected = {
                        '__name__': name,
                        '__package__': name,
                        '__doc__': None,
                        '__file__': None,
                    }
                    os.mkdir(name)
                    with open(bad_path, 'w') as init_file:
                        init_file.write('eggs = None')
                    module = self.init.import_module(name)
                    ns = vars(module).copy()
                    loader = ns.pop('__loader__')
                    path = ns.pop('__path__')
                    spec = ns.pop('__spec__')
                    ns.pop('__builtins__', None)  # An implementation detail.
                    self.assertEqual(spec.name, name)
                    self.assertIsNotNone(spec.loader)
                    self.assertIsNotNone(loader)
                    self.assertEqual(spec.loader, loader)
                    self.assertEqual(set(path),
                                     set([os.path.dirname(bad_path)]))
                    with self.assertRaises(AttributeError):
                        # a NamespaceLoader
                        loader.path
                    self.assertEqual(ns, expected)

                    # Change to a regular package.
                    self.init.invalidate_caches()
                    init_path = os.path.join(cwd, name, '__init__.py')
                    cached = self.util.cache_from_source(init_path)
                    expected = {
                        '__name__': name,
                        '__package__': name,
                        '__file__': init_path,
                        '__cached__': cached,
                        '__path__': [os.path.dirname(init_path)],
                        '__doc__': None,
                        'eggs': None,
                    }
                    os.rename(bad_path, init_path)
                    reloaded = self.init.reload(module)
                    ns = vars(reloaded).copy()
                    loader = ns.pop('__loader__')
                    spec = ns.pop('__spec__')
                    ns.pop('__builtins__', None)  # An implementation detail.
                    self.assertEqual(spec.name, name)
                    self.assertEqual(spec.loader, loader)
                    self.assertIs(reloaded, module)
                    self.assertEqual(loader.path, init_path)
                    self.assertEqual(ns, expected)
 def test_path_in_pyclasspath(self):
     jar = self.prepareJar('classimport_Lib.jar')
     compiled = self.compileToJar(jar, 'Lib')
     Thread.currentThread(
     ).contextClassLoader = support.make_jar_classloader(jar)
     with support.DirsOnSysPath():
         sys.path = ['__pyclasspath__/Lib']
         self.checkImports('__pyclasspath__/Lib', compiled)
示例#4
0
    def test_reload_location_changed(self):
        name = 'spam'
        with support.temp_cwd(None) as cwd:
            with util.uncache('spam'):
                with support.DirsOnSysPath(cwd):
                    # Start as a plain module.
                    self.init.invalidate_caches()
                    path = os.path.join(cwd, name + '.py')
                    cached = self.util.cache_from_source(path)
                    expected = {
                        '__name__': name,
                        '__package__': '',
                        '__file__': path,
                        '__cached__': cached,
                        '__doc__': None,
                        '__builtins__': __builtins__,
                    }
                    support.create_empty_file(path)
                    module = self.init.import_module(name)
                    ns = vars(module)
                    loader = ns.pop('__loader__')
                    spec = ns.pop('__spec__')
                    self.assertEqual(spec.name, name)
                    self.assertEqual(spec.loader, loader)
                    self.assertEqual(loader.path, path)
                    self.assertEqual(ns, expected)

                    # Change to a package.
                    self.init.invalidate_caches()
                    init_path = os.path.join(cwd, name, '__init__.py')
                    cached = self.util.cache_from_source(init_path)
                    expected = {
                        '__name__': name,
                        '__package__': name,
                        '__file__': init_path,
                        '__cached__': cached,
                        '__path__': [os.path.dirname(init_path)],
                        '__doc__': None,
                        '__builtins__': __builtins__,
                    }
                    os.mkdir(name)
                    os.rename(path, init_path)
                    reloaded = self.init.reload(module)
                    ns = vars(reloaded)
                    loader = ns.pop('__loader__')
                    spec = ns.pop('__spec__')
                    self.assertEqual(spec.name, name)
                    self.assertEqual(spec.loader, loader)
                    self.assertIs(reloaded, module)
                    self.assertEqual(loader.path, init_path)
                    self.maxDiff = None
                    self.assertEqual(ns, expected)
示例#5
0
def temp_module(name, content='', *, pkg=False):
    conflicts = [n for n in sys.modules if n.partition('.')[0] == name]
    with support.temp_cwd(None) as cwd:
        with uncache(name, *conflicts):
            with support.DirsOnSysPath(cwd):
                invalidate_caches()
                location = os.path.join(cwd, name)
                if pkg:
                    modpath = os.path.join(location, '__init__.py')
                    os.mkdir(name)
                else:
                    modpath = location + '.py'
                    if content is None:
                        content = ''
                if content is not None:
                    with open(modpath, 'w') as modfile:
                        modfile.write(content)
                yield location
示例#6
0
    def test_discovery_failed_discovery(self):
        loader = unittest.TestLoader()
        package = types.ModuleType('package')

        def _import(packagename, *args, **kwargs):
            sys.modules[packagename] = package
            return package

        with unittest.mock.patch('builtins.__import__', _import):
            # Since loader.discover() can modify sys.path, restore it when done.
            with support.DirsOnSysPath():
                # Make sure to remove 'package' from sys.modules when done.
                with test.test_importlib.util.uncache('package'):
                    with self.assertRaises(TypeError) as cm:
                        loader.discover('package')
                    self.assertEqual(
                        str(cm.exception),
                        'don\'t know how to discover from {!r}'.format(
                            package))
示例#7
0
 def test_DirsOnSysPath(self):
     with support.DirsOnSysPath('foo', 'bar'):
         self.assertIn("foo", sys.path)
         self.assertIn("bar", sys.path)
     self.assertNotIn("foo", sys.path)
     self.assertNotIn("bar", sys.path)
示例#8
0
 def setUp(self):
     cm = support.DirsOnSysPath(scriptsdir)
     cm.__enter__()
     self.addCleanup(cm.__exit__)
示例#9
0
        def fixup():
            sys.argv = oldargv

        self.addCleanup(fixup)
        sys.argv = []

    def test_gprof(self):
        # Issue #14508: this used to fail with an NameError.
        with mock.patch.object(self.gprof, 'webbrowser') as wmock, \
                tempfile.TemporaryDirectory() as tmpdir:
            fn = os.path.join(tmpdir, 'abc')
            open(fn, 'w').close()
            sys.argv = ['gprof2html', fn]
            self.gprof.main()
        self.assertTrue(wmock.open.called)


# Run the tests in Tools/parser/test_unparse.py
with support.DirsOnSysPath(os.path.join(basepath, 'parser')):
    from test_unparse import UnparseTestCase
    from test_unparse import DirectoryTestCase


def test_main():
    support.run_unittest(
        *[obj for obj in globals().values() if isinstance(obj, type)])


if __name__ == '__main__':
    unittest.main()
示例#10
0
def import_tool(toolname):
    with support.DirsOnSysPath(scriptsdir):
        return importlib.import_module(toolname)
示例#11
0
def imports_under_tool(name, *subdirs):
    tooldir = os.path.join(toolsdir, name, *subdirs)
    with support.DirsOnSysPath(tooldir) as cm:
        yield cm
 def test_bug1126(self):
     with support.DirsOnSysPath("Lib/test/bug1126/bug1126.jar"):
         import org.subpackage
 def test_bug1239(self):
     with support.DirsOnSysPath("Lib/test/bug1239.jar"):
         import org.test403javapackage.test403