Python twisted.python.reflect.qual() Examples
The following are 30
code examples of twisted.python.reflect.qual().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
twisted.python.reflect
, or try the search function
.
Example #1
Source File: checkers.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def requestAvatarId(self, credentials): """ Part of the L{ICredentialsChecker} interface. Called by a portal with some credentials to check if they'll authenticate a user. We check the interfaces that the credentials provide against our list of acceptable checkers. If one of them matches, we ask that checker to verify the credentials. If they're valid, we call our L{_cbGoodAuthentication} method to continue. @param credentials: the credentials the L{Portal} wants us to verify """ ifac = providedBy(credentials) for i in ifac: c = self.checkers.get(i) if c is not None: d = defer.maybeDeferred(c.requestAvatarId, credentials) return d.addCallback(self._cbGoodAuthentication, credentials) return defer.fail(UnhandledCredentials("No checker for %s" % \ ', '.join(map(reflect.qual, ifac))))
Example #2
Source File: runner.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def name(thing): """ @param thing: an object from modules (instance of PythonModule, PythonAttribute), a TestCase subclass, or an instance of a TestCase. """ if isTestCase(thing): # TestCase subclass theName = reflect.qual(thing) else: # thing from trial, or thing from modules. # this monstrosity exists so that modules' objects do not have to # implement id(). -jml try: theName = thing.id() except AttributeError: theName = thing.name return theName
Example #3
Source File: workerreporter.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def addFailure(self, test, fail): """ Send a Failure over. """ super(WorkerReporter, self).addFailure(test, fail) testName = test.id() if isinstance(testName, unicode): testName = testName.encode("utf-8") failure = self._getFailure(fail) fail = failure.getErrorMessage().encode("utf-8") failClass = qual(failure.type).encode("utf-8") frames = [frame.encode("utf-8") for frame in self._getFrames(failure)] self.ampProtocol.callRemote(managercommands.AddFailure, testName=testName, fail=fail, failClass=failClass, frames=frames)
Example #4
Source File: test_runner.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def test_reporterDeprecations(self): """ The runner emits a warning if it is using a result that doesn't implement 'done'. """ trialRunner = runner.TrialRunner(None) result = self.FakeReporter() trialRunner._makeResult = lambda: result def f(): # We have to use a pyunit test, otherwise we'll get deprecation # warnings about using iterate() in a test. trialRunner.run(pyunit.TestCase('id')) f() warnings = self.flushWarnings([self.test_reporterDeprecations]) self.assertEqual(warnings[0]['category'], DeprecationWarning) self.assertEqual(warnings[0]['message'], "%s should implement done() but doesn't. Falling back to " "printErrors() and friends." % reflect.qual(result.__class__)) self.assertTrue(__file__.startswith(warnings[0]['filename'])) self.assertEqual(len(warnings), 1)
Example #5
Source File: test_model_change.py From flocker with Apache License 2.0 | 6 votes |
def assert_catches_changes(self, original_class, changed_class): """ Assert that ``generate_model`` changes its output when the underlying class has changed. :param original_class: Class in initial state. :param changed_class: Class in changed state. """ original_model = generate_model(original_class) changed_model = generate_model(changed_class) # Make sure result is JSON serializable: dumps(original_model) dumps(changed_model) self.assertEqual( # If not the calling test is buggy, since it's catching wrong # thing, a mere name change: (fqpn(original_class) == fqpn(changed_class), # Changes result in a difference: original_model != changed_model, # No changes result in same output: original_model == generate_model(original_class), changed_model == generate_model(changed_class)), (True, True, True, True))
Example #6
Source File: workerreporter.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def addError(self, test, error): """ Send an error over. """ super(WorkerReporter, self).addError(test, error) testName = test.id() if isinstance(testName, unicode): testName = testName.encode("utf-8") failure = self._getFailure(error) error = failure.getErrorMessage().encode("utf-8") errorClass = qual(failure.type).encode("utf-8") frames = [frame.encode("utf-8") for frame in self._getFrames(failure)] self.ampProtocol.callRemote(managercommands.AddError, testName=testName, error=error, errorClass=errorClass, frames=frames)
Example #7
Source File: spawnsvc.py From ccs-twistedextensions with Apache License 2.0 | 6 votes |
def spawn(self, hereProto, thereProto, childFDs=None): """ Spawn a subprocess with a connected pair of protocol objects, one in the current process, one in the subprocess. @param hereProto: a L{Protocol} instance to listen in this process. @param thereProto: a top-level class or function that will be imported and called in the spawned subprocess. @param childFDs: File descriptors to share with the subprocess; same format as L{IReactorProcess.spawnProcess}. @return: a L{Deferred} that fires when C{hereProto} is ready. """ if not self.running: self.pendingSpawns.append((hereProto, thereProto)) return name = qual(thereProto) argv = [sys.executable, '-u', '-m', __name__, name] self.reactor.spawnProcess( BridgeProtocol(self, hereProto), sys.executable, argv, os.environ, childFDs=childFDs ) return succeed(hereProto)
Example #8
Source File: test_model_change.py From flocker with Apache License 2.0 | 6 votes |
def _pmap_model(klass): """ Serialize a ``PMap`` model to something JSON-encodable. :param klass: A ``PMap`` subclass. :return: Tuple of (model dictionary, further classes to process). """ record = { u"category": u"map", u"fields": { u"key": sorted( fqpn(cls) for cls in klass._checked_key_types), u"value": sorted( fqpn(cls) for cls in klass._checked_value_types)}} further_classes = set() for cls in klass._checked_key_types + klass._checked_value_types: further_classes.add(cls) return record, further_classes
Example #9
Source File: util.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def spewer(frame, s, ignored): """ A trace function for sys.settrace that prints every function or method call. """ from twisted.python import reflect if 'self' in frame.f_locals: se = frame.f_locals['self'] if hasattr(se, '__class__'): k = reflect.qual(se.__class__) else: k = reflect.qual(type(se)) print('method %s of %s at %s' % ( frame.f_code.co_name, k, id(se))) else: print('function %s in %s, line %s' % ( frame.f_code.co_name, frame.f_code.co_filename, frame.f_lineno))
Example #10
Source File: test_model_change.py From flocker with Apache License 2.0 | 6 votes |
def _precord_model(klass): """ Serialize a ``PRecord`` or ``PClass`` model to something JSON-encodable. :param klass: A ``PRecord`` or ``PClass`` subclass. :return: Tuple of (model dictionary, further classes to process). """ further_classes = set() if issubclass(klass, PRecord): attr_name = "_precord_fields" else: attr_name = "_pclass_fields" record = {u"category": u"record", u"fields": {}} for name, field_info in getattr(klass, attr_name).items(): record[u"fields"][name] = sorted( fqpn(cls) for cls in field_info.type) for cls in field_info.type: further_classes.add(cls) return record, further_classes
Example #11
Source File: components.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def addComponent(self, component, ignoreClass=0): """ Add a component to me, for all appropriate interfaces. In order to determine which interfaces are appropriate, the component's provided interfaces will be scanned. If the argument 'ignoreClass' is True, then all interfaces are considered appropriate. Otherwise, an 'appropriate' interface is one for which its class has been registered as an adapter for my class according to the rules of getComponent. @return: the list of appropriate interfaces """ for iface in declarations.providedBy(component): if (ignoreClass or (self.locateAdapterClass(self.__class__, iface, None) == component.__class__)): self._adapterCache[reflect.qual(iface)] = component
Example #12
Source File: test_pbfailure.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def test_throwExceptionIntoGenerator(self): """ L{pb.CopiedFailure.throwExceptionIntoGenerator} will throw a L{RemoteError} into the given paused generator at the point where it last yielded. """ original = pb.CopyableFailure(AttributeError("foo")) copy = jelly.unjelly(jelly.jelly(original, invoker=DummyInvoker())) exception = [] def generatorFunc(): try: yield None except pb.RemoteError as exc: exception.append(exc) else: self.fail("RemoteError not raised") gen = generatorFunc() gen.send(None) self.assertRaises(StopIteration, copy.throwExceptionIntoGenerator, gen) self.assertEqual(len(exception), 1) exc = exception[0] self.assertEqual(exc.remoteType, qual(AttributeError).encode("ascii")) self.assertEqual(exc.args, ("foo",)) self.assertEqual(exc.remoteTraceback, 'Traceback unavailable\n')
Example #13
Source File: pb.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def getStateToCopy(self): """ Collect state related to the exception which occurred, discarding state which cannot reasonably be serialized. """ state = self.__dict__.copy() state['tb'] = None state['frames'] = [] state['stack'] = [] state['value'] = str(self.value) # Exception instance if isinstance(self.type, bytes): state['type'] = self.type else: state['type'] = reflect.qual(self.type).encode('utf-8') # Exception class if self.unsafeTracebacks: state['traceback'] = self.getTraceback() else: state['traceback'] = 'Traceback unavailable\n' return state
Example #14
Source File: base.py From learn_python3_spider with MIT License | 5 votes |
def __repr__(self): return "<%s instance at 0x%x %s %s>" % ( reflect.qual(self.__class__), id(self), self.state, self.getDestination())
Example #15
Source File: base.py From learn_python3_spider with MIT License | 5 votes |
def removeWriter(self, writer): raise NotImplementedError( reflect.qual(self.__class__) + " did not implement removeWriter")
Example #16
Source File: base.py From learn_python3_spider with MIT License | 5 votes |
def removeAll(self): raise NotImplementedError( reflect.qual(self.__class__) + " did not implement removeAll")
Example #17
Source File: base.py From learn_python3_spider with MIT License | 5 votes |
def getReaders(self): raise NotImplementedError( reflect.qual(self.__class__) + " did not implement getReaders")
Example #18
Source File: base.py From learn_python3_spider with MIT License | 5 votes |
def getWriters(self): raise NotImplementedError( reflect.qual(self.__class__) + " did not implement getWriters") # IReactorCore
Example #19
Source File: unix.py From learn_python3_spider with MIT License | 5 votes |
def __repr__(self): factoryName = reflect.qual(self.factory.__class__) if hasattr(self, 'socket'): return '<%s on %r>' % ( factoryName, _coerceToFilesystemEncoding('', self.port)) else: return '<%s (not listening)>' % (factoryName,)
Example #20
Source File: service.py From learn_python3_spider with MIT License | 5 votes |
def jellyFor(self, jellier): qual = reflect.qual(PBMind) if isinstance(qual, unicode): qual = qual.encode("utf-8") return qual, jellier.invoker.registerReference(self)
Example #21
Source File: unix.py From learn_python3_spider with MIT License | 5 votes |
def setLogStr(self): self.logstr = reflect.qual(self.protocol.__class__) + " (UDP)"
Example #22
Source File: test_model_change.py From flocker with Apache License 2.0 | 5 votes |
def generate_model(root_class=ROOT_CLASS): """ Generate a data-structure that represents the current configuration model. Changes to output may require regenerating the persisted version on-disk. This should switch to Pyrsistent's introspection API once it exists: https://github.com/tobgu/pyrsistent/issues/47 """ classes_result = {} result = {u"root": fqpn(root_class), u"classes": classes_result} classes = {root_class} while classes: klass = classes.pop() klass_name = fqpn(klass) if klass_name in classes_result: continue if issubclass(klass, (PRecord, PClass)): to_model = _precord_model elif issubclass(klass, CheckedPMap): to_model = _pmap_model elif issubclass(klass, (CheckedPSet, CheckedPVector)): to_model = _psequence_model else: to_model = _default_model record, further_classes = to_model(klass) classes_result[klass_name] = record classes |= further_classes return result
Example #23
Source File: test_model_change.py From flocker with Apache License 2.0 | 5 votes |
def _psequence_model(klass): """ Serialize a ``PVector`` or ``PSet`` model to something JSON-encodable. :param klass: A ``PVector`` or ``PSet`` subclass. :return: Tuple of (model dictionary, further classes to process). """ category = u"set" if issubclass(klass, CheckedPSet) else u"list" record = { u"category": category, u"type": sorted(fqpn(cls) for cls in klass._checked_types), } further_classes = set(klass._checked_types) return record, further_classes
Example #24
Source File: test_pbfailure.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def test_printTracebackIncludesValue(self): """ When L{CopiedFailure.printTraceback} is used to print a copied failure which was unjellied from a L{CopyableFailure} with C{unsafeTracebacks} set to C{False}, the string representation of the exception value is included in the output. """ original = pb.CopyableFailure(Exception("some reason")) copied = jelly.unjelly(jelly.jelly(original, invoker=DummyInvoker())) output = NativeStringIO() copied.printTraceback(output) exception = qual(Exception) expectedOutput = ("Traceback from remote host -- " "{}: some reason\n".format(exception)) self.assertEqual(expectedOutput, output.getvalue())
Example #25
Source File: jelly.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def allowInstancesOf(self, *classes): """ SecurityOptions.allowInstances(klass, klass, ...): allow instances of the specified classes This will also allow the 'instance', 'class' (renamed 'classobj' in Python 2.3), and 'module' types, as well as basic types. """ self.allowBasicTypes() self.allowTypes("instance", "class", "classobj", "module") for klass in classes: self.allowTypes(qual(klass)) self.allowModules(klass.__module__) self.allowedClasses[klass] = 1
Example #26
Source File: jelly.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def _unjelly_class(self, rest): cname = nativeString(rest[0]) clist = cname.split(nativeString('.')) modName = nativeString('.').join(clist[:-1]) if not self.taster.isModuleAllowed(modName): raise InsecureJelly("module %s not allowed" % modName) klaus = namedObject(cname) objType = type(klaus) if objType not in (_OldStyleClass, type): raise InsecureJelly( "class %r unjellied to something that isn't a class: %r" % ( cname, klaus)) if not self.taster.isClassAllowed(klaus): raise InsecureJelly("class not allowed: %s" % qual(klaus)) return klaus
Example #27
Source File: jelly.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def jellyFor(self, jellier): """ @see: L{twisted.spread.interfaces.IJellyable.jellyFor} """ sxp = jellier.prepare(self) sxp.extend([ qual(self.__class__).encode('utf-8'), jellier.jelly(self.getStateFor(jellier))]) return jellier.preserve(self, sxp)
Example #28
Source File: jelly.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def getInstanceState(inst, jellier): """ Utility method to default to 'normal' state rules in serialization. """ if hasattr(inst, "__getstate__"): state = inst.__getstate__() else: state = inst.__dict__ sxp = jellier.prepare(inst) sxp.extend([qual(inst.__class__).encode('utf-8'), jellier.jelly(state)]) return jellier.preserve(inst, sxp)
Example #29
Source File: jelly.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def _maybeClass(classnamep): isObject = isinstance(classnamep, type) if isObject or ((not _PY3) and isinstance(classnamep, _OldStyleClass)): classnamep = qual(classnamep) if not isinstance(classnamep, bytes): classnamep = classnamep.encode('utf-8') return classnamep
Example #30
Source File: flavors.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def getTypeToCopy(self): """Determine what type tag to send for me. By default, send the string representation of my class (package.module.Class); normally this is adequate, but you may override this to change it. """ return reflect.qual(self.__class__).encode('utf-8')