[py-svn] r10439 - in py/branch/py-collect: documentation misc/testing path/local path/local/testing test

hpk at codespeak.net hpk at codespeak.net
Fri Apr 8 18:07:45 CEST 2005


Author: hpk
Date: Fri Apr  8 18:07:45 2005
New Revision: 10439

Modified:
   py/branch/py-collect/documentation/rest_test.py
   py/branch/py-collect/misc/testing/test_initpkg.py
   py/branch/py-collect/path/local/local.py
   py/branch/py-collect/path/local/testing/test_local.py
   py/branch/py-collect/test/config.py
Log:
- extpy() usage is gone from py.test 

- transformed a few places to use pyimport() instead of
  getpymodule() 

- extended pyimport() to accept custom module names 
  i which case a pseudo-import via execfile is performed. 



Modified: py/branch/py-collect/documentation/rest_test.py
==============================================================================
--- py/branch/py-collect/documentation/rest_test.py	(original)
+++ py/branch/py-collect/documentation/rest_test.py	Fri Apr  8 18:07:45 2005
@@ -3,7 +3,7 @@
 import py
 
 pydir = py.magic.autopath(vars(py)).dirpath()
-rest = pydir.join('bin', 'py.rest').getpymodule()
+rest = pydir.join('bin', 'py.rest').pyimport('py_rest')
 docdir = py.path.svnwc(pydir.join('documentation'))
 
 def restcheck(path):

Modified: py/branch/py-collect/misc/testing/test_initpkg.py
==============================================================================
--- py/branch/py-collect/misc/testing/test_initpkg.py	(original)
+++ py/branch/py-collect/misc/testing/test_initpkg.py	Fri Apr  8 18:07:45 2005
@@ -52,7 +52,7 @@
                 yield check_import, modpath 
 
 def check_import(modpath): 
-    #print "checking import", modpath
+    print "checking import", modpath
     assert __import__(modpath) 
 
 def test_shahexdigest():

Modified: py/branch/py-collect/path/local/local.py
==============================================================================
--- py/branch/py-collect/path/local/local.py	(original)
+++ py/branch/py-collect/path/local/local.py	Fri Apr  8 18:07:45 2005
@@ -321,7 +321,7 @@
         """ return string representation of the Path. """
         return self.strpath
 
-    def pyimport(self, name=None, ensuresyspath=True): 
+    def pyimport(self, modname=None, ensuresyspath=True): 
         """ return the path as an imported python module. 
             if name is None, look for the containing package 
             and construct an according module name. 
@@ -331,29 +331,47 @@
         """ 
         if not self.check(): 
             raise py.error.ENOENT(self) 
-        #assert self.check() 
-        pkgpath = None
         #print "trying to import", self
-        for p in self.parts(reverse=True)[1:]: 
-            if p.join('__init__.py').check(): 
-                pkgpath = p 
-                continue 
-            if ensuresyspath: 
-                #print "inserting into sys.path", p
-                py.std.sys.path.insert(0, str(p)) 
-            if pkgpath is not None: 
-                pkg = __import__(pkgpath.basename, None, None, [])
-                assert py.path.local(pkg.__file__).relto(pkgpath) 
-                if hasattr(pkg, '__package__'): 
-                    return pkg.__package__.importfrompath(self) 
-                names = self.new(ext='').relto(pkgpath.dirpath())
-                names = names.split(self.sep) 
-                dottedname = ".".join(names) 
-                return __import__(dottedname, None, None, ['something'])
-            else: 
-                #print "sys.path[0] is", sys.path[0]
-                return __import__(self.purebasename) 
-        raise ImportError("cannot import from path %s" %(self,))
+        pkgpath = None
+        if modname is None: 
+            for parent in self.parts(reverse=True)[1:]: 
+                if parent.join('__init__.py').check(): 
+                    pkgpath = parent 
+                    continue 
+                if ensuresyspath: 
+                    #print "inserting into sys.path", parent
+                    py.std.sys.path.insert(0, str(parent)) 
+                if pkgpath is not None: 
+                    pkg = __import__(pkgpath.basename, None, None, [])
+                    assert py.path.local(pkg.__file__).relto(pkgpath) 
+                    if hasattr(pkg, '__package__'): 
+                        return pkg.__package__.importfrompath(self) 
+                    names = self.new(ext='').relto(pkgpath.dirpath())
+                    names = names.split(self.sep) 
+                    modname = ".".join(names) 
+                else: 
+                    #print "sys.path[0] is", sys.path[0]
+                    modname = self.purebasename 
+                try: 
+                    return __import__(modname, None, None, ['something']) 
+                except ImportError: 
+                    if modname in sys.modules: 
+                        del sys.modules[modname]
+            raise ImportError("cannot import from path %s" %(self,))
+        else: 
+            try: 
+                return sys.modules[modname]
+            except KeyError: 
+                # we have a custom modname, do a pseudo-import 
+                mod = py.std.new.module(modname)
+                mod.__file__ = str(self) 
+                sys.modules[modname] = mod
+                try: 
+                    execfile(str(self), mod.__dict__) 
+                except: 
+                    del sys.modules[modname] 
+                    raise 
+                return mod
 
     def getpymodule(self):
         if self.ext != '.c':

Modified: py/branch/py-collect/path/local/testing/test_local.py
==============================================================================
--- py/branch/py-collect/path/local/testing/test_local.py	(original)
+++ py/branch/py-collect/path/local/testing/test_local.py	Fri Apr  8 18:07:45 2005
@@ -209,6 +209,11 @@
         assert obj.x == 42
         assert obj.__name__ == 'execfile' 
 
+    def test_pyimport_execfile_different_name(self):
+        obj = self.root.join('execfile.py').pyimport(modname="0x.y.z")
+        assert obj.x == 42
+        assert obj.__name__ == '0x.y.z' 
+
     def test_pyimport_a(self):
         otherdir = self.root.join('otherdir')
         mod = otherdir.join('a.py').pyimport()

Modified: py/branch/py-collect/test/config.py
==============================================================================
--- py/branch/py-collect/test/config.py	(original)
+++ py/branch/py-collect/test/config.py	Fri Apr  8 18:07:45 2005
@@ -4,7 +4,6 @@
 from py.__impl__.test.tool import optparse
 
 defaultconfig = py.magic.autopath().dirpath('defaultconfig.py')
-defaultconfig = py.path.extpy(defaultconfig)
 dummy = object()
 
 #
@@ -26,16 +25,14 @@
     """ return config value 'name' from the first conftest file found 
         from traversing up from the given 'path'
     """
-    for p in path.parts(reverse=True):
-        x = p.join(configbasename)
-        if x.check(file=1):
-            extpy = py.path.extpy(x, name)
-            if extpy.check():
-                return extpy.resolve()
+    configpaths = [p.join(configbasename) for p in path.parts(reverse=True)]
+    configpaths = [p for p in configpaths if p.check(file=1)]
     if trydefaultconfig: 
-        extpy = defaultconfig.join(name)
-        if extpy.check():
-            return extpy.resolve()
+        configpaths.append(defaultconfig) 
+    for p in configpaths: 
+        mod = p.pyimport() 
+        if hasattr(mod, name): 
+            return getattr(mod, name) 
     if default is dummy: 
         raise ValueError("could not find config value %r" % name)
     return default 
@@ -116,54 +113,60 @@
         option.executable = exe
 
 def makeparser(configpaths):
-    global _lastoptions, _option
-    # trigger loading config options
+    # trigger loading conftest files which might add options! 
     for p in configpaths: 
-        p.resolve() 
-    defaultconfig.join('adddefaultoptions').resolve()() 
+        if not p.dirpath('__init__.py').check(file=1): 
+            # hack: we don't want a "globally" imported 
+            #       conftest, prone to errors ... 
+            modname = str(p).replace('.', p.sep) 
+            p.pyimport(modname=modname) 
+        else: 
+            p.pyimport() 
+    defaultconfig.pyimport().adddefaultoptions() 
     parser = optparse.OptionParser()
-    for groupname, groupoptions in _lastoptions: 
+    for groupname, groupoptions in optionstate.lastoptions: 
         optgroup = optparse.OptionGroup(parser, groupname)
         optgroup.add_options(groupoptions)
         parser.add_option_group(optgroup)
     # each time we make a parser which incorporates 
     # all the cmdline options that users may have provided 
     # we want to start over 
-    parser._pytestvalues = _option 
-    _lastoptions = []
-    _option = optparse.Values() 
+    parser._pytestvalues = optionstate.option 
+    optionstate.reset() 
     return parser 
 
-# XXX _lastoptions holds all options that are added from conftest
-# py.test.addoptions() invocations.  This "global state"
+class optionstate: 
+    lastoptions = []
+    option = optparse.Values() 
+
+    def reset(cls): 
+        cls.lastoptions[:] = []
+        cls.option = optparse.Values() 
+    reset = classmethod(reset)
+
+# XXX optionstate.lastoptions holds all options that are added from 
+# conftest's py.test.addoptions() invocations.  This "global state"
 # manipulation is not completely nice but how else could we allow 
 # test projects to add cmdline options and provide them access to 
 # the resulting values?  (apart from exposing session initialisation 
 # some more which i really don't want to do) 
 
-_lastoptions = []
-_option = optparse.Values()
-
 def addoptions(groupname, *specs): 
     """ add a named group of options to the current testing session. 
         This function gets invoked during testing session initialization. 
     """ 
-    global _lastoptions 
-    _lastoptions.append((groupname, specs))
-    return _option 
+    optionstate.lastoptions.append((groupname, specs))
+    return optionstate.option 
 
 def findconfigpaths(anchors):
     """ return test configuration paths. """ 
-    configpaths = []
     d = {}
     for anchor in anchors:
         for p in anchor.parts():
             x = p.join(configbasename)
             if x.check(file=1):
-                extpy = py.path.extpy(x)
-                if extpy not in d:
-                    configpaths.append(extpy)
-                    d[extpy] = True
+                d[x] = True 
+    configpaths = d.keys() 
     configpaths.sort(lambda x,y: cmp(len(str(x)), len(str(y))))
     return configpaths 
 



More information about the pytest-commit mailing list