diff -r 9b359b6c9a39 Lib/test/test_pkgutil.py --- a/Lib/test/test_pkgutil.py Sun Jul 08 00:45:33 2012 +1000 +++ b/Lib/test/test_pkgutil.py Mon Jul 09 07:08:17 2012 -0700 @@ -1,11 +1,16 @@ -from test.support import run_unittest +from contextlib import contextmanager import unittest import sys import imp +# TODO: replace the next line "import pkgutil" with the appropriate +# form of "from pkgutil import ...". import pkgutil +from pkgutil import ImpImporter import os import os.path import tempfile +from test import support +from test.support import run_unittest import shutil import zipfile @@ -138,6 +143,51 @@ del sys.modules['foo'] +class ImpImporterTests(unittest.TestCase): + + def _create_file(self, path): + """Create a file.""" + f = open(path, 'w') + f.close() + + def _create_package(self, package_name): + """Create a package with an __init__.py.""" + os.mkdir(package_name) + init_file_name = '__init__' + os.extsep + 'py' + init_file_path = os.path.join(package_name, init_file_name) + self._create_file(init_file_path) + + @contextmanager + def new_sys_path(self): + """Set sys.path to a list containing a temp working directory. + + """ + with support.temp_cwd(support.TESTFN) as cwd: + original_sys_path = sys.path + sys.path = [cwd] + try: + yield + finally: + sys.path = original_sys_path + + def test_iter_modules(self): + importer = ImpImporter() + with self.new_sys_path(): + self._create_file('mymodule.py') + self._create_package('mypackage') + modules = list(importer.iter_modules()) + self.assertEqual(modules, [('mymodule', False), ('mypackage', True)]) + + def test_iter_modules__with_prefix(self): + importer = ImpImporter() + with self.new_sys_path(): + self._create_file('mymodule.py') + self._create_package('mypackage') + modules = list(importer.iter_modules(prefix='prefix.')) + self.assertEqual(modules, [('prefix.mymodule', False), + ('prefix.mypackage', True)]) + + # These tests, especially the setup and cleanup, are hideous. They # need to be cleaned up once issue 14715 is addressed. class ExtendPathTests(unittest.TestCase): @@ -215,7 +265,7 @@ def test_main(): - run_unittest(PkgutilTests, PkgutilPEP302Tests, ExtendPathTests) + run_unittest(PkgutilTests, PkgutilPEP302Tests, ExtendPathTests, ImpImporterTests) # this is necessary if test is run repeated (like when finding leaks) import zipimport zipimport._zip_directory_cache.clear()