コード例 #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 = list(originalChildren())
                x.sort()
                x.reverse()
                return x

            o.children = evilChildren
            return o

        mypath.child("abcd.py").setContent(b"\n")
        compileall.compile_dir(mypath.path, quiet=True)
        # sanity check
        self.assertEqual(len(list(mypath.children())), 2)
        pp._smartPath = _evilSmartPath
        self.assertEqual(pp["abcd"].filePath, mypath.child("abcd.py"))
コード例 #2
0
 def test_doesntContainModule(self):
     """
     L{PythonPath} implements the C{in} operator so that when it is the
     right-hand argument and the name of a module which does not exist on
     that L{PythonPath} is the left-hand argument, the result is C{False}.
     """
     thePath = modules.PythonPath()
     self.assertNotIn("bogusModule", thePath)
コード例 #3
0
 def test_containsModule(self):
     """
     L{PythonPath} implements the C{in} operator so that when it is the
     right-hand argument and the name of a module which exists on that
     L{PythonPath} is the left-hand argument, the result is C{True}.
     """
     thePath = modules.PythonPath()
     self.assertIn("os", thePath)
コード例 #4
0
ファイル: test_modules.py プロジェクト: MayuraVerma/Kannada
 def test_unimportablePackageGetItem(self):
     """
     If a package has been explicitly forbidden from importing by setting a
     C{None} key in sys.modules under its name,
     L{modules.PythonPath.__getitem__} should still be able to retrieve an
     unloaded L{modules.PythonModule} for that package.
     """
     shouldNotLoad = []
     path = modules.PythonPath(sysPath=[self.pathEntryWithOnePackage().path],
                               moduleLoader=shouldNotLoad.append,
                               importerCache={},
                               sysPathHooks={},
                               moduleDict={'test_package': None})
     self.assertEquals(shouldNotLoad, [])
     self.assertEquals(path['test_package'].isLoaded(), False)
コード例 #5
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.assertEqual(warnings[0]['category'], UserWarning)
     self.assertEqual(
         warnings[0]['message'],
         FilePath(twisted.__file__).parent().dirname() + " (for module " +
         __name__ + ") not in path importer cache "
         "(PEP 302 violation - check your local configuration).")
     self.assertEqual(len(warnings), 1)
     self.assertEqual(thisModule.name, __name__)
コード例 #6
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(b"del __path__\n")
     sys.path.append(mypath.path)
     __import__("abcd")
     try:
         l = list(pp.walkModules())
         self.assertEqual(len(l), 1)
         self.assertEqual(l[0].name, "abcd")
     finally:
         del sys.modules["abcd"]
         sys.path.remove(mypath.path)
コード例 #7
0
ファイル: test_modules.py プロジェクト: MayuraVerma/Kannada
    def test_unhandledImporter(self):
        """
        Make sure that the behavior when encountering an unknown importer
        type is not catastrophic failure.
        """
        class SecretImporter(object):
            pass

        def hook(name):
            return SecretImporter()

        syspath = ['example/path']
        sysmodules = {}
        syshooks = [hook]
        syscache = {}
        def sysloader(name):
            return None
        space = modules.PythonPath(
            syspath, sysmodules, syshooks, syscache, sysloader)
        entries = list(space.iterEntries())
        self.assertEquals(len(entries), 1)
        self.assertRaises(KeyError, lambda: entries[0]['module'])
コード例 #8
0
import sys

# Override theSystemPath so it throws KeyError on gi.pygtkcompat:
from twisted.python import modules

modules.theSystemPath = modules.PythonPath([], moduleDict={})

# Now, when we import gireactor it shouldn't use pygtkcompat, and should
# instead prevent gobject from being importable:
from twisted.internet import gireactor
for name in gireactor._PYGTK_MODULES:
    if sys.modules[name] is not None:
        sys.stdout.write("failure, sys.modules[%r] is %r, instead of None" %
                         (name, sys.modules["gobject"]))
        sys.exit(0)

try:
    import gobject
except ImportError:
    sys.stdout.write("success")
else:
    sys.stdout.write("failure: %s was imported" % (gobject.__path__, ))