[Python-checkins] r57183 - in sandbox/trunk/import_in_py: _importlib.py tests/test_fs_loader.py

brett.cannon python-checkins at python.org
Sat Aug 18 21:34:06 CEST 2007


Author: brett.cannon
Date: Sat Aug 18 21:34:05 2007
New Revision: 57183

Modified:
   sandbox/trunk/import_in_py/_importlib.py
   sandbox/trunk/import_in_py/tests/test_fs_loader.py
Log:
Add name checks to the extension module loader.  Also finished tests for the
loader.  And since name check tests is generic, write the test for the source
loader as well.


Modified: sandbox/trunk/import_in_py/_importlib.py
==============================================================================
--- sandbox/trunk/import_in_py/_importlib.py	(original)
+++ sandbox/trunk/import_in_py/_importlib.py	Sat Aug 18 21:34:05 2007
@@ -242,6 +242,19 @@
             raise ImportError("can only handle directories")
 
 
+def check_name(method):
+    """Decorator to verify that the module being requested matches the one the
+    loader can handle."""
+    def inner(self, name, *args, **kwargs):
+        if self._name != name:
+            raise ImportError("loader cannot handle %s" % name)
+        return method(self, name, *args, **kwargs)
+    inner.__name__ = method.__name__
+    inner.__doc__ = method.__doc__
+    inner.__dict__.update(method.__dict__)
+    return inner
+
+
 class _ExtensionFileLoader(object):
 
     """Provide the ability to load an extension module."""
@@ -250,7 +263,10 @@
         """Initialize the loader, ignoring the is_pkg argument."""
         self._name = name
         self._path = path
+        if is_pkg:
+            raise ValueError("extension modules cannot be packages")
 
+    @check_name
     def load_module(self, fullname):
         """Load an extension module."""
         assert self._name == fullname
@@ -264,15 +280,18 @@
                 del sys.modules[fullname]
             raise
 
+    @check_name
     def is_package(self, fullname):
         """Return False as an extension module can never be a package."""
         return False
 
+    @check_name
     def get_code(self, fullname):
         """Return None as an extension module cannot create just a code
         object."""
         return None
 
+    @check_name
     def get_source(self, fullname):
         """Return None as extension modules have no source code."""
         return None
@@ -346,19 +365,6 @@
     return module
 
 
-def check_name(method):
-    """Decorator to verify that the module being requested matches the one the
-    loader can handle."""
-    def inner(self, name, *args, **kwargs):
-        if self._name != name:
-            raise ImportError("loader cannot handle %s" % name)
-        return method(self, name, *args, **kwargs)
-    inner.__name__ = method.__name__
-    inner.__doc__ = method.__doc__
-    inner.__dict__.update(method.__dict__)
-    return inner
-
-
 class _PyFileLoader(object):
 
     """Load a Python source or bytecode file."""

Modified: sandbox/trunk/import_in_py/tests/test_fs_loader.py
==============================================================================
--- sandbox/trunk/import_in_py/tests/test_fs_loader.py	(original)
+++ sandbox/trunk/import_in_py/tests/test_fs_loader.py	Sat Aug 18 21:34:05 2007
@@ -9,8 +9,6 @@
 import unittest
 
 
-test_ext_module = '_testcapi'
-
 class LoaderBasics(unittest.TestCase):
 
     def reload_test(self, loader, name):
@@ -32,37 +30,49 @@
         self.assertEqual(loaded.__file__, path)
         self.assertEqual(loaded.__loader__, loader)
 
+    def ImportError_on_bad_name(self, loader, bad_name, extra_methods=[]):
+        to_test = ['load_module', 'is_package', 'get_code', 'get_source']
+        to_test += extra_methods
+        for method_name in to_test:
+            method = getattr(loader, method_name)
+            self.assertRaises(ImportError, method, bad_name)
+
 
 class ExtensionFileLoaderTests(LoaderBasics):
 
+    testing_module = '_testcapi'
+    testing_location = find_ext_location(testing_module)
+    testing_path = os.path.join(*testing_location)
+
+    def setUp(self):
+        self.loader = importlib._ExtensionFileLoader(self.testing_module,
+                                                     self.testing_path, False)
+
     def test_basic(self):
         # Should be able to import an extension module.
-        path, filename = find_ext_location(test_ext_module)
-        module_path = os.path.join(path, filename)
-        loader = importlib._ExtensionFileLoader(test_ext_module, module_path,
-                                                False)
-        self.basic_test(loader, test_ext_module, module_path)
+        self.basic_test(self.loader, self.testing_module, self.testing_path)
 
     def test_reload(self):
         # A module that is already in sys.modules should be reused and be
         # re-initialized.
-        path, filename = find_ext_location(test_ext_module)
-        loader = importlib._ExtensionFileLoader(test_ext_module,
-                                                os.path.join(path, filename),
-                                                False)
-        self.reload_test(loader, test_ext_module)
+        self.reload_test(self.loader, self.testing_module)
+
+    def test_ImportError_on_bad_name(self):
+        # ImportError should be raised when a method is called with a module
+        # name it cannot handle.
+        self.ImportError_on_bad_name(self.loader, self.testing_module + 'asdf')
 
     def test_is_package(self):
         # Should always be False.
-        raise NotImplementedError
+        self.assert_(not self.loader.is_package(self.testing_module))
 
     def test_get_code(self):
         # Should always be None.
-        raise NotImplementedError
+        self.assert_(not self.loader.get_code(self.testing_module))
 
     def test_get_source(self):
         # Should always be None.
-        raise NotImplementedError
+        self.assert_(not self.loader.get_source(self.testing_module))
 
 
 class PyFileLoaderTests(LoaderBasics, TestPyPycPackages):
@@ -75,6 +85,12 @@
         loader = importlib._PyFileLoader(self.module_name, self.py_path, False)
         self.reload_test(loader, self.module_name)
 
+    def test_ImportError_on_bad_name(self):
+        loader = importlib._PyFileLoader(self.module_name, self.py_path, False)
+        extra_methods = ['write_bytecode', 'get_bytecode', 'mod_time']
+        self.ImportError_on_bad_name(loader, self.module_name + 'sdfasdf',
+                                        extra_methods)
+
 
 def test_main():
     test_support.run_unittest(ExtensionFileLoaderTests, PyFileLoaderTests)


More information about the Python-checkins mailing list