コード例 #1
0
ファイル: PluginManager.py プロジェクト: gdumee/LISA
    def getPluginMethods(cls, plugin_name = None):
        # Get plugin by name or pk
        if plugin_name:
            plugin_list = Plugin.objects(name = plugin_name)
        else:
            plugin_list = Plugin.objects

        # Parse plugins
        listallmethods = []
        for plugin in plugin_list:
            plugininstance = namedAny('.'.join(('lisa.plugins', str(plugin.name), 'modules', str(plugin.name).lower(), str(plugin.name))))()
            listpluginmethods = []
            for m in inspect.getmembers(plugininstance, predicate = inspect.ismethod):
                if not "__init__" in m and not m.startswith("_"):
                    listpluginmethods.append(m[0])
            listallmethods.append({'plugin': plugin.name, 'methods': listpluginmethods})

        # Parse core plugins
        for f in os.listdir(os.path.normpath(server_path + '/core')):
            fileName, fileExtension = os.path.splitext(f)
            if os.path.isfile(os.path.join(os.path.normpath(server_path + '/core'), f)) and not f.startswith('__init__') and fileExtension != '.pyc':
                coreinstance = namedAny('.'.join(('lisa.server.core', str(fileName).lower(), str(fileName).capitalize())))()
                listcoremethods = []
                for m in inspect.getmembers(coreinstance, predicate = inspect.ismethod):
                    #init shouldn't be listed in methods and _ is for translation
                    if not "__init__" in m and not m.startswith("_"):
                        listcoremethods.append(m[0])
                listallmethods.append({'core': fileName, 'methods': listcoremethods})

        log.msg(listallmethods)
        return listallmethods
コード例 #2
0
ファイル: test_twisted.py プロジェクト: Architektor/PySnip
 def test_noversionpy(self):
     """
     Former subprojects no longer have an importable C{_version.py}.
     """
     with self.assertRaises(AttributeError):
         reflect.namedAny(
             "twisted.{}._version".format(self.subproject))
コード例 #3
0
        def start():
            node_to_instance = {
                u"client": lambda: maybeDeferred(namedAny("allmydata.client.create_client"), self.basedir),
                u"introducer": lambda: maybeDeferred(namedAny("allmydata.introducer.server.create_introducer"), self.basedir),
                u"stats-gatherer": lambda: maybeDeferred(namedAny("allmydata.stats.StatsGathererService"), read_config(self.basedir, None), self.basedir, verbose=True),
                u"key-generator": key_generator_removed,
            }

            try:
                service_factory = node_to_instance[self.nodetype]
            except KeyError:
                raise ValueError("unknown nodetype %s" % self.nodetype)

            def handle_config_error(fail):
                fail.trap(UnknownConfigError)
                sys.stderr.write("\nConfiguration error:\n{}\n\n".format(fail.value))
                reactor.stop()
                return

            d = service_factory()

            def created(srv):
                srv.setServiceParent(self.parent)
            d.addCallback(created)
            d.addErrback(handle_config_error)
            d.addBoth(self._call_hook, 'running')
            return d
コード例 #4
0
 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()
コード例 #5
0
 def test_colors(self):
     """
     The L{insults.colors} module is deprecated
     """
     namedAny('twisted.conch.insults.colors')
     self.ensureDeprecated("twisted.conch.insults.colors was deprecated "
                           "in Twisted 10.1.0: Please use "
                           "twisted.conch.insults.helper instead.")
コード例 #6
0
 def test_client(self):
     """
     The L{insults.client} module is deprecated
     """
     namedAny('twisted.conch.insults.client')
     self.ensureDeprecated("twisted.conch.insults.client was deprecated "
                           "in Twisted 10.1.0: Please use "
                           "twisted.conch.insults.insults instead.")
コード例 #7
0
def load(S):
    for line in S.split('\n'):
        line = line.strip()
        if line and not line.startswith('#'):
            (a, o , i) = line.split()
            a = reflect.namedAny(a)
            o = reflect.namedAny(o)
            i = reflect.namedAny(i)
            compy.registerAdapter(a,o,i)
コード例 #8
0
ファイル: test_basic.py プロジェクト: 12019/OpenWrt_Luci_Lua
 def test_NMEADeprecation(self):
     """
     L{twisted.protocols.gps.nmea} is deprecated since Twisted 15.2.
     """
     reflect.namedAny("twisted.protocols.gps.nmea")
     warningsShown = self.flushWarnings()
     self.assertEqual(1, len(warningsShown))
     self.assertEqual(
         "twisted.protocols.gps was deprecated in Twisted 15.2.0: "
         "Use twisted.positioning instead.", warningsShown[0]['message'])
コード例 #9
0
 def test_loreDeprecation(self):
     """
     L{twisted.lore} is deprecated since Twisted 14.0.
     """
     reflect.namedAny("twisted.lore")
     warningsShown = self.flushWarnings()
     self.assertEqual(1, len(warningsShown))
     self.assertEqual(
         "twisted.lore was deprecated in Twisted 14.0.0: "
         "Use Sphinx instead.", warningsShown[0]['message'])
コード例 #10
0
 def test_MiceDeprecation(self):
     """
     L{twisted.protocols.mice} is deprecated since Twisted 16.0.
     """
     reflect.namedAny("twisted.protocols.mice")
     warningsShown = self.flushWarnings()
     self.assertEqual(1, len(warningsShown))
     self.assertEqual(
         "twisted.protocols.mice was deprecated in Twisted 16.0.0: "
         "There is no replacement for this module.",
         warningsShown[0]['message'])
コード例 #11
0
ファイル: source.py プロジェクト: lmacken/moksha
 def update_params(self, d):
     super(SourceCodeWidget, self).update_params(d)
     title = d.widget.__class__.__name__
     if not d.source:
         try:
             d.widget = moksha.get_widget(d.widget)
         except Exception, e:
             d.widget = namedAny(d.widget)
         if d.module:
             obj = namedAny(d.widget.__module__)
         else:
             obj = d.widget.__class__
         d.source = inspect.getsource(obj)
コード例 #12
0
ファイル: tahoe_daemonize.py プロジェクト: warner/tahoe-lafs
        def start():
            node_to_instance = {
                u"client": lambda: namedAny("allmydata.client.create_client")(self.basedir),
                u"introducer": lambda: namedAny("allmydata.introducer.server.create_introducer")(self.basedir),
                u"stats-gatherer": lambda: namedAny("allmydata.stats.StatsGathererService")(read_config(self.basedir, None), self.basedir, verbose=True),
                u"key-generator": key_generator_removed,
            }

            try:
                service_factory = node_to_instance[self.nodetype]
            except KeyError:
                raise ValueError("unknown nodetype %s" % self.nodetype)

            srv = service_factory()
            srv.setServiceParent(self.parent)
コード例 #13
0
ファイル: rpcproxy.py プロジェクト: wgnet/twoost
def make_loop_proxy(params):
    target = params.get('target')
    timeout = params.get('timeout', 60.0)
    if isinstance(target, basestring):
        target = reflect.namedAny(target)
    logger.debug("create loop-rpc-proxy, target is %r", target)
    return LoopRPCProxy(target=target, timeout=timeout)
コード例 #14
0
    def test_newStyleClassesOnly(self):
        """
        Test that C{self.module} has no old-style classes in it.
        """
        try:
            module = namedAny(self.module)
        except ImportError as e:
            raise unittest.SkipTest("Not importable: {}".format(e))

        oldStyleClasses = []

        for name, val in inspect.getmembers(module):
            if hasattr(val, "__module__") \
               and val.__module__ == self.module:
                if isinstance(val, types.ClassType):
                    oldStyleClasses.append(fullyQualifiedName(val))

        if oldStyleClasses:

            self.todo = "Not all classes are made new-style yet. See #8243."

            for x in forbiddenModules:
                if self.module.startswith(x):
                    delattr(self, "todo")

            raise unittest.FailTest(
                "Old-style classes in {module}: {val}".format(
                    module=self.module,
                    val=", ".join(oldStyleClasses)))
コード例 #15
0
ファイル: main.py プロジェクト: jakebarnwell/PythonGenerator
 def render_examples(self, ctx, data):
     for name in examples:
         cls = reflect.namedAny(name)
         yield T.div(class_='example')[
             T.h1[T.a(href=url.here.child(name))[cls.title]],
             T.p[cls.description],
             ]
コード例 #16
0
    def getResults(self):
        """ return resultset
		"""
        if self.isValidRequest():
            if self.dataChanged == False:
                self.results = None
                try:
                    self.modelClass = namedAny(self.requestObj["sourcetable"])
                    self.modelObj = self.modelClass()
                    self.searchstring = self.requestObj["searchstring"]
                    colName = self.requestObj["column"]
                    attr = getattr(self.modelObj, colName)
                    op = self.requestObj["operation"]
                    print "Operation = ", op, "colName = ", colName.strip(), "sourcestring = ", self.searchstring
                    if op == "in":
                        lookup = "%s__contains" % colName.strip()
                    elif op == "eq":
                        lookup = "%s__exact" % colName.strip()
                    elif op == "sw":
                        lookup = "%s__startswith" % colName.strip()
                    elif op == "ew":
                        lookup = "%s__endswith" % colName.strip()

                    query = {lookup: self.searchstring}
                    self.results = list(self.modelClass.objects.filter(**query).values())
                except:
                    e = sys.exc_info()[0]
                    print "Exception in AutocompleteRequest.getResults():", e
                    pass
        else:
            self.results = None
        self.dataChanged = True
        return self.results
コード例 #17
0
ファイル: utils.py プロジェクト: hybridlogic/txHybridCluster
def tryImports(*names):
    for name in names:
        try:
            return namedAny(name)
        except ObjectNotFound:
            pass
    raise
コード例 #18
0
ファイル: runner.py プロジェクト: shelmesky/twisted
def filenameToModule(fn):
    """
    Given a filename, do whatever possible to return a module object matching
    that file.

    If the file in question is a module in Python path, properly import and
    return that module. Otherwise, load the source manually.

    @param fn: A filename.
    @return: A module object.
    @raise ValueError: If C{fn} does not exist.
    """
    if not os.path.exists(fn):
        raise ValueError("%r doesn't exist" % (fn,))
    try:
        ret = reflect.namedAny(reflect.filenameToModuleName(fn))
    except (ValueError, AttributeError):
        # Couldn't find module.  The file 'fn' is not in PYTHONPATH
        return _importFromFile(fn)
    # ensure that the loaded module matches the file
    retFile = os.path.splitext(ret.__file__)[0] + '.py'
    # not all platforms (e.g. win32) have os.path.samefile
    same = getattr(os.path, 'samefile', samefile)
    if os.path.isfile(fn) and not same(fn, retFile):
        del sys.modules[ret.__name__]
        ret = _importFromFile(fn)
    return ret
コード例 #19
0
ファイル: _base.py プロジェクト: BackupTheBerlios/nufox-svn
def getExamples():
    liveChildren = {}
    for mod in os.listdir(util.sibpath(__file__, ".")):
        if mod.startswith("_") or not mod.endswith(".py"):
            continue
        moduleId = mod[:-3]
        print "Found example 'examples.%s.example'" % (moduleId,)
        example = reflect.namedAny("examples.%s.Example" % (moduleId,))

        class Viewer(ExampleViewer):
            pass

        example.moduleId = moduleId
        doc = unicode(example.__doc__)
        title = getattr(example, "title", None)
        if not title:
            if doc:
                # Take the first line of the docstring.
                title = u"".join(doc.split(u"\n")[:1])
            else:
                title = splitNerdyCaps(moduleId)
        example.title = title
        Viewer.example = example
        Viewer.liveChildren = {"example": example}
        liveChildren[moduleId] = Viewer
    return liveChildren
コード例 #20
0
    def makeService(self, options):
        srv = service.MultiService()
        s = None

        if options["app"]:
            app = reflect.namedAny(options["app"])
        else:
            app = App

        # http
        s = internet.TCPServer(options["port"], app(options),
                               interface=options["listen"])
        s.setServiceParent(srv)

        # https
        if options["use-ssl"]:
            if ssl_support:
                s = internet.SSLServer(options["ssl-port"], app(options),
                                       ssl.DefaultOpenSSLContextFactory(
                                       options["ssl-key"],
                                       options["ssl-cert"]),
                                       interface=options["ssl-listen"])
                s.setServiceParent(srv)
            else:
                print("SSL is not supported. Please install PyOpenSSL.")

        if s is None:
            print("Nothing to do. Try --help")
            sys.exit(1)

        return srv
コード例 #21
0
ファイル: djangorequest.py プロジェクト: psiCode/shoutserver
	def isValidSelect(self, selects):
		"""this method checks the validity of the selects section of the JSON request
			1. check if the selects: section contains all 3 sub-sections - 'name', 'label', and 'cols'
			2. for each select section
				2.1 Check if Twisted can load a model named 'name'
				2.2 Make sure the 'label' assigned to each 'name' is unique
				2.3 Make sure that each column names in 'cols' exists in 'name'

		"""

		returnVal = True
		for select in selects:
			if "name" not in select.keys() or "label" not in select.keys() or "cols" not in select.keys():
		 		print "selects: should have 'name', 'label' and 'cols' sections"
				returnVal = False
			else:
				name = select["name"]
				label = select["label"]
				cols = select["cols"]
				try:
					modelClass = namedAny(name)
					if label not in self.namesLabels.values():
						self.namesLabels[name.strip()] = label.strip()
						self.namesCols[label.strip()] = cols
						for fieldname in cols:
							if not hasattr(modelClass(), fieldname.strip()):
								returnVal = False
								print name, " doesn't have a field named ", fieldname.strip(), "'"
					else:
						print "Error! label '", label.strip(), "' reused"
						returnVal = False
				except:
					print "Could not load ", name
					returnVal = False
		return returnVal
コード例 #22
0
 def test_namedAnyClassLookup(self):
     """
     L{namedAny} should return the class object for the name it is passed.
     """
     self.assertIs(
         reflect.namedAny("twisted.test.test_reflect.Summer"),
         Summer)
コード例 #23
0
ファイル: runner.py プロジェクト: shelmesky/twisted
    def loadDoctests(self, module):
        """
        Return a suite of tests for all the doctests defined in C{module}.

        @param module: A module object or a module name.
        """
        if isinstance(module, str):
            try:
                module = reflect.namedAny(module)
            except:
                return ErrorHolder(module, failure.Failure())
        if not inspect.ismodule(module):
            warnings.warn("trial only supports doctesting modules")
            return
        extraArgs = {}
        if sys.version_info > (2, 4):
            # Work around Python issue2604: DocTestCase.tearDown clobbers globs
            def saveGlobals(test):
                """
                Save C{test.globs} and replace it with a copy so that if
                necessary, the original will be available for the next test
                run.
                """
                test._savedGlobals = getattr(test, '_savedGlobals', test.globs)
                test.globs = test._savedGlobals.copy()
            extraArgs['setUp'] = saveGlobals
        return doctest.DocTestSuite(module, **extraArgs)
コード例 #24
0
 def test_namedAnyModuleLookup(self):
     """
     L{namedAny} should return the module object for the name it is passed.
     """
     from twisted.python import monkey
     self.assertIs(
         reflect.namedAny("twisted.python.monkey"), monkey)
コード例 #25
0
ファイル: db.py プロジェクト: hooplab/piped-contrib-database
    def __init__(self, profile_name, engine, events=None, checkout=None, checkin=None, ping_interval=10.0, retry_interval=5.0):
        super(EngineManager, self).__init__()
        self.profile_name = profile_name
        self.ping_interval = ping_interval
        self.retry_interval = retry_interval

        self.events = {} if events is None else events
        self.checkout = [] if checkout is None else checkout
        self.checkin = [] if checkin is None else checkin

        self.engine_configuration = copy.deepcopy(engine)
        self._fail_if_configuration_is_invalid()
        self.engine_configuration.setdefault('proxy', self.proxy_factory(self))

        if 'poolclass' in self.engine_configuration:
            self.engine_configuration['poolclass'] = reflect.namedAny(self.engine_configuration['poolclass'])

        self.is_connected = False

        self.engine = sa.engine_from_config(self.engine_configuration, prefix='')
        self._bind_events()

        self.on_connection_established = event.Event()
        self.on_connection_lost = event.Event()
        self.on_connection_failed = event.Event()
コード例 #26
0
ファイル: trial.py プロジェクト: pwarren/AGDeviceControl
    def _tryNamedAny(self, arg):
        try:
            try:
                n = reflect.namedAny(arg)
            except ValueError, ve:
                if ve.args == ('Empty module name',):
                    raise ArgumentError
                else:
                    raise
        except ArgumentError:
            raise
        except:
            f = failure.Failure()
            f.printTraceback()
            self['_couldNotImport'][arg] = f
            return

        # okay, we can use named any to import it, so now wtf is it?
        if inspect.ismodule(n):
            filename = os.path.basename(n.__file__)
            filename = os.path.splitext(filename)[0]
            if filename == '__init__':
                self['packages'].append(n)
            else:
                self['modules'].append(n)
        elif inspect.isclass(n):
            self['testcases'].append(n)
        elif inspect.ismethod(n):
            self['methods'].append(n)
        else:
            raise ArgumentError, "could not figure out how to use %s" % arg
コード例 #27
0
ファイル: tricks.py プロジェクト: dreid/loki
 def __init__(self, regex, probability, trick, kwargs):
     self.regexStr = regex
     self._regex = re.compile(regex)
     self.probability = probability
     self.trickStr = trick
     self._trick = namedAny(trick)
     self.kwargs = kwargs
コード例 #28
0
ファイル: hyperblurb.py プロジェクト: pombredanne/hyperbola
    def _getChildPerms(self, childAuthor):
        """
        Get the permissions that should be applied to a child of this blurb

        @param childAuthor: the author of the child blurb
        @type childAuthor: L{xmantissa.sharing.Role}

        @return: mapping of roles to interfaces
        @rtype: C{dict} of L{xmantissa.sharing.Role} to C{list} of
        L{zope.interface.Interface}
        """
        # By default, the author is allowed to edit and comment upon their own
        # entries.  Not even the owner of the area gets to edit (although they
        # probably get to delete).
        roleToPerms = {childAuthor: [ihyperbola.IEditable, ihyperbola.ICommentable]}
        currentBlurb = self

        # With regards to permission, children supersede their parents.  For
        # example, if you want to lock comments on a particular entry, you can
        # give it a new FlavorPermission and its parents will no longer
        # override.  We are specifically iterating upwards from the child here
        # for this reason.
        newFlavor = FLAVOR.commentFlavors[self.flavor]
        while currentBlurb is not None:
            for fp in self.store.query(
                FlavorPermission, AND(FlavorPermission.flavor == newFlavor, FlavorPermission.blurb == currentBlurb)
            ):
                # This test makes sure the parent doesn't override by
                # clobbering the entry in the dictionary.
                if fp.role not in roleToPerms:
                    roleToPerms[fp.role] = [namedAny(x.encode("ascii")) for x in fp.permissions]
            currentBlurb = currentBlurb.parent
        return roleToPerms
コード例 #29
0
ファイル: yamlutil.py プロジェクト: alexbrasetvik/Piped
def pipedpath_constructor(loader, node):
    path = loader.construct_python_str(node)
    original_path = path
    package = piped
    
    # the path may be an empty string, which should be the root piped package path.
    if path:
        paths = path.split(os.path.sep)

        for i in range(1, len(paths)+1):
            package_name = '.'.join(['piped'] + paths[:i])

            try:
                any = reflect.namedAny(package_name)
            except (AttributeError, reflect.ObjectNotFound) as e:
                # AttributeErrors may occur if we look a file that has the
                # same prefix as an existing module or package
                break

            # we don't want to start looking into modules:
            if not is_package(any):
                break
            package = any

            # update the remaining path
            path = os.path.sep.join(paths[i:])

    root = filepath.FilePath(package.__file__).parent()
    fp = root.preauthChild(util.expand_filepath(path))

    # add markers for dumping the configuration
    fp.origpath = original_path
    fp.pipedpath = True
    return fp
コード例 #30
0
 def test_namedAnyPackageLookup(self):
     """
     L{namedAny} should return the package object for the name it is passed.
     """
     import twisted.python
     self.assertIdentical(
         reflect.namedAny("twisted.python"), twisted.python)
コード例 #31
0
class AsynchronousSkipClassTests(SkipClassesMixin, unittest.TestCase):
    """
    Test the class skipping features in the asynchronous case.

    See: L{twisted.trial.test.test_tests.SkipClassesMixin}
    """

    SkippedClass = namedAny(
        "twisted.trial.test.skipping.AsynchronousSkippedClass")
コード例 #32
0
    def test_importerror(self, module_names):
        """
        While the ``disable_modules`` context manager is active any import of the
        modules identified by the names passed to it result in ``ImportError``
        being raised.
        """
        def get_modules():
            return list(namedAny(name) for name in module_names)

        before_modules = get_modules()

        with disable_modules(*module_names):
            for name in module_names:
                with self.assertRaises(ModuleNotFound):
                    namedAny(name)

        after_modules = get_modules()
        self.assertThat(before_modules, Equals(after_modules))
コード例 #33
0
ファイル: migrate.py プロジェクト: gingerkaan/serveros
 def configure(self, filename, appropriateStoreClass, merge):
     subsvc = None
     self.upgrader = UpgradeToDatabaseStep(
         FileStore(
             CachingFilePath(filename), None, None, True, True,
             propertyStoreClass=namedAny(appropriateStoreClass)
         ), self.store, subsvc, merge=merge
     )
     return {}
コード例 #34
0
 def test_loadPackagesAndModules(self):
     """
     Verify that we can locate and load packages, modules, submodules, and
     subpackages.
     """
     for n in ['os', 'exocet', 'exocet.test', 'exocet.test.test_modules']:
         m = namedAny(n)
         self.failUnlessIdentical(modules.getModule(n).load(), m)
         self.failUnlessIdentical(self.findByIteration(n).load(), m)
コード例 #35
0
class AsynchronousStrictTodoTests(StrictTodoMixin, unittest.TestCase):
    """
    Tests for the expected failure case when the exact failure that is expected
    is indicated in the asynchronous case

    See: L{twisted.trial.test.test_tests.StrictTodoMixin}
    """

    StrictTodo = namedAny("twisted.trial.test.skipping.AsynchronousStrictTodo")
コード例 #36
0
ファイル: jelly.py プロジェクト: devkral/twisted
 def _unjelly_function(self, rest):
     fname = nativeString(rest[0])
     modSplit = fname.split(nativeString('.'))
     modName = nativeString('.').join(modSplit[:-1])
     if not self.taster.isModuleAllowed(modName):
         raise InsecureJelly("Module not allowed: %s" % modName)
     # XXX do I need an isFunctionAllowed?
     function = namedAny(fname)
     return function
コード例 #37
0
 class testcase(cls, SynchronousTestCase
                ):  # type: ignore[valid-type,misc]
     __module__ = cls.__module__
     if reactor in cls.skippedReactors:
         skip = cls.skippedReactors[reactor]
     try:
         reactorFactory = namedAny(reactor)
     except BaseException:
         skip = Failure().getErrorMessage()
コード例 #38
0
 def getDBAPIClass(klass, name):
     """
     Per U{http://www.python.org/dev/peps/pep-0249/} each DBAPI driver must implement it's
     own Date/Time/Timestamp/etc classes.  This method provides a generalized way to get them
     from whatever DB driver is being used.
     """        
     driver = Registry.DBPOOL.dbapi.__name__
     path = "%s.%s" % (driver, name)
     return reflect.namedAny(path)
コード例 #39
0
class SynchronousAddCleanupTests(AddCleanupMixin,
                                 unittest.SynchronousTestCase):
    """
    Test the addCleanup method of TestCase in the synchronous case

    See: L{twisted.trial.test.test_tests.AddCleanupMixin}
    """

    AddCleanup = namedAny("twisted.trial.test.skipping.SynchronousAddCleanup")
コード例 #40
0
ファイル: test_scripts.py プロジェクト: blaverick62/SIREN
 def test_tap2rpmDeprecation(self):
     """
     L{twisted.scripts.tap2rpm} is deprecated since Twisted 15.2.
     """
     reload(reflect.namedAny("twisted.scripts.tap2rpm"))
     warningsShown = self.flushWarnings()
     self.assertEqual(1, len(warningsShown))
     self.assertEqual("tap2rpm is deprecated since Twisted 15.2.",
                      warningsShown[0]['message'])
コード例 #41
0
 def opt_element(self, qualifiedName):
     """
     Specify the LiveElement or LiveFragment class to serve.
     """
     try:
         factory = namedAny(qualifiedName)
     except (ValueError, AttributeError):
         raise UsageError("Specify a valid class name to --element")
     self['element'] = factory
コード例 #42
0
 def test_loadPackagesAndModules(self):
     """
     Verify that we can locate and load packages, modules, submodules, and
     subpackages.
     """
     for n in ['os', 'twisted', 'twisted.python', 'twisted.python.reflect']:
         m = namedAny(n)
         self.failUnlessIdentical(modules.getModule(n).load(), m)
         self.failUnlessIdentical(self.findByIteration(n).load(), m)
コード例 #43
0
ファイル: app.py プロジェクト: haomeihong/twisted
 def postOptions(self):
     if self.subCommand or self['python']:
         self['no_save'] = True
     if self['logger'] is not None:
         try:
             self['logger'] = namedAny(self['logger'])
         except Exception as e:
             raise usage.UsageError("Logger '%s' could not be imported: %s"
                                    % (self['logger'], e))
コード例 #44
0
    def run(self):
        schema_store = namedAny(self.options["schema_store_fqpn"])

        appContainer = namedAny(self.arguments[0])

        # This is the path of the file that contains the autoklein directive.
        src_path = FilePath(self.state_machine.get_source(self.lineno))

        # self.options["examples_path"] is a path relative to the source file
        # containing it to a file containing examples to include.
        examples_path = src_path.parent().preauthChild(
            self.options["examples_path"])

        self._examples = _loadExamples(examples_path)

        # The contents of the example file are included in the output so the
        # example file is a dependency of the document.
        self.state.document.settings.record_dependencies.add(
            examples_path.path)

        # The following three lines record (some?) of the dependencies of the
        # directive, so automatic regeneration happens.

        # Specifically, it records this file, and the file where the app
        # is declared.  If we ever have routes for a single app declared
        # across multiple files, this will need to be updated.
        appFileName = getsourcefile(appContainer)
        self.state.document.settings.record_dependencies.add(appFileName)
        self.state.document.settings.record_dependencies.add(__file__)

        # Copied from sphinxcontrib.autohttp.flask
        # Return the result of parsing the rst f
        node = nodes.section()
        node.document = self.state.document
        result = ViewList()
        restLines = makeRst(prefix=self.options['prefix'],
                            section=self.options['section'],
                            app=appContainer.app,
                            exampleByIdentifier=self._exampleByIdentifier,
                            schema_store=schema_store)
        for line in restLines:
            result.append(line, '<autoklein>')
        nested_parse_with_titles(self.state, result, node)
        return node.children
コード例 #45
0
 def parseArgs(self, *args):
     if len(args) != 1:
         raise usage.UsageError(
             "Must pass exactly one FQPN to a WSGI application")
     try:
         application = reflect.namedAny(args[0])
     except (AttributeError, ValueError):
         raise usage.UsageError("No such WSGI application: %r" %
                                (args[0], ))
     self['application'] = application
コード例 #46
0
ファイル: storage.py プロジェクト: byrgazov/foolscap
    def receiveChild(self, obj, ready_deferred=None):
        assert not isinstance(obj, Deferred)
        assert ready_deferred is None

        if self.finished:
            raise BananaError("FunctionUnslicer only accepts one string")

        self.finished = True
        # TODO: taste here!
        self.func = reflect.namedAny(obj)
コード例 #47
0
 def postOptions(self):
     if self.subCommand or self["python"]:
         self["no_save"] = True
     if self["logger"] is not None:
         try:
             self["logger"] = namedAny(self["logger"])
         except Exception as e:
             raise usage.UsageError(
                 "Logger '{}' could not be imported: {}".format(
                     self["logger"], e))
コード例 #48
0
 def _loadReporterByName(self, name):
     for p in plugin.getPlugins(itrial.IReporter):
         qual = f"{p.module}.{p.klass}"
         if p.longOpt == name:
             return reflect.namedAny(qual)
     raise usage.UsageError(
         "Only pass names of Reporter plugins to "
         "--reporter. See --help-reporters for "
         "more info."
     )
コード例 #49
0
ファイル: pipeline.py プロジェクト: carze/vappio
def pipelineSSFromDict(d):
    return PipelineSnapshot(name=d['name'],
                            taskName=d['taskName'],
                            pid=d['pid'],
                            ptype=reflect.namedAny('vappio.pipelines.' +
                                                   d['ptype']),
                            config=config.configFromMap(d['config']),
                            complete=d['complete'],
                            total=d['total'],
                            state=d['state'])
コード例 #50
0
ファイル: runner.py プロジェクト: UstadMobile/eXePUB
 def loadDoctests(self, module):
     if isinstance(module, str):
         try:
             module = reflect.namedAny(module)
         except:
             return ErrorHolder(module, failure.Failure())
     if not inspect.ismodule(module):
         warnings.warn("trial only supports doctesting modules")
         return
     return DocTestSuite(module)
コード例 #51
0
ファイル: test_reflect.py プロジェクト: DT021/wau
 def test_namedAnySecondAttributeLookup(self):
     """
     L{namedAny} should return the object an attribute of an object which
     itself was an attribute of a non-module, non-package object is bound to
     for the name it is passed.
     """
     self.assertIdentical(
         reflect.namedAny("twisted.test.test_reflect."
                          "Summer.reallySet.__doc__"),
         Summer.reallySet.__doc__)
コード例 #52
0
    def test_deprecation_WindowsError(self):
        """Importing C{WindowsError} triggers a L{DeprecationWarning}."""

        self.assertWarns(
            DeprecationWarning,
            "twisted.python.win32.WindowsError was deprecated in Twisted NEXT: "
            "Catch OSError and check presence of 'winerror' attribute.",
            reflect.__file__,
            lambda: reflect.namedAny("twisted.python.win32.WindowsError"),
        )
コード例 #53
0
ファイル: product.py プロジェクト: jonathanj/mantissa
 def install(self):
     """
     Called when installed on the user store. Installs my powerups.
     """
     items = []
     for typeName in self.types:
         it = self.store.findOrCreate(namedAny(typeName))
         installOn(it, self.store)
         items.append(str(it.storeID).decode('ascii'))
     self._items = items
コード例 #54
0
ファイル: tahoe_daemonize.py プロジェクト: e7dal/tahoe-lafs
        def start():
            node_to_instance = {
                u"client":
                lambda: maybeDeferred(
                    namedAny("allmydata.client.create_client"), self.basedir),
                u"introducer":
                lambda: maybeDeferred(
                    namedAny("allmydata.introducer.server.create_introducer"),
                    self.basedir),
                u"stats-gatherer":
                lambda: maybeDeferred(namedAny(
                    "allmydata.stats.StatsGathererService"),
                                      read_config(self.basedir, None),
                                      self.basedir,
                                      verbose=True),
                u"key-generator":
                key_generator_removed,
            }

            try:
                service_factory = node_to_instance[self.nodetype]
            except KeyError:
                raise ValueError("unknown nodetype %s" % self.nodetype)

            def handle_config_error(fail):
                if fail.check(UnknownConfigError):
                    self.stderr.write("\nConfiguration error:\n{}\n\n".format(
                        fail.value))
                else:
                    self.stderr.write("\nUnknown error\n")
                    fail.printTraceback(self.stderr)
                reactor.stop()

            d = service_factory()

            def created(srv):
                srv.setServiceParent(self.parent)

            d.addCallback(created)
            d.addErrback(handle_config_error)
            d.addBoth(self._call_hook, 'running')
            return d
コード例 #55
0
ファイル: test_reflect.py プロジェクト: DT021/wau
 def test_namedAnyAttributeLookup(self):
     """
     L{namedAny} should return the object an attribute of a non-module,
     non-package object is bound to for the name it is passed.
     """
     # Note - not assertIs because unbound method lookup creates a new
     # object every time.  This is a foolishness of Python's object
     # implementation, not a bug in Twisted.
     self.assertEqual(
         reflect.namedAny("twisted.test.test_reflect.Summer.reallySet"),
         Summer.reallySet)
コード例 #56
0
    def run_tests(self):
        tdef = reflect.namedAny(self.test_def)

        config = {}
        runner = dtester.runner.Runner()
        runner.run(tdef, config)

        if True:
            sys.exit(0)  # success
        else:
            sys.exit(1)  # failure
コード例 #57
0
	def __init__(self, **attribs):
		avatar.ConchUser.__init__(self)
		self.attribs = attribs
		self.channelLookup.update({"session": session.SSHSession})
		
		server_class = conf.get('server-class')
		if(server_class and server_class != 'default'):
			server_class = reflect.namedAny(server_class)
			self.subsystemLookup.update({"sftp": server_class})
		else:
			self.subsystemLookup.update({"sftp": filetransfer.FileTransferServer})
コード例 #58
0
    def _checkRoundTrip(self, obj):
        """
        Make sure that an object will properly round-trip through 'qual' and
        'namedAny'.

        Raise a L{RuntimeError} if they aren't.
        """
        tripped = reflect.namedAny(reflect.qual(obj))
        if tripped is not obj:
            raise RuntimeError("importing %r is not the same as %r" %
                               (reflect.qual(obj), obj))
コード例 #59
0
ファイル: test_tests.py プロジェクト: MaxWayne/ScraperWeb
class AsynchronousSuppressionTests(SuppressionMixin, unittest.TestCase):
    """
    Tests for the warning suppression features of
    L{twisted.trial.unittest.TestCase}

    See L{twisted.trial.test.test_suppression.SuppressionMixin}
    """

    TestSetUpSuppression = namedAny(
        "twisted.trial.test.suppression.AsynchronousTestSetUpSuppression"
    )
    TestTearDownSuppression = namedAny(
        "twisted.trial.test.suppression.AsynchronousTestTearDownSuppression"
    )
    TestSuppression = namedAny(
        "twisted.trial.test.suppression.AsynchronousTestSuppression"
    )
    TestSuppression2 = namedAny(
        "twisted.trial.test.suppression.AsynchronousTestSuppression2"
    )
コード例 #60
0
def pluginModules(moduleNames):
    from twisted.python.reflect import namedAny
    for moduleName in moduleNames:
        try:
            yield namedAny(moduleName)
        except ImportError:
            pass
        except ValueError, ve:
            if ve.args[0] != 'Empty module name':
                traceback.print_exc()
        except: