rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
timings = [0.05, 0.1, 0.1, 0.1]
timings = [0.05, 0.1, 0.1]
def testBasicFunction(self): # Arrange to have time advanced enough so that our function is # called a few times. timings = [0.05, 0.1, 0.1, 0.1]
timings = [0.05, 0.1, 0.1, 0.1]
timings = [0.05, 0.1, 0.1]
def testDelayedStart(self): timings = [0.05, 0.1, 0.1, 0.1]
except socket.error: log.msg('port %s already bound' % port.port)
except socket.error, msg: log.msg('error on port %s: %s' % (port.port, msg[1]))
def run(self, save=1, installSignalHandlers=1): """Run this application, running the main loop if necessary. """ global resolver if not self.running: log.logOwner.own(self) for delayed in self.delayeds: main.addDelayed(delayed) if save: main.addShutdown(self.shutDownSave) for port in self.ports: try: port.startListenin...
self.failUnless('*' in f.openFile.getvalue())
v = f.openFile.getvalue() self.failUnless('*' in v, "* not found in %r" % (v,))
def testThingsGetLogged(self): t = StringTransportWithDisconnection() f = TestLoggingFactory(Server(), 'test') p = f.buildProtocol(('1.2.3.4', 5678)) t.protocol = p p.makeConnection(t)
self.assertNotEqual(-1, f.openFile.getvalue().find("C 1: 'here are some bytes'")) self.assertNotEqual(-1, f.openFile.getvalue().find("S 1: 'here are some bytes'"))
v = f.openFile.getvalue() self.assertNotEqual(-1, v.find("C 1: 'here are some bytes'"), "Expected client string not found in %r" % (v,)) self.assertNotEqual(-1, v.find("S 1: 'here are some bytes'"), "Expected server string not found in %r" % (v,))
def testThingsGetLogged(self): t = StringTransportWithDisconnection() f = TestLoggingFactory(Server(), 'test') p = f.buildProtocol(('1.2.3.4', 5678)) t.protocol = p p.makeConnection(t)
self.assertNotEqual(-1, f.openFile.getvalue().find('ConnectionDone'))
v = f.openFile.getvalue() self.assertNotEqual(-1, v.find('ConnectionDone'), "Connection done notification not found in %r" % (v,))
def testThingsGetLogged(self): t = StringTransportWithDisconnection() f = TestLoggingFactory(Server(), 'test') p = f.buildProtocol(('1.2.3.4', 5678)) t.protocol = p p.makeConnection(t)
client's address
client's address.
def getPeer(self): """ Returns a tuple of ('INET', hostname, port), indicating the connected client's address """ return ('INET',)+self.client
a.connectionLost()
a.connectionLost(IOError("all one"))
def testBuffer(self): b = StringIOWithoutClosing() a = http.HTTPChannel() a.requestFactory = DummyHTTPHandler a.makeConnection(protocol.FileWrapper(b)) # one byte at a time, to stress it. for byte in self.requests: a.dataReceived(byte) a.connectionLost() value = b.getvalue() if value != self.expected_response: for i in...
a.connectionLost()
a.connectionLost(IOError("all done"))
def runRequest(self, httpRequest, requestClass): httpRequest = httpRequest.replace("\n", "\r\n") b = StringIOWithoutClosing() a = http.HTTPChannel() a.requestFactory = requestClass a.makeConnection(protocol.FileWrapper(b)) # one byte at a time, to stress it. for byte in httpRequest: a.dataReceived(byte) a.connectionLos...
map(lambda line, self=self: self.sendLine(fmt % line), lines)
map(lambda line, self=self, fmt=fmt: self.sendLine(fmt % line), lines)
def msg(self, user, message, length = None): fmt = "PRIVMSG %s :%%s" % (user,)
print cnames
def processAnswer_1(self, message): '''looking for name->address resolution choose one of the IPs at random''' answers, cnames, cnameMap = [], [], {} for answer in message.answers: if answer.type in (1, 5): cnameMap[answer.name.name] = answer if answer.name.name != self.name: continue if answer.type == 1: answers.appe...
svc = internet.TCPServer(1025, factory) service.IService(application).addService(svc)
internet.TCPServer(1025, factory).setServiceParent(application)
def message(self, message): self.transport.write(message + '\n')
for child in node.childNodes: node.removeChild(child)
while node.childNodes.length: node.removeChild(node.firstChild)
def clearNode(node): """ Remove all children from the given node. """ if node.hasChildNodes(): for child in node.childNodes: node.removeChild(child)
A result that is true (which will be a negtive number) implies the
A result that is true (which will be a negative number) implies the
def doWrite(self): """Called when data is available for writing.
methodPrefix = 'test'
def getResult(self): """I return a tuple containing the first result obtained from the test. If the test was successful, this is also the only result. """ if self.runs > 0: if not self.failures: if self.todo: self.failures.append((reporter.UNEXPECTED_SUCCESS, self.todo)) else: self.failures.append((reporter.SUCCESS,)) ...
if e.args[0] == EWOULDBLOCK:
if e.args[0] == tcp.EWOULDBLOCK:
def doRead(self): """Called when my socket is ready for reading.
return unittest.wait(d)
return unittest.wait(d, timeout=timeout)
def wait(self, d, timeout=10.0): return unittest.wait(d)
reactor.callFromThread(self.response.stream.finish, failure.Failure())
reactor.callFromThread(self.stream.finish, failure.Failure())
def run(self): from twisted.internet import reactor # Called in application thread try: result = self.application(self.environment, self.startWSGIResponse) self.handleResult(result) except: if not self.headersSent: reactor.callFromThread(self.__error, failure.Failure()) else: reactor.callFromThread(self.response.stream...
self.response.stream=stream.ProducerStream()
self.stream=self.response.stream=stream.ProducerStream()
def write(self, output): # Called in application thread from twisted.internet import reactor if self.response is None: raise RuntimeError( "Application didn't call startResponse before writing data!") if not self.headersSent: self.response.stream=stream.ProducerStream() self.headersSent = True # After this, we cannot ...
self.response.stream.registerProducer(self, True)
self.stream.registerProducer(self, True)
def _start(): # Called in IO thread self.response.stream.registerProducer(self, True) self.__callback() # Notify application thread to start writing self.unpaused.set()
reactor.callFromThread(self.response.stream.write, output)
reactor.callFromThread(self.stream.write, output)
def _start(): # Called in IO thread self.response.stream.registerProducer(self, True) self.__callback() # Notify application thread to start writing self.unpaused.set()
reactor.callFromThread(self.response.stream.finish)
reactor.callFromThread(self.stream.finish)
def handleResult(self, result): # Called in application thread try: from twisted.internet import reactor if (isinstance(result, FileWrapper) and hasattr(result.filelike, 'fileno') and not self.headersSent): if self.response is None: raise RuntimeError( "Application didn't call startResponse before writing data!") self....
''' % (i.__class__, s)
''' % (i.__class__, id(i), s)
def htmlInst(i): if hasattr(i, "__html__"): s = i.__html__() else: s = '<code>'+html.escape(repr(i))+'</code>' return '''<table bgcolor="#cc7777"><tr><td><b>%s</b> instance</td></tr> <tr bgcolor="#ff9999"><td>%s</td></tr> </table> ''' % (i.__class__, s)
from xml.dom.minidom import parse
try: from xml.dom.minidom import parse except ImportError: return
def _getSVNVersion(self): mod = sys.modules.get(self.package) if mod: ent = os.path.join(os.path.dirname(mod.__file__), '.svn', 'entries') if os.path.exists(ent): from xml.dom.minidom import parse doc = parse(file(ent)).documentElement for node in doc.childNodes: if hasattr(node, 'getAttribute'): rev = node.getAttribut...
state = LogFile.__getstate__(self)
state = BaseLogFile.__getstate__(self)
def __getstate__(self): state = LogFile.__getstate__(self) del state["size"] return state
state = LogFile.__getstate__(self)
state = BaseLogFile.__getstate__(self)
def __getstate__(self): state = LogFile.__getstate__(self) del state["lastDate"] return state
import domhandlers, domwidgets
import dominput, domwidgets
def getMethodForNode(self, node): if not node.hasAttributes(): return id = node.getAttribute("id") if id: if self._byid.has_key(id): return self._byid[id] klass = node.getAttribute("class") if klass: if self._byclass.has_key(klass): return self._byclass[klass] if self._bytag.has_key(str(node.nodeName)): return self._by...
controllerFactory = getattr(domhandlers, controllerName, DefaultHandler)
controllerFactory = getattr(dominput, controllerName, DefaultHandler)
def getNodeController(self, request, node): # Most specific controllerName = node.getAttribute('controller') # Next-most specific if not controllerName: controllerName = node.getAttribute('id') # Least specific if not controllerName: controllerName = node.getAttribute('class') # Look up a handler controllerFactory = D...
self.escapeMode = 1 fd = 0 try: new = tty.tcgetattr(fd) except: log.msg('not a typewriter!') else: new[3] = new[3] & ~tty.ICANON & ~tty.ECHO new[6][tty.VMIN] = 1 new[6][tty.VTIME] = 0 tty.tcsetattr(fd, tty.TCSANOW, new) tty.setraw(fd)
if (options['command'] and options['tty']) or not options['notty']: fd = 0 try: new = tty.tcgetattr(fd) except: log.msg('not a typewriter!') else: new[3] = new[3] & ~tty.ICANON & ~tty.ECHO new[6][tty.VMIN] = 1 new[6][tty.VTIME] = 0 tty.tcsetattr(fd, tty.TCSANOW, new) tty.setraw(fd)
def channelOpen(self, foo): #global globalSession #globalSession = self # turn off local echo if options['agent']: d = self.conn.sendRequest(self, 'auth-agent-req@openssh.com', '', wantReply=1) d.addBoth(lambda x:log.msg(x)) if options['noshell']: return self.escapeMode = 1 fd = 0 #sys.stdin.fileno() try: new = tty.tcg...
if options['escape']:
if options['escape'] and not options['notty']: self.escapeMode = 1
def channelOpen(self, foo): #global globalSession #globalSession = self # turn off local echo if options['agent']: d = self.conn.sendRequest(self, 'auth-agent-req@openssh.com', '', wantReply=1) d.addBoth(lambda x:log.msg(x)) if options['noshell']: return self.escapeMode = 1 fd = 0 #sys.stdin.fileno() try: new = tty.tcg...
val = eval(code, self.factory.namespace)
val = eval(code)
def perspective_do(self, mesg): fn = "$manhole" try: code = compile(mesg, fn, 'eval') except: try: code = compile(mesg, fn, 'exec') except: io = StringIO.StringIO() traceback.print_exc(file=io) return io.getvalue() try: val = eval(code, self.factory.namespace) except: io = StringIO.StringIO() traceback.print_exc(file=i...
from twisted.names.authority import FileAuthority
def _lookup(self, name, cls, type, timeout=None): if not self.soa or not self.records: return defer.fail(failure.Failure(dns.DomainError(name))) from twisted.names.authority import FileAuthority return FileAuthority.__dict__['_lookup'](self, name, cls, type, timeout)
def _(*args, **kwargs):
def enclosingScope(warnings, warningz): exec """def %s(*args, **kwargs): for warning in warningz: warnings.filterwarnings('ignore', *warning) try: ret = f(*args, **kwargs) finally:
def _(*args, **kwargs): for warning in warningz: warnings.filterwarnings('ignore', *warning) try: ret = f(*args, **kwargs) finally: for warning in warningz: warnings.filterwarnings('default', *warning) return ret
warnings.filterwarnings('ignore', *warning) try: ret = f(*args, **kwargs) finally: for warning in warningz: warnings.filterwarnings('default', *warning) return ret try: return new.function(_.func_code, _.func_globals, f.func_name, inspect.getargspec(_), _.func_closure) except TypeError: return new.function(_.func_code,...
warnings.filterwarnings('default', *warning) return ret """ % (f.func_name,) in locals() return locals()[f.func_name] return enclosingScope(warnings, warningz)
def _(*args, **kwargs): for warning in warningz: warnings.filterwarnings('ignore', *warning) try: ret = f(*args, **kwargs) finally: for warning in warningz: warnings.filterwarnings('default', *warning) return ret
(os.write, self.fd, 0)])
(os.write, self.fd, data)])
def writeChunk(self, offset, data): return self.server._runAsUser([(os.lseek, self.fd, offset, 0), (os.write, self.fd, 0)])
def registerAdapter(adapterClass, origClass, interfaceClass):
def registerAdapter(adapterClass, origClass, *interfaceClasses):
def registerAdapter(adapterClass, origClass, interfaceClass): """Register an adapter class. An adapter class is expected to implement the given interface, by adapting instances of paramter 'origClass'. An adapter class's __init__ method should accept one parameter, an instance of 'origClass'. """ if adapterRegistry.ha...
if adapterRegistry.has_key((origClass, interfaceClass)): raise ValueError( "an adapter (%s) was already registered." % ( adapterRegistry[(origClass, interfaceClass)]
assert interfaceClasses, "You need to pass an Interface" for interfaceClass in interfaceClasses: if adapterRegistry.has_key((origClass, interfaceClass)): raise ValueError( "an adapter (%s) was already registered." % ( adapterRegistry[(origClass, interfaceClass)] )
def registerAdapter(adapterClass, origClass, interfaceClass): """Register an adapter class. An adapter class is expected to implement the given interface, by adapting instances of paramter 'origClass'. An adapter class's __init__ method should accept one parameter, an instance of 'origClass'. """ if adapterRegistry.ha...
) if not implements(adapterClass, interfaceClass): raise ValueError, "%s instances don't implement interface %s" % (adapterClass, interfaceClass) if not issubclass(interfaceClass, Interface): raise ValueError, "interface %s doesn't inherit from %s" % (interfaceClass, Interface) for i in superInterfaces(interfaceCla...
if not implements(adapterClass, interfaceClass): raise ValueError, "%s instances don't implement interface %s" % (adapterClass, interfaceClass) if not issubclass(interfaceClass, Interface): raise ValueError, "interface %s doesn't inherit from %s" % (interfaceClass, Interface) for i in superInterfaces(interfaceClass):...
def registerAdapter(adapterClass, origClass, interfaceClass): """Register an adapter class. An adapter class is expected to implement the given interface, by adapting instances of paramter 'origClass'. An adapter class's __init__ method should accept one parameter, an instance of 'origClass'. """ if adapterRegistry.ha...
class _default: pass def getAdapter(obj, interfaceClass, default=_default,
class _Nothing: pass def getAdapter(obj, interfaceClass, default=_Nothing,
def getAdapterClassWithInheritance(klass, interfaceClass, default): """Return registered adapter for a given class and interface. """ adapterClass = adapterRegistry.get((klass, interfaceClass), _Nothing) if adapterClass is _Nothing: for baseClass in reflect.allYourBase(klass): adapterClass = adapterRegistry.get((baseCl...
if default is _default:
if default is _Nothing:
def getAdapter(obj, interfaceClass, default=_default, adapterClassLocator=None): """Return an object that implements the given interface. The result will be a wrapper around the object passed as a paramter, or the parameter itself if it already implements the interface. If no adapter can be found, the 'default' parame...
class _Nothing: pass
def getAdapter(obj, interfaceClass, default=_default, adapterClassLocator=None): """Return an object that implements the given interface. The result will be a wrapper around the object passed as a paramter, or the parameter itself if it already implements the interface. If no adapter can be found, the 'default' parame...
options["typein"])
self["typein"])
def postOptions(self): if self['in'] is None: self.opt_help() raise usage.UsageError("You must specify the input filename.") if self["typein"] == "guess": try: self["typein"] = app.guessType(self["in"]) except KeyError: raise usage.UsageError("Could not guess type for '%s'" % options["typein"])
import zope
self.__original=original attrs=[]
def __init__(self, original, interfaces=None): import zope if interfaces is None: interfaces = zope.interface.providedBy(original) for interface in interfaces: for name in interface.names(): attr = interface[name] if zope.interface.interfaces.IMethod.providedBy(attr): setattr(self, name, _functionWrapper(original, nam...
interfaces = zope.interface.providedBy(original)
interfaces = providedBy(original)
def __init__(self, original, interfaces=None): import zope if interfaces is None: interfaces = zope.interface.providedBy(original) for interface in interfaces: for name in interface.names(): attr = interface[name] if zope.interface.interfaces.IMethod.providedBy(attr): setattr(self, name, _functionWrapper(original, nam...
if zope.interface.interfaces.IMethod.providedBy(attr):
if zinterfaces.IMethod.providedBy(attr):
def __init__(self, original, interfaces=None): import zope if interfaces is None: interfaces = zope.interface.providedBy(original) for interface in interfaces: for name in interface.names(): attr = interface[name] if zope.interface.interfaces.IMethod.providedBy(attr): setattr(self, name, _functionWrapper(original, nam...
raise TypeError("Cannot handle non-function attributes yet")
raise TypeError("Unknown kind of attribute.") self.__attrs=attrs self.__setattr__=self.__setattr def __getattr__(self, name): if name not in self.__attrs: raise AttributeError("%s object has no attribute '%s'" %( getClass(self.__original).__name__, name)) return getattr(self.__original, name) def __setattr(self, name...
def __init__(self, original, interfaces=None): import zope if interfaces is None: interfaces = zope.interface.providedBy(original) for interface in interfaces: for name in interface.names(): attr = interface[name] if zope.interface.interfaces.IMethod.providedBy(attr): setattr(self, name, _functionWrapper(original, nam...
if k not in kwargs:
if k not in optional:
def _callthrough(*pos, **kw): argcount = len(pos) kwcount = len(kw) if len(positional) > 0 and positional[0] == 'self': # FIXME, hack. # 'self' shouldn't be in the interface declarations, but is. argcount=argcount+1 if len(positional) > 0 or kwargs is not None or varargs is not None: if varargs is None and argcount > ...
for n in positional[:arglen]:
for n in positional[:argcount]:
def _callthrough(*pos, **kw): argcount = len(pos) kwcount = len(kw) if len(positional) > 0 and positional[0] == 'self': # FIXME, hack. # 'self' shouldn't be in the interface declarations, but is. argcount=argcount+1 if len(positional) > 0 or kwargs is not None or varargs is not None: if varargs is None and argcount > ...
open(os.path.expanduser('~/.ssh/known_hosts'),'a').write('localhost '+publicRSA)
open('kh_test','w').write('localhost '+publicRSA)
def setUp(self): open('rsa_test','w').write(privateRSA) open('rsa_test.pub','w').write(publicRSA) open('dsa_test.pub','w').write(publicDSA) open('dsa_test','w').write(privateDSA) os.chmod('dsa_test', 33152) os.chmod('rsa_test', 33152) open(os.path.expanduser('~/.ssh/known_hosts'),'a').write('localhost '+publicRSA)
for f in ['rsa_test','rsa_test.pub','dsa_test','dsa_test.pub']:
for f in ['rsa_test','rsa_test.pub','dsa_test','dsa_test.pub', 'kh_test']:
def tearDown(self): for f in ['rsa_test','rsa_test.pub','dsa_test','dsa_test.pub']: os.remove(f) lines = open(os.path.expanduser('~/.ssh/known_hosts'),'r').readlines() try: lines.remove('localhost ' + publicRSA) except ValueError: lines.remove('localhost ' + publicRSA + '\n') open(os.path.expanduser('~/.ssh/known_hosts...
lines = open(os.path.expanduser('~/.ssh/known_hosts'),'r').readlines() try: lines.remove('localhost ' + publicRSA) except ValueError: lines.remove('localhost ' + publicRSA + '\n') open(os.path.expanduser('~/.ssh/known_hosts'), 'w').writelines(lines)
def tearDown(self): for f in ['rsa_test','rsa_test.pub','dsa_test','dsa_test.pub']: os.remove(f) lines = open(os.path.expanduser('~/.ssh/known_hosts'),'r').readlines() try: lines.remove('localhost ' + publicRSA) except ValueError: lines.remove('localhost ' + publicRSA + '\n') open(os.path.expanduser('~/.ssh/known_hosts...
self.transport.write('+OK %s\r\n' % message)
self.sendLine('+OK ' + str(message))
def successResponse(self, message=''): self.transport.write('+OK %s\r\n' % message)
self.transport.write('-ERR %s\r\n' % message)
self.sendLine('-ERR ' + str(message))
def failResponse(self, message=''): self.transport.write('-ERR %s\r\n' % message)
return apply(getattr(self, 'do_'+command), args)
f = getattr(self, 'do_' + command, None) if f: return apply(getattr(self, 'do_'+command), args) raise POP3Error("Unknown protocol command: " + command)
def processCommand(self, command, *args): command = string.upper(command) if self.mbox is None and command != 'APOP': raise POP3Error("not authenticated yet: cannot do %s" % command) return apply(getattr(self, 'do_'+command), args)
self.transport.write('%d %d\r\n' % (i, message))
self.sendLine('%d %d' % (i, message))
def do_LIST(self, i=None): messages = self.mbox.listMessages() total = reduce(operator.add, messages, 0) self.successResponse(len(messages)) i = 1 for message in messages: if message: self.transport.write('%d %d\r\n' % (i, message)) i = i+1 self.transport.write('.\r\n')
self.transport.write('.\r\n')
self.sendLine('.')
def do_LIST(self, i=None): messages = self.mbox.listMessages() total = reduce(operator.add, messages, 0) self.successResponse(len(messages)) i = 1 for message in messages: if message: self.transport.write('%d %d\r\n' % (i, message)) i = i+1 self.transport.write('.\r\n')
self.transport.write('%d %s\r\n' % (i+1, self.mbox.getUidl(i))) self.transport.write('.\r\n')
self.sendLine('%d %s' % (i+1, self.mbox.getUidl(i))) self.sendLine('.')
def do_UIDL(self, i=None): messages = self.mbox.listMessages() self.successResponse() for i in range(len(messages)): if messages[i]: self.transport.write('%d %s\r\n' % (i+1, self.mbox.getUidl(i))) self.transport.write('.\r\n')
self.transport.write(line[:size]+'\r\n')
self.sendLine(line[:size])
def do_TOP(self, i, size): resp, fp = self.getMessageFile(i) if not fp: return size = max(int(size), resp) self.successResponse(size) while size: line = fp.readline() if not line: break if line[-1] == '\n': line = line[:-1] if line[:1] == '.': line = '.'+line self.transport.write(line[:size]+'\r\n') size = size-len(lin...
self.sendLine('.')
def do_TOP(self, i, size): resp, fp = self.getMessageFile(i) if not fp: return size = max(int(size), resp) self.successResponse(size) while size: line = fp.readline() if not line: break if line[-1] == '\n': line = line[:-1] if line[:1] == '.': line = '.'+line self.transport.write(line[:size]+'\r\n') size = size-len(lin...
self.transport.write(line+'\r\n') self.transport.write('.\r\n')
self.sendLine(line) self.sendLine('.')
def do_RETR(self, i): resp, fp = self.getMessageFile(i) if not fp: return self.successResponse(resp) while 1: line = fp.readline() if not line: break if line[-1] == '\n': line = line[:-1] if line[:1] == '.': line = '.'+line self.transport.write(line+'\r\n') self.transport.write('.\r\n')
self.transport.write('%s %s\r\n' % (command, params))
self.sendLine('%s %s' % (command, params))
def sendShort(self, command, params): self.transport.write('%s %s\r\n' % (command, params)) self.command = command self.mode = SHORT
self.transport.write('%s %s\r\n' % (command, params))
self.sendLine('%s %s' % (command, params))
def sendLong(self, command, params): self.transport.write('%s %s\r\n' % (command, params)) self.command = command self.mode = FIRST_LONG
return socket.inet_ntoa(struct.pack("<l", i))
return socket.inet_ntoa(struct.pack("@l", i))
def getOutgoingInterface(self): i = self.socket.getsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF) # is this cross-platform? return socket.inet_ntoa(struct.pack("<l", i))
isinstance(self.result, failure.Failure) and self.result.frames):
isinstance(self.result, failure.Failure)): log.msg("Unhandled error in Deferred:")
def __del__(self): """Print tracebacks and die. If the *last* (and I do mean *last*) callback leaves me in an error state, print a traceback (if said errback is a Failure). """ if (self.called and self.isError and isinstance(self.result, failure.Failure) and self.result.frames): log.err(self.result)
Throws: a CannotListenError, as defined in twisted.internet.error, if it
@raise CannotListenError: as defined in twisted.internet.error, if it
def listenTCP(self, port, factory, backlog=5, interface=''): """Connects a given protocol factory to the given numeric TCP/IP port.
Returns an object implementing IConnector. This connector will call various callbacks on the factory when a connection is made, failed, or lost - see ClientFactory docs for details.
@returns: An object implementing IConnector. This connector will call various callbacks on the factory when a connection is made, failed, or lost - see ClientFactory docs for details.
def connectTCP(self, host, port, factory, timeout=30, bindAddress=None): """Connect a TCP client.
def setdesc(self,desc): obj.description=desc def forgetit(self): pass
def setdesc(desc, obj=obj): obj.description = desc def forgetit(): pass
def setdesc(self,desc): obj.description=desc
reactor.callLater(0, protocol.lineReceived, response)
reactor.callLater(0.1, protocol.lineReceived, response)
def writeResponses(self, protocol, responses): for response in responses: reactor.callLater(0, protocol.lineReceived, response)
cmdline = ' '.join([_cmdLineQuote(a) for a in args[1:]])
cmdline = ' '.join([_cmdLineQuote(a) for a in args])
def __init__(self, reactor, protocol, command, args, environment, path): self.reactor = reactor self.protocol = protocol
log.msg(iface=ITrialDebug, reporter="reporter option: %s, returning %r" % (opt, nany))
def getReporter(self): """return the class of the selected reporter @param config: a usage.Options instance after parsing options """ if not hasattr(self, 'optToQual'): self._loadReporters() for opt, qual in self.optToQual.iteritems(): if self[opt]: nany = reflect.namedAny(qual) log.msg(iface=ITrialDebug, reporter="rep...
log.msg(iface=ITrialDebug, reporter="config['reporter']: %s" % (config['reporter'],))
def _getReporter(config): log.msg(iface=ITrialDebug, reporter="config['reporter']: %s" % (config['reporter'],)) if config['reporter'] is not None: reporterKlass = config['reporter'] else: reporterKlass = config.getReporter() log.msg(iface=ITrialDebug, reporter="using reporter class: %r" % (reporterKlass,)) reporter = r...
log.msg(iface=ITrialDebug, reporter="using reporter class: %r" % (reporterKlass,))
def _getReporter(config): log.msg(iface=ITrialDebug, reporter="config['reporter']: %s" % (config['reporter'],)) if config['reporter'] is not None: reporterKlass = config['reporter'] else: reporterKlass = config.getReporter() log.msg(iface=ITrialDebug, reporter="using reporter class: %r" % (reporterKlass,)) reporter = r...
assert (path.dirname(setup.__file__) == path.dirname(path.dirname(twisted.__file__)) ), "%s is not Twisted setup.py" % (setup,) self.packageNames = setup.setup_args['packages']
remove = len(os.path.dirname(os.path.dirname(twisted.__file__)))+1 def visit(dirlist, directory, files): if '__init__.py' in files: d = directory[remove:].replace('/','.') dirlist.append(d) self.packageNames = [] os.path.walk(os.path.dirname(twisted.__file__), visit, self.packageNames)
def setUp(self): assert (path.dirname(setup.__file__) == path.dirname(path.dirname(twisted.__file__)) ), "%s is not Twisted setup.py" % (setup,) self.packageNames = setup.setup_args['packages']
del package
def testPackages(self): """Looking for docstrings in all packages.""" docless = [] for packageName in self.packageNames: try: package = reflect.namedModule(packageName) except Exception, e: # This is testing doc coverage, not importability. # (Really, I don't want to deal with the fact that I don't # have pyserial ins...
self._append(Failure())
self._buffer.append(Failure())
def _process(self): """ pull values from the iterable and add them to the buffer """ try: self._iterable = iter(self._iterable) except: self._append(Failure()) else: try: while 1: self._buffer.append(self._iterable.next()) except StopIteration: pass except: self._append(Failure()) self._stop = 1
if os.path.isfile(fn) and not os.path.samefile(fn, retFile):
samefile = getattr(os.path, 'samefile', lambda x, y: x == y) if os.path.isfile(fn) and not samefile(fn, retFile):
def filenameToModule(fn): 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 matc...
def __setitem__(self, key, value):
def add(self, key):
def __setitem__(self, key, value): if self.map.has_key(key): self.keys[self.map[key]] = value else: self.keys.append(key) self.map[key] = len(self.keys) - 1
self.keys[self.map[key]] = value
return
def __setitem__(self, key, value): if self.map.has_key(key): self.keys[self.map[key]] = value else: self.keys.append(key) self.map[key] = len(self.keys) - 1
self.dirtyRows = OrderedDict() self.insertedRows = OrderedDict() self.deletedRows = OrderedDict()
self.dirtyRows = OrderedSet() self.insertedRows = OrderedSet() self.deletedRows = OrderedSet()
def __init__(self, log, journaledService, reflector): self.reflector = reflector self.dirtyRows = OrderedDict() self.insertedRows = OrderedDict() self.deletedRows = OrderedDict() self.syncing = 0 base.Journal.__init__(self, log, journaledService)
self.insertedRows[obj] = 1
self.insertedRows.add(obj)
def updateRow(self, obj): """Mark on object for updating when sync()ing.""" if self.insertedRows.has_key(obj): self.insertedRows[obj] = 1 else: self.dirtyRows[obj] = 1
self.dirtyRows[obj] = 1
self.dirtyRows.add(obj)
def updateRow(self, obj): """Mark on object for updating when sync()ing.""" if self.insertedRows.has_key(obj): self.insertedRows[obj] = 1 else: self.dirtyRows[obj] = 1
self.dirtyRows[obj] = 1
self.dirtyRows.add(obj)
def insertRow(self, obj): """Mark on object for inserting when sync()ing.""" if self.deletedRows.has_key(obj): del self.deletedRows[obj] self.dirtyRows[obj] = 1 else: self.insertedRows[obj] = 1
self.insertedRows[obj] = 1
self.insertedRows.add(obj)
def insertRow(self, obj): """Mark on object for inserting when sync()ing.""" if self.deletedRows.has_key(obj): del self.deletedRows[obj] self.dirtyRows[obj] = 1 else: self.insertedRows[obj] = 1
self.deletedRows[obj] = 1
self.deletedRows.add(obj)
def deleteRow(self, obj): """Mark on object for deleting when sync()ing.""" if self.insertedRows.has_key(obj): del self.insertedRows[obj] return if self.dirtyRows.has_key(obj): del self.dirtyRows[obj] self.deletedRows[obj] = 1
def handleResponsePart(self, data):
self.got_metadata = True def handleEndHeaders(self): if self.got_metadata: self.handleResponsePart = self.handleResponsePart_with_metadata else: self.handleResponsePart = self.gotMP3Data def handleResponsePart_with_metadata(self, data):
def handleHeader(self, key, value): if key.lower() == 'icy-metaint': self.metaint = int(value)
"""Called with a list of (key, value) pairs of metadata.
"""Called with a list of (key, value) pairs of metadata, if metadata is available on the server.
def gotMetaData(self, metadata): """Called with a list of (key, value) pairs of metadata.
file('omg', 'a').write(repr(bytes) + '\n') self.lastWrite = bytes lines = bytes.splitlines() if len(lines) == 1: self.transport.write(lines[0]) else: lastLine = lines.pop() for L in lines: self.transport.write(L)
if bytes: self.lastWrite = bytes lines = bytes.splitlines() if len(lines) == 1: self.transport.write(lines[0]) else: lastLine = lines.pop() for L in lines: self.transport.write(L) self.nextLine() self.transport.write(lastLine) if bytes.endswith('\n'):
def write(self, bytes): file('omg', 'a').write(repr(bytes) + '\n') self.lastWrite = bytes lines = bytes.splitlines() if len(lines) == 1: self.transport.write(lines[0]) else: lastLine = lines.pop() for L in lines: self.transport.write(L) self.nextLine() self.transport.write(lastLine) if bytes.endswith('\n'): self.nextLi...
self.transport.write(lastLine) if bytes.endswith('\n'): self.nextLine()
def write(self, bytes): file('omg', 'a').write(repr(bytes) + '\n') self.lastWrite = bytes lines = bytes.splitlines() if len(lines) == 1: self.transport.write(lines[0]) else: lastLine = lines.pop() for L in lines: self.transport.write(L) self.nextLine() self.transport.write(lastLine) if bytes.endswith('\n'): self.nextLi...
self._cbPasswordMatch, credentials.username)
self._cbPasswordMatch, str(credentials.username))
def requestAvatarId(self, credentials): if credentials.username in self.users: return defer.maybeDeferred( credentials.checkPassword, self.users[credentials.username]).addCallback( self._cbPasswordMatch, credentials.username) else: return defer.fail(error.UnauthorizedLogin())
raise KeyError(u)
raise KeyError(username)
def getUser(self, username): if not self.caseSensitive: username = username.lower()
Create and return IMessages for delivery to each given recipient DEPRECATED. Implement validateTo() correctly. @type recipients: C{list} of C{Address} @param recipients: The addresses for which to create IMessages. @rtype: C{list} @return: The IMessage objects.
def validateFrom(self, helo, origin): """ Validate the address from which the message originates. @type helo: C{(str, str)} @param helo: The argument to the HELO command and the client's IP address.
def __getattr__(self,attr): attrmap = { 'name' : 'local', 'domain' : 'domain' } if attr in attrmap: warnings.warn("User.%s is deprecated, use User.dest.%s instead" % (attr, attrmap[attr]), category=DeprecationWarning, stacklevel=2) return getattr(self.dest, attrmap[attr]) else: raise AttributeError, ("'%s' object has n...
def __getattr__(self,attr): attrmap = { 'name' : 'local', 'domain' : 'domain' } if attr in attrmap: warnings.warn("User.%s is deprecated, use User.dest.%s instead" % (attr, attrmap[attr]), category=DeprecationWarning, stacklevel=2) return getattr(self.dest, attrmap[attr]) else: raise AttributeError, ("'%s' object has n...
self._user_to = []
def __init__(self, delivery=None): self.mode = COMMAND self._from = None self._helo = None self._to = [] self._user_to = [] self.delivery = delivery
self._user_to = []
def do_HELO(self, rest): peer = self.transport.getPeer()[1] self._helo = (rest, peer) self._from = None self._to = [] self._user_to = [] self.sendCode(250, '%s Hello %s, nice to meet you' % (self.host, peer))
self._user_to = []
def do_MAIL(self, rest): if self._from: self.sendCode(503,"Only one sender per message, please") return # Clear old recipient list self._to = [] self._user_to = [] m = self.mail_re.match(rest) if not m: self.sendCode(501, "Syntax error") return
try: defer.maybeDeferred(self.validateFrom, self._helo, addr ).addCallbacks(self._cbFromValidate, self._ebFromValidate) except TypeError: if self.validateFrom.func_code.co_argcount == 5: warnings.warn( 'File "%s", line %d, in %s\n' ' %s.validateFrom call syntax has changed!\n' ' Please update your code!' % (self.vali...
defer.maybeDeferred(self.validateFrom, self._helo, addr ).addCallbacks(self._cbFromValidate, self._ebFromValidate )
def do_MAIL(self, rest): if self._from: self.sendCode(503,"Only one sender per message, please") return # Clear old recipient list self._to = [] self._user_to = [] m = self.mail_re.match(rest) if not m: self.sendCode(501, "Syntax error") return
if from_ is None: warnings.warn( "Returning None from validateFrom is deprecated. " "Raise smtp.SMTPBadSender instead", DeprecationWarning ) self.sendCode(550, 'Cannot receive for specified address')
def _cbFromValidate(self, from_, code=250, msg='Sender address accepted'): if from_ is None: warnings.warn( "Returning None from validateFrom is deprecated. " "Raise smtp.SMTPBadSender instead", DeprecationWarning ) self.sendCode(550, 'Cannot receive for specified address') self._from = from_ self.sendCode(code, msg)
try: d = defer.maybeDeferred(self.validateTo, user) d.addCallbacks( self._cbToValidate, self._ebToValidate, callbackArgs=(user,) ) except TypeError: if self.validateTo.func_code.co_argcount == 4: warnings.warn( 'File "%s", line %d, in %s\n' ' %s.validateTo call syntax has changed!\n' ' Please update your code!' % (se...
d = defer.maybeDeferred(self.validateTo, user) d.addCallbacks( self._cbToValidate, self._ebToValidate, callbackArgs=(user,) )
def do_RCPT(self, rest): if not self._from: self.sendCode(503, "Must have sender before recipient") return m = self.rcpt_re.match(rest) if not m: self.sendCode(501, "Syntax error") return
if to is None: warnings.warn( "Returning None from validateTo is deprecated. " "Raise smtp.SMTPBadRcpt instead.", DeprecationWarning ) self.sendCode(550, 'Cannot receive for specified address') elif isinstance(to, User): warnings.warn( "Returning a User from validateTo is deprecated. " "Return an IMessage factory ins...
self._to.append((user, to))
def _cbToValidate(self, to, user=None, code=250, msg='Recipient address accepted'): if user is None: user = to if to is None: warnings.warn( "Returning None from validateTo is deprecated. " "Raise smtp.SMTPBadRcpt instead.", DeprecationWarning ) self.sendCode(550, 'Cannot receive for specified address') elif isinstanc...
if failure.check(SMTPBadRcpt): self.sendCode(failure.value.code, failure.value.resp) elif failure.check(SMTPServerError):
if failure.check(SMTPBadRcpt, SMTPServerError):
def _ebToValidate(self, failure): if failure.check(SMTPBadRcpt): self.sendCode(failure.value.code, failure.value.resp) elif failure.check(SMTPServerError): self.sendCode(failure.value.code, failure.value.resp) else: log.err(failure) self.sendCode( 451, 'Requested action aborted: local error in processing' )