[py-svn] r13610 - in py/dist/py: . misc/testing

dstanek at codespeak.net dstanek at codespeak.net
Mon Jun 20 11:43:06 CEST 2005


Author: dstanek
Date: Mon Jun 20 11:43:04 2005
New Revision: 13610

Modified:
   py/dist/py/__init__.py
   py/dist/py/initpkg.py
   py/dist/py/misc/testing/test_initpkg.py
Log:
Made changes to the export system to allow the compatibility modules to be
imported in more natural ways. Before this change they could only be used
by importing py and then using their fully qualified path to access them.


Modified: py/dist/py/__init__.py
==============================================================================
--- py/dist/py/__init__.py	(original)
+++ py/dist/py/__init__.py	Mon Jun 20 11:43:04 2005
@@ -3,7 +3,7 @@
 py.test, an interactive testing tool which supports 
 unit-testing with practically no boilerplate.
 """  
-from initpkg import initpkg
+from initpkg import initpkg, RealModule
 
 initpkg(__name__, 
     description = "py.test and the py lib",
@@ -109,7 +109,7 @@
     'log.STDOUT'             : ('./log/consumer.py', 'STDOUT'), 
     'log.STDERR'             : ('./log/consumer.py', 'STDERR'), 
 
-    'compat.doctest'         : ('./compat/doctest.py', None),
-    'compat.optparse'        : ('./compat/optparse.py', None),
-    'compat.textwrap'        : ('./compat/textwrap.py', None),
+    'compat.doctest'         : ('./compat/doctest.py', RealModule),
+    'compat.optparse'        : ('./compat/optparse.py', RealModule),
+    'compat.textwrap'        : ('./compat/textwrap.py', RealModule),
 })

Modified: py/dist/py/initpkg.py
==============================================================================
--- py/dist/py/initpkg.py	(original)
+++ py/dist/py/initpkg.py	Mon Jun 20 11:43:04 2005
@@ -22,7 +22,8 @@
 
 """
 from __future__ import generators
-import sys, os
+import sys
+import os
 assert sys.version_info >= (2,2,0), "py lib requires python 2.2 or higher"
 
 ModuleType = type(sys.modules[__name__])
@@ -66,7 +67,7 @@
         assert fspath.startswith('./'), \
                "%r is not an implementation path (XXX)" % (extpyish,)
         implmodule = self._loadimpl(fspath[:-3])
-        if not modpath: # export the entire module
+        if not isinstance(modpath, basestring): # export the entire module
             return implmodule
 
         current = implmodule
@@ -204,6 +205,39 @@
     __dict__ = property(getdict)
     del getdict
 
+class RealModule(ModuleType):
+    def __init__(self, pkg, name, extpy):
+        self.__package__ = pkg
+        self.__name__ = name
+        self.__extpy__ = extpy
+        self.__isimported__ = False
+
+    def __getattr__(self, name):
+        dct = self.__doimport()
+        if not name in dct:
+            raise AttributeError, name
+        return dct[name]
+
+    def __repr__(self):
+        return '<RealModule %r>' % (self.__name__, )
+
+    def __doimport(self):
+        dictdescr = ModuleType.__dict__['__dict__']
+        dct = dictdescr.__get__(self) # avoid infinite recursion
+        if not self.__isimported__:
+            module = self.__package__._resolve(self.__extpy__)
+            dct.update(module.__dict__)
+            self.__isimported__ = True
+        return dct
+
+    def getdict(self):
+        self.__doimport()
+        dictdescr = ModuleType.__dict__['__dict__']
+        return dictdescr.__get__(self)
+
+    __dict__ = property(getdict)
+    del getdict
+
 # ---------------------------------------------------
 # Bootstrap Virtual Module Hierarchy
 # ---------------------------------------------------
@@ -230,6 +264,18 @@
                 seen[current] = mod = Module(pkg, current)
                 setattr(seen[previous], name, mod)
                 setmodule(current, mod)
+
+        if not isinstance(extpy[1], basestring):
+            klass = extpy[1]
+            previous = current
+            name = pyparts[-1]
+            current += '.' + name
+            if current not in seen:
+                seen[current] = mod = klass(pkg, current, extpy)
+                setattr(seen[previous], name, mod)
+                setmodule(current, mod)
+            continue
+
         mod = seen[current]
         if not hasattr(mod, '__map__'):
             assert mod is pkg.module, \

Modified: py/dist/py/misc/testing/test_initpkg.py
==============================================================================
--- py/dist/py/misc/testing/test_initpkg.py	(original)
+++ py/dist/py/misc/testing/test_initpkg.py	Mon Jun 20 11:43:04 2005
@@ -2,6 +2,7 @@
 
 import py
 import types
+import sys
 
 def checksubpackage(name):
     obj = getattr(py, name)
@@ -98,6 +99,133 @@
     from py.process import cmdexec as cmdexec2
     assert cmdexec is cmdexec2
 
+#
+# test support for importing modules
+#
+
+class TestRealModule:
+
+    def setup_class(cls):
+        cls.tmpdir = py.test.ensuretemp('test_initpkg')
+        sys.path = [str(cls.tmpdir)] + sys.path
+        pkgdir = cls.tmpdir.ensure('realtest', dir=1)
+
+        tfile = pkgdir.join('__init__.py')
+        tfile.write(py.code.Source("""if True:
+            import py
+            py.initpkg('realtest', {
+                'module': ('./testmodule.py', py.__.initpkg.RealModule)
+            })
+        """))
+
+        tfile = pkgdir.join('testmodule.py')
+        tfile.write(py.code.Source("""if True:
+            __all__ = ['mytest0', 'mytest1', 'MyTest']
+        
+            def mytest0():
+                pass
+            def mytest1():
+                pass
+            class MyTest:
+                pass
+
+        """))
+
+        import realtest # need to mimic what a user would do
+        #py.initpkg('realtest', {
+        #    'module': ('./testmodule.py', None)
+        #})
+
+    def setup_method(self, *args):
+        """Unload the test modules before each test."""
+        module_names = ['realtest.module', 'realtest']
+        for modname in module_names:
+            if modname in sys.modules:
+                del sys.modules[modname]
+
+    def test_realmodule(self):
+        """Testing 'import realtest.module'"""
+        import realtest.module
+        assert 'realtest.module' in sys.modules
+        assert getattr(realtest.module, 'mytest0')
+
+    def test_realmodule_from(self):
+        """Testing 'from test import module'."""
+        from realtest import module
+        assert getattr(module, 'mytest1')
+
+    def test_realmodule_star(self):
+        """Testing 'from test.module import *'."""
+        tfile = self.tmpdir.join('startest.py')
+        tfile.write(py.code.Source("""if True:
+            from realtest.module import *
+            globals()['mytest0']
+            globals()['mytest1']
+            globals()['MyTest']
+        """))
+        import startest # an exception will be raise if an error occurs
+
+    def test_realmodule_dict_import(self):
+        "Test verifying that accessing the __dict__ invokes the import"
+        import realtest.module
+        assert realtest.module.__isimported__ == False
+        moddict = dir(realtest.module)
+        assert realtest.module.__isimported__ == True
+        assert 'mytest0' in moddict
+        assert 'mytest1' in moddict
+        assert 'MyTest' in moddict
+
+
+#class TestStdHook:
+#    """Tests imports for the standard Python library hook."""
+#
+#    def setup_method(self, *args):
+#        """Unload the test modules before each test."""
+#        module_names = ['py.std.StringIO', 'py.std', 'py']
+#        for modname in module_names:
+#            if modname in sys.modules:
+#                del sys.modules[modname]
+#
+#    def test_std_import_simple(self):
+#        import py
+#        StringIO = py.std.StringIO
+#        assert 'py' in sys.modules
+#        assert 'py.std' in sys.modules
+#        assert 'py.std.StringIO' in sys.modules
+#        assert hasattr(py.std.StringIO, 'StringIO')
+#
+#    def test_std_import0(self):
+#        """Testing 'import py.std.StringIO'."""
+#        import py.std.StringIO
+#        assert 'py' in sys.modules
+#        assert 'py.std' in sys.modules
+#        assert 'py.std.StringIO' in sys.modules
+#        assert hasattr(py.std.StringIO, 'StringIO')
+#
+#    def test_std_import1(self):
+#        """Testing 'from py import std'."""
+#        from py import std
+#        assert 'py' in sys.modules
+#        assert 'py.std' in sys.modules
+#
+#    def test_std_from(self):
+#        """Testing 'from py.std import StringIO'."""
+#        from py.std import StringIO
+#        assert getattr(StringIO, 'StringIO')
+#
+#    def test_std_star(self):
+#        "Test from py.std.string import *"
+#        """Testing 'from test.module import *'."""
+#        tmpdir = py.test.ensuretemp('test_initpkg')
+#        tfile = tmpdir.join('stdstartest.py')
+#        tfile.write(py.code.Source("""if True:
+#            from realtest.module import *
+#            globals()['mytest0']
+#            globals()['mytest1']
+#            globals()['MyTest']
+#        """))
+#        import stdstartest  # an exception will be raise if an error occurs
+
 ##def test_help():
 #    help(std.path)
 #    #assert False



More information about the pytest-commit mailing list