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_connectionLostAfterReceivingResponseBeforeRequestGenerationDone(self):
"""
If response bytes are delivered to L{HTTP11ClientProtocol} before the
request completes, calling C{connectionLost} on the protocol will
result in protocol being moved to C{'CONNECTION_LOST'} state.
"""
request = SlowRequest()
d = self.protocol.request(request)
self.protocol.dataReceived(
b"HTTP/1.1 400 BAD REQUEST\r\n"
b"Content-Length: 9\r\n"
b"\r\n"
b"tisk tisk")
def cbResponse(response):
p = AccumulatingProtocol()
whenFinished = p.closedDeferred = Deferred()
response.deliverBody(p)
return whenFinished.addCallback(
lambda ign: (response, p.data))
d.addCallback(cbResponse)
def cbAllResponse(ignore):
request.finished.callback(None)
# Nothing dire will happen when the connection is lost
self.protocol.connectionLost(Failure(ArbitraryException()))
self.assertEqual(self.protocol._state, u'CONNECTION_LOST')
d.addCallback(cbAllResponse)
return d | If response bytes are delivered to L{HTTP11ClientProtocol} before the
request completes, calling C{connectionLost} on the protocol will
result in protocol being moved to C{'CONNECTION_LOST'} state. | test_connectionLostAfterReceivingResponseBeforeRequestGenerationDone | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_receiveResponseBody(self):
"""
The C{deliverBody} method of the response object with which the
L{Deferred} returned by L{HTTP11ClientProtocol.request} fires can be
used to get the body of the response.
"""
protocol = AccumulatingProtocol()
whenFinished = protocol.closedDeferred = Deferred()
requestDeferred = self.protocol.request(Request(b'GET', b'/', _boringHeaders, None))
self.protocol.dataReceived(
b"HTTP/1.1 200 OK\r\n"
b"Content-Length: 6\r\n"
b"\r")
# Here's what's going on: all the response headers have been delivered
# by this point, so the request Deferred can fire with a Response
# object. The body is yet to come, but that's okay, because the
# Response object is how you *get* the body.
result = []
requestDeferred.addCallback(result.append)
self.assertEqual(result, [])
# Deliver the very last byte of the response. It is exactly at this
# point which the Deferred returned by request should fire.
self.protocol.dataReceived(b"\n")
response = result[0]
response.deliverBody(protocol)
self.protocol.dataReceived(b"foo")
self.protocol.dataReceived(b"bar")
def cbAllResponse(ignored):
self.assertEqual(protocol.data, b"foobar")
protocol.closedReason.trap(ResponseDone)
whenFinished.addCallback(cbAllResponse)
return whenFinished | The C{deliverBody} method of the response object with which the
L{Deferred} returned by L{HTTP11ClientProtocol.request} fires can be
used to get the body of the response. | test_receiveResponseBody | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_responseBodyFinishedWhenConnectionLostWhenContentLengthIsUnknown(
self):
"""
If the length of the response body is unknown, the protocol passed to
the response's C{deliverBody} method has its C{connectionLost}
method called with a L{Failure} wrapping a L{PotentialDataLoss}
exception.
"""
requestDeferred = self.protocol.request(Request(b'GET', b'/',
_boringHeaders, None))
self.protocol.dataReceived(
b"HTTP/1.1 200 OK\r\n"
b"\r\n")
result = []
requestDeferred.addCallback(result.append)
response = result[0]
protocol = AccumulatingProtocol()
response.deliverBody(protocol)
self.protocol.dataReceived(b"foo")
self.protocol.dataReceived(b"bar")
self.assertEqual(protocol.data, b"foobar")
self.protocol.connectionLost(
Failure(ConnectionDone(u"low-level transport disconnected")))
protocol.closedReason.trap(PotentialDataLoss) | If the length of the response body is unknown, the protocol passed to
the response's C{deliverBody} method has its C{connectionLost}
method called with a L{Failure} wrapping a L{PotentialDataLoss}
exception. | test_responseBodyFinishedWhenConnectionLostWhenContentLengthIsUnknown | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_chunkedResponseBodyUnfinishedWhenConnectionLost(self):
"""
If the final chunk has not been received when the connection is lost
(for any reason), the protocol passed to C{deliverBody} has its
C{connectionLost} method called with a L{Failure} wrapping the
exception for that reason.
"""
requestDeferred = self.protocol.request(Request(b'GET', b'/',
_boringHeaders, None))
self.protocol.dataReceived(
b"HTTP/1.1 200 OK\r\n"
b"Transfer-Encoding: chunked\r\n"
b"\r\n")
result = []
requestDeferred.addCallback(result.append)
response = result[0]
protocol = AccumulatingProtocol()
response.deliverBody(protocol)
self.protocol.dataReceived(b"3\r\nfoo\r\n")
self.protocol.dataReceived(b"3\r\nbar\r\n")
self.assertEqual(protocol.data, b"foobar")
self.protocol.connectionLost(Failure(ArbitraryException()))
return assertResponseFailed(
self, fail(protocol.closedReason), [ArbitraryException, _DataLoss]) | If the final chunk has not been received when the connection is lost
(for any reason), the protocol passed to C{deliverBody} has its
C{connectionLost} method called with a L{Failure} wrapping the
exception for that reason. | test_chunkedResponseBodyUnfinishedWhenConnectionLost | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_parserDataReceivedException(self):
"""
If the parser L{HTTP11ClientProtocol} delivers bytes to in
C{dataReceived} raises an exception, the exception is wrapped in a
L{Failure} and passed to the parser's C{connectionLost} and then the
L{HTTP11ClientProtocol}'s transport is disconnected.
"""
requestDeferred = self.protocol.request(Request(b'GET', b'/',
_boringHeaders, None))
self.protocol.dataReceived(b'unparseable garbage goes here\r\n')
d = assertResponseFailed(self, requestDeferred, [ParseError])
def cbFailed(exc):
self.assertTrue(self.transport.disconnecting)
self.assertEqual(
exc.reasons[0].value.data, b'unparseable garbage goes here')
# Now do what StringTransport doesn't do but a real transport would
# have, call connectionLost on the HTTP11ClientProtocol. Nothing
# is asserted about this, but it's important for it to not raise an
# exception.
self.protocol.connectionLost(Failure(ConnectionDone(u"it is done")))
d.addCallback(cbFailed)
return d | If the parser L{HTTP11ClientProtocol} delivers bytes to in
C{dataReceived} raises an exception, the exception is wrapped in a
L{Failure} and passed to the parser's C{connectionLost} and then the
L{HTTP11ClientProtocol}'s transport is disconnected. | test_parserDataReceivedException | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_proxyStopped(self):
"""
When the HTTP response parser is disconnected, the
L{TransportProxyProducer} which was connected to it as a transport is
stopped.
"""
requestDeferred = self.protocol.request(Request(b'GET', b'/',
_boringHeaders, None))
transport = self.protocol._parser.transport
self.assertIdentical(transport._producer, self.transport)
self.protocol._disconnectParser(
Failure(ConnectionDone(u"connection done")))
self.assertIdentical(transport._producer, None)
return assertResponseFailed(self, requestDeferred, [ConnectionDone]) | When the HTTP response parser is disconnected, the
L{TransportProxyProducer} which was connected to it as a transport is
stopped. | test_proxyStopped | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_abortClosesConnection(self):
"""
L{HTTP11ClientProtocol.abort} will tell the transport to close its
connection when it is invoked, and returns a C{Deferred} that fires
when the connection is lost.
"""
transport = StringTransport()
protocol = HTTP11ClientProtocol()
protocol.makeConnection(transport)
r1 = []
r2 = []
protocol.abort().addCallback(r1.append)
protocol.abort().addCallback(r2.append)
self.assertEqual((r1, r2), ([], []))
self.assertTrue(transport.disconnecting)
# Disconnect protocol, the Deferreds will fire:
protocol.connectionLost(Failure(ConnectionDone()))
self.assertEqual(r1, [None])
self.assertEqual(r2, [None]) | L{HTTP11ClientProtocol.abort} will tell the transport to close its
connection when it is invoked, and returns a C{Deferred} that fires
when the connection is lost. | test_abortClosesConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_abortAfterConnectionLost(self):
"""
L{HTTP11ClientProtocol.abort} called after the connection is lost
returns a C{Deferred} that fires immediately.
"""
transport = StringTransport()
protocol = HTTP11ClientProtocol()
protocol.makeConnection(transport)
protocol.connectionLost(Failure(ConnectionDone()))
result = []
protocol.abort().addCallback(result.append)
self.assertEqual(result, [None])
self.assertEqual(protocol._state, u"CONNECTION_LOST") | L{HTTP11ClientProtocol.abort} called after the connection is lost
returns a C{Deferred} that fires immediately. | test_abortAfterConnectionLost | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_abortBeforeResponseBody(self):
"""
The Deferred returned by L{HTTP11ClientProtocol.request} will fire
with a L{ResponseFailed} failure containing a L{ConnectionAborted}
exception, if the connection was aborted before all response headers
have been received.
"""
transport = StringTransport()
protocol = HTTP11ClientProtocol()
protocol.makeConnection(transport)
result = protocol.request(Request(b'GET', b'/', _boringHeaders, None))
protocol.abort()
self.assertTrue(transport.disconnecting)
protocol.connectionLost(Failure(ConnectionDone()))
return assertResponseFailed(self, result, [ConnectionAborted]) | The Deferred returned by L{HTTP11ClientProtocol.request} will fire
with a L{ResponseFailed} failure containing a L{ConnectionAborted}
exception, if the connection was aborted before all response headers
have been received. | test_abortBeforeResponseBody | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def connectionMade(self):
"""
Abort the HTTP connection.
"""
protocol.abort() | Abort the HTTP connection. | test_abortAfterResponseHeaders.connectionMade | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def connectionLost(self, reason):
"""
Make the reason for the losing of the connection available to
the unit test via C{testResult}.
"""
testResult.errback(reason) | Make the reason for the losing of the connection available to
the unit test via C{testResult}. | test_abortAfterResponseHeaders.connectionLost | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def deliverBody(response):
"""
Connect the L{BodyDestination} response body protocol to the
response, and then simulate connection loss after ensuring that
the HTTP connection has been aborted.
"""
response.deliverBody(BodyDestination())
self.assertTrue(transport.disconnecting)
protocol.connectionLost(Failure(ConnectionDone())) | Connect the L{BodyDestination} response body protocol to the
response, and then simulate connection loss after ensuring that
the HTTP connection has been aborted. | test_abortAfterResponseHeaders.deliverBody | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_abortAfterResponseHeaders(self):
"""
When the connection is aborted after the response headers have
been received and the L{Response} has been made available to
application code, the response body protocol's C{connectionLost}
method will be invoked with a L{ResponseFailed} failure containing a
L{ConnectionAborted} exception.
"""
# We need to set StringTransport to lenient mode because we'll call
# resumeProducing on it after the connection is aborted. That's ok:
# for real transports nothing will happen.
transport = StringTransport(lenient=True)
protocol = HTTP11ClientProtocol()
protocol.makeConnection(transport)
result = protocol.request(Request(b'GET', b'/', _boringHeaders, None))
protocol.dataReceived(
b"HTTP/1.1 200 OK\r\n"
b"Content-Length: 1\r\n"
b"\r\n"
)
testResult = Deferred()
class BodyDestination(Protocol):
"""
A body response protocol which immediately aborts the HTTP
connection.
"""
def connectionMade(self):
"""
Abort the HTTP connection.
"""
protocol.abort()
def connectionLost(self, reason):
"""
Make the reason for the losing of the connection available to
the unit test via C{testResult}.
"""
testResult.errback(reason)
def deliverBody(response):
"""
Connect the L{BodyDestination} response body protocol to the
response, and then simulate connection loss after ensuring that
the HTTP connection has been aborted.
"""
response.deliverBody(BodyDestination())
self.assertTrue(transport.disconnecting)
protocol.connectionLost(Failure(ConnectionDone()))
def checkError(error):
self.assertIsInstance(error.response, Response)
result.addCallback(deliverBody)
deferred = assertResponseFailed(self, testResult,
[ConnectionAborted, _DataLoss])
return deferred.addCallback(checkError) | When the connection is aborted after the response headers have
been received and the L{Response} has been made available to
application code, the response body protocol's C{connectionLost}
method will be invoked with a L{ResponseFailed} failure containing a
L{ConnectionAborted} exception. | test_abortAfterResponseHeaders | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_quiescentCallbackCalled(self):
"""
If after a response is done the {HTTP11ClientProtocol} stays open and
returns to QUIESCENT state, all per-request state is reset and the
C{quiescentCallback} is called with the protocol instance.
This is useful for implementing a persistent connection pool.
The C{quiescentCallback} is called *before* the response-receiving
protocol's C{connectionLost}, so that new requests triggered by end of
first request can re-use a persistent connection.
"""
quiescentResult = []
def callback(p):
self.assertEqual(p, protocol)
self.assertEqual(p.state, u"QUIESCENT")
quiescentResult.append(p)
transport = StringTransport()
protocol = HTTP11ClientProtocol(callback)
protocol.makeConnection(transport)
requestDeferred = protocol.request(
Request(b'GET', b'/', _boringHeaders, None, persistent=True))
protocol.dataReceived(
b"HTTP/1.1 200 OK\r\n"
b"Content-length: 3\r\n"
b"\r\n")
# Headers done, but still no quiescent callback:
self.assertEqual(quiescentResult, [])
result = []
requestDeferred.addCallback(result.append)
response = result[0]
# When response body is done (i.e. connectionLost is called), note the
# fact in quiescentResult:
bodyProtocol = AccumulatingProtocol()
bodyProtocol.closedDeferred = Deferred()
bodyProtocol.closedDeferred.addCallback(
lambda ign: quiescentResult.append(u"response done"))
response.deliverBody(bodyProtocol)
protocol.dataReceived(b"abc")
bodyProtocol.closedReason.trap(ResponseDone)
# Quiescent callback called *before* protocol handling the response
# body gets its connectionLost called:
self.assertEqual(quiescentResult, [protocol, u"response done"])
# Make sure everything was cleaned up:
self.assertEqual(protocol._parser, None)
self.assertEqual(protocol._finishedRequest, None)
self.assertEqual(protocol._currentRequest, None)
self.assertEqual(protocol._transportProxy, None)
self.assertEqual(protocol._responseDeferred, None) | If after a response is done the {HTTP11ClientProtocol} stays open and
returns to QUIESCENT state, all per-request state is reset and the
C{quiescentCallback} is called with the protocol instance.
This is useful for implementing a persistent connection pool.
The C{quiescentCallback} is called *before* the response-receiving
protocol's C{connectionLost}, so that new requests triggered by end of
first request can re-use a persistent connection. | test_quiescentCallbackCalled | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_transportProducingWhenQuiescentAfterFullBody(self):
"""
The C{quiescentCallback} passed to L{HTTP11ClientProtocol} will only be
invoked once that protocol is in a state similar to its initial state.
One of the aspects of this initial state is the producer-state of its
transport; an L{HTTP11ClientProtocol} begins with a transport that is
producing, i.e. not C{pauseProducing}'d.
Therefore, when C{quiescentCallback} is invoked the protocol will still
be producing.
"""
quiescentResult = []
def callback(p):
self.assertEqual(p, protocol)
self.assertEqual(p.state, u"QUIESCENT")
quiescentResult.append(p)
transport = StringTransport()
protocol = HTTP11ClientProtocol(callback)
protocol.makeConnection(transport)
requestDeferred = protocol.request(
Request(b'GET', b'/', _boringHeaders, None, persistent=True))
protocol.dataReceived(
b"HTTP/1.1 200 OK\r\n"
b"Content-length: 3\r\n"
b"\r\n"
b"BBB" # _full_ content of the response.
)
response = self.successResultOf(requestDeferred)
# Sanity check: response should have full response body, just waiting
# for deliverBody
self.assertEqual(response._state, u'DEFERRED_CLOSE')
# The transport is quiescent, because the response has been received.
# If we were connection pooling here, it would have been returned to
# the pool.
self.assertEqual(len(quiescentResult), 1)
# And that transport is totally still reading, right? Because it would
# leak forever if it were sitting there disconnected from the
# reactor...
self.assertEqual(transport.producerState, u'producing') | The C{quiescentCallback} passed to L{HTTP11ClientProtocol} will only be
invoked once that protocol is in a state similar to its initial state.
One of the aspects of this initial state is the producer-state of its
transport; an L{HTTP11ClientProtocol} begins with a transport that is
producing, i.e. not C{pauseProducing}'d.
Therefore, when C{quiescentCallback} is invoked the protocol will still
be producing. | test_transportProducingWhenQuiescentAfterFullBody | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_quiescentCallbackCalledEmptyResponse(self):
"""
The quiescentCallback is called before the request C{Deferred} fires,
in cases where the response has no body.
"""
quiescentResult = []
def callback(p):
self.assertEqual(p, protocol)
self.assertEqual(p.state, u"QUIESCENT")
quiescentResult.append(p)
transport = StringTransport()
protocol = HTTP11ClientProtocol(callback)
protocol.makeConnection(transport)
requestDeferred = protocol.request(
Request(b'GET', b'/', _boringHeaders, None, persistent=True))
requestDeferred.addCallback(quiescentResult.append)
protocol.dataReceived(
b"HTTP/1.1 200 OK\r\n"
b"Content-length: 0\r\n"
b"\r\n")
self.assertEqual(len(quiescentResult), 2)
self.assertIdentical(quiescentResult[0], protocol)
self.assertIsInstance(quiescentResult[1], Response) | The quiescentCallback is called before the request C{Deferred} fires,
in cases where the response has no body. | test_quiescentCallbackCalledEmptyResponse | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_quiescentCallbackNotCalled(self):
"""
If after a response is done the {HTTP11ClientProtocol} returns a
C{Connection: close} header in the response, the C{quiescentCallback}
is not called and the connection is lost.
"""
quiescentResult = []
transport = StringTransport()
protocol = HTTP11ClientProtocol(quiescentResult.append)
protocol.makeConnection(transport)
requestDeferred = protocol.request(
Request(b'GET', b'/', _boringHeaders, None, persistent=True))
protocol.dataReceived(
b"HTTP/1.1 200 OK\r\n"
b"Content-length: 0\r\n"
b"Connection: close\r\n"
b"\r\n")
result = []
requestDeferred.addCallback(result.append)
response = result[0]
bodyProtocol = AccumulatingProtocol()
response.deliverBody(bodyProtocol)
bodyProtocol.closedReason.trap(ResponseDone)
self.assertEqual(quiescentResult, [])
self.assertTrue(transport.disconnecting) | If after a response is done the {HTTP11ClientProtocol} returns a
C{Connection: close} header in the response, the C{quiescentCallback}
is not called and the connection is lost. | test_quiescentCallbackNotCalled | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_quiescentCallbackNotCalledNonPersistentQuery(self):
"""
If the request was non-persistent (i.e. sent C{Connection: close}),
the C{quiescentCallback} is not called and the connection is lost.
"""
quiescentResult = []
transport = StringTransport()
protocol = HTTP11ClientProtocol(quiescentResult.append)
protocol.makeConnection(transport)
requestDeferred = protocol.request(
Request(b'GET', b'/', _boringHeaders, None, persistent=False))
protocol.dataReceived(
b"HTTP/1.1 200 OK\r\n"
b"Content-length: 0\r\n"
b"\r\n")
result = []
requestDeferred.addCallback(result.append)
response = result[0]
bodyProtocol = AccumulatingProtocol()
response.deliverBody(bodyProtocol)
bodyProtocol.closedReason.trap(ResponseDone)
self.assertEqual(quiescentResult, [])
self.assertTrue(transport.disconnecting) | If the request was non-persistent (i.e. sent C{Connection: close}),
the C{quiescentCallback} is not called and the connection is lost. | test_quiescentCallbackNotCalledNonPersistentQuery | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_quiescentCallbackThrows(self):
"""
If C{quiescentCallback} throws an exception, the error is logged and
protocol is disconnected.
"""
def callback(p):
raise ZeroDivisionError()
logObserver = EventLoggingObserver.createWithCleanup(
self,
globalLogPublisher
)
transport = StringTransport()
protocol = HTTP11ClientProtocol(callback)
protocol.makeConnection(transport)
requestDeferred = protocol.request(
Request(b'GET', b'/', _boringHeaders, None, persistent=True))
protocol.dataReceived(
b"HTTP/1.1 200 OK\r\n"
b"Content-length: 0\r\n"
b"\r\n")
result = []
requestDeferred.addCallback(result.append)
response = result[0]
bodyProtocol = AccumulatingProtocol()
response.deliverBody(bodyProtocol)
bodyProtocol.closedReason.trap(ResponseDone)
self.assertEquals(1, len(logObserver))
event = logObserver[0]
f = event["log_failure"]
self.assertIsInstance(f.value, ZeroDivisionError)
self.flushLoggedErrors(ZeroDivisionError)
self.assertTrue(transport.disconnecting) | If C{quiescentCallback} throws an exception, the error is logged and
protocol is disconnected. | test_quiescentCallbackThrows | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_cancelBeforeResponse(self):
"""
The L{Deferred} returned by L{HTTP11ClientProtocol.request} will fire
with a L{ResponseNeverReceived} failure containing a L{CancelledError}
exception if the request was cancelled before any response headers were
received.
"""
transport = StringTransport()
protocol = HTTP11ClientProtocol()
protocol.makeConnection(transport)
result = protocol.request(Request(b'GET', b'/', _boringHeaders, None))
result.cancel()
self.assertTrue(transport.disconnected)
return assertWrapperExceptionTypes(
self, result, ResponseNeverReceived, [CancelledError]) | The L{Deferred} returned by L{HTTP11ClientProtocol.request} will fire
with a L{ResponseNeverReceived} failure containing a L{CancelledError}
exception if the request was cancelled before any response headers were
received. | test_cancelBeforeResponse | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_cancelDuringResponse(self):
"""
The L{Deferred} returned by L{HTTP11ClientProtocol.request} will fire
with a L{ResponseFailed} failure containing a L{CancelledError}
exception if the request was cancelled before all response headers were
received.
"""
transport = StringTransport()
protocol = HTTP11ClientProtocol()
protocol.makeConnection(transport)
result = protocol.request(Request(b'GET', b'/', _boringHeaders, None))
protocol.dataReceived(b"HTTP/1.1 200 OK\r\n")
result.cancel()
self.assertTrue(transport.disconnected)
return assertResponseFailed(self, result, [CancelledError]) | The L{Deferred} returned by L{HTTP11ClientProtocol.request} will fire
with a L{ResponseFailed} failure containing a L{CancelledError}
exception if the request was cancelled before all response headers were
received. | test_cancelDuringResponse | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def assertCancelDuringBodyProduction(self, producerLength):
"""
The L{Deferred} returned by L{HTTP11ClientProtocol.request} will fire
with a L{RequestGenerationFailed} failure containing a
L{CancelledError} exception if the request was cancelled before a
C{bodyProducer} has finished producing.
"""
transport = StringTransport()
protocol = HTTP11ClientProtocol()
protocol.makeConnection(transport)
producer = StringProducer(producerLength)
nonLocal = {'cancelled': False}
def cancel(ign):
nonLocal['cancelled'] = True
def startProducing(consumer):
producer.consumer = consumer
producer.finished = Deferred(cancel)
return producer.finished
producer.startProducing = startProducing
result = protocol.request(Request(b'POST', b'/bar', _boringHeaders,
producer))
producer.consumer.write(b'x' * 5)
result.cancel()
self.assertTrue(transport.disconnected)
self.assertTrue(nonLocal['cancelled'])
return assertRequestGenerationFailed(self, result, [CancelledError]) | The L{Deferred} returned by L{HTTP11ClientProtocol.request} will fire
with a L{RequestGenerationFailed} failure containing a
L{CancelledError} exception if the request was cancelled before a
C{bodyProducer} has finished producing. | assertCancelDuringBodyProduction | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_cancelDuringBodyProduction(self):
"""
The L{Deferred} returned by L{HTTP11ClientProtocol.request} will fire
with a L{RequestGenerationFailed} failure containing a
L{CancelledError} exception if the request was cancelled before a
C{bodyProducer} with an explicit length has finished producing.
"""
return self.assertCancelDuringBodyProduction(10) | The L{Deferred} returned by L{HTTP11ClientProtocol.request} will fire
with a L{RequestGenerationFailed} failure containing a
L{CancelledError} exception if the request was cancelled before a
C{bodyProducer} with an explicit length has finished producing. | test_cancelDuringBodyProduction | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_cancelDuringChunkedBodyProduction(self):
"""
The L{Deferred} returned by L{HTTP11ClientProtocol.request} will fire
with a L{RequestGenerationFailed} failure containing a
L{CancelledError} exception if the request was cancelled before a
C{bodyProducer} with C{UNKNOWN_LENGTH} has finished producing.
"""
return self.assertCancelDuringBodyProduction(UNKNOWN_LENGTH) | The L{Deferred} returned by L{HTTP11ClientProtocol.request} will fire
with a L{RequestGenerationFailed} failure containing a
L{CancelledError} exception if the request was cancelled before a
C{bodyProducer} with C{UNKNOWN_LENGTH} has finished producing. | test_cancelDuringChunkedBodyProduction | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_sendSimplestRequest(self):
"""
L{Request.writeTo} formats the request data and writes it to the given
transport.
"""
Request(b'GET', b'/', _boringHeaders, None).writeTo(self.transport)
self.assertEqual(
self.transport.value(),
b"GET / HTTP/1.1\r\n"
b"Connection: close\r\n"
b"Host: example.com\r\n"
b"\r\n") | L{Request.writeTo} formats the request data and writes it to the given
transport. | test_sendSimplestRequest | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_sendSimplestPersistentRequest(self):
"""
A pesistent request does not send 'Connection: close' header.
"""
req = Request(b'GET', b'/', _boringHeaders, None, persistent=True)
req.writeTo(self.transport)
self.assertEqual(
self.transport.value(),
b"GET / HTTP/1.1\r\n"
b"Host: example.com\r\n"
b"\r\n") | A pesistent request does not send 'Connection: close' header. | test_sendSimplestPersistentRequest | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_sendRequestHeaders(self):
"""
L{Request.writeTo} formats header data and writes it to the given
transport.
"""
headers = Headers({b'x-foo': [b'bar', b'baz'],
b'host': [b'example.com']})
Request(b'GET', b'/foo', headers, None).writeTo(self.transport)
lines = self.transport.value().split(b'\r\n')
self.assertEqual(lines[0], b"GET /foo HTTP/1.1")
self.assertEqual(lines[-2:], [b"", b""])
del lines[0], lines[-2:]
lines.sort()
self.assertEqual(
lines,
[b"Connection: close",
b"Host: example.com",
b"X-Foo: bar",
b"X-Foo: baz"]) | L{Request.writeTo} formats header data and writes it to the given
transport. | test_sendRequestHeaders | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_sanitizeLinearWhitespaceInRequestHeaders(self):
"""
Linear whitespace in request headers is replaced with a single
space.
"""
for component in bytesLinearWhitespaceComponents:
headers = Headers({component: [component],
b"host": [b"example.invalid"]})
transport = StringTransport()
Request(b'GET', b'/foo', headers, None).writeTo(transport)
lines = transport.value().split(b'\r\n')
self.assertEqual(lines[0], b"GET /foo HTTP/1.1")
self.assertEqual(lines[-2:], [b"", b""])
del lines[0], lines[-2:]
lines.remove(b"Connection: close")
lines.remove(b"Host: example.invalid")
sanitizedHeaderLine = b": ".join([sanitizedBytes, sanitizedBytes])
self.assertEqual(lines, [sanitizedHeaderLine]) | Linear whitespace in request headers is replaced with a single
space. | test_sanitizeLinearWhitespaceInRequestHeaders | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_sendChunkedRequestBody(self):
"""
L{Request.writeTo} uses chunked encoding to write data from the request
body producer to the given transport. It registers the request body
producer with the transport.
"""
producer = StringProducer(UNKNOWN_LENGTH)
request = Request(b'POST', b'/bar', _boringHeaders, producer)
request.writeTo(self.transport)
self.assertNotIdentical(producer.consumer, None)
self.assertIdentical(self.transport.producer, producer)
self.assertTrue(self.transport.streaming)
self.assertEqual(
self.transport.value(),
b"POST /bar HTTP/1.1\r\n"
b"Connection: close\r\n"
b"Transfer-Encoding: chunked\r\n"
b"Host: example.com\r\n"
b"\r\n")
self.transport.clear()
producer.consumer.write(b'x' * 3)
producer.consumer.write(b'y' * 15)
producer.finished.callback(None)
self.assertIdentical(self.transport.producer, None)
self.assertEqual(
self.transport.value(),
b"3\r\n"
b"xxx\r\n"
b"f\r\n"
b"yyyyyyyyyyyyyyy\r\n"
b"0\r\n"
b"\r\n") | L{Request.writeTo} uses chunked encoding to write data from the request
body producer to the given transport. It registers the request body
producer with the transport. | test_sendChunkedRequestBody | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_sendChunkedRequestBodyWithError(self):
"""
If L{Request} is created with a C{bodyProducer} without a known length
and the L{Deferred} returned from its C{startProducing} method fires
with a L{Failure}, the L{Deferred} returned by L{Request.writeTo} fires
with that L{Failure} and the body producer is unregistered from the
transport. The final zero-length chunk is not written to the
transport.
"""
producer = StringProducer(UNKNOWN_LENGTH)
request = Request(b'POST', b'/bar', _boringHeaders, producer)
writeDeferred = request.writeTo(self.transport)
self.transport.clear()
producer.finished.errback(ArbitraryException())
def cbFailed(ignored):
self.assertEqual(self.transport.value(), b"")
self.assertIdentical(self.transport.producer, None)
d = self.assertFailure(writeDeferred, ArbitraryException)
d.addCallback(cbFailed)
return d | If L{Request} is created with a C{bodyProducer} without a known length
and the L{Deferred} returned from its C{startProducing} method fires
with a L{Failure}, the L{Deferred} returned by L{Request.writeTo} fires
with that L{Failure} and the body producer is unregistered from the
transport. The final zero-length chunk is not written to the
transport. | test_sendChunkedRequestBodyWithError | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_sendRequestBodyWithLength(self):
"""
If L{Request} is created with a C{bodyProducer} with a known length,
that length is sent as the value for the I{Content-Length} header and
chunked encoding is not used.
"""
producer = StringProducer(3)
request = Request(b'POST', b'/bar', _boringHeaders, producer)
request.writeTo(self.transport)
self.assertNotIdentical(producer.consumer, None)
self.assertIdentical(self.transport.producer, producer)
self.assertTrue(self.transport.streaming)
self.assertEqual(
self.transport.value(),
b"POST /bar HTTP/1.1\r\n"
b"Connection: close\r\n"
b"Content-Length: 3\r\n"
b"Host: example.com\r\n"
b"\r\n")
self.transport.clear()
producer.consumer.write(b'abc')
producer.finished.callback(None)
self.assertIdentical(self.transport.producer, None)
self.assertEqual(self.transport.value(), b"abc") | If L{Request} is created with a C{bodyProducer} with a known length,
that length is sent as the value for the I{Content-Length} header and
chunked encoding is not used. | test_sendRequestBodyWithLength | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def _sendRequestEmptyBodyWithLength(self, method):
"""
Verify that the message generated by a L{Request} initialized with
the given method and C{None} as the C{bodyProducer} includes
I{Content-Length: 0} in the header.
@param method: The HTTP method issue in the request.
@type method: L{bytes}
"""
request = Request(method, b"/foo", _boringHeaders, None)
request.writeTo(self.transport)
self.assertEqual(
self.transport.value(),
method + b" /foo HTTP/1.1\r\n"
b"Connection: close\r\n"
b"Content-Length: 0\r\n"
b"Host: example.com\r\n"
b"\r\n") | Verify that the message generated by a L{Request} initialized with
the given method and C{None} as the C{bodyProducer} includes
I{Content-Length: 0} in the header.
@param method: The HTTP method issue in the request.
@type method: L{bytes} | _sendRequestEmptyBodyWithLength | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_sendPUTRequestEmptyBody(self):
"""
If I{PUT} L{Request} is created without a C{bodyProducer},
I{Content-Length: 0} is included in the header and chunked
encoding is not used.
"""
self._sendRequestEmptyBodyWithLength(b"PUT") | If I{PUT} L{Request} is created without a C{bodyProducer},
I{Content-Length: 0} is included in the header and chunked
encoding is not used. | test_sendPUTRequestEmptyBody | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_sendPOSTRequestEmptyBody(self):
"""
If I{POST} L{Request} is created without a C{bodyProducer},
I{Content-Length: 0} is included in the header and chunked
encoding is not used.
"""
self._sendRequestEmptyBodyWithLength(b"POST") | If I{POST} L{Request} is created without a C{bodyProducer},
I{Content-Length: 0} is included in the header and chunked
encoding is not used. | test_sendPOSTRequestEmptyBody | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_sendRequestBodyWithTooFewBytes(self):
"""
If L{Request} is created with a C{bodyProducer} with a known length and
the producer does not produce that many bytes, the L{Deferred} returned
by L{Request.writeTo} fires with a L{Failure} wrapping a
L{WrongBodyLength} exception.
"""
producer = StringProducer(3)
request = Request(b'POST', b'/bar', _boringHeaders, producer)
writeDeferred = request.writeTo(self.transport)
producer.consumer.write(b'ab')
producer.finished.callback(None)
self.assertIdentical(self.transport.producer, None)
return self.assertFailure(writeDeferred, WrongBodyLength) | If L{Request} is created with a C{bodyProducer} with a known length and
the producer does not produce that many bytes, the L{Deferred} returned
by L{Request.writeTo} fires with a L{Failure} wrapping a
L{WrongBodyLength} exception. | test_sendRequestBodyWithTooFewBytes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def _sendRequestBodyWithTooManyBytesTest(self, finisher):
"""
Verify that when too many bytes have been written by a body producer
and then the body producer's C{startProducing} L{Deferred} fires that
the producer is unregistered from the transport and that the
L{Deferred} returned from L{Request.writeTo} is fired with a L{Failure}
wrapping a L{WrongBodyLength}.
@param finisher: A callable which will be invoked with the body
producer after too many bytes have been written to the transport.
It should fire the startProducing Deferred somehow.
"""
producer = StringProducer(3)
request = Request(b'POST', b'/bar', _boringHeaders, producer)
writeDeferred = request.writeTo(self.transport)
producer.consumer.write(b'ab')
# The producer hasn't misbehaved yet, so it shouldn't have been
# stopped.
self.assertFalse(producer.stopped)
producer.consumer.write(b'cd')
# Now the producer *has* misbehaved, so we should have tried to
# make it stop.
self.assertTrue(producer.stopped)
# The transport should have had the producer unregistered from it as
# well.
self.assertIdentical(self.transport.producer, None)
def cbFailed(exc):
# The "cd" should not have been written to the transport because
# the request can now locally be recognized to be invalid. If we
# had written the extra bytes, the server could have decided to
# start processing the request, which would be bad since we're
# going to indicate failure locally.
self.assertEqual(
self.transport.value(),
b"POST /bar HTTP/1.1\r\n"
b"Connection: close\r\n"
b"Content-Length: 3\r\n"
b"Host: example.com\r\n"
b"\r\n"
b"ab")
self.transport.clear()
# Subsequent writes should be ignored, as should firing the
# Deferred returned from startProducing.
self.assertRaises(ExcessWrite, producer.consumer.write, b'ef')
# Likewise, if the Deferred returned from startProducing fires,
# this should more or less be ignored (aside from possibly logging
# an error).
finisher(producer)
# There should have been nothing further written to the transport.
self.assertEqual(self.transport.value(), b"")
d = self.assertFailure(writeDeferred, WrongBodyLength)
d.addCallback(cbFailed)
return d | Verify that when too many bytes have been written by a body producer
and then the body producer's C{startProducing} L{Deferred} fires that
the producer is unregistered from the transport and that the
L{Deferred} returned from L{Request.writeTo} is fired with a L{Failure}
wrapping a L{WrongBodyLength}.
@param finisher: A callable which will be invoked with the body
producer after too many bytes have been written to the transport.
It should fire the startProducing Deferred somehow. | _sendRequestBodyWithTooManyBytesTest | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_sendRequestBodyWithTooManyBytes(self):
"""
If L{Request} is created with a C{bodyProducer} with a known length and
the producer tries to produce more than than many bytes, the
L{Deferred} returned by L{Request.writeTo} fires with a L{Failure}
wrapping a L{WrongBodyLength} exception.
"""
def finisher(producer):
producer.finished.callback(None)
return self._sendRequestBodyWithTooManyBytesTest(finisher) | If L{Request} is created with a C{bodyProducer} with a known length and
the producer tries to produce more than than many bytes, the
L{Deferred} returned by L{Request.writeTo} fires with a L{Failure}
wrapping a L{WrongBodyLength} exception. | test_sendRequestBodyWithTooManyBytes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_sendRequestBodyErrorWithTooManyBytes(self):
"""
If L{Request} is created with a C{bodyProducer} with a known length and
the producer tries to produce more than than many bytes, the
L{Deferred} returned by L{Request.writeTo} fires with a L{Failure}
wrapping a L{WrongBodyLength} exception.
"""
logObserver = EventLoggingObserver.createWithCleanup(
self,
globalLogPublisher
)
def finisher(producer):
producer.finished.errback(ArbitraryException())
event = logObserver[0]
self.assertIn("log_failure", event)
f = event["log_failure"]
self.assertIsInstance(f.value, ArbitraryException)
errors = self.flushLoggedErrors(ArbitraryException)
self.assertEqual(len(errors), 1)
return self._sendRequestBodyWithTooManyBytesTest(finisher) | If L{Request} is created with a C{bodyProducer} with a known length and
the producer tries to produce more than than many bytes, the
L{Deferred} returned by L{Request.writeTo} fires with a L{Failure}
wrapping a L{WrongBodyLength} exception. | test_sendRequestBodyErrorWithTooManyBytes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_sendRequestBodyErrorWithConsumerError(self):
"""
Though there should be no way for the internal C{finishedConsuming}
L{Deferred} in L{Request._writeToBodyProducerContentLength} to fire a
L{Failure} after the C{finishedProducing} L{Deferred} has fired, in
case this does happen, the error should be logged with a message about
how there's probably a bug in L{Request}.
This is a whitebox test.
"""
logObserver = EventLoggingObserver.createWithCleanup(
self,
globalLogPublisher
)
producer = StringProducer(3)
request = Request(b'POST', b'/bar', _boringHeaders, producer)
request.writeTo(self.transport)
finishedConsuming = producer.consumer._finished
producer.consumer.write(b'abc')
producer.finished.callback(None)
finishedConsuming.errback(ArbitraryException())
event = logObserver[0]
self.assertIn("log_failure", event)
f = event["log_failure"]
self.assertIsInstance(f.value, ArbitraryException)
self.assertEqual(len(self.flushLoggedErrors(ArbitraryException)), 1) | Though there should be no way for the internal C{finishedConsuming}
L{Deferred} in L{Request._writeToBodyProducerContentLength} to fire a
L{Failure} after the C{finishedProducing} L{Deferred} has fired, in
case this does happen, the error should be logged with a message about
how there's probably a bug in L{Request}.
This is a whitebox test. | test_sendRequestBodyErrorWithConsumerError | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def _sendRequestBodyFinishedEarlyThenTooManyBytes(self, finisher):
"""
Verify that if the body producer fires its Deferred and then keeps
writing to the consumer that the extra writes are ignored and the
L{Deferred} returned by L{Request.writeTo} fires with a L{Failure}
wrapping the most appropriate exception type.
"""
producer = StringProducer(3)
request = Request(b'POST', b'/bar', _boringHeaders, producer)
writeDeferred = request.writeTo(self.transport)
producer.consumer.write(b'ab')
finisher(producer)
self.assertIdentical(self.transport.producer, None)
self.transport.clear()
self.assertRaises(ExcessWrite, producer.consumer.write, b'cd')
self.assertEqual(self.transport.value(), b"")
return writeDeferred | Verify that if the body producer fires its Deferred and then keeps
writing to the consumer that the extra writes are ignored and the
L{Deferred} returned by L{Request.writeTo} fires with a L{Failure}
wrapping the most appropriate exception type. | _sendRequestBodyFinishedEarlyThenTooManyBytes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_sendRequestBodyFinishedEarlyThenTooManyBytes(self):
"""
If the request body producer indicates it is done by firing the
L{Deferred} returned from its C{startProducing} method but then goes on
to write too many bytes, the L{Deferred} returned by {Request.writeTo}
fires with a L{Failure} wrapping L{WrongBodyLength}.
"""
def finisher(producer):
producer.finished.callback(None)
return self.assertFailure(
self._sendRequestBodyFinishedEarlyThenTooManyBytes(finisher),
WrongBodyLength) | If the request body producer indicates it is done by firing the
L{Deferred} returned from its C{startProducing} method but then goes on
to write too many bytes, the L{Deferred} returned by {Request.writeTo}
fires with a L{Failure} wrapping L{WrongBodyLength}. | test_sendRequestBodyFinishedEarlyThenTooManyBytes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_sendRequestBodyErroredEarlyThenTooManyBytes(self):
"""
If the request body producer indicates an error by firing the
L{Deferred} returned from its C{startProducing} method but then goes on
to write too many bytes, the L{Deferred} returned by {Request.writeTo}
fires with that L{Failure} and L{WrongBodyLength} is logged.
"""
def finisher(producer):
producer.finished.errback(ArbitraryException())
return self.assertFailure(
self._sendRequestBodyFinishedEarlyThenTooManyBytes(finisher),
ArbitraryException) | If the request body producer indicates an error by firing the
L{Deferred} returned from its C{startProducing} method but then goes on
to write too many bytes, the L{Deferred} returned by {Request.writeTo}
fires with that L{Failure} and L{WrongBodyLength} is logged. | test_sendRequestBodyErroredEarlyThenTooManyBytes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_sendChunkedRequestBodyFinishedThenWriteMore(self, _with=None):
"""
If the request body producer with an unknown length tries to write
after firing the L{Deferred} returned by its C{startProducing} method,
the C{write} call raises an exception and does not write anything to
the underlying transport.
"""
producer = StringProducer(UNKNOWN_LENGTH)
request = Request(b'POST', b'/bar', _boringHeaders, producer)
writeDeferred = request.writeTo(self.transport)
producer.finished.callback(_with)
self.transport.clear()
self.assertRaises(ExcessWrite, producer.consumer.write, b'foo')
self.assertEqual(self.transport.value(), b"")
return writeDeferred | If the request body producer with an unknown length tries to write
after firing the L{Deferred} returned by its C{startProducing} method,
the C{write} call raises an exception and does not write anything to
the underlying transport. | test_sendChunkedRequestBodyFinishedThenWriteMore | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_sendChunkedRequestBodyFinishedWithErrorThenWriteMore(self):
"""
If the request body producer with an unknown length tries to write
after firing the L{Deferred} returned by its C{startProducing} method
with a L{Failure}, the C{write} call raises an exception and does not
write anything to the underlying transport.
"""
d = self.test_sendChunkedRequestBodyFinishedThenWriteMore(
Failure(ArbitraryException()))
return self.assertFailure(d, ArbitraryException) | If the request body producer with an unknown length tries to write
after firing the L{Deferred} returned by its C{startProducing} method
with a L{Failure}, the C{write} call raises an exception and does not
write anything to the underlying transport. | test_sendChunkedRequestBodyFinishedWithErrorThenWriteMore | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_sendRequestBodyWithError(self):
"""
If the L{Deferred} returned from the C{startProducing} method of the
L{IBodyProducer} passed to L{Request} fires with a L{Failure}, the
L{Deferred} returned from L{Request.writeTo} fails with that
L{Failure}.
"""
producer = StringProducer(5)
request = Request(b'POST', b'/bar', _boringHeaders, producer)
writeDeferred = request.writeTo(self.transport)
# Sanity check - the producer should be registered with the underlying
# transport.
self.assertIdentical(self.transport.producer, producer)
self.assertTrue(self.transport.streaming)
producer.consumer.write(b'ab')
self.assertEqual(
self.transport.value(),
b"POST /bar HTTP/1.1\r\n"
b"Connection: close\r\n"
b"Content-Length: 5\r\n"
b"Host: example.com\r\n"
b"\r\n"
b"ab")
self.assertFalse(self.transport.disconnecting)
producer.finished.errback(Failure(ArbitraryException()))
# Disconnection is handled by a higher level. Request should leave the
# transport alone in this case.
self.assertFalse(self.transport.disconnecting)
# Oh. Except it should unregister the producer that it registered.
self.assertIdentical(self.transport.producer, None)
return self.assertFailure(writeDeferred, ArbitraryException) | If the L{Deferred} returned from the C{startProducing} method of the
L{IBodyProducer} passed to L{Request} fires with a L{Failure}, the
L{Deferred} returned from L{Request.writeTo} fails with that
L{Failure}. | test_sendRequestBodyWithError | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_hostHeaderRequired(self):
"""
L{Request.writeTo} raises L{BadHeaders} if there is not exactly one
I{Host} header and writes nothing to the given transport.
"""
request = Request(b'GET', b'/', Headers({}), None)
self.assertRaises(BadHeaders, request.writeTo, self.transport)
self.assertEqual(self.transport.value(), b'')
request = Request(b'GET', b'/',
Headers({b'Host': [b'example.com', b'example.org']}), None)
self.assertRaises(BadHeaders, request.writeTo, self.transport)
self.assertEqual(self.transport.value(), b'') | L{Request.writeTo} raises L{BadHeaders} if there is not exactly one
I{Host} header and writes nothing to the given transport. | test_hostHeaderRequired | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_stopWriting(self):
"""
L{Request.stopWriting} calls its body producer's C{stopProducing}
method.
"""
producer = StringProducer(3)
request = Request(b'GET', b'/', _boringHeaders, producer)
request.writeTo(self.transport)
self.assertFalse(producer.stopped)
request.stopWriting()
self.assertTrue(producer.stopped) | L{Request.stopWriting} calls its body producer's C{stopProducing}
method. | test_stopWriting | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_brokenStopProducing(self):
"""
If the body producer's C{stopProducing} method raises an exception,
L{Request.stopWriting} logs it and does not re-raise it.
"""
logObserver = EventLoggingObserver.createWithCleanup(
self,
globalLogPublisher
)
producer = StringProducer(3)
def brokenStopProducing():
raise ArbitraryException(u"stopProducing is busted")
producer.stopProducing = brokenStopProducing
request = Request(b'GET', b'/', _boringHeaders, producer)
request.writeTo(self.transport)
request.stopWriting()
self.assertEqual(
len(self.flushLoggedErrors(ArbitraryException)), 1)
self.assertEquals(1, len(logObserver))
event = logObserver[0]
self.assertIn("log_failure", event)
f = event["log_failure"]
self.assertIsInstance(f.value, ArbitraryException) | If the body producer's C{stopProducing} method raises an exception,
L{Request.stopWriting} logs it and does not re-raise it. | test_brokenStopProducing | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_write(self):
"""
L{LengthEnforcingConsumer.write} calls the wrapped consumer's C{write}
method with the bytes it is passed as long as there are fewer of them
than the C{length} attribute indicates remain to be received.
"""
self.enforcer.write(b'abc')
self.assertEqual(self.transport.value(), b'abc')
self.transport.clear()
self.enforcer.write(b'def')
self.assertEqual(self.transport.value(), b'def') | L{LengthEnforcingConsumer.write} calls the wrapped consumer's C{write}
method with the bytes it is passed as long as there are fewer of them
than the C{length} attribute indicates remain to be received. | test_write | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_finishedEarly(self):
"""
L{LengthEnforcingConsumer._noMoreWritesExpected} raises
L{WrongBodyLength} if it is called before the indicated number of bytes
have been written.
"""
self.enforcer.write(b'x' * 9)
self.assertRaises(WrongBodyLength, self.enforcer._noMoreWritesExpected) | L{LengthEnforcingConsumer._noMoreWritesExpected} raises
L{WrongBodyLength} if it is called before the indicated number of bytes
have been written. | test_finishedEarly | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_writeTooMany(self, _unregisterAfter=False):
"""
If it is called with a total number of bytes exceeding the indicated
limit passed to L{LengthEnforcingConsumer.__init__},
L{LengthEnforcingConsumer.write} fires the L{Deferred} with a
L{Failure} wrapping a L{WrongBodyLength} and also calls the
C{stopProducing} method of the producer.
"""
self.enforcer.write(b'x' * 10)
self.assertFalse(self.producer.stopped)
self.enforcer.write(b'x')
self.assertTrue(self.producer.stopped)
if _unregisterAfter:
self.enforcer._noMoreWritesExpected()
return self.assertFailure(self.result, WrongBodyLength) | If it is called with a total number of bytes exceeding the indicated
limit passed to L{LengthEnforcingConsumer.__init__},
L{LengthEnforcingConsumer.write} fires the L{Deferred} with a
L{Failure} wrapping a L{WrongBodyLength} and also calls the
C{stopProducing} method of the producer. | test_writeTooMany | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_writeAfterNoMoreExpected(self):
"""
If L{LengthEnforcingConsumer.write} is called after
L{LengthEnforcingConsumer._noMoreWritesExpected}, it calls the
producer's C{stopProducing} method and raises L{ExcessWrite}.
"""
self.enforcer.write(b'x' * 10)
self.enforcer._noMoreWritesExpected()
self.assertFalse(self.producer.stopped)
self.assertRaises(ExcessWrite, self.enforcer.write, b'x')
self.assertTrue(self.producer.stopped) | If L{LengthEnforcingConsumer.write} is called after
L{LengthEnforcingConsumer._noMoreWritesExpected}, it calls the
producer's C{stopProducing} method and raises L{ExcessWrite}. | test_writeAfterNoMoreExpected | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_finishedLate(self):
"""
L{LengthEnforcingConsumer._noMoreWritesExpected} does nothing (in
particular, it does not raise any exception) if called after too many
bytes have been passed to C{write}.
"""
return self.test_writeTooMany(True) | L{LengthEnforcingConsumer._noMoreWritesExpected} does nothing (in
particular, it does not raise any exception) if called after too many
bytes have been passed to C{write}. | test_finishedLate | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_finished(self):
"""
If L{LengthEnforcingConsumer._noMoreWritesExpected} is called after
the correct number of bytes have been written it returns L{None}.
"""
self.enforcer.write(b'x' * 10)
self.assertIdentical(self.enforcer._noMoreWritesExpected(), None) | If L{LengthEnforcingConsumer._noMoreWritesExpected} is called after
the correct number of bytes have been written it returns L{None}. | test_finished | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_stopProducingRaises(self):
"""
If L{LengthEnforcingConsumer.write} calls the producer's
C{stopProducing} because too many bytes were written and the
C{stopProducing} method raises an exception, the exception is logged
and the L{LengthEnforcingConsumer} still errbacks the finished
L{Deferred}.
"""
def brokenStopProducing():
StringProducer.stopProducing(self.producer)
raise ArbitraryException(u"stopProducing is busted")
self.producer.stopProducing = brokenStopProducing
def cbFinished(ignored):
self.assertEqual(
len(self.flushLoggedErrors(ArbitraryException)), 1)
d = self.test_writeTooMany()
d.addCallback(cbFinished)
return d | If L{LengthEnforcingConsumer.write} calls the producer's
C{stopProducing} because too many bytes were written and the
C{stopProducing} method raises an exception, the exception is logged
and the L{LengthEnforcingConsumer} still errbacks the finished
L{Deferred}. | test_stopProducingRaises | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_interface(self):
"""
L{ChunkedEncoder} instances provide L{IConsumer}.
"""
self.assertTrue(
verifyObject(IConsumer, ChunkedEncoder(StringTransport()))) | L{ChunkedEncoder} instances provide L{IConsumer}. | test_interface | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_write(self):
"""
L{ChunkedEncoder.write} writes to the transport the chunked encoded
form of the bytes passed to it.
"""
transport = StringTransport()
encoder = ChunkedEncoder(transport)
encoder.write(b'foo')
self.assertEqual(transport.value(), b'3\r\nfoo\r\n')
transport.clear()
encoder.write(b'x' * 16)
self.assertEqual(transport.value(), b'10\r\n' + b'x' * 16 + b'\r\n') | L{ChunkedEncoder.write} writes to the transport the chunked encoded
form of the bytes passed to it. | test_write | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_producerRegistration(self):
"""
L{ChunkedEncoder.registerProducer} registers the given streaming
producer with its transport and L{ChunkedEncoder.unregisterProducer}
writes a zero-length chunk to its transport and unregisters the
transport's producer.
"""
transport = StringTransport()
producer = object()
encoder = ChunkedEncoder(transport)
encoder.registerProducer(producer, True)
self.assertIdentical(transport.producer, producer)
self.assertTrue(transport.streaming)
encoder.unregisterProducer()
self.assertIdentical(transport.producer, None)
self.assertEqual(transport.value(), b'0\r\n\r\n') | L{ChunkedEncoder.registerProducer} registers the given streaming
producer with its transport and L{ChunkedEncoder.unregisterProducer}
writes a zero-length chunk to its transport and unregisters the
transport's producer. | test_producerRegistration | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_interface(self):
"""
L{TransportProxyProducer} instances provide L{IPushProducer}.
"""
self.assertTrue(
verifyObject(IPushProducer, TransportProxyProducer(None))) | L{TransportProxyProducer} instances provide L{IPushProducer}. | test_interface | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_stopProxyingUnreferencesProducer(self):
"""
L{TransportProxyProducer.stopProxying} drops the reference to the
wrapped L{IPushProducer} provider.
"""
transport = StringTransport()
proxy = TransportProxyProducer(transport)
self.assertIdentical(proxy._producer, transport)
proxy.stopProxying()
self.assertIdentical(proxy._producer, None) | L{TransportProxyProducer.stopProxying} drops the reference to the
wrapped L{IPushProducer} provider. | test_stopProxyingUnreferencesProducer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_resumeProducing(self):
"""
L{TransportProxyProducer.resumeProducing} calls the wrapped
transport's C{resumeProducing} method unless told to stop proxying.
"""
transport = StringTransport()
transport.pauseProducing()
proxy = TransportProxyProducer(transport)
# The transport should still be paused.
self.assertEqual(transport.producerState, u'paused')
proxy.resumeProducing()
# The transport should now be resumed.
self.assertEqual(transport.producerState, u'producing')
transport.pauseProducing()
proxy.stopProxying()
# The proxy should no longer do anything to the transport.
proxy.resumeProducing()
self.assertEqual(transport.producerState, u'paused') | L{TransportProxyProducer.resumeProducing} calls the wrapped
transport's C{resumeProducing} method unless told to stop proxying. | test_resumeProducing | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_pauseProducing(self):
"""
L{TransportProxyProducer.pauseProducing} calls the wrapped transport's
C{pauseProducing} method unless told to stop proxying.
"""
transport = StringTransport()
proxy = TransportProxyProducer(transport)
# The transport should still be producing.
self.assertEqual(transport.producerState, u'producing')
proxy.pauseProducing()
# The transport should now be paused.
self.assertEqual(transport.producerState, u'paused')
transport.resumeProducing()
proxy.stopProxying()
# The proxy should no longer do anything to the transport.
proxy.pauseProducing()
self.assertEqual(transport.producerState, u'producing') | L{TransportProxyProducer.pauseProducing} calls the wrapped transport's
C{pauseProducing} method unless told to stop proxying. | test_pauseProducing | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_stopProducing(self):
"""
L{TransportProxyProducer.stopProducing} calls the wrapped transport's
C{stopProducing} method unless told to stop proxying.
"""
transport = StringTransport()
proxy = TransportProxyProducer(transport)
# The transport should still be producing.
self.assertEqual(transport.producerState, u'producing')
proxy.stopProducing()
# The transport should now be stopped.
self.assertEqual(transport.producerState, u'stopped')
transport = StringTransport()
proxy = TransportProxyProducer(transport)
proxy.stopProxying()
proxy.stopProducing()
# The transport should not have been stopped.
self.assertEqual(transport.producerState, u'producing') | L{TransportProxyProducer.stopProducing} calls the wrapped transport's
C{stopProducing} method unless told to stop proxying. | test_stopProducing | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_loseConnectionWhileProxying(self):
"""
L{TransportProxyProducer.loseConnection} calls the wrapped transport's
C{loseConnection}.
"""
transport = StringTransportWithDisconnection()
protocol = AccumulatingProtocol()
protocol.makeConnection(transport)
transport.protocol = protocol
proxy = TransportProxyProducer(transport)
# Transport is connected and production.
self.assertTrue(transport.connected)
self.assertEqual(transport.producerState, u'producing')
proxy.loseConnection()
# The transport is not explicitly stopped, but requested to
# disconnect.
self.assertEqual(transport.producerState, u'producing')
self.assertFalse(transport.connected) | L{TransportProxyProducer.loseConnection} calls the wrapped transport's
C{loseConnection}. | test_loseConnectionWhileProxying | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_loseConnectionNotProxying(self):
"""
L{TransportProxyProducer.loseConnection} does nothing when the
proxy is not active.
"""
transport = StringTransportWithDisconnection()
protocol = AccumulatingProtocol()
protocol.makeConnection(transport)
transport.protocol = protocol
proxy = TransportProxyProducer(transport)
proxy.stopProxying()
self.assertTrue(transport.connected)
proxy.loseConnection()
# The transport is not touched, when not proxying.
self.assertTrue(transport.connected) | L{TransportProxyProducer.loseConnection} does nothing when the
proxy is not active. | test_loseConnectionNotProxying | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_verifyInterface(self):
"""
L{Response} instances provide L{IResponse}.
"""
response = justTransportResponse(StringTransport())
self.assertTrue(verifyObject(IResponse, response)) | L{Response} instances provide L{IResponse}. | test_verifyInterface | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_makeConnection(self):
"""
The L{IProtocol} provider passed to L{Response.deliverBody} has its
C{makeConnection} method called with an L{IPushProducer} provider
hooked up to the response as an argument.
"""
producers = []
transport = StringTransport()
class SomeProtocol(Protocol):
def makeConnection(self, producer):
producers.append(producer)
consumer = SomeProtocol()
response = justTransportResponse(transport)
response.deliverBody(consumer)
[theProducer] = producers
theProducer.pauseProducing()
self.assertEqual(transport.producerState, u'paused')
theProducer.resumeProducing()
self.assertEqual(transport.producerState, u'producing') | The L{IProtocol} provider passed to L{Response.deliverBody} has its
C{makeConnection} method called with an L{IPushProducer} provider
hooked up to the response as an argument. | test_makeConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_dataReceived(self):
"""
The L{IProtocol} provider passed to L{Response.deliverBody} has its
C{dataReceived} method called with bytes received as part of the
response body.
"""
bytes = []
class ListConsumer(Protocol):
def dataReceived(self, data):
bytes.append(data)
consumer = ListConsumer()
response = justTransportResponse(StringTransport())
response.deliverBody(consumer)
response._bodyDataReceived(b'foo')
self.assertEqual(bytes, [b'foo']) | The L{IProtocol} provider passed to L{Response.deliverBody} has its
C{dataReceived} method called with bytes received as part of the
response body. | test_dataReceived | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_connectionLost(self):
"""
The L{IProtocol} provider passed to L{Response.deliverBody} has its
C{connectionLost} method called with a L{Failure} wrapping
L{ResponseDone} when the response's C{_bodyDataFinished} method is
called.
"""
lost = []
class ListConsumer(Protocol):
def connectionLost(self, reason):
lost.append(reason)
consumer = ListConsumer()
response = justTransportResponse(StringTransport())
response.deliverBody(consumer)
response._bodyDataFinished()
lost[0].trap(ResponseDone)
self.assertEqual(len(lost), 1)
# The protocol reference should be dropped, too, to facilitate GC or
# whatever.
self.assertIdentical(response._bodyProtocol, None) | The L{IProtocol} provider passed to L{Response.deliverBody} has its
C{connectionLost} method called with a L{Failure} wrapping
L{ResponseDone} when the response's C{_bodyDataFinished} method is
called. | test_connectionLost | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_bufferEarlyData(self):
"""
If data is delivered to the L{Response} before a protocol is registered
with C{deliverBody}, that data is buffered until the protocol is
registered and then is delivered.
"""
bytes = []
class ListConsumer(Protocol):
def dataReceived(self, data):
bytes.append(data)
protocol = ListConsumer()
response = justTransportResponse(StringTransport())
response._bodyDataReceived(b'foo')
response._bodyDataReceived(b'bar')
response.deliverBody(protocol)
response._bodyDataReceived(b'baz')
self.assertEqual(bytes, [b'foo', b'bar', b'baz'])
# Make sure the implementation-detail-byte-buffer is cleared because
# not clearing it wastes memory.
self.assertIdentical(response._bodyBuffer, None) | If data is delivered to the L{Response} before a protocol is registered
with C{deliverBody}, that data is buffered until the protocol is
registered and then is delivered. | test_bufferEarlyData | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_multipleStartProducingFails(self):
"""
L{Response.deliverBody} raises L{RuntimeError} if called more than
once.
"""
response = justTransportResponse(StringTransport())
response.deliverBody(Protocol())
self.assertRaises(RuntimeError, response.deliverBody, Protocol()) | L{Response.deliverBody} raises L{RuntimeError} if called more than
once. | test_multipleStartProducingFails | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_startProducingAfterFinishedFails(self):
"""
L{Response.deliverBody} raises L{RuntimeError} if called after
L{Response._bodyDataFinished}.
"""
response = justTransportResponse(StringTransport())
response.deliverBody(Protocol())
response._bodyDataFinished()
self.assertRaises(RuntimeError, response.deliverBody, Protocol()) | L{Response.deliverBody} raises L{RuntimeError} if called after
L{Response._bodyDataFinished}. | test_startProducingAfterFinishedFails | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_bodyDataReceivedAfterFinishedFails(self):
"""
L{Response._bodyDataReceived} raises L{RuntimeError} if called after
L{Response._bodyDataFinished} but before L{Response.deliverBody}.
"""
response = justTransportResponse(StringTransport())
response._bodyDataFinished()
self.assertRaises(RuntimeError, response._bodyDataReceived, b'foo') | L{Response._bodyDataReceived} raises L{RuntimeError} if called after
L{Response._bodyDataFinished} but before L{Response.deliverBody}. | test_bodyDataReceivedAfterFinishedFails | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_bodyDataReceivedAfterDeliveryFails(self):
"""
L{Response._bodyDataReceived} raises L{RuntimeError} if called after
L{Response._bodyDataFinished} and after L{Response.deliverBody}.
"""
response = justTransportResponse(StringTransport())
response._bodyDataFinished()
response.deliverBody(Protocol())
self.assertRaises(RuntimeError, response._bodyDataReceived, b'foo') | L{Response._bodyDataReceived} raises L{RuntimeError} if called after
L{Response._bodyDataFinished} and after L{Response.deliverBody}. | test_bodyDataReceivedAfterDeliveryFails | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_bodyDataFinishedAfterFinishedFails(self):
"""
L{Response._bodyDataFinished} raises L{RuntimeError} if called more
than once.
"""
response = justTransportResponse(StringTransport())
response._bodyDataFinished()
self.assertRaises(RuntimeError, response._bodyDataFinished) | L{Response._bodyDataFinished} raises L{RuntimeError} if called more
than once. | test_bodyDataFinishedAfterFinishedFails | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_bodyDataFinishedAfterDeliveryFails(self):
"""
L{Response._bodyDataFinished} raises L{RuntimeError} if called after
the body has been delivered.
"""
response = justTransportResponse(StringTransport())
response._bodyDataFinished()
response.deliverBody(Protocol())
self.assertRaises(RuntimeError, response._bodyDataFinished) | L{Response._bodyDataFinished} raises L{RuntimeError} if called after
the body has been delivered. | test_bodyDataFinishedAfterDeliveryFails | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_transportResumed(self):
"""
L{Response.deliverBody} resumes the HTTP connection's transport
after passing it to the consumer's C{makeConnection} method.
"""
transportState = []
class ListConsumer(Protocol):
def makeConnection(self, transport):
transportState.append(transport.producerState)
transport = StringTransport()
transport.pauseProducing()
protocol = ListConsumer()
response = justTransportResponse(transport)
self.assertEqual(transport.producerState, u'paused')
response.deliverBody(protocol)
self.assertEqual(transportState, [u'paused'])
self.assertEqual(transport.producerState, u'producing') | L{Response.deliverBody} resumes the HTTP connection's transport
after passing it to the consumer's C{makeConnection} method. | test_transportResumed | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_bodyDataFinishedBeforeStartProducing(self):
"""
If the entire body is delivered to the L{Response} before the
response's C{deliverBody} method is called, the protocol passed to
C{deliverBody} is immediately given the body data and then
disconnected.
"""
transport = StringTransport()
response = justTransportResponse(transport)
response._bodyDataReceived(b'foo')
response._bodyDataReceived(b'bar')
response._bodyDataFinished()
protocol = AccumulatingProtocol()
response.deliverBody(protocol)
self.assertEqual(protocol.data, b'foobar')
protocol.closedReason.trap(ResponseDone) | If the entire body is delivered to the L{Response} before the
response's C{deliverBody} method is called, the protocol passed to
C{deliverBody} is immediately given the body data and then
disconnected. | test_bodyDataFinishedBeforeStartProducing | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_finishedWithErrorWhenConnected(self):
"""
The L{Failure} passed to L{Response._bodyDataFinished} when the response
is in the I{connected} state is passed to the C{connectionLost} method
of the L{IProtocol} provider passed to the L{Response}'s
C{deliverBody} method.
"""
transport = StringTransport()
response = justTransportResponse(transport)
protocol = AccumulatingProtocol()
response.deliverBody(protocol)
# Sanity check - this test is for the connected state
self.assertEqual(response._state, u'CONNECTED')
response._bodyDataFinished(Failure(ArbitraryException()))
protocol.closedReason.trap(ArbitraryException) | The L{Failure} passed to L{Response._bodyDataFinished} when the response
is in the I{connected} state is passed to the C{connectionLost} method
of the L{IProtocol} provider passed to the L{Response}'s
C{deliverBody} method. | test_finishedWithErrorWhenConnected | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_finishedWithErrorWhenInitial(self):
"""
The L{Failure} passed to L{Response._bodyDataFinished} when the response
is in the I{initial} state is passed to the C{connectionLost} method of
the L{IProtocol} provider passed to the L{Response}'s C{deliverBody}
method.
"""
transport = StringTransport()
response = justTransportResponse(transport)
# Sanity check - this test is for the initial state
self.assertEqual(response._state, u'INITIAL')
response._bodyDataFinished(Failure(ArbitraryException()))
protocol = AccumulatingProtocol()
response.deliverBody(protocol)
protocol.closedReason.trap(ArbitraryException) | The L{Failure} passed to L{Response._bodyDataFinished} when the response
is in the I{initial} state is passed to the C{connectionLost} method of
the L{IProtocol} provider passed to the L{Response}'s C{deliverBody}
method. | test_finishedWithErrorWhenInitial | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_newclient.py | MIT |
def test_headersAndCode(self):
"""
L{redirectTo} will set the C{Location} and C{Content-Type} headers on
its request, and set the response code to C{FOUND}, so the browser will
be redirected.
"""
request = Request(DummyChannel(), True)
request.method = b'GET'
targetURL = b"http://target.example.com/4321"
redirectTo(targetURL, request)
self.assertEqual(request.code, FOUND)
self.assertEqual(
request.responseHeaders.getRawHeaders(b'location'), [targetURL])
self.assertEqual(
request.responseHeaders.getRawHeaders(b'content-type'),
[b'text/html; charset=utf-8']) | L{redirectTo} will set the C{Location} and C{Content-Type} headers on
its request, and set the response code to C{FOUND}, so the browser will
be redirected. | test_headersAndCode | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | MIT |
def test_redirectToUnicodeURL(self) :
"""
L{redirectTo} will raise TypeError if unicode object is passed in URL
"""
request = Request(DummyChannel(), True)
request.method = b'GET'
targetURL = u'http://target.example.com/4321'
self.assertRaises(TypeError, redirectTo, targetURL, request) | L{redirectTo} will raise TypeError if unicode object is passed in URL | test_redirectToUnicodeURL | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | MIT |
def setUp(self):
"""
Create a L{Failure} which can be used by the rendering tests.
"""
def lineNumberProbeAlsoBroken():
message = "This is a problem"
raise Exception(message)
# Figure out the line number from which the exception will be raised.
self.base = lineNumberProbeAlsoBroken.__code__.co_firstlineno + 1
try:
lineNumberProbeAlsoBroken()
except:
self.failure = Failure(captureVars=True)
self.frame = self.failure.frames[-1] | Create a L{Failure} which can be used by the rendering tests. | setUp | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | MIT |
def test_sourceLineElement(self):
"""
L{_SourceLineElement} renders a source line and line number.
"""
element = _SourceLineElement(
TagLoader(tags.div(
tags.span(render="lineNumber"),
tags.span(render="sourceLine"))),
50, " print 'hello'")
d = flattenString(None, element)
expected = (
u"<div><span>50</span><span>"
u" \N{NO-BREAK SPACE} \N{NO-BREAK SPACE}print 'hello'</span></div>")
d.addCallback(
self.assertEqual, expected.encode('utf-8'))
return d | L{_SourceLineElement} renders a source line and line number. | test_sourceLineElement | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | MIT |
def test_sourceFragmentElement(self):
"""
L{_SourceFragmentElement} renders source lines at and around the line
number indicated by a frame object.
"""
element = _SourceFragmentElement(
TagLoader(tags.div(
tags.span(render="lineNumber"),
tags.span(render="sourceLine"),
render="sourceLines")),
self.frame)
source = [
u' \N{NO-BREAK SPACE} \N{NO-BREAK SPACE}message = '
u'"This is a problem"',
u' \N{NO-BREAK SPACE} \N{NO-BREAK SPACE}raise Exception(message)',
u'# Figure out the line number from which the exception will be '
u'raised.',
]
d = flattenString(None, element)
if _PY3:
stringToCheckFor = ''.join([
'<div class="snippet%sLine"><span>%d</span><span>%s</span>'
'</div>' % (
["", "Highlight"][lineNumber == 1],
self.base + lineNumber,
(u" \N{NO-BREAK SPACE}" * 4 + sourceLine))
for (lineNumber, sourceLine)
in enumerate(source)]).encode("utf8")
else:
stringToCheckFor = ''.join([
'<div class="snippet%sLine"><span>%d</span><span>%s</span>'
'</div>' % (
["", "Highlight"][lineNumber == 1],
self.base + lineNumber,
(u" \N{NO-BREAK SPACE}" * 4 + sourceLine).encode('utf8'))
for (lineNumber, sourceLine)
in enumerate(source)])
d.addCallback(self.assertEqual, stringToCheckFor)
return d | L{_SourceFragmentElement} renders source lines at and around the line
number indicated by a frame object. | test_sourceFragmentElement | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | MIT |
def test_frameElementFilename(self):
"""
The I{filename} renderer of L{_FrameElement} renders the filename
associated with the frame object used to initialize the
L{_FrameElement}.
"""
element = _FrameElement(
TagLoader(tags.span(render="filename")),
self.frame)
d = flattenString(None, element)
d.addCallback(
# __file__ differs depending on whether an up-to-date .pyc file
# already existed.
self.assertEqual,
b"<span>" + networkString(__file__.rstrip('c')) + b"</span>")
return d | The I{filename} renderer of L{_FrameElement} renders the filename
associated with the frame object used to initialize the
L{_FrameElement}. | test_frameElementFilename | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | MIT |
def test_frameElementLineNumber(self):
"""
The I{lineNumber} renderer of L{_FrameElement} renders the line number
associated with the frame object used to initialize the
L{_FrameElement}.
"""
element = _FrameElement(
TagLoader(tags.span(render="lineNumber")),
self.frame)
d = flattenString(None, element)
d.addCallback(
self.assertEqual, b"<span>" + intToBytes(self.base + 1) + b"</span>")
return d | The I{lineNumber} renderer of L{_FrameElement} renders the line number
associated with the frame object used to initialize the
L{_FrameElement}. | test_frameElementLineNumber | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | MIT |
def test_frameElementFunction(self):
"""
The I{function} renderer of L{_FrameElement} renders the line number
associated with the frame object used to initialize the
L{_FrameElement}.
"""
element = _FrameElement(
TagLoader(tags.span(render="function")),
self.frame)
d = flattenString(None, element)
d.addCallback(
self.assertEqual, b"<span>lineNumberProbeAlsoBroken</span>")
return d | The I{function} renderer of L{_FrameElement} renders the line number
associated with the frame object used to initialize the
L{_FrameElement}. | test_frameElementFunction | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | MIT |
def test_frameElementSource(self):
"""
The I{source} renderer of L{_FrameElement} renders the source code near
the source filename/line number associated with the frame object used to
initialize the L{_FrameElement}.
"""
element = _FrameElement(None, self.frame)
renderer = element.lookupRenderMethod("source")
tag = tags.div()
result = renderer(None, tag)
self.assertIsInstance(result, _SourceFragmentElement)
self.assertIdentical(result.frame, self.frame)
self.assertEqual([tag], result.loader.load()) | The I{source} renderer of L{_FrameElement} renders the source code near
the source filename/line number associated with the frame object used to
initialize the L{_FrameElement}. | test_frameElementSource | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | MIT |
def test_stackElement(self):
"""
The I{frames} renderer of L{_StackElement} renders each stack frame in
the list of frames used to initialize the L{_StackElement}.
"""
element = _StackElement(None, self.failure.frames[:2])
renderer = element.lookupRenderMethod("frames")
tag = tags.div()
result = renderer(None, tag)
self.assertIsInstance(result, list)
self.assertIsInstance(result[0], _FrameElement)
self.assertIdentical(result[0].frame, self.failure.frames[0])
self.assertIsInstance(result[1], _FrameElement)
self.assertIdentical(result[1].frame, self.failure.frames[1])
# They must not share the same tag object.
self.assertNotEqual(result[0].loader.load(), result[1].loader.load())
self.assertEqual(2, len(result)) | The I{frames} renderer of L{_StackElement} renders each stack frame in
the list of frames used to initialize the L{_StackElement}. | test_stackElement | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | MIT |
def test_failureElementTraceback(self):
"""
The I{traceback} renderer of L{FailureElement} renders the failure's
stack frames using L{_StackElement}.
"""
element = FailureElement(self.failure)
renderer = element.lookupRenderMethod("traceback")
tag = tags.div()
result = renderer(None, tag)
self.assertIsInstance(result, _StackElement)
self.assertIdentical(result.stackFrames, self.failure.frames)
self.assertEqual([tag], result.loader.load()) | The I{traceback} renderer of L{FailureElement} renders the failure's
stack frames using L{_StackElement}. | test_failureElementTraceback | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | MIT |
def test_failureElementType(self):
"""
The I{type} renderer of L{FailureElement} renders the failure's
exception type.
"""
element = FailureElement(
self.failure, TagLoader(tags.span(render="type")))
d = flattenString(None, element)
if _PY3:
exc = b"builtins.Exception"
else:
exc = b"exceptions.Exception"
d.addCallback(
self.assertEqual, b"<span>" + exc + b"</span>")
return d | The I{type} renderer of L{FailureElement} renders the failure's
exception type. | test_failureElementType | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | MIT |
def test_failureElementValue(self):
"""
The I{value} renderer of L{FailureElement} renders the value's exception
value.
"""
element = FailureElement(
self.failure, TagLoader(tags.span(render="value")))
d = flattenString(None, element)
d.addCallback(
self.assertEqual, b'<span>This is a problem</span>')
return d | The I{value} renderer of L{FailureElement} renders the value's exception
value. | test_failureElementValue | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | MIT |
def test_flattenerError(self):
"""
If there is an error flattening the L{Failure} instance,
L{formatFailure} raises L{FlattenerError}.
"""
self.assertRaises(FlattenerError, formatFailure, object()) | If there is an error flattening the L{Failure} instance,
L{formatFailure} raises L{FlattenerError}. | test_flattenerError | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | MIT |
def test_returnsBytes(self):
"""
The return value of L{formatFailure} is a C{str} instance (not a
C{unicode} instance) with numeric character references for any non-ASCII
characters meant to appear in the output.
"""
try:
raise Exception("Fake bug")
except:
result = formatFailure(Failure())
self.assertIsInstance(result, bytes)
if _PY3:
self.assertTrue(all(ch < 128 for ch in result))
else:
self.assertTrue(all(ord(ch) < 128 for ch in result))
# Indentation happens to rely on NO-BREAK SPACE
self.assertIn(b" ", result) | The return value of L{formatFailure} is a C{str} instance (not a
C{unicode} instance) with numeric character references for any non-ASCII
characters meant to appear in the output. | test_returnsBytes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | MIT |
def test_render(self):
"""
L{DeferredResource} uses the request object's C{render} method to
render the resource which is the result of the L{Deferred} being
handled.
"""
rendered = []
request = DummyRequest([])
request.render = rendered.append
result = resource.Resource()
deferredResource = DeferredResource(defer.succeed(result))
deferredResource.render(request)
self.assertEqual(rendered, [result]) | L{DeferredResource} uses the request object's C{render} method to
render the resource which is the result of the L{Deferred} being
handled. | test_render | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | MIT |
def test_renderNoFailure(self):
"""
If the L{Deferred} fails, L{DeferredResource} reports the failure via
C{processingFailed}, and does not cause an unhandled error to be
logged.
"""
request = DummyRequest([])
d = request.notifyFinish()
failure = Failure(RuntimeError())
deferredResource = DeferredResource(defer.fail(failure))
deferredResource.render(request)
self.assertEqual(self.failureResultOf(d), failure)
del deferredResource
gc.collect()
errors = self.flushLoggedErrors(RuntimeError)
self.assertEqual(errors, []) | If the L{Deferred} fails, L{DeferredResource} reports the failure via
C{processingFailed}, and does not cause an unhandled error to be
logged. | test_renderNoFailure | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_util.py | MIT |
def attemptRequestWithMaliciousMethod(self, method):
"""
Attempt to send a request with the given method. This should
synchronously raise a L{ValueError} if either is invalid.
@param method: the method (e.g. C{GET\x00})
@param uri: the URI
@type method:
"""
raise NotImplementedError() | Attempt to send a request with the given method. This should
synchronously raise a L{ValueError} if either is invalid.
@param method: the method (e.g. C{GET\x00})
@param uri: the URI
@type method: | attemptRequestWithMaliciousMethod | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/injectionhelpers.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/injectionhelpers.py | MIT |
def test_methodWithCLRFRejected(self):
"""
Issuing a request with a method that contains a carriage
return and line feed fails with a L{ValueError}.
"""
with self.assertRaises(ValueError) as cm:
method = b"GET\r\nX-Injected-Header: value"
self.attemptRequestWithMaliciousMethod(method)
self.assertRegex(str(cm.exception), "^Invalid method") | Issuing a request with a method that contains a carriage
return and line feed fails with a L{ValueError}. | test_methodWithCLRFRejected | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/injectionhelpers.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/injectionhelpers.py | MIT |
def test_methodWithUnprintableASCIIRejected(self):
"""
Issuing a request with a method that contains unprintable
ASCII characters fails with a L{ValueError}.
"""
for c in UNPRINTABLE_ASCII:
method = b"GET%s" % (bytearray([c]),)
with self.assertRaises(ValueError) as cm:
self.attemptRequestWithMaliciousMethod(method)
self.assertRegex(str(cm.exception), "^Invalid method") | Issuing a request with a method that contains unprintable
ASCII characters fails with a L{ValueError}. | test_methodWithUnprintableASCIIRejected | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/injectionhelpers.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/injectionhelpers.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.