Beispiel #1
0
    def test_alwaysPreferPy(self):
        """
        Verify that .py files will always be preferred to .pyc files, regardless of
        directory listing order.
        """
        mypath = FilePath(self.mktemp())
        mypath.createDirectory()
        pp = modules.PythonPath(sysPath=[mypath.path])
        originalSmartPath = pp._smartPath

        def _evilSmartPath(pathName):
            o = originalSmartPath(pathName)
            originalChildren = o.children

            def evilChildren():
                # normally this order is random; let's make sure it always
                # comes up .pyc-first.
                x = originalChildren()
                x.sort()
                x.reverse()
                return x

            o.children = evilChildren
            return o

        mypath.child("abcd.py").setContent('\n')
        compileall.compile_dir(mypath.path, quiet=True)
        # sanity check
        self.assertEquals(len(mypath.children()), 2)
        pp._smartPath = _evilSmartPath
        self.assertEquals(pp['abcd'].filePath, mypath.child('abcd.py'))
Beispiel #2
0
    def _findEntryPathString(self, modobj):
        """
        Determine where a given Python module object came from by looking at path
        entries.
        """
        topPackageObj = modobj
        while '.' in topPackageObj.__name__:
            topPackageObj = self.moduleDict['.'.join(
                    topPackageObj.__name__.split('.')[:-1])]
        if _isPackagePath(FilePath(topPackageObj.__file__)):
            # if package 'foo' is on sys.path at /a/b/foo, package 'foo's
            # __file__ will be /a/b/foo/__init__.py, and we are looking for
            # /a/b here, the path-entry; so go up two steps.
            rval = dirname(dirname(topPackageObj.__file__))
        else:
            # the module is completely top-level, not within any packages.  The
            # path entry it's on is just its dirname.
            rval = dirname(topPackageObj.__file__)

        # There are probably some awful tricks that an importer could pull
        # which would break this, so let's just make sure... it's a loaded
        # module after all, which means that its path MUST be in
        # path_importer_cache according to PEP 302 -glyph
        if rval not in self.importerCache:
            warnings.warn(
                "%s (for module %s) not in path importer cache "
                "(PEP 302 violation - check your local configuration)." % (
                    rval, modobj.__name__),
                stacklevel=3)

        return rval
Beispiel #3
0
 def pathEntryWithOnePackage(self, pkgname="test_package"):
     """
     Generate a L{FilePath} with one package, named C{pkgname}, on it, and
     return the L{FilePath} of the path entry.
     """
     entry = FilePath(self.mktemp())
     pkg = entry.child("test_package")
     pkg.makedirs()
     pkg.child("__init__.py").setContent("")
     return entry
Beispiel #4
0
    def mapPath(self, fsPathString):
        """
        Map the given FS path to a ZipPath, by looking at the ZipImporter's
        "archive" attribute and using it as our ZipArchive root, then walking
        down into the archive from there.

        @return: a L{zippath.ZipPath} or L{zippath.ZipArchive} instance.
        """
        za = ZipArchive(self.importer.archive)
        myPath = FilePath(self.importer.archive)
        itsPath = FilePath(fsPathString)
        if myPath == itsPath:
            return za
        # This is NOT a general-purpose rule for sys.path or __file__:
        # zipimport specifically uses regular OS path syntax in its pathnames,
        # even though zip files specify that slashes are always the separator,
        # regardless of platform.
        segs = itsPath.segmentsFrom(myPath)
        zp = za
        for seg in segs:
            zp = zp.child(seg)
        return zp
Beispiel #5
0
 def _underUnderPathTest(self, doImport=True):
     moddir2 = self.mktemp()
     fpmd = FilePath(moddir2)
     fpmd.createDirectory()
     fpmd.child("foozle.py").setContent("x = 123\n")
     self.packagePath.child("__init__.py").setContent(
         "__path__.append(%r)\n" % (moddir2, ))
     # Cut here
     self._setupSysPath()
     modinfo = modules.getModule(self.packageName)
     self.assertEquals(
         self.findByIteration(self.packageName + ".foozle",
                              modinfo,
                              importPackages=doImport), modinfo['foozle'])
     self.assertEquals(modinfo['foozle'].load().x, 123)
Beispiel #6
0
    def setUp(self):
        self.pathExtensionName = self.mktemp()
        self.pathExtension = FilePath(self.pathExtensionName)
        self.pathExtension.createDirectory()
        self.packageName = "pyspacetests%d" % (self._serialnum(), )
        self.packagePath = self.pathExtension.child(self.packageName)
        self.packagePath.createDirectory()
        self.packagePath.child("__init__.py").setContent("")
        self.packagePath.child("a.py").setContent(sampleModuleContents)
        self.packagePath.child("b.py").setContent(
            sampleModuleWithExportsContents)
        self.packagePath.child("c__init__.py").setContent("")
        self.packagePath.child("d.py").setContent(
            sampleModuleWithExportedImportsContents)

        self.pathSetUp = False
Beispiel #7
0
 def test_inconsistentImporterCache(self):
     """
     If the path a module loaded with L{PythonPath.__getitem__} is not
     present in the path importer cache, a warning is emitted, but the
     L{PythonModule} is returned as usual.
     """
     space = modules.PythonPath([], sys.modules, [], {})
     thisModule = space[__name__]
     warnings = self.flushWarnings([self.test_inconsistentImporterCache])
     self.assertEquals(warnings[0]['category'], UserWarning)
     self.assertEquals(
         warnings[0]['message'],
         FilePath(modules.__file__).parent().dirname() + " (for module " +
         __name__ + ") not in path importer cache "
         "(PEP 302 violation - check your local configuration).")
     self.assertEquals(len(warnings), 1)
     self.assertEquals(thisModule.name, __name__)
Beispiel #8
0
    def test_nonDirectoryPaths(self):
        """
        Verify that L{modules.walkModules} ignores entries in sys.path which
        refer to regular files in the filesystem.
        """
        existentPath = self.pathEntryWithOnePackage()

        nonDirectoryPath = FilePath(self.mktemp())
        self.failIf(nonDirectoryPath.exists())
        nonDirectoryPath.setContent("zip file or whatever\n")

        self.replaceSysPath([existentPath.path])

        beforeModules = list(modules.walkModules())
        sys.path.append(nonDirectoryPath.path)
        afterModules = list(modules.walkModules())

        self.assertEquals(beforeModules, afterModules)
Beispiel #9
0
    def test_nonexistentPaths(self):
        """
        Verify that L{modules.walkModules} ignores entries in sys.path which
        do not exist in the filesystem.
        """
        existentPath = self.pathEntryWithOnePackage()

        nonexistentPath = FilePath(self.mktemp())
        self.failIf(nonexistentPath.exists())

        self.replaceSysPath([existentPath.path])

        expected = [modules.getModule("test_package")]

        beforeModules = list(modules.walkModules())
        sys.path.append(nonexistentPath.path)
        afterModules = list(modules.walkModules())

        self.assertEquals(beforeModules, expected)
        self.assertEquals(afterModules, expected)
Beispiel #10
0
 def test_packageMissingPath(self):
     """
     A package can delete its __path__ for some reasons,
     C{modules.PythonPath} should be able to deal with it.
     """
     mypath = FilePath(self.mktemp())
     mypath.createDirectory()
     pp = modules.PythonPath(sysPath=[mypath.path])
     subpath = mypath.child("abcd")
     subpath.createDirectory()
     subpath.child("__init__.py").setContent('del __path__\n')
     sys.path.append(mypath.path)
     import abcd
     try:
         l = list(pp.walkModules())
         self.assertEquals(len(l), 1)
         self.assertEquals(l[0].name, 'abcd')
     finally:
         del abcd
         del sys.modules['abcd']
         sys.path.remove(mypath.path)
Beispiel #11
0
 def getStatusChangeTime(self):
     """
     Return the archive file's status change time.
     """
     return FilePath(self.zipfile.filename).getStatusChangeTime()
Beispiel #12
0
 def getModificationTime(self):
     """
     Return the archive file's modification time.
     """
     return FilePath(self.zipfile.filename).getModificationTime()
Beispiel #13
0
 def getAccessTime(self):
     """
     Return the archive file's last access time.
     """
     return FilePath(self.zipfile.filename).getAccessTime()
Beispiel #14
0
 def exists(self):
     """
     Returns true if the underlying archive exists.
     """
     return FilePath(self.zipfile.filename).exists()
Beispiel #15
0
 def mapPath(self, fsPathString):
     return FilePath(fsPathString)