Пример #1
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
Пример #2
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
Пример #3
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'))
Пример #4
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)
Пример #5
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
Пример #6
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
Пример #7
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'))
Пример #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)
Пример #9
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)
Пример #10
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)
Пример #11
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)
Пример #12
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)
Пример #13
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)
Пример #14
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
Пример #15
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
Пример #16
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__)
Пример #17
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)
Пример #18
0
class PathModificationTest(PySpaceTestCase):
    """
    These tests share setup/cleanup behavior of creating a dummy package and
    stuffing some code in it.
    """

    _serialnum = itertools.count().next # used to generate serial numbers for
                                        # package names.

    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


    def _setupSysPath(self):
        assert not self.pathSetUp
        self.pathSetUp = True
        sys.path.append(self.pathExtensionName)


    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)


    def test_underUnderPathAlreadyImported(self):
        """
        Verify that iterModules will honor the __path__ of already-loaded packages.
        """
        self._underUnderPathTest()


    def test_underUnderPathNotAlreadyImported(self):
        """
        Verify that iterModules will honor the __path__ of already-loaded packages.
        """
        self._underUnderPathTest(False)


    test_underUnderPathNotAlreadyImported.todo = (
        "This may be impossible but it sure would be nice.")


    def _listModules(self):
        pkginfo = modules.getModule(self.packageName)
        nfni = [modinfo.name.split(".")[-1] for modinfo in
                pkginfo.iterModules()]
        nfni.sort()
        self.failUnlessEqual(nfni, ['a', 'b', 'c__init__', 'd'])


    def test_listingModules(self):
        """
        Make sure the module list comes back as we expect from iterModules on a
        package, whether zipped or not.
        """
        self._setupSysPath()
        self._listModules()


    def test_listingModulesAlreadyImported(self):
        """
        Make sure the module list comes back as we expect from iterModules on a
        package, whether zipped or not, even if the package has already been
        imported.
        """
        self._setupSysPath()
        namedAny(self.packageName)
        self._listModules()



    def test_moduleAttributes(self):
        """
        Module attributes can be iterated over without executing the code.
        """
        self._setupSysPath()
        modinfo = modules.getModule(self.packageName + ".a")
        attrs = sorted(modinfo.iterAttributes(), key=lambda a: a.name)
        names = sorted(["foo", "doFoo", "Foo"])
        for attr, name in zip(attrs, names):
            self.assertEquals(attr.onObject, modinfo)
            self.assertFalse(attr.isLoaded())
            self.assertEquals(attr.name, modinfo.name + '.' + name)
            self.assertRaises(NotImplementedError, lambda: list(attr.iterAttributes()))


    def test_loadedModuleAttributes(self):
        """
        Module attributes can be iterated over after the module has been loaded.
        """
        self._setupSysPath()
        modinfo = modules.getModule(self.packageName + ".a")
        modinfo.load()
        attrs = sorted([a for a in modinfo.iterAttributes() if '_' not in a.name], key=lambda a: a.name)
        names = sorted(["foo", "doFoo", "Foo"])
        for attr, name in zip(attrs, names):
            self.assertEquals(attr.onObject, modinfo)
            self.assertTrue(attr.isLoaded())
            self.assertEquals(attr.name, modinfo.name + '.' + name)
            if name == "Foo":
                classattrs = [a.name for a in attr.iterAttributes()]
                self.assertIn(modinfo.name + '.Foo.x', classattrs)


    def test_attributeLoading(self):
        """
        Calling .load() on a L{PythonAttribute} loads the module it's a part of and returns the attribute value.
        """
        self._setupSysPath()
        modinfo = modules.getModule(self.packageName + ".a")
        attr = [x for x in modinfo.iterAttributes() if x.name.endswith('foo')][0]

        mod = attr.onObject
        self.assertFalse(attr.isLoaded())
        self.assertFalse(mod.isLoaded())
        val = attr.load()
        self.assertTrue(attr.isLoaded())
        self.assertTrue(mod.isLoaded())
        self.assertEquals(val, 123)
        self.assertEquals(attr.pythonValue, 123)
        self.assertEquals(attr.load(), 123)


    def test_moduleImportNames(self):
        """
        The fully qualified names imported by a module can be inspected.
        """
        self._setupSysPath()
        modinfo = modules.getModule(self.packageName + ".a")
        self.assertEquals(sorted(modinfo.iterImportNames()),
                         sorted(["sys", "os", "datetime",
                                 "twisted.python.reflect",
                                 "twisted.python.filepath",
                                 "twisted.python.components.registerAdapter"]))


    def test_moduleExportDefinedNames(self):
        """
        The exports of a module with no __all__ are all its defined
        names.
        """
        self._setupSysPath()
        modinfo = modules.getModule(self.packageName + ".a")
        self.assertEqual(sorted(modinfo.iterExportNames()),
                         sorted(["foo", "doFoo", "Foo"]))


    def test_moduleExportAll(self):
        """
        If __all__ is defined as a list of string literals, the names
        in it are used as the list of the module's exports.
        """
        self._setupSysPath()
        modinfo = modules.getModule(self.packageName + ".b")
        self.assertEqual(sorted(modinfo.iterExportNames()),
                         sorted(["foo"]))


    def test_exportedImports(self):
        """
        If __all__ mentions imports, they're included in the collection of defined names.
        """
        self._setupSysPath()
        modinfo = modules.getModule(self.packageName + ".d")
        self.assertEqual(sorted([x.name.rsplit('.', 1)[1] for x in
                                 modinfo.iterAttributes()]),
                         sorted(["foo", "registerAdapter", "reflect"]))


    def test_moduleExportProblems(self):
        """
        C{SyntaxError} is raised when doing inspection of module
        exports if __all__ is not a single list of string literals.
        """
        self.packagePath.child("e.py").setContent("__all__ = ['a' + 'b']")
        self.packagePath.child("f.py").setContent("__all__ = ['a']\n__all__ = ['a', 'b']")
        self._setupSysPath()
        modinfo1 = modules.getModule(self.packageName + ".e")
        modinfo2 = modules.getModule(self.packageName + ".f")
        self.assertRaises(SyntaxError, lambda: list(modinfo1.iterExportNames()))
        self.assertRaises(SyntaxError, lambda: list(modinfo2.iterExportNames()))


    if ast is None:
        astMsg = ("Examining unloaded module attributes requires the 'ast'"
                 " module from Python 2.6.")
        test_moduleAttributes.skip = astMsg
        test_moduleImportNames.skip = astMsg
        test_moduleExportAll.skip = astMsg
        test_moduleExportDefinedNames.skip = astMsg
        test_moduleExportProblems.skip = astMsg


    def tearDown(self):
        # Intentionally using 'assert' here, this is not a test assertion, this
        # is just an "oh f**k what is going ON" assertion. -glyph
        if self.pathSetUp:
            HORK = "path cleanup failed: don't be surprised if other tests break"
            assert sys.path.pop() is self.pathExtensionName, HORK+", 1"
            assert self.pathExtensionName not in sys.path, HORK+", 2"
Пример #19
0
class PathModificationTest(PySpaceTestCase):
    """
    These tests share setup/cleanup behavior of creating a dummy package and
    stuffing some code in it.
    """

    _serialnum = itertools.count().next  # used to generate serial numbers for

    # package names.

    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

    def _setupSysPath(self):
        assert not self.pathSetUp
        self.pathSetUp = True
        sys.path.append(self.pathExtensionName)

    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)

    def test_underUnderPathAlreadyImported(self):
        """
        Verify that iterModules will honor the __path__ of already-loaded packages.
        """
        self._underUnderPathTest()

    def test_underUnderPathNotAlreadyImported(self):
        """
        Verify that iterModules will honor the __path__ of already-loaded packages.
        """
        self._underUnderPathTest(False)

    test_underUnderPathNotAlreadyImported.todo = (
        "This may be impossible but it sure would be nice.")

    def _listModules(self):
        pkginfo = modules.getModule(self.packageName)
        nfni = [
            modinfo.name.split(".")[-1] for modinfo in pkginfo.iterModules()
        ]
        nfni.sort()
        self.failUnlessEqual(nfni, ['a', 'b', 'c__init__', 'd'])

    def test_listingModules(self):
        """
        Make sure the module list comes back as we expect from iterModules on a
        package, whether zipped or not.
        """
        self._setupSysPath()
        self._listModules()

    def test_listingModulesAlreadyImported(self):
        """
        Make sure the module list comes back as we expect from iterModules on a
        package, whether zipped or not, even if the package has already been
        imported.
        """
        self._setupSysPath()
        namedAny(self.packageName)
        self._listModules()

    def test_moduleAttributes(self):
        """
        Module attributes can be iterated over without executing the code.
        """
        self._setupSysPath()
        modinfo = modules.getModule(self.packageName + ".a")
        attrs = sorted(modinfo.iterAttributes(), key=lambda a: a.name)
        names = sorted(["foo", "doFoo", "Foo"])
        for attr, name in zip(attrs, names):
            self.assertEquals(attr.onObject, modinfo)
            self.assertFalse(attr.isLoaded())
            self.assertEquals(attr.name, modinfo.name + '.' + name)
            self.assertRaises(NotImplementedError,
                              lambda: list(attr.iterAttributes()))

    def test_loadedModuleAttributes(self):
        """
        Module attributes can be iterated over after the module has been loaded.
        """
        self._setupSysPath()
        modinfo = modules.getModule(self.packageName + ".a")
        modinfo.load()
        attrs = sorted(
            [a for a in modinfo.iterAttributes() if '_' not in a.name],
            key=lambda a: a.name)
        names = sorted(["foo", "doFoo", "Foo"])
        for attr, name in zip(attrs, names):
            self.assertEquals(attr.onObject, modinfo)
            self.assertTrue(attr.isLoaded())
            self.assertEquals(attr.name, modinfo.name + '.' + name)
            if name == "Foo":
                classattrs = [a.name for a in attr.iterAttributes()]
                self.assertIn(modinfo.name + '.Foo.x', classattrs)

    def test_attributeLoading(self):
        """
        Calling .load() on a L{PythonAttribute} loads the module it's a part of and returns the attribute value.
        """
        self._setupSysPath()
        modinfo = modules.getModule(self.packageName + ".a")
        attr = [x for x in modinfo.iterAttributes()
                if x.name.endswith('foo')][0]

        mod = attr.onObject
        self.assertFalse(attr.isLoaded())
        self.assertFalse(mod.isLoaded())
        val = attr.load()
        self.assertTrue(attr.isLoaded())
        self.assertTrue(mod.isLoaded())
        self.assertEquals(val, 123)
        self.assertEquals(attr.pythonValue, 123)
        self.assertEquals(attr.load(), 123)

    def test_moduleImportNames(self):
        """
        The fully qualified names imported by a module can be inspected.
        """
        self._setupSysPath()
        modinfo = modules.getModule(self.packageName + ".a")
        self.assertEquals(
            sorted(modinfo.iterImportNames()),
            sorted([
                "sys", "os", "datetime", "twisted.python.reflect",
                "twisted.python.filepath",
                "twisted.python.components.registerAdapter"
            ]))

    def test_moduleExportDefinedNames(self):
        """
        The exports of a module with no __all__ are all its defined
        names.
        """
        self._setupSysPath()
        modinfo = modules.getModule(self.packageName + ".a")
        self.assertEqual(sorted(modinfo.iterExportNames()),
                         sorted(["foo", "doFoo", "Foo"]))

    def test_moduleExportAll(self):
        """
        If __all__ is defined as a list of string literals, the names
        in it are used as the list of the module's exports.
        """
        self._setupSysPath()
        modinfo = modules.getModule(self.packageName + ".b")
        self.assertEqual(sorted(modinfo.iterExportNames()), sorted(["foo"]))

    def test_exportedImports(self):
        """
        If __all__ mentions imports, they're included in the collection of defined names.
        """
        self._setupSysPath()
        modinfo = modules.getModule(self.packageName + ".d")
        self.assertEqual(
            sorted(
                [x.name.rsplit('.', 1)[1] for x in modinfo.iterAttributes()]),
            sorted(["foo", "registerAdapter", "reflect"]))

    def test_moduleExportProblems(self):
        """
        C{SyntaxError} is raised when doing inspection of module
        exports if __all__ is not a single list of string literals.
        """
        self.packagePath.child("e.py").setContent("__all__ = ['a' + 'b']")
        self.packagePath.child("f.py").setContent(
            "__all__ = ['a']\n__all__ = ['a', 'b']")
        self._setupSysPath()
        modinfo1 = modules.getModule(self.packageName + ".e")
        modinfo2 = modules.getModule(self.packageName + ".f")
        self.assertRaises(SyntaxError,
                          lambda: list(modinfo1.iterExportNames()))
        self.assertRaises(SyntaxError,
                          lambda: list(modinfo2.iterExportNames()))

    if ast is None:
        astMsg = ("Examining unloaded module attributes requires the 'ast'"
                  " module from Python 2.6.")
        test_moduleAttributes.skip = astMsg
        test_moduleImportNames.skip = astMsg
        test_moduleExportAll.skip = astMsg
        test_moduleExportDefinedNames.skip = astMsg
        test_moduleExportProblems.skip = astMsg

    def tearDown(self):
        # Intentionally using 'assert' here, this is not a test assertion, this
        # is just an "oh f**k what is going ON" assertion. -glyph
        if self.pathSetUp:
            HORK = "path cleanup failed: don't be surprised if other tests break"
            assert sys.path.pop() is self.pathExtensionName, HORK + ", 1"
            assert self.pathExtensionName not in sys.path, HORK + ", 2"
Пример #20
0
 def getAccessTime(self):
     """
     Return the archive file's last access time.
     """
     return FilePath(self.zipfile.filename).getAccessTime()
Пример #21
0
 def getStatusChangeTime(self):
     """
     Return the archive file's status change time.
     """
     return FilePath(self.zipfile.filename).getStatusChangeTime()
Пример #22
0
 def getModificationTime(self):
     """
     Return the archive file's modification time.
     """
     return FilePath(self.zipfile.filename).getModificationTime()
Пример #23
0
 def exists(self):
     """
     Returns true if the underlying archive exists.
     """
     return FilePath(self.zipfile.filename).exists()
Пример #24
0
 def mapPath(self, fsPathString):
     return FilePath(fsPathString)