code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
194
| url
stringlengths 46
254
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def test_lengthLimitExceeded(self):
"""
When a length prefix is received which is greater than the protocol's
C{MAX_LENGTH} attribute, the C{lengthLimitExceeded} method is called
with the received length prefix.
"""
length = []
r = self.getProtocol()
r.lengthLimitExceeded = length.append
r.MAX_LENGTH = 10
r.dataReceived(struct.pack(r.structFormat, 11))
self.assertEqual(length, [11]) | When a length prefix is received which is greater than the protocol's
C{MAX_LENGTH} attribute, the C{lengthLimitExceeded} method is called
with the received length prefix. | test_lengthLimitExceeded | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | MIT |
def test_longStringNotDelivered(self):
"""
If a length prefix for a string longer than C{MAX_LENGTH} is delivered
to C{dataReceived} at the same time as the entire string, the string is
not passed to C{stringReceived}.
"""
r = self.getProtocol()
r.MAX_LENGTH = 10
r.dataReceived(
struct.pack(r.structFormat, 11) + b'x' * 11)
self.assertEqual(r.received, []) | If a length prefix for a string longer than C{MAX_LENGTH} is delivered
to C{dataReceived} at the same time as the entire string, the string is
not passed to C{stringReceived}. | test_longStringNotDelivered | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | MIT |
def test_stringReceivedNotImplemented(self):
"""
When L{IntNStringReceiver.stringReceived} is not overridden in a
subclass, calling it raises C{NotImplementedError}.
"""
proto = basic.IntNStringReceiver()
self.assertRaises(NotImplementedError, proto.stringReceived, 'foo') | When L{IntNStringReceiver.stringReceived} is not overridden in a
subclass, calling it raises C{NotImplementedError}. | test_stringReceivedNotImplemented | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | MIT |
def makeMessage(self, protocol, data):
"""
Return C{data} prefixed with message length in C{protocol.structFormat}
form.
"""
return struct.pack(protocol.structFormat, len(data)) + data | Return C{data} prefixed with message length in C{protocol.structFormat}
form. | makeMessage | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | MIT |
def test_recvdContainsRemainingData(self):
"""
In stringReceived, recvd contains the remaining data that was passed to
dataReceived that was not part of the current message.
"""
result = []
r = self.getProtocol()
def stringReceived(receivedString):
result.append(r.recvd)
r.stringReceived = stringReceived
completeMessage = (struct.pack(r.structFormat, 5) + (b'a' * 5))
incompleteMessage = (struct.pack(r.structFormat, 5) + (b'b' * 4))
# Receive a complete message, followed by an incomplete one
r.dataReceived(completeMessage + incompleteMessage)
self.assertEqual(result, [incompleteMessage]) | In stringReceived, recvd contains the remaining data that was passed to
dataReceived that was not part of the current message. | test_recvdContainsRemainingData | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | MIT |
def test_recvdChanged(self):
"""
In stringReceived, if recvd is changed, messages should be parsed from
it rather than the input to dataReceived.
"""
r = self.getProtocol()
result = []
payloadC = b'c' * 5
messageC = self.makeMessage(r, payloadC)
def stringReceived(receivedString):
if not result:
r.recvd = messageC
result.append(receivedString)
r.stringReceived = stringReceived
payloadA = b'a' * 5
payloadB = b'b' * 5
messageA = self.makeMessage(r, payloadA)
messageB = self.makeMessage(r, payloadB)
r.dataReceived(messageA + messageB)
self.assertEqual(result, [payloadA, payloadC]) | In stringReceived, if recvd is changed, messages should be parsed from
it rather than the input to dataReceived. | test_recvdChanged | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | MIT |
def test_switching(self):
"""
Data already parsed by L{IntNStringReceiver.dataReceived} is not
reparsed if C{stringReceived} consumes some of the
L{IntNStringReceiver.recvd} buffer.
"""
proto = self.getProtocol()
mix = []
SWITCH = b"\x00\x00\x00\x00"
for s in self.strings:
mix.append(self.makeMessage(proto, s))
mix.append(SWITCH)
result = []
def stringReceived(receivedString):
result.append(receivedString)
proto.recvd = proto.recvd[len(SWITCH):]
proto.stringReceived = stringReceived
proto.dataReceived(b"".join(mix))
# Just another byte, to trigger processing of anything that might have
# been left in the buffer (should be nothing).
proto.dataReceived(b"\x01")
self.assertEqual(result, self.strings)
# And verify that another way
self.assertEqual(proto.recvd, b"\x01") | Data already parsed by L{IntNStringReceiver.dataReceived} is not
reparsed if C{stringReceived} consumes some of the
L{IntNStringReceiver.recvd} buffer. | test_switching | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | MIT |
def test_recvdInLengthLimitExceeded(self):
"""
The L{IntNStringReceiver.recvd} buffer contains all data not yet
processed by L{IntNStringReceiver.dataReceived} if the
C{lengthLimitExceeded} event occurs.
"""
proto = self.getProtocol()
DATA = b"too long"
proto.MAX_LENGTH = len(DATA) - 1
message = self.makeMessage(proto, DATA)
result = []
def lengthLimitExceeded(length):
result.append(length)
result.append(proto.recvd)
proto.lengthLimitExceeded = lengthLimitExceeded
proto.dataReceived(message)
self.assertEqual(result[0], len(DATA))
self.assertEqual(result[1], message) | The L{IntNStringReceiver.recvd} buffer contains all data not yet
processed by L{IntNStringReceiver.dataReceived} if the
C{lengthLimitExceeded} event occurs. | test_recvdInLengthLimitExceeded | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | MIT |
def test_data(self):
"""
Test specific behavior of the 32-bits length.
"""
r = self.getProtocol()
r.sendString(b"foo")
self.assertEqual(r.transport.value(), b"\x00\x00\x00\x03foo")
r.dataReceived(b"\x00\x00\x00\x04ubar")
self.assertEqual(r.received, [b"ubar"]) | Test specific behavior of the 32-bits length. | test_data | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | MIT |
def test_data(self):
"""
Test specific behavior of the 16-bits length.
"""
r = self.getProtocol()
r.sendString(b"foo")
self.assertEqual(r.transport.value(), b"\x00\x03foo")
r.dataReceived(b"\x00\x04ubar")
self.assertEqual(r.received, [b"ubar"]) | Test specific behavior of the 16-bits length. | test_data | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | MIT |
def test_tooLongSend(self):
"""
Send too much data: that should cause an error.
"""
r = self.getProtocol()
tooSend = b"b" * (2**(r.prefixLength * 8) + 1)
self.assertRaises(AssertionError, r.sendString, tooSend) | Send too much data: that should cause an error. | test_tooLongSend | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | MIT |
def test_data(self):
"""
Test specific behavior of the 8-bits length.
"""
r = self.getProtocol()
r.sendString(b"foo")
self.assertEqual(r.transport.value(), b"\x03foo")
r.dataReceived(b"\x04ubar")
self.assertEqual(r.received, [b"ubar"]) | Test specific behavior of the 8-bits length. | test_data | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | MIT |
def test_tooLongSend(self):
"""
Send too much data: that should cause an error.
"""
r = self.getProtocol()
tooSend = b"b" * (2**(r.prefixLength * 8) + 1)
self.assertRaises(AssertionError, r.sendString, tooSend) | Send too much data: that should cause an error. | test_tooLongSend | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | MIT |
def test_pauseResume(self):
"""
When L{basic.LineReceiver} is paused, it doesn't deliver lines to
L{basic.LineReceiver.lineReceived} and delivers them immediately upon
being resumed.
L{ConsumingProtocol} is a L{LineReceiver} that pauses itself after
every line, and writes that line to its transport.
"""
p = ConsumingProtocol()
t = OnlyProducerTransport()
p.makeConnection(t)
# Deliver a partial line.
# This doesn't trigger a pause and doesn't deliver a line.
p.dataReceived(b'hello, ')
self.assertEqual(t.data, [])
self.assertFalse(t.paused)
self.assertFalse(p.paused)
# Deliver the rest of the line.
# This triggers the pause, and the line is echoed.
p.dataReceived(b'world\r\n')
self.assertEqual(t.data, [b'hello, world'])
self.assertTrue(t.paused)
self.assertTrue(p.paused)
# Unpausing doesn't deliver more data, and the protocol is unpaused.
p.resumeProducing()
self.assertEqual(t.data, [b'hello, world'])
self.assertFalse(t.paused)
self.assertFalse(p.paused)
# Deliver two lines at once.
# The protocol is paused after receiving and echoing the first line.
p.dataReceived(b'hello\r\nworld\r\n')
self.assertEqual(t.data, [b'hello, world', b'hello'])
self.assertTrue(t.paused)
self.assertTrue(p.paused)
# Unpausing delivers the waiting line, and causes the protocol to
# pause again.
p.resumeProducing()
self.assertEqual(t.data, [b'hello, world', b'hello', b'world'])
self.assertTrue(t.paused)
self.assertTrue(p.paused)
# Deliver a line while paused.
# This doesn't have a visible effect.
p.dataReceived(b'goodbye\r\n')
self.assertEqual(t.data, [b'hello, world', b'hello', b'world'])
self.assertTrue(t.paused)
self.assertTrue(p.paused)
# Unpausing delivers the waiting line, and causes the protocol to
# pause again.
p.resumeProducing()
self.assertEqual(
t.data, [b'hello, world', b'hello', b'world', b'goodbye'])
self.assertTrue(t.paused)
self.assertTrue(p.paused)
# Unpausing doesn't deliver more data, and the protocol is unpaused.
p.resumeProducing()
self.assertEqual(
t.data, [b'hello, world', b'hello', b'world', b'goodbye'])
self.assertFalse(t.paused)
self.assertFalse(p.paused) | When L{basic.LineReceiver} is paused, it doesn't deliver lines to
L{basic.LineReceiver.lineReceived} and delivers them immediately upon
being resumed.
L{ConsumingProtocol} is a L{LineReceiver} that pauses itself after
every line, and writes that line to its transport. | test_pauseResume | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | MIT |
def test_interface(self):
"""
L{basic.FileSender} implements the L{IPullProducer} interface.
"""
sender = basic.FileSender()
self.assertTrue(verifyObject(IProducer, sender)) | L{basic.FileSender} implements the L{IPullProducer} interface. | test_interface | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | MIT |
def test_producerRegistered(self):
"""
When L{basic.FileSender.beginFileTransfer} is called, it registers
itself with provided consumer, as a non-streaming producer.
"""
source = BytesIO(b"Test content")
consumer = proto_helpers.StringTransport()
sender = basic.FileSender()
sender.beginFileTransfer(source, consumer)
self.assertEqual(consumer.producer, sender)
self.assertFalse(consumer.streaming) | When L{basic.FileSender.beginFileTransfer} is called, it registers
itself with provided consumer, as a non-streaming producer. | test_producerRegistered | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | MIT |
def test_transfer(self):
"""
L{basic.FileSender} sends the content of the given file using a
C{IConsumer} interface via C{beginFileTransfer}. It returns a
L{Deferred} which fires with the last byte sent.
"""
source = BytesIO(b"Test content")
consumer = proto_helpers.StringTransport()
sender = basic.FileSender()
d = sender.beginFileTransfer(source, consumer)
sender.resumeProducing()
# resumeProducing only finishes after trying to read at eof
sender.resumeProducing()
self.assertIsNone(consumer.producer)
self.assertEqual(b"t", self.successResultOf(d))
self.assertEqual(b"Test content", consumer.value()) | L{basic.FileSender} sends the content of the given file using a
C{IConsumer} interface via C{beginFileTransfer}. It returns a
L{Deferred} which fires with the last byte sent. | test_transfer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | MIT |
def test_transferMultipleChunks(self):
"""
L{basic.FileSender} reads at most C{CHUNK_SIZE} every time it resumes
producing.
"""
source = BytesIO(b"Test content")
consumer = proto_helpers.StringTransport()
sender = basic.FileSender()
sender.CHUNK_SIZE = 4
d = sender.beginFileTransfer(source, consumer)
# Ideally we would assertNoResult(d) here, but <http://tm.tl/6291>
sender.resumeProducing()
self.assertEqual(b"Test", consumer.value())
sender.resumeProducing()
self.assertEqual(b"Test con", consumer.value())
sender.resumeProducing()
self.assertEqual(b"Test content", consumer.value())
# resumeProducing only finishes after trying to read at eof
sender.resumeProducing()
self.assertEqual(b"t", self.successResultOf(d))
self.assertEqual(b"Test content", consumer.value()) | L{basic.FileSender} reads at most C{CHUNK_SIZE} every time it resumes
producing. | test_transferMultipleChunks | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | MIT |
def test_transferWithTransform(self):
"""
L{basic.FileSender.beginFileTransfer} takes a C{transform} argument
which allows to manipulate the data on the fly.
"""
def transform(chunk):
return chunk.swapcase()
source = BytesIO(b"Test content")
consumer = proto_helpers.StringTransport()
sender = basic.FileSender()
d = sender.beginFileTransfer(source, consumer, transform)
sender.resumeProducing()
# resumeProducing only finishes after trying to read at eof
sender.resumeProducing()
self.assertEqual(b"T", self.successResultOf(d))
self.assertEqual(b"tEST CONTENT", consumer.value()) | L{basic.FileSender.beginFileTransfer} takes a C{transform} argument
which allows to manipulate the data on the fly. | test_transferWithTransform | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | MIT |
def test_abortedTransfer(self):
"""
The C{Deferred} returned by L{basic.FileSender.beginFileTransfer} fails
with an C{Exception} if C{stopProducing} when the transfer is not
complete.
"""
source = BytesIO(b"Test content")
consumer = proto_helpers.StringTransport()
sender = basic.FileSender()
d = sender.beginFileTransfer(source, consumer)
# Abort the transfer right away
sender.stopProducing()
failure = self.failureResultOf(d)
failure.trap(Exception)
self.assertEqual("Consumer asked us to stop producing",
str(failure.value)) | The C{Deferred} returned by L{basic.FileSender.beginFileTransfer} fails
with an C{Exception} if C{stopProducing} when the transfer is not
complete. | test_abortedTransfer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_basic.py | MIT |
def factoryAndDeferred(cls):
"""
Create a new L{HandshakeCallbackContextFactory} and return a two-tuple
of it and a L{Deferred} which will fire when a connection created with
it completes a TLS handshake.
"""
contextFactory = cls()
return contextFactory, contextFactory._finished | Create a new L{HandshakeCallbackContextFactory} and return a two-tuple
of it and a L{Deferred} which will fire when a connection created with
it completes a TLS handshake. | factoryAndDeferred | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def _info(self, connection, where, ret):
"""
This is the "info callback" on the context. It will be called
periodically by pyOpenSSL with information about the state of a
connection. When it indicates the handshake is complete, it will fire
C{self._finished}.
"""
if where & self.SSL_CB_HANDSHAKE_DONE:
self._finished.callback(None) | This is the "info callback" on the context. It will be called
periodically by pyOpenSSL with information about the state of a
connection. When it indicates the handshake is complete, it will fire
C{self._finished}. | _info | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def getContext(self):
"""
Create and return an SSL context configured to use L{self._info} as the
info callback.
"""
context = Context(self._method)
context.set_info_callback(self._info)
return context | Create and return an SSL context configured to use L{self._info} as the
info callback. | getContext | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def buildTLSProtocol(server=False, transport=None, fakeConnection=None):
"""
Create a protocol hooked up to a TLS transport hooked up to a
StringTransport.
"""
# We want to accumulate bytes without disconnecting, so set high limit:
clientProtocol = AccumulatingProtocol(999999999999)
clientFactory = ClientFactory()
clientFactory.protocol = lambda: clientProtocol
if fakeConnection:
@implementer(IOpenSSLServerConnectionCreator,
IOpenSSLClientConnectionCreator)
class HardCodedConnection(object):
def clientConnectionForTLS(self, tlsProtocol):
return fakeConnection
serverConnectionForTLS = clientConnectionForTLS
contextFactory = HardCodedConnection()
else:
if server:
contextFactory = ServerTLSContext()
else:
contextFactory = ClientTLSContext()
wrapperFactory = TLSMemoryBIOFactory(
contextFactory, not server, clientFactory)
sslProtocol = wrapperFactory.buildProtocol(None)
if transport is None:
transport = StringTransport()
sslProtocol.makeConnection(transport)
return clientProtocol, sslProtocol | Create a protocol hooked up to a TLS transport hooked up to a
StringTransport. | buildTLSProtocol | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_quiet(self):
"""
L{TLSMemoryBIOFactory.doStart} and L{TLSMemoryBIOFactory.doStop} do
not log any messages.
"""
contextFactory = ServerTLSContext()
logs = []
logger = logs.append
log.addObserver(logger)
self.addCleanup(log.removeObserver, logger)
wrappedFactory = ServerFactory()
# Disable logging on the wrapped factory:
wrappedFactory.doStart = lambda: None
wrappedFactory.doStop = lambda: None
factory = TLSMemoryBIOFactory(contextFactory, False, wrappedFactory)
factory.doStart()
factory.doStop()
self.assertEqual(logs, []) | L{TLSMemoryBIOFactory.doStart} and L{TLSMemoryBIOFactory.doStop} do
not log any messages. | test_quiet | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_logPrefix(self):
"""
L{TLSMemoryBIOFactory.logPrefix} amends the wrapped factory's log prefix
with a short string (C{"TLS"}) indicating the wrapping, rather than its
full class name.
"""
contextFactory = ServerTLSContext()
factory = TLSMemoryBIOFactory(contextFactory, False, ServerFactory())
self.assertEqual("ServerFactory (TLS)", factory.logPrefix()) | L{TLSMemoryBIOFactory.logPrefix} amends the wrapped factory's log prefix
with a short string (C{"TLS"}) indicating the wrapping, rather than its
full class name. | test_logPrefix | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_logPrefixFallback(self):
"""
If the wrapped factory does not provide L{ILoggingContext},
L{TLSMemoryBIOFactory.logPrefix} uses the wrapped factory's class name.
"""
class NoFactory(object):
pass
contextFactory = ServerTLSContext()
factory = TLSMemoryBIOFactory(contextFactory, False, NoFactory())
self.assertEqual("NoFactory (TLS)", factory.logPrefix()) | If the wrapped factory does not provide L{ILoggingContext},
L{TLSMemoryBIOFactory.logPrefix} uses the wrapped factory's class name. | test_logPrefixFallback | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def handshakingClientAndServer(clientGreetingData=None,
clientAbortAfterHandshake=False):
"""
Construct a client and server L{TLSMemoryBIOProtocol} connected by an IO
pump.
@param greetingData: The data which should be written in L{connectionMade}.
@type greetingData: L{bytes}
@return: 3-tuple of client, server, L{twisted.test.iosim.IOPump}
"""
authCert, serverCert = certificatesForAuthorityAndServer()
@implementer(IHandshakeListener)
class Client(AccumulatingProtocol, object):
handshook = False
peerAfterHandshake = None
def connectionMade(self):
super(Client, self).connectionMade()
if clientGreetingData is not None:
self.transport.write(clientGreetingData)
def handshakeCompleted(self):
self.handshook = True
self.peerAfterHandshake = self.transport.getPeerCertificate()
if clientAbortAfterHandshake:
self.transport.abortConnection()
def connectionLost(self, reason):
pass
@implementer(IHandshakeListener)
class Server(AccumulatingProtocol, object):
handshaked = False
def handshakeCompleted(self):
self.handshaked = True
def connectionLost(self, reason):
pass
clientF = TLSMemoryBIOFactory(
optionsForClientTLS(u"example.com", trustRoot=authCert),
isClient=True,
wrappedFactory=ClientFactory.forProtocol(lambda: Client(999999))
)
serverF = TLSMemoryBIOFactory(
serverCert.options(), isClient=False,
wrappedFactory=ServerFactory.forProtocol(lambda: Server(999999))
)
client, server, pump = connectedServerAndClient(
lambda: serverF.buildProtocol(None),
lambda: clientF.buildProtocol(None),
greet=False,
)
return client, server, pump | Construct a client and server L{TLSMemoryBIOProtocol} connected by an IO
pump.
@param greetingData: The data which should be written in L{connectionMade}.
@type greetingData: L{bytes}
@return: 3-tuple of client, server, L{twisted.test.iosim.IOPump} | handshakingClientAndServer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_handshakeNotification(self):
"""
The completion of the TLS handshake calls C{handshakeCompleted} on
L{Protocol} objects that provide L{IHandshakeListener}. At the time
C{handshakeCompleted} is invoked, the transport's peer certificate will
have been initialized.
"""
client, server, pump = handshakingClientAndServer()
self.assertEqual(client.wrappedProtocol.handshook, False)
self.assertEqual(server.wrappedProtocol.handshaked, False)
pump.flush()
self.assertEqual(client.wrappedProtocol.handshook, True)
self.assertEqual(server.wrappedProtocol.handshaked, True)
self.assertIsNot(client.wrappedProtocol.peerAfterHandshake, None) | The completion of the TLS handshake calls C{handshakeCompleted} on
L{Protocol} objects that provide L{IHandshakeListener}. At the time
C{handshakeCompleted} is invoked, the transport's peer certificate will
have been initialized. | test_handshakeNotification | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_handshakeStopWriting(self):
"""
If some data is written to the transport in C{connectionMade}, but
C{handshakeDone} doesn't like something it sees about the handshake, it
can use C{abortConnection} to ensure that the application never
receives that data.
"""
client, server, pump = handshakingClientAndServer(b"untrustworthy",
True)
wrappedServerProtocol = server.wrappedProtocol
pump.flush()
self.assertEqual(wrappedServerProtocol.received, []) | If some data is written to the transport in C{connectionMade}, but
C{handshakeDone} doesn't like something it sees about the handshake, it
can use C{abortConnection} to ensure that the application never
receives that data. | test_handshakeStopWriting | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_interfaces(self):
"""
L{TLSMemoryBIOProtocol} instances provide L{ISSLTransport} and
L{ISystemHandle}.
"""
proto = TLSMemoryBIOProtocol(None, None)
self.assertTrue(ISSLTransport.providedBy(proto))
self.assertTrue(ISystemHandle.providedBy(proto)) | L{TLSMemoryBIOProtocol} instances provide L{ISSLTransport} and
L{ISystemHandle}. | test_interfaces | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_wrappedProtocolInterfaces(self):
"""
L{TLSMemoryBIOProtocol} instances provide the interfaces provided by
the transport they wrap.
"""
class ITransport(Interface):
pass
class MyTransport(object):
def write(self, data):
pass
clientFactory = ClientFactory()
contextFactory = ClientTLSContext()
wrapperFactory = TLSMemoryBIOFactory(
contextFactory, True, clientFactory)
transport = MyTransport()
directlyProvides(transport, ITransport)
tlsProtocol = TLSMemoryBIOProtocol(wrapperFactory, Protocol())
tlsProtocol.makeConnection(transport)
self.assertTrue(ITransport.providedBy(tlsProtocol)) | L{TLSMemoryBIOProtocol} instances provide the interfaces provided by
the transport they wrap. | test_wrappedProtocolInterfaces | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_getHandle(self):
"""
L{TLSMemoryBIOProtocol.getHandle} returns the L{OpenSSL.SSL.Connection}
instance it uses to actually implement TLS.
This may seem odd. In fact, it is. The L{OpenSSL.SSL.Connection} is
not actually the "system handle" here, nor even an object the reactor
knows about directly. However, L{twisted.internet.ssl.Certificate}'s
C{peerFromTransport} and C{hostFromTransport} methods depend on being
able to get an L{OpenSSL.SSL.Connection} object in order to work
properly. Implementing L{ISystemHandle.getHandle} like this is the
easiest way for those APIs to be made to work. If they are changed,
then it may make sense to get rid of this implementation of
L{ISystemHandle} and return the underlying socket instead.
"""
factory = ClientFactory()
contextFactory = ClientTLSContext()
wrapperFactory = TLSMemoryBIOFactory(contextFactory, True, factory)
proto = TLSMemoryBIOProtocol(wrapperFactory, Protocol())
transport = StringTransport()
proto.makeConnection(transport)
self.assertIsInstance(proto.getHandle(), ConnectionType) | L{TLSMemoryBIOProtocol.getHandle} returns the L{OpenSSL.SSL.Connection}
instance it uses to actually implement TLS.
This may seem odd. In fact, it is. The L{OpenSSL.SSL.Connection} is
not actually the "system handle" here, nor even an object the reactor
knows about directly. However, L{twisted.internet.ssl.Certificate}'s
C{peerFromTransport} and C{hostFromTransport} methods depend on being
able to get an L{OpenSSL.SSL.Connection} object in order to work
properly. Implementing L{ISystemHandle.getHandle} like this is the
easiest way for those APIs to be made to work. If they are changed,
then it may make sense to get rid of this implementation of
L{ISystemHandle} and return the underlying socket instead. | test_getHandle | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_makeConnection(self):
"""
When L{TLSMemoryBIOProtocol} is connected to a transport, it connects
the protocol it wraps to a transport.
"""
clientProtocol = Protocol()
clientFactory = ClientFactory()
clientFactory.protocol = lambda: clientProtocol
contextFactory = ClientTLSContext()
wrapperFactory = TLSMemoryBIOFactory(
contextFactory, True, clientFactory)
sslProtocol = wrapperFactory.buildProtocol(None)
transport = StringTransport()
sslProtocol.makeConnection(transport)
self.assertIsNotNone(clientProtocol.transport)
self.assertIsNot(clientProtocol.transport, transport)
self.assertIs(clientProtocol.transport, sslProtocol) | When L{TLSMemoryBIOProtocol} is connected to a transport, it connects
the protocol it wraps to a transport. | test_makeConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def handshakeProtocols(self):
"""
Start handshake between TLS client and server.
"""
clientFactory = ClientFactory()
clientFactory.protocol = Protocol
clientContextFactory, handshakeDeferred = (
HandshakeCallbackContextFactory.factoryAndDeferred())
wrapperFactory = TLSMemoryBIOFactory(
clientContextFactory, True, clientFactory)
sslClientProtocol = wrapperFactory.buildProtocol(None)
serverFactory = ServerFactory()
serverFactory.protocol = Protocol
serverContextFactory = ServerTLSContext()
wrapperFactory = TLSMemoryBIOFactory(
serverContextFactory, False, serverFactory)
sslServerProtocol = wrapperFactory.buildProtocol(None)
connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol)
return (sslClientProtocol, sslServerProtocol, handshakeDeferred,
connectionDeferred) | Start handshake between TLS client and server. | handshakeProtocols | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_handshake(self):
"""
The TLS handshake is performed when L{TLSMemoryBIOProtocol} is
connected to a transport.
"""
tlsClient, tlsServer, handshakeDeferred, _ = self.handshakeProtocols()
# Only wait for the handshake to complete. Anything after that isn't
# important here.
return handshakeDeferred | The TLS handshake is performed when L{TLSMemoryBIOProtocol} is
connected to a transport. | test_handshake | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_handshakeFailure(self):
"""
L{TLSMemoryBIOProtocol} reports errors in the handshake process to the
application-level protocol object using its C{connectionLost} method
and disconnects the underlying transport.
"""
clientConnectionLost = Deferred()
clientFactory = ClientFactory()
clientFactory.protocol = (
lambda: ConnectionLostNotifyingProtocol(
clientConnectionLost))
clientContextFactory = HandshakeCallbackContextFactory()
wrapperFactory = TLSMemoryBIOFactory(
clientContextFactory, True, clientFactory)
sslClientProtocol = wrapperFactory.buildProtocol(None)
serverConnectionLost = Deferred()
serverFactory = ServerFactory()
serverFactory.protocol = (
lambda: ConnectionLostNotifyingProtocol(
serverConnectionLost))
# This context factory rejects any clients which do not present a
# certificate.
certificateData = FilePath(certPath).getContent()
certificate = PrivateCertificate.loadPEM(certificateData)
serverContextFactory = certificate.options(certificate)
wrapperFactory = TLSMemoryBIOFactory(
serverContextFactory, False, serverFactory)
sslServerProtocol = wrapperFactory.buildProtocol(None)
connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol)
def cbConnectionLost(protocol):
# The connection should close on its own in response to the error
# induced by the client not supplying the required certificate.
# After that, check to make sure the protocol's connectionLost was
# called with the right thing.
protocol.lostConnectionReason.trap(Error)
clientConnectionLost.addCallback(cbConnectionLost)
serverConnectionLost.addCallback(cbConnectionLost)
# Additionally, the underlying transport should have been told to
# go away.
return gatherResults([
clientConnectionLost, serverConnectionLost,
connectionDeferred]) | L{TLSMemoryBIOProtocol} reports errors in the handshake process to the
application-level protocol object using its C{connectionLost} method
and disconnects the underlying transport. | test_handshakeFailure | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_getPeerCertificate(self):
"""
L{TLSMemoryBIOProtocol.getPeerCertificate} returns the
L{OpenSSL.crypto.X509Type} instance representing the peer's
certificate.
"""
# Set up a client and server so there's a certificate to grab.
clientFactory = ClientFactory()
clientFactory.protocol = Protocol
clientContextFactory, handshakeDeferred = (
HandshakeCallbackContextFactory.factoryAndDeferred())
wrapperFactory = TLSMemoryBIOFactory(
clientContextFactory, True, clientFactory)
sslClientProtocol = wrapperFactory.buildProtocol(None)
serverFactory = ServerFactory()
serverFactory.protocol = Protocol
serverContextFactory = ServerTLSContext()
wrapperFactory = TLSMemoryBIOFactory(
serverContextFactory, False, serverFactory)
sslServerProtocol = wrapperFactory.buildProtocol(None)
loopbackAsync(sslServerProtocol, sslClientProtocol)
# Wait for the handshake
def cbHandshook(ignored):
# Grab the server's certificate and check it out
cert = sslClientProtocol.getPeerCertificate()
self.assertIsInstance(cert, X509Type)
self.assertEqual(
cert.digest('sha1'),
# openssl x509 -noout -sha1 -fingerprint -in server.pem
b'23:4B:72:99:2E:5D:5E:2B:02:C3:BC:1B:7C:50:67:05:4F:60:FF:C9')
handshakeDeferred.addCallback(cbHandshook)
return handshakeDeferred | L{TLSMemoryBIOProtocol.getPeerCertificate} returns the
L{OpenSSL.crypto.X509Type} instance representing the peer's
certificate. | test_getPeerCertificate | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_writeAfterHandshake(self):
"""
Bytes written to L{TLSMemoryBIOProtocol} before the handshake is
complete are received by the protocol on the other side of the
connection once the handshake succeeds.
"""
data = b"some bytes"
clientProtocol = Protocol()
clientFactory = ClientFactory()
clientFactory.protocol = lambda: clientProtocol
clientContextFactory, handshakeDeferred = (
HandshakeCallbackContextFactory.factoryAndDeferred())
wrapperFactory = TLSMemoryBIOFactory(
clientContextFactory, True, clientFactory)
sslClientProtocol = wrapperFactory.buildProtocol(None)
serverProtocol = AccumulatingProtocol(len(data))
serverFactory = ServerFactory()
serverFactory.protocol = lambda: serverProtocol
serverContextFactory = ServerTLSContext()
wrapperFactory = TLSMemoryBIOFactory(
serverContextFactory, False, serverFactory)
sslServerProtocol = wrapperFactory.buildProtocol(None)
connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol)
# Wait for the handshake to finish before writing anything.
def cbHandshook(ignored):
clientProtocol.transport.write(data)
# The server will drop the connection once it gets the bytes.
return connectionDeferred
handshakeDeferred.addCallback(cbHandshook)
# Once the connection is lost, make sure the server received the
# expected bytes.
def cbDisconnected(ignored):
self.assertEqual(b"".join(serverProtocol.received), data)
handshakeDeferred.addCallback(cbDisconnected)
return handshakeDeferred | Bytes written to L{TLSMemoryBIOProtocol} before the handshake is
complete are received by the protocol on the other side of the
connection once the handshake succeeds. | test_writeAfterHandshake | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def writeBeforeHandshakeTest(self, sendingProtocol, data):
"""
Run test where client sends data before handshake, given the sending
protocol and expected bytes.
"""
clientFactory = ClientFactory()
clientFactory.protocol = sendingProtocol
clientContextFactory, handshakeDeferred = (
HandshakeCallbackContextFactory.factoryAndDeferred())
wrapperFactory = TLSMemoryBIOFactory(
clientContextFactory, True, clientFactory)
sslClientProtocol = wrapperFactory.buildProtocol(None)
serverProtocol = AccumulatingProtocol(len(data))
serverFactory = ServerFactory()
serverFactory.protocol = lambda: serverProtocol
serverContextFactory = ServerTLSContext()
wrapperFactory = TLSMemoryBIOFactory(
serverContextFactory, False, serverFactory)
sslServerProtocol = wrapperFactory.buildProtocol(None)
connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol)
# Wait for the connection to end, then make sure the server received
# the bytes sent by the client.
def cbConnectionDone(ignored):
self.assertEqual(b"".join(serverProtocol.received), data)
connectionDeferred.addCallback(cbConnectionDone)
return connectionDeferred | Run test where client sends data before handshake, given the sending
protocol and expected bytes. | writeBeforeHandshakeTest | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_writeBeforeHandshake(self):
"""
Bytes written to L{TLSMemoryBIOProtocol} before the handshake is
complete are received by the protocol on the other side of the
connection once the handshake succeeds.
"""
data = b"some bytes"
class SimpleSendingProtocol(Protocol):
def connectionMade(self):
self.transport.write(data)
return self.writeBeforeHandshakeTest(SimpleSendingProtocol, data) | Bytes written to L{TLSMemoryBIOProtocol} before the handshake is
complete are received by the protocol on the other side of the
connection once the handshake succeeds. | test_writeBeforeHandshake | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_writeSequence(self):
"""
Bytes written to L{TLSMemoryBIOProtocol} with C{writeSequence} are
received by the protocol on the other side of the connection.
"""
data = b"some bytes"
class SimpleSendingProtocol(Protocol):
def connectionMade(self):
self.transport.writeSequence(list(iterbytes(data)))
return self.writeBeforeHandshakeTest(SimpleSendingProtocol, data) | Bytes written to L{TLSMemoryBIOProtocol} with C{writeSequence} are
received by the protocol on the other side of the connection. | test_writeSequence | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_writeAfterLoseConnection(self):
"""
Bytes written to L{TLSMemoryBIOProtocol} after C{loseConnection} is
called are not transmitted (unless there is a registered producer,
which will be tested elsewhere).
"""
data = b"some bytes"
class SimpleSendingProtocol(Protocol):
def connectionMade(self):
self.transport.write(data)
self.transport.loseConnection()
self.transport.write(b"hello")
self.transport.writeSequence([b"world"])
return self.writeBeforeHandshakeTest(SimpleSendingProtocol, data) | Bytes written to L{TLSMemoryBIOProtocol} after C{loseConnection} is
called are not transmitted (unless there is a registered producer,
which will be tested elsewhere). | test_writeAfterLoseConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_writeUnicodeRaisesTypeError(self):
"""
Writing C{unicode} to L{TLSMemoryBIOProtocol} throws a C{TypeError}.
"""
notBytes = u"hello"
result = []
class SimpleSendingProtocol(Protocol):
def connectionMade(self):
try:
self.transport.write(notBytes)
except TypeError:
result.append(True)
self.transport.write(b"bytes")
self.transport.loseConnection()
d = self.writeBeforeHandshakeTest(SimpleSendingProtocol, b"bytes")
return d.addCallback(lambda ign: self.assertEqual(result, [True])) | Writing C{unicode} to L{TLSMemoryBIOProtocol} throws a C{TypeError}. | test_writeUnicodeRaisesTypeError | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_multipleWrites(self):
"""
If multiple separate TLS messages are received in a single chunk from
the underlying transport, all of the application bytes from each
message are delivered to the application-level protocol.
"""
data = [b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h', b'i']
class SimpleSendingProtocol(Protocol):
def connectionMade(self):
for b in data:
self.transport.write(b)
clientFactory = ClientFactory()
clientFactory.protocol = SimpleSendingProtocol
clientContextFactory = HandshakeCallbackContextFactory()
wrapperFactory = TLSMemoryBIOFactory(
clientContextFactory, True, clientFactory)
sslClientProtocol = wrapperFactory.buildProtocol(None)
serverProtocol = AccumulatingProtocol(sum(map(len, data)))
serverFactory = ServerFactory()
serverFactory.protocol = lambda: serverProtocol
serverContextFactory = ServerTLSContext()
wrapperFactory = TLSMemoryBIOFactory(
serverContextFactory, False, serverFactory)
sslServerProtocol = wrapperFactory.buildProtocol(None)
connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol, collapsingPumpPolicy)
# Wait for the connection to end, then make sure the server received
# the bytes sent by the client.
def cbConnectionDone(ignored):
self.assertEqual(b"".join(serverProtocol.received), b''.join(data))
connectionDeferred.addCallback(cbConnectionDone)
return connectionDeferred | If multiple separate TLS messages are received in a single chunk from
the underlying transport, all of the application bytes from each
message are delivered to the application-level protocol. | test_multipleWrites | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def hugeWrite(self, method=TLSv1_METHOD):
"""
If a very long string is passed to L{TLSMemoryBIOProtocol.write}, any
trailing part of it which cannot be send immediately is buffered and
sent later.
"""
data = b"some bytes"
factor = 2 ** 20
class SimpleSendingProtocol(Protocol):
def connectionMade(self):
self.transport.write(data * factor)
clientFactory = ClientFactory()
clientFactory.protocol = SimpleSendingProtocol
clientContextFactory = HandshakeCallbackContextFactory(method=method)
wrapperFactory = TLSMemoryBIOFactory(
clientContextFactory, True, clientFactory)
sslClientProtocol = wrapperFactory.buildProtocol(None)
serverProtocol = AccumulatingProtocol(len(data) * factor)
serverFactory = ServerFactory()
serverFactory.protocol = lambda: serverProtocol
serverContextFactory = ServerTLSContext(method=method)
wrapperFactory = TLSMemoryBIOFactory(
serverContextFactory, False, serverFactory)
sslServerProtocol = wrapperFactory.buildProtocol(None)
connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol)
# Wait for the connection to end, then make sure the server received
# the bytes sent by the client.
def cbConnectionDone(ignored):
self.assertEqual(b"".join(serverProtocol.received), data * factor)
connectionDeferred.addCallback(cbConnectionDone)
return connectionDeferred | If a very long string is passed to L{TLSMemoryBIOProtocol.write}, any
trailing part of it which cannot be send immediately is buffered and
sent later. | hugeWrite | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_disorderlyShutdown(self):
"""
If a L{TLSMemoryBIOProtocol} loses its connection unexpectedly, this is
reported to the application.
"""
clientConnectionLost = Deferred()
clientFactory = ClientFactory()
clientFactory.protocol = (
lambda: ConnectionLostNotifyingProtocol(
clientConnectionLost))
clientContextFactory = HandshakeCallbackContextFactory()
wrapperFactory = TLSMemoryBIOFactory(
clientContextFactory, True, clientFactory)
sslClientProtocol = wrapperFactory.buildProtocol(None)
# Client speaks first, so the server can be dumb.
serverProtocol = Protocol()
loopbackAsync(serverProtocol, sslClientProtocol)
# Now destroy the connection.
serverProtocol.transport.loseConnection()
# And when the connection completely dies, check the reason.
def cbDisconnected(clientProtocol):
clientProtocol.lostConnectionReason.trap(Error, ConnectionLost)
clientConnectionLost.addCallback(cbDisconnected)
return clientConnectionLost | If a L{TLSMemoryBIOProtocol} loses its connection unexpectedly, this is
reported to the application. | test_disorderlyShutdown | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_loseConnectionAfterHandshake(self):
"""
L{TLSMemoryBIOProtocol.loseConnection} sends a TLS close alert and
shuts down the underlying connection cleanly on both sides, after
transmitting all buffered data.
"""
class NotifyingProtocol(ConnectionLostNotifyingProtocol):
def __init__(self, onConnectionLost):
ConnectionLostNotifyingProtocol.__init__(self,
onConnectionLost)
self.data = []
def dataReceived(self, data):
self.data.append(data)
clientConnectionLost = Deferred()
clientFactory = ClientFactory()
clientProtocol = NotifyingProtocol(clientConnectionLost)
clientFactory.protocol = lambda: clientProtocol
clientContextFactory, handshakeDeferred = (
HandshakeCallbackContextFactory.factoryAndDeferred())
wrapperFactory = TLSMemoryBIOFactory(
clientContextFactory, True, clientFactory)
sslClientProtocol = wrapperFactory.buildProtocol(None)
serverConnectionLost = Deferred()
serverProtocol = NotifyingProtocol(serverConnectionLost)
serverFactory = ServerFactory()
serverFactory.protocol = lambda: serverProtocol
serverContextFactory = ServerTLSContext()
wrapperFactory = TLSMemoryBIOFactory(
serverContextFactory, False, serverFactory)
sslServerProtocol = wrapperFactory.buildProtocol(None)
loopbackAsync(sslServerProtocol, sslClientProtocol)
chunkOfBytes = b"123456890" * 100000
# Wait for the handshake before dropping the connection.
def cbHandshake(ignored):
# Write more than a single bio_read, to ensure client will still
# have some data it needs to write when it receives the TLS close
# alert, and that simply doing a single bio_read won't be
# sufficient. Thus we will verify that any amount of buffered data
# will be written out before the connection is closed, rather than
# just small amounts that can be returned in a single bio_read:
clientProtocol.transport.write(chunkOfBytes)
serverProtocol.transport.write(b'x')
serverProtocol.transport.loseConnection()
# Now wait for the client and server to notice.
return gatherResults([clientConnectionLost, serverConnectionLost])
handshakeDeferred.addCallback(cbHandshake)
# Wait for the connection to end, then make sure the client and server
# weren't notified of a handshake failure that would cause the test to
# fail.
def cbConnectionDone(result):
(clientProtocol, serverProtocol) = result
clientProtocol.lostConnectionReason.trap(ConnectionDone)
serverProtocol.lostConnectionReason.trap(ConnectionDone)
# The server should have received all bytes sent by the client:
self.assertEqual(b"".join(serverProtocol.data), chunkOfBytes)
# The server should have closed its underlying transport, in
# addition to whatever it did to shut down the TLS layer.
self.assertTrue(serverProtocol.transport.q.disconnect)
# The client should also have closed its underlying transport once
# it saw the server shut down the TLS layer, so as to avoid relying
# on the server to close the underlying connection.
self.assertTrue(clientProtocol.transport.q.disconnect)
handshakeDeferred.addCallback(cbConnectionDone)
return handshakeDeferred | L{TLSMemoryBIOProtocol.loseConnection} sends a TLS close alert and
shuts down the underlying connection cleanly on both sides, after
transmitting all buffered data. | test_loseConnectionAfterHandshake | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_connectionLostOnlyAfterUnderlyingCloses(self):
"""
The user protocol's connectionLost is only called when transport
underlying TLS is disconnected.
"""
class LostProtocol(Protocol):
disconnected = None
def connectionLost(self, reason):
self.disconnected = reason
wrapperFactory = TLSMemoryBIOFactory(ClientTLSContext(),
True, ClientFactory())
protocol = LostProtocol()
tlsProtocol = TLSMemoryBIOProtocol(wrapperFactory, protocol)
transport = StringTransport()
tlsProtocol.makeConnection(transport)
# Pretend TLS shutdown finished cleanly; the underlying transport
# should be told to close, but the user protocol should not yet be
# notified:
tlsProtocol._tlsShutdownFinished(None)
self.assertTrue(transport.disconnecting)
self.assertIsNone(protocol.disconnected)
# Now close the underlying connection; the user protocol should be
# notified with the given reason (since TLS closed cleanly):
tlsProtocol.connectionLost(Failure(ConnectionLost("ono")))
self.assertTrue(protocol.disconnected.check(ConnectionLost))
self.assertEqual(protocol.disconnected.value.args, ("ono",)) | The user protocol's connectionLost is only called when transport
underlying TLS is disconnected. | test_connectionLostOnlyAfterUnderlyingCloses | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_loseConnectionTwice(self):
"""
If TLSMemoryBIOProtocol.loseConnection is called multiple times, all
but the first call have no effect.
"""
tlsClient, tlsServer, handshakeDeferred, disconnectDeferred = (
self.handshakeProtocols())
self.successResultOf(handshakeDeferred)
# Make sure loseConnection calls _shutdownTLS the first time (mostly
# to make sure we've overriding it correctly):
calls = []
def _shutdownTLS(shutdown=tlsClient._shutdownTLS):
calls.append(1)
return shutdown()
tlsClient._shutdownTLS = _shutdownTLS
tlsClient.write(b'x')
tlsClient.loseConnection()
self.assertTrue(tlsClient.disconnecting)
self.assertEqual(calls, [1])
# Make sure _shutdownTLS isn't called a second time:
tlsClient.loseConnection()
self.assertEqual(calls, [1])
# We do successfully disconnect at some point:
return disconnectDeferred | If TLSMemoryBIOProtocol.loseConnection is called multiple times, all
but the first call have no effect. | test_loseConnectionTwice | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_loseConnectionAfterConnectionLost(self):
"""
If TLSMemoryBIOProtocol.loseConnection is called after connectionLost,
it does nothing.
"""
tlsClient, tlsServer, handshakeDeferred, disconnectDeferred = (
self.handshakeProtocols())
# Make sure connectionLost calls _shutdownTLS, but loseConnection
# doesnt call it for the second time.
calls = []
def _shutdownTLS(shutdown=tlsClient._shutdownTLS):
calls.append(1)
return shutdown()
tlsServer._shutdownTLS = _shutdownTLS
tlsServer.write(b'x')
tlsClient.loseConnection()
def disconnected(_):
# At this point tlsServer.connectionLost is already called
self.assertEqual(calls, [1])
# This call should do nothing
tlsServer.loseConnection()
self.assertEqual(calls, [1])
disconnectDeferred.addCallback(disconnected)
return disconnectDeferred | If TLSMemoryBIOProtocol.loseConnection is called after connectionLost,
it does nothing. | test_loseConnectionAfterConnectionLost | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_unexpectedEOF(self):
"""
Unexpected disconnects get converted to ConnectionLost errors.
"""
tlsClient, tlsServer, handshakeDeferred, disconnectDeferred = (
self.handshakeProtocols())
serverProtocol = tlsServer.wrappedProtocol
data = []
reason = []
serverProtocol.dataReceived = data.append
serverProtocol.connectionLost = reason.append
# Write data, then disconnect *underlying* transport, resulting in an
# unexpected TLS disconnect:
def handshakeDone(ign):
tlsClient.write(b"hello")
tlsClient.transport.loseConnection()
handshakeDeferred.addCallback(handshakeDone)
# Receiver should be disconnected, with ConnectionLost notification
# (masking the Unexpected EOF SSL error):
def disconnected(ign):
self.assertTrue(reason[0].check(ConnectionLost), reason[0])
disconnectDeferred.addCallback(disconnected)
return disconnectDeferred | Unexpected disconnects get converted to ConnectionLost errors. | test_unexpectedEOF | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_errorWriting(self):
"""
Errors while writing cause the protocols to be disconnected.
"""
tlsClient, tlsServer, handshakeDeferred, disconnectDeferred = (
self.handshakeProtocols())
reason = []
tlsClient.wrappedProtocol.connectionLost = reason.append
# Pretend TLS connection is unhappy sending:
class Wrapper(object):
def __init__(self, wrapped):
self._wrapped = wrapped
def __getattr__(self, attr):
return getattr(self._wrapped, attr)
def send(self, *args):
raise Error("ONO!")
tlsClient._tlsConnection = Wrapper(tlsClient._tlsConnection)
# Write some data:
def handshakeDone(ign):
tlsClient.write(b"hello")
handshakeDeferred.addCallback(handshakeDone)
# Failed writer should be disconnected with SSL error:
def disconnected(ign):
self.assertTrue(reason[0].check(Error), reason[0])
disconnectDeferred.addCallback(disconnected)
return disconnectDeferred | Errors while writing cause the protocols to be disconnected. | test_errorWriting | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def nObjectsOfType(type):
"""
Return the number of instances of a given type in memory.
@param type: Type whose instances to find.
@return: The number of instances found.
"""
return sum(1 for x in gc.get_objects() if isinstance(x, type)) | Return the number of instances of a given type in memory.
@param type: Type whose instances to find.
@return: The number of instances found. | test_noCircularReferences.nObjectsOfType | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_noCircularReferences(self):
"""
TLSMemoryBIOProtocol doesn't leave circular references that keep
it in memory after connection is closed.
"""
def nObjectsOfType(type):
"""
Return the number of instances of a given type in memory.
@param type: Type whose instances to find.
@return: The number of instances found.
"""
return sum(1 for x in gc.get_objects() if isinstance(x, type))
self.addCleanup(gc.enable)
gc.disable()
class CloserProtocol(Protocol):
def dataReceived(self, data):
self.transport.loseConnection()
class GreeterProtocol(Protocol):
def connectionMade(self):
self.transport.write(b'hello')
origTLSProtos = nObjectsOfType(TLSMemoryBIOProtocol)
origServerProtos = nObjectsOfType(CloserProtocol)
authCert, serverCert = certificatesForAuthorityAndServer()
serverFactory = TLSMemoryBIOFactory(
serverCert.options(), False,
Factory.forProtocol(CloserProtocol)
)
clientFactory = TLSMemoryBIOFactory(
optionsForClientTLS(u'example.com', trustRoot=authCert), True,
Factory.forProtocol(GreeterProtocol)
)
loopbackAsync(
TLSMemoryBIOProtocol(serverFactory, CloserProtocol()),
TLSMemoryBIOProtocol(clientFactory, GreeterProtocol())
)
newTLSProtos = nObjectsOfType(TLSMemoryBIOProtocol)
newServerProtos = nObjectsOfType(CloserProtocol)
self.assertEqual(newTLSProtos, origTLSProtos)
self.assertEqual(newServerProtos, origServerProtos) | TLSMemoryBIOProtocol doesn't leave circular references that keep
it in memory after connection is closed. | test_noCircularReferences | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def drain(self, transport, allowEmpty=False):
"""
Drain the bytes currently pending write from a L{StringTransport}, then
clear it, since those bytes have been consumed.
@param transport: The L{StringTransport} to get the bytes from.
@type transport: L{StringTransport}
@param allowEmpty: Allow the test to pass even if the transport has no
outgoing bytes in it.
@type allowEmpty: L{bool}
@return: the outgoing bytes from the given transport
@rtype: L{bytes}
"""
value = transport.value()
transport.clear()
self.assertEqual(bool(allowEmpty or value), True)
return value | Drain the bytes currently pending write from a L{StringTransport}, then
clear it, since those bytes have been consumed.
@param transport: The L{StringTransport} to get the bytes from.
@type transport: L{StringTransport}
@param allowEmpty: Allow the test to pass even if the transport has no
outgoing bytes in it.
@type allowEmpty: L{bool}
@return: the outgoing bytes from the given transport
@rtype: L{bytes} | drain | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def flushTwoTLSProtocols(self, tlsProtocol, serverTLSProtocol):
"""
Transfer bytes back and forth between two TLS protocols.
"""
# We want to make sure all bytes are passed back and forth; JP
# estimated that 3 rounds should be enough:
for i in range(3):
clientData = self.drain(tlsProtocol.transport, True)
if clientData:
serverTLSProtocol.dataReceived(clientData)
serverData = self.drain(serverTLSProtocol.transport, True)
if serverData:
tlsProtocol.dataReceived(serverData)
if not serverData and not clientData:
break
self.assertEqual(tlsProtocol.transport.value(), b"")
self.assertEqual(serverTLSProtocol.transport.value(), b"") | Transfer bytes back and forth between two TLS protocols. | flushTwoTLSProtocols | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_producerDuringRenegotiation(self):
"""
If we write some data to a TLS connection that is blocked waiting for a
renegotiation with its peer, it will pause and resume its registered
producer exactly once.
"""
c, ct, cp = self.setupStreamingProducer()
s, st, sp = self.setupStreamingProducer(server=True)
self.flushTwoTLSProtocols(ct, st)
# no public API for this yet because it's (mostly) unnecessary, but we
# have to be prepared for a peer to do it to us
tlsc = ct._tlsConnection
tlsc.renegotiate()
self.assertRaises(WantReadError, tlsc.do_handshake)
ct._flushSendBIO()
st.dataReceived(self.drain(ct.transport))
payload = b'payload'
s.transport.write(payload)
s.transport.loseConnection()
# give the client the server the client's response...
ct.dataReceived(self.drain(st.transport))
messageThatUnblocksTheServer = self.drain(ct.transport)
# split it into just enough chunks that it would provoke the producer
# with an incorrect implementation...
for fragment in (messageThatUnblocksTheServer[0:1],
messageThatUnblocksTheServer[1:2],
messageThatUnblocksTheServer[2:]):
st.dataReceived(fragment)
self.assertEqual(st.transport.disconnecting, False)
s.transport.unregisterProducer()
self.flushTwoTLSProtocols(ct, st)
self.assertEqual(st.transport.disconnecting, True)
self.assertEqual(b''.join(c.received), payload)
self.assertEqual(sp.producerHistory, ['pause', 'resume']) | If we write some data to a TLS connection that is blocked waiting for a
renegotiation with its peer, it will pause and resume its registered
producer exactly once. | test_producerDuringRenegotiation | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_streamingProducerPausedInNormalMode(self):
"""
When the TLS transport is not blocked on reads, it correctly calls
pauseProducing on the registered producer.
"""
_, tlsProtocol, producer = self.setupStreamingProducer()
# The TLS protocol's transport pretends to be full, pausing its
# producer:
tlsProtocol.transport.producer.pauseProducing()
self.assertEqual(producer.producerState, 'paused')
self.assertEqual(producer.producerHistory, ['pause'])
self.assertTrue(tlsProtocol._producer._producerPaused) | When the TLS transport is not blocked on reads, it correctly calls
pauseProducing on the registered producer. | test_streamingProducerPausedInNormalMode | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_streamingProducerResumedInNormalMode(self):
"""
When the TLS transport is not blocked on reads, it correctly calls
resumeProducing on the registered producer.
"""
_, tlsProtocol, producer = self.setupStreamingProducer()
tlsProtocol.transport.producer.pauseProducing()
self.assertEqual(producer.producerHistory, ['pause'])
# The TLS protocol's transport pretends to have written everything
# out, so it resumes its producer:
tlsProtocol.transport.producer.resumeProducing()
self.assertEqual(producer.producerState, 'producing')
self.assertEqual(producer.producerHistory, ['pause', 'resume'])
self.assertFalse(tlsProtocol._producer._producerPaused) | When the TLS transport is not blocked on reads, it correctly calls
resumeProducing on the registered producer. | test_streamingProducerResumedInNormalMode | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_streamingProducerPausedInWriteBlockedOnReadMode(self):
"""
When the TLS transport is blocked on reads, it correctly calls
pauseProducing on the registered producer.
"""
clientProtocol, tlsProtocol, producer = self.setupStreamingProducer()
# Write to TLS transport. Because we do this before the initial TLS
# handshake is finished, writing bytes triggers a WantReadError,
# indicating that until bytes are read for the handshake, more bytes
# cannot be written. Thus writing bytes before the handshake should
# cause the producer to be paused:
clientProtocol.transport.write(b"hello")
self.assertEqual(producer.producerState, 'paused')
self.assertEqual(producer.producerHistory, ['pause'])
self.assertTrue(tlsProtocol._producer._producerPaused) | When the TLS transport is blocked on reads, it correctly calls
pauseProducing on the registered producer. | test_streamingProducerPausedInWriteBlockedOnReadMode | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_streamingProducerResumedInWriteBlockedOnReadMode(self):
"""
When the TLS transport is blocked on reads, it correctly calls
resumeProducing on the registered producer.
"""
clientProtocol, tlsProtocol, producer = self.setupStreamingProducer()
# Write to TLS transport, triggering WantReadError; this should cause
# the producer to be paused. We use a large chunk of data to make sure
# large writes don't trigger multiple pauses:
clientProtocol.transport.write(b"hello world" * 320000)
self.assertEqual(producer.producerHistory, ['pause'])
# Now deliver bytes that will fix the WantRead condition; this should
# unpause the producer:
serverProtocol, serverTLSProtocol = buildTLSProtocol(server=True)
self.flushTwoTLSProtocols(tlsProtocol, serverTLSProtocol)
self.assertEqual(producer.producerHistory, ['pause', 'resume'])
self.assertFalse(tlsProtocol._producer._producerPaused)
# Make sure we haven't disconnected for some reason:
self.assertFalse(tlsProtocol.transport.disconnecting)
self.assertEqual(producer.producerState, 'producing') | When the TLS transport is blocked on reads, it correctly calls
resumeProducing on the registered producer. | test_streamingProducerResumedInWriteBlockedOnReadMode | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_streamingProducerTwice(self):
"""
Registering a streaming producer twice throws an exception.
"""
clientProtocol, tlsProtocol, producer = self.setupStreamingProducer()
originalProducer = tlsProtocol._producer
producer2 = object()
self.assertRaises(RuntimeError,
clientProtocol.transport.registerProducer, producer2, True)
self.assertIs(tlsProtocol._producer, originalProducer) | Registering a streaming producer twice throws an exception. | test_streamingProducerTwice | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_streamingProducerUnregister(self):
"""
Unregistering a streaming producer removes it, reverting to initial state.
"""
clientProtocol, tlsProtocol, producer = self.setupStreamingProducer()
clientProtocol.transport.unregisterProducer()
self.assertIsNone(tlsProtocol._producer)
self.assertIsNone(tlsProtocol.transport.producer) | Unregistering a streaming producer removes it, reverting to initial state. | test_streamingProducerUnregister | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_streamingProducerUnregisterTwice(self):
"""
Unregistering a streaming producer when no producer is registered is
safe.
"""
clientProtocol, tlsProtocol, producer = self.setupStreamingProducer()
clientProtocol.transport.unregisterProducer()
clientProtocol.transport.unregisterProducer()
self.assertIsNone(tlsProtocol._producer)
self.assertIsNone(tlsProtocol.transport.producer) | Unregistering a streaming producer when no producer is registered is
safe. | test_streamingProducerUnregisterTwice | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def loseConnectionWithProducer(self, writeBlockedOnRead):
"""
Common code for tests involving writes by producer after
loseConnection is called.
"""
clientProtocol, tlsProtocol, producer = self.setupStreamingProducer()
serverProtocol, serverTLSProtocol = buildTLSProtocol(server=True)
if not writeBlockedOnRead:
# Do the initial handshake before write:
self.flushTwoTLSProtocols(tlsProtocol, serverTLSProtocol)
else:
# In this case the write below will trigger write-blocked-on-read
# condition...
pass
# Now write, then lose connection:
clientProtocol.transport.write(b"x ")
clientProtocol.transport.loseConnection()
self.flushTwoTLSProtocols(tlsProtocol, serverTLSProtocol)
# Underlying transport should not have loseConnection called yet, nor
# should producer be stopped:
self.assertFalse(tlsProtocol.transport.disconnecting)
self.assertFalse("stop" in producer.producerHistory)
# Writes from client to server should continue to go through, since we
# haven't unregistered producer yet:
clientProtocol.transport.write(b"hello")
clientProtocol.transport.writeSequence([b" ", b"world"])
# Unregister producer; this should trigger TLS shutdown:
clientProtocol.transport.unregisterProducer()
self.assertNotEqual(tlsProtocol.transport.value(), b"")
self.assertFalse(tlsProtocol.transport.disconnecting)
# Additional writes should not go through:
clientProtocol.transport.write(b"won't")
clientProtocol.transport.writeSequence([b"won't!"])
# Finish TLS close handshake:
self.flushTwoTLSProtocols(tlsProtocol, serverTLSProtocol)
self.assertTrue(tlsProtocol.transport.disconnecting)
# Bytes made it through, as long as they were written before producer
# was unregistered:
self.assertEqual(b"".join(serverProtocol.received), b"x hello world") | Common code for tests involving writes by producer after
loseConnection is called. | loseConnectionWithProducer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_streamingProducerLoseConnectionWithProducer(self):
"""
loseConnection() waits for the producer to unregister itself, then
does a clean TLS close alert, then closes the underlying connection.
"""
return self.loseConnectionWithProducer(False) | loseConnection() waits for the producer to unregister itself, then
does a clean TLS close alert, then closes the underlying connection. | test_streamingProducerLoseConnectionWithProducer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_streamingProducerLoseConnectionWithProducerWBOR(self):
"""
Even when writes are blocked on reading, loseConnection() waits for
the producer to unregister itself, then does a clean TLS close alert,
then closes the underlying connection.
"""
return self.loseConnectionWithProducer(True) | Even when writes are blocked on reading, loseConnection() waits for
the producer to unregister itself, then does a clean TLS close alert,
then closes the underlying connection. | test_streamingProducerLoseConnectionWithProducerWBOR | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_streamingProducerBothTransportsDecideToPause(self):
"""
pauseProducing() events can come from both the TLS transport layer and
the underlying transport. In this case, both decide to pause,
underlying first.
"""
class PausingStringTransport(StringTransport):
_didPause = False
def write(self, data):
if not self._didPause and self.producer is not None:
self._didPause = True
self.producer.pauseProducing()
StringTransport.write(self, data)
class TLSConnection(object):
def __init__(self):
self.l = []
def send(self, data):
# on first write, don't send all bytes:
if not self.l:
data = data[:-1]
# pause on second write:
if len(self.l) == 1:
self.l.append("paused")
raise WantReadError()
# otherwise just take in data:
self.l.append(data)
return len(data)
def set_connect_state(self):
pass
def do_handshake(self):
pass
def bio_write(self, data):
pass
def bio_read(self, size):
return b'X'
def recv(self, size):
raise WantReadError()
transport = PausingStringTransport()
clientProtocol, tlsProtocol, producer = self.setupStreamingProducer(
transport, fakeConnection=TLSConnection())
self.assertEqual(producer.producerState, 'producing')
# Shove in fake TLSConnection that will raise WantReadError the second
# time send() is called. This will allow us to have bytes written to
# to the PausingStringTransport, so it will pause the producer. Then,
# WantReadError will be thrown, triggering the TLS transport's
# producer code path.
clientProtocol.transport.write(b"hello")
self.assertEqual(producer.producerState, 'paused')
self.assertEqual(producer.producerHistory, ['pause'])
# Now, underlying transport resumes, and then we deliver some data to
# TLS transport so that it will resume:
tlsProtocol.transport.producer.resumeProducing()
self.assertEqual(producer.producerState, 'producing')
self.assertEqual(producer.producerHistory, ['pause', 'resume'])
tlsProtocol.dataReceived(b"hello")
self.assertEqual(producer.producerState, 'producing')
self.assertEqual(producer.producerHistory, ['pause', 'resume']) | pauseProducing() events can come from both the TLS transport layer and
the underlying transport. In this case, both decide to pause,
underlying first. | test_streamingProducerBothTransportsDecideToPause | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_streamingProducerStopProducing(self):
"""
If the underlying transport tells its producer to stopProducing(),
this is passed on to the high-level producer.
"""
_, tlsProtocol, producer = self.setupStreamingProducer()
tlsProtocol.transport.producer.stopProducing()
self.assertEqual(producer.producerState, 'stopped') | If the underlying transport tells its producer to stopProducing(),
this is passed on to the high-level producer. | test_streamingProducerStopProducing | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_nonStreamingProducer(self):
"""
Non-streaming producers get wrapped as streaming producers.
"""
clientProtocol, tlsProtocol = buildTLSProtocol()
producer = NonStreamingProducer(clientProtocol.transport)
# Register non-streaming producer:
clientProtocol.transport.registerProducer(producer, False)
streamingProducer = tlsProtocol.transport.producer._producer
# Verify it was wrapped into streaming producer:
self.assertIsInstance(streamingProducer, _PullToPush)
self.assertEqual(streamingProducer._producer, producer)
self.assertEqual(streamingProducer._consumer, clientProtocol.transport)
self.assertTrue(tlsProtocol.transport.streaming)
# Verify the streaming producer was started, and ran until the end:
def done(ignore):
# Our own producer is done:
self.assertIsNone(producer.consumer)
# The producer has been unregistered:
self.assertIsNone(tlsProtocol.transport.producer)
# The streaming producer wrapper knows it's done:
self.assertTrue(streamingProducer._finished)
producer.result.addCallback(done)
serverProtocol, serverTLSProtocol = buildTLSProtocol(server=True)
self.flushTwoTLSProtocols(tlsProtocol, serverTLSProtocol)
return producer.result | Non-streaming producers get wrapped as streaming producers. | test_nonStreamingProducer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_interface(self):
"""
L{_ProducerMembrane} implements L{IPushProducer}.
"""
producer = StringTransport()
membrane = _ProducerMembrane(producer)
self.assertTrue(verifyObject(IPushProducer, membrane)) | L{_ProducerMembrane} implements L{IPushProducer}. | test_interface | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def registerProducerAfterConnectionLost(self, streaming):
"""
If a producer is registered after the transport has disconnected, the
producer is not used, and its stopProducing method is called.
"""
clientProtocol, tlsProtocol = buildTLSProtocol()
clientProtocol.connectionLost = lambda reason: reason.trap(
Error, ConnectionLost)
class Producer(object):
stopped = False
def resumeProducing(self):
return 1/0 # this should never be called
def stopProducing(self):
self.stopped = True
# Disconnect the transport:
tlsProtocol.connectionLost(Failure(ConnectionDone()))
# Register the producer; startProducing should not be called, but
# stopProducing will:
producer = Producer()
tlsProtocol.registerProducer(producer, False)
self.assertIsNone(tlsProtocol.transport.producer)
self.assertTrue(producer.stopped) | If a producer is registered after the transport has disconnected, the
producer is not used, and its stopProducing method is called. | registerProducerAfterConnectionLost | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_streamingProducerAfterConnectionLost(self):
"""
If a streaming producer is registered after the transport has
disconnected, the producer is not used, and its stopProducing method
is called.
"""
self.registerProducerAfterConnectionLost(True) | If a streaming producer is registered after the transport has
disconnected, the producer is not used, and its stopProducing method
is called. | test_streamingProducerAfterConnectionLost | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_nonStreamingProducerAfterConnectionLost(self):
"""
If a non-streaming producer is registered after the transport has
disconnected, the producer is not used, and its stopProducing method
is called.
"""
self.registerProducerAfterConnectionLost(False) | If a non-streaming producer is registered after the transport has
disconnected, the producer is not used, and its stopProducing method
is called. | test_nonStreamingProducerAfterConnectionLost | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def streamUntilEnd(self, consumer):
"""
Verify the consumer writes out all its data, but is not called after
that.
"""
nsProducer = NonStreamingProducer(consumer)
streamingProducer = _PullToPush(nsProducer, consumer)
consumer.registerProducer(streamingProducer, True)
# The producer will call unregisterProducer(), and we need to hook
# that up so the streaming wrapper is notified; the
# TLSMemoryBIOProtocol will have to do this itself, which is tested
# elsewhere:
def unregister(orig=consumer.unregisterProducer):
orig()
streamingProducer.stopStreaming()
consumer.unregisterProducer = unregister
done = nsProducer.result
def doneStreaming(_):
# All data was streamed, and the producer unregistered itself:
self.assertEqual(consumer.value(), b"0123456789")
self.assertIsNone(consumer.producer)
# And the streaming wrapper stopped:
self.assertTrue(streamingProducer._finished)
done.addCallback(doneStreaming)
# Now, start streaming:
streamingProducer.startStreaming()
return done | Verify the consumer writes out all its data, but is not called after
that. | streamUntilEnd | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_writeUntilDone(self):
"""
When converted to a streaming producer, the non-streaming producer
writes out all its data, but is not called after that.
"""
consumer = StringTransport()
return self.streamUntilEnd(consumer) | When converted to a streaming producer, the non-streaming producer
writes out all its data, but is not called after that. | test_writeUntilDone | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_pause(self):
"""
When the streaming producer is paused, the underlying producer stops
getting resumeProducing calls.
"""
class PausingStringTransport(StringTransport):
writes = 0
def __init__(self):
StringTransport.__init__(self)
self.paused = Deferred()
def write(self, data):
self.writes += 1
StringTransport.write(self, data)
if self.writes == 3:
self.producer.pauseProducing()
d = self.paused
del self.paused
d.callback(None)
consumer = PausingStringTransport()
nsProducer = NonStreamingProducer(consumer)
streamingProducer = _PullToPush(nsProducer, consumer)
consumer.registerProducer(streamingProducer, True)
# Make sure the consumer does not continue:
def shouldNotBeCalled(ignore):
self.fail("BUG: The producer should not finish!")
nsProducer.result.addCallback(shouldNotBeCalled)
done = consumer.paused
def paused(ignore):
# The CooperatorTask driving the producer was paused:
self.assertEqual(streamingProducer._coopTask._pauseCount, 1)
done.addCallback(paused)
# Now, start streaming:
streamingProducer.startStreaming()
return done | When the streaming producer is paused, the underlying producer stops
getting resumeProducing calls. | test_pause | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_resume(self):
"""
When the streaming producer is paused and then resumed, the underlying
producer starts getting resumeProducing calls again after the resume.
The test will never finish (or rather, time out) if the resume
producing call is not working.
"""
class PausingStringTransport(StringTransport):
writes = 0
def write(self, data):
self.writes += 1
StringTransport.write(self, data)
if self.writes == 3:
self.producer.pauseProducing()
self.producer.resumeProducing()
consumer = PausingStringTransport()
return self.streamUntilEnd(consumer) | When the streaming producer is paused and then resumed, the underlying
producer starts getting resumeProducing calls again after the resume.
The test will never finish (or rather, time out) if the resume
producing call is not working. | test_resume | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_stopProducing(self):
"""
When the streaming producer is stopped by the consumer, the underlying
producer is stopped, and streaming is stopped.
"""
class StoppingStringTransport(StringTransport):
writes = 0
def write(self, data):
self.writes += 1
StringTransport.write(self, data)
if self.writes == 3:
self.producer.stopProducing()
consumer = StoppingStringTransport()
nsProducer = NonStreamingProducer(consumer)
streamingProducer = _PullToPush(nsProducer, consumer)
consumer.registerProducer(streamingProducer, True)
done = nsProducer.result
def doneStreaming(_):
# Not all data was streamed, and the producer was stopped:
self.assertEqual(consumer.value(), b"012")
self.assertTrue(nsProducer.stopped)
# And the streaming wrapper stopped:
self.assertTrue(streamingProducer._finished)
done.addCallback(doneStreaming)
# Now, start streaming:
streamingProducer.startStreaming()
return done | When the streaming producer is stopped by the consumer, the underlying
producer is stopped, and streaming is stopped. | test_stopProducing | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def resumeProducingRaises(self, consumer, expectedExceptions):
"""
Common implementation for tests where the underlying producer throws
an exception when its resumeProducing is called.
"""
class ThrowingProducer(NonStreamingProducer):
def resumeProducing(self):
if self.counter == 2:
return 1/0
else:
NonStreamingProducer.resumeProducing(self)
nsProducer = ThrowingProducer(consumer)
streamingProducer = _PullToPush(nsProducer, consumer)
consumer.registerProducer(streamingProducer, True)
# Register log observer:
loggedMsgs = []
log.addObserver(loggedMsgs.append)
self.addCleanup(log.removeObserver, loggedMsgs.append)
# Make consumer unregister do what TLSMemoryBIOProtocol would do:
def unregister(orig=consumer.unregisterProducer):
orig()
streamingProducer.stopStreaming()
consumer.unregisterProducer = unregister
# Start streaming:
streamingProducer.startStreaming()
done = streamingProducer._coopTask.whenDone()
done.addErrback(lambda reason: reason.trap(TaskStopped))
def stopped(ign):
self.assertEqual(consumer.value(), b"01")
# Any errors from resumeProducing were logged:
errors = self.flushLoggedErrors()
self.assertEqual(len(errors), len(expectedExceptions))
for f, (expected, msg), logMsg in zip(
errors, expectedExceptions, loggedMsgs):
self.assertTrue(f.check(expected))
self.assertIn(msg, logMsg['why'])
# And the streaming wrapper stopped:
self.assertTrue(streamingProducer._finished)
done.addCallback(stopped)
return done | Common implementation for tests where the underlying producer throws
an exception when its resumeProducing is called. | resumeProducingRaises | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_resumeProducingRaises(self):
"""
If the underlying producer raises an exception when resumeProducing is
called, the streaming wrapper should log the error, unregister from
the consumer and stop streaming.
"""
consumer = StringTransport()
done = self.resumeProducingRaises(
consumer,
[(ZeroDivisionError, "failed, producing will be stopped")])
def cleanShutdown(ignore):
# Producer was unregistered from consumer:
self.assertIsNone(consumer.producer)
done.addCallback(cleanShutdown)
return done | If the underlying producer raises an exception when resumeProducing is
called, the streaming wrapper should log the error, unregister from
the consumer and stop streaming. | test_resumeProducingRaises | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_resumeProducingRaiseAndUnregisterProducerRaises(self):
"""
If the underlying producer raises an exception when resumeProducing is
called, the streaming wrapper should log the error, unregister from
the consumer and stop streaming even if the unregisterProducer call
also raise.
"""
consumer = StringTransport()
def raiser():
raise RuntimeError()
consumer.unregisterProducer = raiser
return self.resumeProducingRaises(
consumer,
[(ZeroDivisionError, "failed, producing will be stopped"),
(RuntimeError, "failed to unregister producer")]) | If the underlying producer raises an exception when resumeProducing is
called, the streaming wrapper should log the error, unregister from
the consumer and stop streaming even if the unregisterProducer call
also raise. | test_resumeProducingRaiseAndUnregisterProducerRaises | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_stopStreamingTwice(self):
"""
stopStreaming() can be called more than once without blowing
up. This is useful for error-handling paths.
"""
consumer = StringTransport()
nsProducer = NonStreamingProducer(consumer)
streamingProducer = _PullToPush(nsProducer, consumer)
streamingProducer.startStreaming()
streamingProducer.stopStreaming()
streamingProducer.stopStreaming()
self.assertTrue(streamingProducer._finished) | stopStreaming() can be called more than once without blowing
up. This is useful for error-handling paths. | test_stopStreamingTwice | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_interface(self):
"""
L{_PullToPush} implements L{IPushProducer}.
"""
consumer = StringTransport()
nsProducer = NonStreamingProducer(consumer)
streamingProducer = _PullToPush(nsProducer, consumer)
self.assertTrue(verifyObject(IPushProducer, streamingProducer)) | L{_PullToPush} implements L{IPushProducer}. | test_interface | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def __init__(self, acceptableProtocols):
"""
Create a L{ClientNegotiationFactory}.
@param acceptableProtocols: The protocols the client will accept
speaking after the TLS handshake is complete.
@type acceptableProtocols: L{list} of L{bytes}
"""
self._acceptableProtocols = acceptableProtocols | Create a L{ClientNegotiationFactory}.
@param acceptableProtocols: The protocols the client will accept
speaking after the TLS handshake is complete.
@type acceptableProtocols: L{list} of L{bytes} | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def acceptableProtocols(self):
"""
Returns a list of protocols that can be spoken by the connection
factory in the form of ALPN tokens, as laid out in the IANA registry
for ALPN tokens.
@return: a list of ALPN tokens in order of preference.
@rtype: L{list} of L{bytes}
"""
return self._acceptableProtocols | Returns a list of protocols that can be spoken by the connection
factory in the form of ALPN tokens, as laid out in the IANA registry
for ALPN tokens.
@return: a list of ALPN tokens in order of preference.
@rtype: L{list} of L{bytes} | acceptableProtocols | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def __init__(self, acceptableProtocols):
"""
Create a L{ServerNegotiationFactory}.
@param acceptableProtocols: The protocols the server will accept
speaking after the TLS handshake is complete.
@type acceptableProtocols: L{list} of L{bytes}
"""
self._acceptableProtocols = acceptableProtocols | Create a L{ServerNegotiationFactory}.
@param acceptableProtocols: The protocols the server will accept
speaking after the TLS handshake is complete.
@type acceptableProtocols: L{list} of L{bytes} | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def acceptableProtocols(self):
"""
Returns a list of protocols that can be spoken by the connection
factory in the form of ALPN tokens, as laid out in the IANA registry
for ALPN tokens.
@return: a list of ALPN tokens in order of preference.
@rtype: L{list} of L{bytes}
"""
return self._acceptableProtocols | Returns a list of protocols that can be spoken by the connection
factory in the form of ALPN tokens, as laid out in the IANA registry
for ALPN tokens.
@return: a list of ALPN tokens in order of preference.
@rtype: L{list} of L{bytes} | acceptableProtocols | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def handshakeProtocols(self, clientProtocols, serverProtocols):
"""
Start handshake between TLS client and server.
@param clientProtocols: The protocols the client will accept speaking
after the TLS handshake is complete.
@type clientProtocols: L{list} of L{bytes}
@param serverProtocols: The protocols the server will accept speaking
after the TLS handshake is complete.
@type serverProtocols: L{list} of L{bytes}
@return: A L{tuple} of four different items: the client L{Protocol},
the server L{Protocol}, a L{Deferred} that fires when the client
first receives bytes (and so the TLS connection is complete), and a
L{Deferred} that fires when the server first receives bytes.
@rtype: A L{tuple} of (L{Protocol}, L{Protocol}, L{Deferred},
L{Deferred})
"""
data = b'some bytes'
class NotifyingSender(Protocol):
def __init__(self, notifier):
self.notifier = notifier
def connectionMade(self):
self.transport.writeSequence(list(iterbytes(data)))
def dataReceived(self, data):
if self.notifier is not None:
self.notifier.callback(self)
self.notifier = None
clientDataReceived = Deferred()
clientFactory = ClientNegotiationFactory(clientProtocols)
clientFactory.protocol = lambda: NotifyingSender(
clientDataReceived
)
clientContextFactory, _ = (
HandshakeCallbackContextFactory.factoryAndDeferred())
wrapperFactory = TLSMemoryBIOFactory(
clientContextFactory, True, clientFactory)
sslClientProtocol = wrapperFactory.buildProtocol(None)
serverDataReceived = Deferred()
serverFactory = ServerNegotiationFactory(serverProtocols)
serverFactory.protocol = lambda: NotifyingSender(
serverDataReceived
)
serverContextFactory = ServerTLSContext()
wrapperFactory = TLSMemoryBIOFactory(
serverContextFactory, False, serverFactory)
sslServerProtocol = wrapperFactory.buildProtocol(None)
loopbackAsync(
sslServerProtocol, sslClientProtocol
)
return (sslClientProtocol, sslServerProtocol, clientDataReceived,
serverDataReceived) | Start handshake between TLS client and server.
@param clientProtocols: The protocols the client will accept speaking
after the TLS handshake is complete.
@type clientProtocols: L{list} of L{bytes}
@param serverProtocols: The protocols the server will accept speaking
after the TLS handshake is complete.
@type serverProtocols: L{list} of L{bytes}
@return: A L{tuple} of four different items: the client L{Protocol},
the server L{Protocol}, a L{Deferred} that fires when the client
first receives bytes (and so the TLS connection is complete), and a
L{Deferred} that fires when the server first receives bytes.
@rtype: A L{tuple} of (L{Protocol}, L{Protocol}, L{Deferred},
L{Deferred}) | handshakeProtocols | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_negotiationWithNoProtocols(self):
"""
When factories support L{IProtocolNegotiationFactory} but don't
advertise support for any protocols, no protocols are negotiated.
"""
client, server, clientDataReceived, serverDataReceived = (
self.handshakeProtocols([], [])
)
def checkNegotiatedProtocol(ignored):
self.assertEqual(client.negotiatedProtocol, None)
self.assertEqual(server.negotiatedProtocol, None)
clientDataReceived.addCallback(lambda ignored: serverDataReceived)
serverDataReceived.addCallback(checkNegotiatedProtocol)
return clientDataReceived | When factories support L{IProtocolNegotiationFactory} but don't
advertise support for any protocols, no protocols are negotiated. | test_negotiationWithNoProtocols | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_negotiationWithProtocolOverlap(self):
"""
When factories support L{IProtocolNegotiationFactory} and support
overlapping protocols, the first protocol is negotiated.
"""
client, server, clientDataReceived, serverDataReceived = (
self.handshakeProtocols([b'h2', b'http/1.1'], [b'h2', b'http/1.1'])
)
def checkNegotiatedProtocol(ignored):
self.assertEqual(client.negotiatedProtocol, b'h2')
self.assertEqual(server.negotiatedProtocol, b'h2')
clientDataReceived.addCallback(lambda ignored: serverDataReceived)
serverDataReceived.addCallback(checkNegotiatedProtocol)
return clientDataReceived | When factories support L{IProtocolNegotiationFactory} and support
overlapping protocols, the first protocol is negotiated. | test_negotiationWithProtocolOverlap | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_negotiationClientOnly(self):
"""
When factories support L{IProtocolNegotiationFactory} and only the
client advertises, nothing is negotiated.
"""
client, server, clientDataReceived, serverDataReceived = (
self.handshakeProtocols([b'h2', b'http/1.1'], [])
)
def checkNegotiatedProtocol(ignored):
self.assertEqual(client.negotiatedProtocol, None)
self.assertEqual(server.negotiatedProtocol, None)
clientDataReceived.addCallback(lambda ignored: serverDataReceived)
serverDataReceived.addCallback(checkNegotiatedProtocol)
return clientDataReceived | When factories support L{IProtocolNegotiationFactory} and only the
client advertises, nothing is negotiated. | test_negotiationClientOnly | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def test_negotiationServerOnly(self):
"""
When factories support L{IProtocolNegotiationFactory} and only the
server advertises, nothing is negotiated.
"""
client, server, clientDataReceived, serverDataReceived = (
self.handshakeProtocols([], [b'h2', b'http/1.1'])
)
def checkNegotiatedProtocol(ignored):
self.assertEqual(client.negotiatedProtocol, None)
self.assertEqual(server.negotiatedProtocol, None)
clientDataReceived.addCallback(lambda ignored: serverDataReceived)
serverDataReceived.addCallback(checkNegotiatedProtocol)
return clientDataReceived | When factories support L{IProtocolNegotiationFactory} and only the
server advertises, nothing is negotiated. | test_negotiationServerOnly | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/test/test_tls.py | MIT |
def getSource(ao):
"""Pass me an AO, I'll return a nicely-formatted source representation."""
return indentify("app = " + prettify(ao)) | Pass me an AO, I'll return a nicely-formatted source representation. | getSource | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/aot.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/aot.py | MIT |
def unjellyFromAOT(aot):
"""
Pass me an Abstract Object Tree, and I'll unjelly it for you.
"""
return AOTUnjellier().unjelly(aot) | Pass me an Abstract Object Tree, and I'll unjelly it for you. | unjellyFromAOT | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/aot.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/aot.py | MIT |
def unjellyFromSource(stringOrFile):
"""
Pass me a string of code or a filename that defines an 'app' variable (in
terms of Abstract Objects!), and I'll execute it and unjelly the resulting
AOT for you, returning a newly unpersisted Application object!
"""
ns = {"Instance": Instance,
"InstanceMethod": InstanceMethod,
"Class": Class,
"Function": Function,
"Module": Module,
"Ref": Ref,
"Deref": Deref,
"Copyreg": Copyreg,
}
if hasattr(stringOrFile, "read"):
source = stringOrFile.read()
else:
source = stringOrFile
code = compile(source, "<source>", "exec")
eval(code, ns, ns)
if 'app' in ns:
return unjellyFromAOT(ns['app'])
else:
raise ValueError("%s needs to define an 'app', it didn't!" % stringOrFile) | Pass me a string of code or a filename that defines an 'app' variable (in
terms of Abstract Objects!), and I'll execute it and unjelly the resulting
AOT for you, returning a newly unpersisted Application object! | unjellyFromSource | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/aot.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/aot.py | MIT |
def unjellyLater(self, node):
"""Unjelly a node, later.
"""
d = crefutil._Defer()
self.unjellyInto(d, 0, node)
return d | Unjelly a node, later. | unjellyLater | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/aot.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/aot.py | MIT |
def unjellyInto(self, obj, loc, ao):
"""Utility method for unjellying one object into another.
This automates the handling of backreferences.
"""
o = self.unjellyAO(ao)
obj[loc] = o
if isinstance(o, crefutil.NotKnown):
o.addDependant(obj, loc)
return o | Utility method for unjellying one object into another.
This automates the handling of backreferences. | unjellyInto | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/aot.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/aot.py | MIT |
def unjellyAttribute(self, instance, attrName, ao):
#XXX this is unused????
"""Utility method for unjellying into instances of attributes.
Use this rather than unjellyAO unless you like surprising bugs!
Alternatively, you can use unjellyInto on your instance's __dict__.
"""
self.unjellyInto(instance.__dict__, attrName, ao) | Utility method for unjellying into instances of attributes.
Use this rather than unjellyAO unless you like surprising bugs!
Alternatively, you can use unjellyInto on your instance's __dict__. | unjellyAttribute | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/aot.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/aot.py | MIT |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.