Author: brett.cannon
Date: Wed Nov 1 03:15:22 2006
New Revision: 52571
Modified:
sandbox/trunk/import_in_py/mock_importer.py
sandbox/trunk/import_in_py/test_importer.py
Log:
Added an __init__ the the filesystem mock object. Also reorganize tests for
importer.Importer.
Modified: sandbox/trunk/import_in_py/mock_importer.py
==============================================================================
--- sandbox/trunk/import_in_py/mock_importer.py (original)
+++ sandbox/trunk/import_in_py/mock_importer.py Wed Nov 1 03:15:22 2006
@@ -19,11 +19,19 @@
the base path and another string representing the type.
"""
+
+ def __init__(self, file_path, handler, package=None):
+ """Store arguments passed into the constructor for verification."""
+ self.init_file_path = file_path
+ self.init_handler = handler
+ self.init_package = package
- def __init__(self, good_magic=True, good_timestamp=True, pyc_exists=True,
+ @classmethod
+ def setup(cls, good_magic=True, good_timestamp=True, pyc_exists=True,
py_exists=True):
"""Set up the mock loader based on possible scenarios of source and
bytecode combinations/issues."""
+ self = cls('<setup>', '<setup>')
self.module_name = 'test_module'
self.py_ext = "source" if py_exists else None
self.pyc_ext = "bytecode" if pyc_exists else None
@@ -45,6 +53,7 @@
# Needed for read_data on .pyc path.
self.pyc = pyc + bytecode
self.log = []
+ return self
def _create_handler(self, handler):
if self.py_ext:
@@ -189,6 +198,7 @@
def load_module(self, fullname, path=None):
self.load_request = fullname, path
+ sys.modules[fullname] = self.module
return self.module
@classmethod
Modified: sandbox/trunk/import_in_py/test_importer.py
==============================================================================
--- sandbox/trunk/import_in_py/test_importer.py (original)
+++ sandbox/trunk/import_in_py/test_importer.py Wed Nov 1 03:15:22 2006
@@ -375,7 +375,7 @@
"""Test PyPycHandler.handle_code()."""
def test_good_pyc_w_py(self):
- loader = mock_importer.MockPyPycLoader()
+ loader = mock_importer.MockPyPycLoader.setup()
handler = loader._create_handler(importer.PyPycHandler)
module = loader._handle_pyc(handler)
loader._verify_module(module)
@@ -401,7 +401,7 @@
pass
def test_py_no_pyc(self):
- loader = mock_importer.MockPyPycLoader(pyc_exists=False)
+ loader = mock_importer.MockPyPycLoader.setup(pyc_exists=False)
handler = loader._create_handler(importer.PyPycHandler)
module = loader._handle_py(handler)
loader._verify_module(module)
@@ -410,7 +410,7 @@
self.failUnlessEqual(loader.log.count('read_data'), 1)
def test_py_w_pyc(self):
- loader = mock_importer.MockPyPycLoader()
+ loader = mock_importer.MockPyPycLoader.setup()
handler = loader._create_handler(importer.PyPycHandler)
module = loader._handle_py(handler)
loader._verify_module(module)
@@ -447,19 +447,24 @@
if not attr.startswith('_')))
-class SimpleImportTests(unittest.TestCase):
+class ImporterHelper(unittest.TestCase):
- """Test Importer class with only direct module imports; no packages."""
+ """Common helper methods for testing the Importer class."""
def setUp(self):
"""Store a copy of the 'sys' attribute pertaining to imports."""
- # Don't backup sys.modules since dict is cached and losing the cache
- # is not that severe.
+ # Don't backup sys.modules since dict is cached.
+ # Don't clear sys.modules as it can wreak havoc
+ # (e.g., losing __builtin__).
self.old_sys_modules = sys.modules.copy()
self.old_meta_path = sys.meta_path[:]
+ sys.meta_path = []
self.old_sys_path = sys.path[:]
+ sys.path = []
self.old_path_hooks = sys.path_hooks[:]
+ sys.path_hooks = []
self.old_path_importer_cache = sys.path_importer_cache.copy()
+ sys.path_importer_cache.clear()
self.import_ = importer.Importer()
def tearDown(self):
@@ -470,38 +475,37 @@
sys.path = self.old_sys_path
sys.path_hooks = self.old_path_hooks
sys.path_importer_cache = self.old_path_importer_cache
-
- def test_default_importer_factory(self):
- # Make sure that the object passed in during initialization is used
- # when sys.path_importer_cache has a value of None.
- succeed_importer = mock_importer.SucceedImporter()
- import_ = importer.Importer(succeed_importer, ())
- sys.meta_path = []
- sys.path = ['<succeed>']
- sys.path_importer_cache['<succeed>'] = None
- module = import_('sys')
- self.failUnlessEqual(succeed_importer.find_request, ('sys', None))
- self.failUnless(module is mock_importer.SucceedImporter.module)
-
- def test_extended_meta_path(self):
- # Default meta_path entries set during initialization should be
- # queried after sys.meta_path.
- pass_importer = mock_importer.PassImporter()
- sys.meta_path = [pass_importer]
- succeed_importer = mock_importer.SucceedImporter()
- import_ = importer.Importer(extended_meta_path=(succeed_importer,))
- module = import_('sys')
- for meta_importer in (pass_importer, succeed_importer):
- self.failUnlessEqual(meta_importer.find_request, ('sys', None))
- self.failUnless(module is mock_importer.SucceedImporter.module)
-
+
+ def clear_sys_module(*modules):
+ for module in modules:
+ try:
+ del sys.modules[module]
+ except KeyError:
+ pass
+
+
+class ImporterMiscTests(ImporterHelper):
+
+ """Test miscellaneous parts of the Importer class."""
+
+ def test_sys_module_return(self):
+ # A module found in sys.modules should be returned immediately.
+ sys.path_importer_cache.clear()
+ sys.path = []
+ test_module = '<test>'
+ sys.modules[test_module] = test_module
+ module = self.import_('<test>')
+ self.failUnlessEqual(module, test_module)
+
def test_default_init(self):
# The default initialization should work with a None entry for every
# sys.path entry in sys.path_importer_cache. It should also lead to
# built-in, frozen, extension, .pyc, and .py files being imported if
# desired.
sys.path_importer_cache = dict((entry, None) for entry in sys.path)
- sys.modules = {}
+ self.clear_sys_module('sys', '__hello__', 'time', 'token')
+ # Restore sys.path for 'time' import.
+ sys.path = self.old_sys_path
# Built-ins.
module = self.import_('sys')
self.failUnlessEqual(module.__name__, 'sys')
@@ -521,10 +525,26 @@
module = self.import_('token')
self.failUnlessEqual(module.__name__, 'token')
self.failUnless(hasattr(module, 'ISTERMINAL'))
-
+
+ def test_empty_fromlist(self):
+ # An empty fromlist means that the root module is returned.
+ # XXX
+ pass
+
+ def test_nonempty_fromlist(self):
+ # A fromlist with values should return the specified module.
+ # XXX
+ pass
+
+
+class ImporterMetaPathTests(ImporterHelper):
+
+ """Test meta_path usage."""
+
def test_search_meta_path(self):
# Test search method of sys.meta_path.
# Should raise ImportError on error.
+ self.clear_sys_module('sys')
import_ = importer.Importer(extended_meta_path=())
sys.meta_path = []
self.failUnlessRaises(ImportError, import_.search_meta_path,
@@ -538,9 +558,40 @@
self.failUnlessEqual(entry.find_request, ('sys', None))
self.failUnless(loader is meta_path[-1])
+ def test_extended_meta_path(self):
+ # Default meta_path entries set during initialization should be
+ # queried after sys.meta_path.
+ self.clear_sys_module('sys')
+ pass_importer = mock_importer.PassImporter()
+ sys.meta_path = [pass_importer]
+ succeed_importer = mock_importer.SucceedImporter()
+ import_ = importer.Importer(extended_meta_path=(succeed_importer,))
+ module = import_('sys')
+ for meta_importer in (pass_importer, succeed_importer):
+ self.failUnlessEqual(meta_importer.find_request, ('sys', None))
+ self.failUnless(module is mock_importer.SucceedImporter.module)
+
+
+class ImporterSysPathTests(ImporterHelper):
+
+ """Test sys.path usage."""
+
+ def test_default_importer_factory(self):
+ # Make sure that the object passed in during initialization is used
+ # when sys.path_importer_cache has a value of None.
+ self.clear_sys_module('sys')
+ succeed_importer = mock_importer.SucceedImporter()
+ import_ = importer.Importer(succeed_importer, ())
+ sys.meta_path = []
+ sys.path = ['<succeed>']
+ sys.path_importer_cache['<succeed>'] = None
+ module = import_('sys')
+ self.failUnlessEqual(succeed_importer.find_request, ('sys', None))
+ self.failUnless(module is mock_importer.SucceedImporter.module)
+
def test_search_sys_path(self):
# Test sys.path searching for a loader.
- sys.meta_path = []
+ self.clear_sys_module('sys')
import_ = importer.Importer(extended_meta_path=())
sys.path = []
sys_path = (mock_importer.PassImporter.set_on_sys_path(),
@@ -553,6 +604,7 @@
def test_importer_cache_preexisting(self):
# A pre-existing importer should be returned if it exists in
# sys.path_importer_cache.
+ self.clear_sys_module('sys')
sys.path = []
succeed_importer = mock_importer.SucceedImporter.set_on_sys_path()
loader = self.import_.search_sys_path('sys')
@@ -562,6 +614,7 @@
# If an entry does not exist for a sys.path entry in the importer cache
# then sys.path_hooks should be searched and if one is found then cache
# it.
+ self.clear_sys_module('sys')
path_entry = '<succeed>'
succeed_importer = mock_importer.SucceedImporter()
sys.path = [path_entry]
@@ -575,25 +628,13 @@
def test_importer_cache_no_path_hooks(self):
# If an entry does not exist for a sys.path entry in the importer cache
# and sys.path_hooks has nothing for the entry, None should be set.
+ self.clear_sys_module('sys')
path_entry = '<test>'
sys.path = [path_entry]
sys.path_hooks = []
sys.path_importer_cache.clear()
self.failUnlessRaises(ImportError, self.import_.search_sys_path, 'sys')
self.failUnless(sys.path_importer_cache[path_entry] is None)
-
-
-class PackageImportTests(unittest.TestCase):
-
- """Test cases involving package semantics."""
-
- def test_empty_fromlist(self):
- # An empty fromlist means that the root module is returned.
- pass
-
- def test_nonempty_fromlist(self):
- # A fromlist with values should return the specified module.
- pass
def test_main():