[Python-checkins] r57550 - sandbox/trunk/import_in_py/zipimport_/tests.py sandbox/trunk/import_in_py/zipimport_/zipimport.py

brett.cannon python-checkins at python.org
Mon Aug 27 07:23:11 CEST 2007


Author: brett.cannon
Date: Mon Aug 27 07:23:10 2007
New Revision: 57550

Modified:
   sandbox/trunk/import_in_py/zipimport_/tests.py
   sandbox/trunk/import_in_py/zipimport_/zipimport.py
Log:
Implement get_code (along with __repr__).


Modified: sandbox/trunk/import_in_py/zipimport_/tests.py
==============================================================================
--- sandbox/trunk/import_in_py/zipimport_/tests.py	(original)
+++ sandbox/trunk/import_in_py/zipimport_/tests.py	Mon Aug 27 07:23:10 2007
@@ -1,11 +1,14 @@
 from zipimport_ import zipimport
 #import zipimport
 
+import importlib
+
 import contextlib
 import os
 import py_compile
 import shutil
 from test import test_support
+import time
 import unittest
 import zipfile
 
@@ -203,13 +206,29 @@
     """Test zipimporter.get_code()."""
 
     def test_mod_time(self):
-        raise NotImplementedError
+        with temp_zipfile() as zip_path:
+            actual_mtime = int(os.stat('_top_level.py').st_mtime)
+            importer = zipimport.zipimporter(zip_path)
+            zip_mtime = importer.mod_time('_top_level')
+            self.assertEqual(zip_mtime, actual_mtime)
+
+    def verify_code(self, archive_path, module):
+        importer = zipimport.zipimporter(archive_path)
+        code_obj = importer.get_code(module)
+        ns = {}
+        exec code_obj in ns
+        self.assert_('attr' in ns)
+        self.assertEqual(ns['attr'], None)
 
     def test_top_level(self):
-        raise NotImplementedError
+        for args in [[True, True], [True, False], [False, True]]:
+            with temp_zipfile(*args) as zip_path:
+                self.verify_code(zip_path, '_top_level')
 
     def test_pkg(self):
-        raise NotImplementedError
+        for args in [[True, True], [True, False], [False, True]]:
+            with temp_zipfile(*args) as zip_path:
+                self.verify_code(zip_path, '_pkg')
 
 
 class LoadModule(unittest.TestCase):
@@ -239,7 +258,7 @@
                                 GetData,
                                 IsPackage,
                                 GetSource,
-                                #GetCode,
+                                GetCode,
                                 #LoadModule
                              )
 

Modified: sandbox/trunk/import_in_py/zipimport_/zipimport.py
==============================================================================
--- sandbox/trunk/import_in_py/zipimport_/zipimport.py	(original)
+++ sandbox/trunk/import_in_py/zipimport_/zipimport.py	Mon Aug 27 07:23:10 2007
@@ -2,10 +2,10 @@
 import importlib
 
 import contextlib
-#import datetime
+import datetime
 import imp
 import os
-#import time
+import time
 import zipfile
 
 
@@ -54,8 +54,11 @@
         self._files = _zip_directory_cache[path]
 
     def __repr__(self):
-        raise NotImplementedError
-        return '<zipimport.zipimporter instance for %r>' % self._path_entry
+        if self.prefix:
+            path = os.path.join(self.archive, self.prefix)
+        else:
+            path = self.archive
+        return '<zipimporter object %r>' % path
 
     def _check_paths(self, tail, pkg=False):
         """Check if the module (or package) is contained within the package
@@ -94,25 +97,20 @@
             return self
         return None
 
-    def _resolve_path(self, internal_path):
-        """Return the path to the file, consisting of the zip file and the path
-        within the zip file (if the path is true)."""
-        raise NotImplementedError
-        if internal_path:
-            return os.path.join(self._zip_path, internal_path)
-        else:
-            return internal_path
-
     def get_code(self, fullname):
         """Return the code object for the module, raising ZipImportError if the
         module is not found."""
-        raise NotImplementedError
-        try:
-            info = self._path_cache[fullname]
-        except KeyError:
-            raise ZipImportError('%s is not known' % fullname)
-        return self._handler(fullname, self._resolve_path(info[0]),
-                             self._resolve_path(info[1]))[0]
+        tail = fullname.rpartition('.')[2]
+        info = self._check_paths(tail, '__init__')
+        if info:
+            pkg = True
+        else:
+            info = self._check_paths(tail)
+            if info:
+                pkg = False
+            else:
+                raise ZipImportError('%s is not known' % fullname)
+        return self._handler(fullname, info[0], info[1])[0]
 
     def get_data(self, pathname):
         """Return the data (raw source or bytecode) for the specified module,
@@ -126,8 +124,8 @@
             try:
                 return zip_.open(pathname, 'r').read()
             except KeyError:
-                raise IOError('%s does not exist in the zip file %s' % (pathname,
-                                self._zip_path))
+                raise IOError('%s does not exist in the zip file %s' %
+                                (pathname, self.archive))
 
     def get_source(self, fullname):
         """Get the source code for the specified module, raising ZipImportError
@@ -159,25 +157,30 @@
     def mod_time(self, name):
         """Return the last modification time of the module's source code from
         the epoch (based on the local time)."""
-        raise NotImplementedError
-        try:
-            info = self._path_cache[fullname]
-        except KeyError:
-            raise ZipImportError('%s is not known' % name)
-        with contextlib.closing(zipfile.ZipFile(self._zip_path)) as zip_:
-            file_info = zip_.getinfo(info[0])
+        tail = name.rpartition('.')[2]
+        info = self._check_paths(tail, '__init__')
+        if not info:
+            info = self._check_paths(tail)
+        if not info[0]:
+            raise ZipImportError("no source for %s" % name)
+        file_info = _zip_directory_cache[self.archive][info[0]]
         file_mtime = datetime.datetime(*file_info.date_time)
-        return int(time.mktime(file_time.timetuple()))
+        return int(time.mktime(file_mtime.timetuple()))
 
     def get_bytecode(self, name):
         """Get the bytecode for the module."""
-        raise NotImplementedError
-        try:
-            bytecode_path = self._path_cache[name][1]
-        except KeyError:
+        tail = name.rpartition('.')[2]
+        info = self._check_paths(tail, '__init__')
+        if not info:
+            info = self._check_paths(tail)
+        if info and info[1]:
+            with contextlib.closing(zipfile.ZipFile(self.archive)) as zip_:
+                bytecode = zip_.open(info[1], 'r').read()
+            return bytecode[:4], importlib._r_long(bytecode[4:8]), bytecode[8:]
+        elif info:
+            return None
+        else:
             raise ZipImportError('%s is not known' % name)
-        with contextlib.closing(zipfile.ZipFile(self._zip_path)) as zip_:
-            return zip_.open(bytecode_path, 'r').read()
 
     def write_bytecode(self, name, timestamp, data):
         """Return False as zip files are never modified."""
@@ -188,12 +191,3 @@
         """Load the specified module, returning the module or raising
         ZipImportError if the module could not be found."""
         raise NotImplementedError
-        try:
-            info = self._path_cache[fullname]
-        except KeyError:
-            raise ZipImportError('%s is not known' % fullname)
-        code_object, path = self._handler(fullname, self._resolve_path(info[0]),
-                                            self._resolve_path(info[1]))
-        # XXX __path__ needs to start with the zip file.
-        return importlib.module_init(loader, code_object, fullname, path,
-                                        info[2])


More information about the Python-checkins mailing list