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_prematureEndOfHeaders(self): """ If the process communicating with L{CGIProcessProtocol} ends before finishing writing out headers, the response has I{INTERNAL SERVER ERROR} as its status code. """ request = DummyRequest(['']) protocol = twcgi.CGIProcessProtocol(request) protocol.processEnded(failure.Failure(error.ProcessTerminated())) self.assertEqual(request.responseCode, INTERNAL_SERVER_ERROR)
If the process communicating with L{CGIProcessProtocol} ends before finishing writing out headers, the response has I{INTERNAL SERVER ERROR} as its status code.
test_prematureEndOfHeaders
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
MIT
def discardBody(response): """ Discard the body of a HTTP response. @param response: The response. @return: The response. """ return client.readBody(response).addCallback(lambda _: response)
Discard the body of a HTTP response. @param response: The response. @return: The response.
discardBody
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
MIT
def _makeRequestProxyFactory(clsToWrap): """ Return a callable that proxies instances of C{clsToWrap} via L{_IDeprecatedHTTPChannelToRequestInterface}. @param clsToWrap: The class whose instances will be proxied. @type cls: L{_IDeprecatedHTTPChannelToRequestInterface} implementer. @return: A factory that returns L{_IDeprecatedHTTPChannelToRequestInterface} proxies. @rtype: L{callable} whose interface matches C{clsToWrap}'s constructor. """ def _makeRequestProxy(*args, **kwargs): instance = clsToWrap(*args, **kwargs) return _IDeprecatedHTTPChannelToRequestInterfaceProxy(instance) # For INonQueuedRequestFactory directlyProvides(_makeRequestProxy, providedBy(clsToWrap)) return _makeRequestProxy
Return a callable that proxies instances of C{clsToWrap} via L{_IDeprecatedHTTPChannelToRequestInterface}. @param clsToWrap: The class whose instances will be proxied. @type cls: L{_IDeprecatedHTTPChannelToRequestInterface} implementer. @return: A factory that returns L{_IDeprecatedHTTPChannelToRequestInterface} proxies. @rtype: L{callable} whose interface matches C{clsToWrap}'s constructor.
_makeRequestProxyFactory
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def parametrizeTimeoutMixin(protocol, reactor): """ Parametrizes the L{TimeoutMixin} so that it works with whatever reactor is being used by the test. @param protocol: A L{_GenericHTTPChannel} or something implementing a similar interface. @type protocol: L{_GenericHTTPChannel} @param reactor: An L{IReactorTime} implementation. @type reactor: L{IReactorTime} @return: The C{channel}, with its C{callLater} method patched. """ # This is a terrible violation of the abstraction later of # _genericHTTPChannelProtocol, but we need to do it because # policies.TimeoutMixin doesn't accept a reactor on the object. # See https://twistedmatrix.com/trac/ticket/8488 protocol._channel.callLater = reactor.callLater return protocol
Parametrizes the L{TimeoutMixin} so that it works with whatever reactor is being used by the test. @param protocol: A L{_GenericHTTPChannel} or something implementing a similar interface. @type protocol: L{_GenericHTTPChannel} @param reactor: An L{IReactorTime} implementation. @type reactor: L{IReactorTime} @return: The C{channel}, with its C{callLater} method patched.
parametrizeTimeoutMixin
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def assertResponseEquals(self, responses, expected): """ Assert that the C{responses} matches the C{expected} responses. @type responses: C{bytes} @param responses: The bytes sent in response to one or more requests. @type expected: C{list} of C{tuple} of C{bytes} @param expected: The expected values for the responses. Each tuple element of the list represents one response. Each byte string element of the tuple is a full header line without delimiter, except for the last element which gives the full response body. """ for response in expected: expectedHeaders, expectedContent = response[:-1], response[-1] # Intentionally avoid mutating the inputs here. expectedStatus = expectedHeaders[0] expectedHeaders = expectedHeaders[1:] headers, rest = responses.split(b'\r\n\r\n', 1) headers = headers.splitlines() status = headers.pop(0) self.assertEqual(expectedStatus, status) self.assertEqual(set(headers), set(expectedHeaders)) content = rest[:len(expectedContent)] responses = rest[len(expectedContent):] self.assertEqual(content, expectedContent)
Assert that the C{responses} matches the C{expected} responses. @type responses: C{bytes} @param responses: The bytes sent in response to one or more requests. @type expected: C{list} of C{tuple} of C{bytes} @param expected: The expected values for the responses. Each tuple element of the list represents one response. Each byte string element of the tuple is a full header line without delimiter, except for the last element which gives the full response body.
assertResponseEquals
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_buffer(self): """ Send requests over a channel and check responses match what is expected. """ b = StringTransport() a = http.HTTPChannel() a.requestFactory = DummyHTTPHandlerProxy a.makeConnection(b) # one byte at a time, to stress it. for byte in iterbytes(self.requests): a.dataReceived(byte) a.connectionLost(IOError("all one")) value = b.value() self.assertResponseEquals(value, self.expected_response)
Send requests over a channel and check responses match what is expected.
test_buffer
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_requestBodyTimeout(self): """ L{HTTPChannel} resets its timeout whenever data from a request body is delivered to it. """ clock = Clock() transport = StringTransport() protocol = http.HTTPChannel() protocol.timeOut = 100 protocol.callLater = clock.callLater protocol.makeConnection(transport) protocol.dataReceived(b'POST / HTTP/1.0\r\nContent-Length: 2\r\n\r\n') clock.advance(99) self.assertFalse(transport.disconnecting) protocol.dataReceived(b'x') clock.advance(99) self.assertFalse(transport.disconnecting) protocol.dataReceived(b'x') self.assertEqual(len(protocol.requests), 1)
L{HTTPChannel} resets its timeout whenever data from a request body is delivered to it.
test_requestBodyTimeout
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_requestBodyDefaultTimeout(self): """ L{HTTPChannel}'s default timeout is 60 seconds. """ clock = Clock() transport = StringTransport() factory = http.HTTPFactory() protocol = factory.buildProtocol(None) protocol = parametrizeTimeoutMixin(protocol, clock) protocol.makeConnection(transport) protocol.dataReceived(b'POST / HTTP/1.0\r\nContent-Length: 2\r\n\r\n') clock.advance(59) self.assertFalse(transport.disconnecting) clock.advance(1) self.assertTrue(transport.disconnecting)
L{HTTPChannel}'s default timeout is 60 seconds.
test_requestBodyDefaultTimeout
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_transportForciblyClosed(self): """ If a timed out transport doesn't close after 15 seconds, the L{HTTPChannel} will forcibly close it. """ logObserver = EventLoggingObserver.createWithCleanup( self, globalLogPublisher ) clock = Clock() transport = StringTransport() factory = http.HTTPFactory() protocol = factory.buildProtocol(None) protocol = parametrizeTimeoutMixin(protocol, clock) protocol.makeConnection(transport) protocol.dataReceived(b'POST / HTTP/1.0\r\nContent-Length: 2\r\n\r\n') self.assertFalse(transport.disconnecting) self.assertFalse(transport.disconnected) # Force the initial timeout. clock.advance(60) self.assertTrue(transport.disconnecting) self.assertFalse(transport.disconnected) self.assertEquals(1, len(logObserver)) event = logObserver[0] self.assertIn("Timing out client: {peer}", event["log_format"]) # Watch the transport get force-closed. clock.advance(14) self.assertTrue(transport.disconnecting) self.assertFalse(transport.disconnected) clock.advance(1) self.assertTrue(transport.disconnecting) self.assertTrue(transport.disconnected) self.assertEquals(2, len(logObserver)) event = logObserver[1] self.assertEquals( "Forcibly timing out client: {peer}", event["log_format"] )
If a timed out transport doesn't close after 15 seconds, the L{HTTPChannel} will forcibly close it.
test_transportForciblyClosed
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_transportNotAbortedAfterConnectionLost(self): """ If a timed out transport ends up calling C{connectionLost}, it prevents the force-closure of the transport. """ clock = Clock() transport = StringTransport() factory = http.HTTPFactory() protocol = factory.buildProtocol(None) protocol = parametrizeTimeoutMixin(protocol, clock) protocol.makeConnection(transport) protocol.dataReceived(b'POST / HTTP/1.0\r\nContent-Length: 2\r\n\r\n') self.assertFalse(transport.disconnecting) self.assertFalse(transport.disconnected) # Force the initial timeout. clock.advance(60) self.assertTrue(transport.disconnecting) self.assertFalse(transport.disconnected) # Move forward nearly to the timeout, then fire connectionLost. clock.advance(14) protocol.connectionLost(None) # Check that the transport isn't forcibly closed. clock.advance(1) self.assertTrue(transport.disconnecting) self.assertFalse(transport.disconnected)
If a timed out transport ends up calling C{connectionLost}, it prevents the force-closure of the transport.
test_transportNotAbortedAfterConnectionLost
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_transportNotAbortedWithZeroAbortTimeout(self): """ If the L{HTTPChannel} has its c{abortTimeout} set to L{None}, it never aborts. """ clock = Clock() transport = StringTransport() factory = http.HTTPFactory() protocol = factory.buildProtocol(None) protocol._channel.abortTimeout = None protocol = parametrizeTimeoutMixin(protocol, clock) protocol.makeConnection(transport) protocol.dataReceived(b'POST / HTTP/1.0\r\nContent-Length: 2\r\n\r\n') self.assertFalse(transport.disconnecting) self.assertFalse(transport.disconnected) # Force the initial timeout. clock.advance(60) self.assertTrue(transport.disconnecting) self.assertFalse(transport.disconnected) # Move an absurdly long way just to prove the point. clock.advance(2**32) self.assertTrue(transport.disconnecting) self.assertFalse(transport.disconnected)
If the L{HTTPChannel} has its c{abortTimeout} set to L{None}, it never aborts.
test_transportNotAbortedWithZeroAbortTimeout
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_connectionLostAfterForceClose(self): """ If a timed out transport doesn't close after 15 seconds, the L{HTTPChannel} will forcibly close it. """ clock = Clock() transport = StringTransport() factory = http.HTTPFactory() protocol = factory.buildProtocol(None) protocol = parametrizeTimeoutMixin(protocol, clock) protocol.makeConnection(transport) protocol.dataReceived(b'POST / HTTP/1.0\r\nContent-Length: 2\r\n\r\n') self.assertFalse(transport.disconnecting) self.assertFalse(transport.disconnected) # Force the initial timeout and the follow-on forced closure. clock.advance(60) clock.advance(15) self.assertTrue(transport.disconnecting) self.assertTrue(transport.disconnected) # Now call connectionLost on the protocol. This is done by some # transports, including TCP and TLS. We don't have anything we can # assert on here: this just must not explode. protocol.connectionLost(ConnectionDone)
If a timed out transport doesn't close after 15 seconds, the L{HTTPChannel} will forcibly close it.
test_connectionLostAfterForceClose
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_noPipeliningApi(self): """ Test that a L{http.Request} subclass with no queued kwarg works as expected. """ b = StringTransport() a = http.HTTPChannel() a.requestFactory = DummyHTTPHandlerProxy a.makeConnection(b) # one byte at a time, to stress it. for byte in iterbytes(self.requests): a.dataReceived(byte) a.connectionLost(IOError("all done")) value = b.value() self.assertResponseEquals(value, self.expected_response)
Test that a L{http.Request} subclass with no queued kwarg works as expected.
test_noPipeliningApi
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_noPipelining(self): """ Test that pipelined requests get buffered, not processed in parallel. """ b = StringTransport() a = http.HTTPChannel() a.requestFactory = DelayedHTTPHandlerProxy a.makeConnection(b) # one byte at a time, to stress it. for byte in iterbytes(self.requests): a.dataReceived(byte) value = b.value() # So far only one request should have been dispatched. self.assertEqual(value, b'') self.assertEqual(1, len(a.requests)) # Now, process each request one at a time. while a.requests: self.assertEqual(1, len(a.requests)) request = a.requests[0].original request.delayedProcess() value = b.value() self.assertResponseEquals(value, self.expected_response)
Test that pipelined requests get buffered, not processed in parallel.
test_noPipelining
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_noPipelining(self): """ Test that pipelined requests get buffered, not processed in parallel. """ b = StringTransport() a = http.HTTPChannel() a.requestFactory = DelayedHTTPHandlerProxy a.makeConnection(b) # one byte at a time, to stress it. for byte in iterbytes(self.requests): a.dataReceived(byte) value = b.value() # So far only one request should have been dispatched. self.assertEqual(value, b'') self.assertEqual(1, len(a.requests)) # Now, process each request one at a time. while a.requests: self.assertEqual(1, len(a.requests)) request = a.requests[0].original request.delayedProcess() value = b.value() self.assertResponseEquals(value, self.expectedResponses)
Test that pipelined requests get buffered, not processed in parallel.
test_noPipelining
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_pipeliningReadLimit(self): """ When pipelined requests are received, we will optimistically continue receiving data up to a specified limit, then pause the transport. @see: L{http.HTTPChannel._optimisticEagerReadSize} """ b = StringTransport() a = http.HTTPChannel() a.requestFactory = DelayedHTTPHandlerProxy a.makeConnection(b) underLimit = a._optimisticEagerReadSize // len(self.requests) for x in range(1, underLimit + 1): a.dataReceived(self.requests) self.assertEqual(b.producerState, 'producing', 'state was {state!r} after {x} iterations' .format(state=b.producerState, x=x)) a.dataReceived(self.requests) self.assertEquals(b.producerState, 'paused')
When pipelined requests are received, we will optimistically continue receiving data up to a specified limit, then pause the transport. @see: L{http.HTTPChannel._optimisticEagerReadSize}
test_pipeliningReadLimit
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_losingConnection(self): """ Calling L{http.Request.loseConnection} causes the transport to be disconnected. """ b = StringTransport() a = http.HTTPChannel() a.requestFactory = _makeRequestProxyFactory(self.ShutdownHTTPHandler) a.makeConnection(b) a.dataReceived(self.request) # The transport should have been shut down. self.assertTrue(b.disconnecting) # No response should have been written. value = b.value() self.assertEqual(value, b'')
Calling L{http.Request.loseConnection} causes the transport to be disconnected.
test_losingConnection
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_isSecure(self): """ Calling L{http.Request.isSecure} when the channel is backed with a secure transport will return L{True}. """ b = DummyChannel.SSL() a = http.HTTPChannel() a.makeConnection(b) req = http.Request(a) self.assertTrue(req.isSecure())
Calling L{http.Request.isSecure} when the channel is backed with a secure transport will return L{True}.
test_isSecure
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_notSecure(self): """ Calling L{http.Request.isSecure} when the channel is not backed with a secure transport will return L{False}. """ b = DummyChannel.TCP() a = http.HTTPChannel() a.makeConnection(b) req = http.Request(a) self.assertFalse(req.isSecure())
Calling L{http.Request.isSecure} when the channel is not backed with a secure transport will return L{False}.
test_notSecure
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_notSecureAfterFinish(self): """ After a request is finished, calling L{http.Request.isSecure} will always return L{False}. """ b = DummyChannel.SSL() a = http.HTTPChannel() a.makeConnection(b) req = http.Request(a) a.requests.append(req) req.setResponseCode(200) req.finish() self.assertFalse(req.isSecure())
After a request is finished, calling L{http.Request.isSecure} will always return L{False}.
test_notSecureAfterFinish
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def _negotiatedProtocolForTransportInstance(self, t): """ Run a request using the specific instance of a transport. Returns the negotiated protocol string. """ a = http._genericHTTPChannelProtocolFactory(b'') a.requestFactory = DummyHTTPHandlerProxy a.makeConnection(t) # one byte at a time, to stress it. for byte in iterbytes(self.requests): a.dataReceived(byte) a.connectionLost(IOError("all done")) return a._negotiatedProtocol
Run a request using the specific instance of a transport. Returns the negotiated protocol string.
_negotiatedProtocolForTransportInstance
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_protocolUnspecified(self): """ If the transport has no support for protocol negotiation (no negotiatedProtocol attribute), HTTP/1.1 is assumed. """ b = StringTransport() negotiatedProtocol = self._negotiatedProtocolForTransportInstance(b) self.assertEqual(negotiatedProtocol, b'http/1.1')
If the transport has no support for protocol negotiation (no negotiatedProtocol attribute), HTTP/1.1 is assumed.
test_protocolUnspecified
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_protocolNone(self): """ If the transport has no support for protocol negotiation (returns None for negotiatedProtocol), HTTP/1.1 is assumed. """ b = StringTransport() b.negotiatedProtocol = None negotiatedProtocol = self._negotiatedProtocolForTransportInstance(b) self.assertEqual(negotiatedProtocol, b'http/1.1')
If the transport has no support for protocol negotiation (returns None for negotiatedProtocol), HTTP/1.1 is assumed.
test_protocolNone
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_http11(self): """ If the transport reports that HTTP/1.1 is negotiated, that's what's negotiated. """ b = StringTransport() b.negotiatedProtocol = b'http/1.1' negotiatedProtocol = self._negotiatedProtocolForTransportInstance(b) self.assertEqual(negotiatedProtocol, b'http/1.1')
If the transport reports that HTTP/1.1 is negotiated, that's what's negotiated.
test_http11
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_http2_present(self): """ If the transport reports that HTTP/2 is negotiated and HTTP/2 is present, that's what's negotiated. """ b = StringTransport() b.negotiatedProtocol = b'h2' negotiatedProtocol = self._negotiatedProtocolForTransportInstance(b) self.assertEqual(negotiatedProtocol, b'h2')
If the transport reports that HTTP/2 is negotiated and HTTP/2 is present, that's what's negotiated.
test_http2_present
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_http2_absent(self): """ If the transport reports that HTTP/2 is negotiated and HTTP/2 is not present, an error is encountered. """ b = StringTransport() b.negotiatedProtocol = b'h2' self.assertRaises( ValueError, self._negotiatedProtocolForTransportInstance, b, )
If the transport reports that HTTP/2 is negotiated and HTTP/2 is not present, an error is encountered.
test_http2_absent
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_unknownProtocol(self): """ If the transport reports that a protocol other than HTTP/1.1 or HTTP/2 is negotiated, an error occurs. """ b = StringTransport() b.negotiatedProtocol = b'smtp' self.assertRaises( AssertionError, self._negotiatedProtocolForTransportInstance, b, )
If the transport reports that a protocol other than HTTP/1.1 or HTTP/2 is negotiated, an error occurs.
test_unknownProtocol
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_factory(self): """ The C{factory} attribute is taken from the inner channel. """ a = http._genericHTTPChannelProtocolFactory(b'') a._channel.factory = b"Foo" self.assertEqual(a.factory, b"Foo")
The C{factory} attribute is taken from the inner channel.
test_factory
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_GenericHTTPChannelPropagatesCallLater(self): """ If C{callLater} is patched onto the L{http._GenericHTTPChannelProtocol} then we need to propagate it through to the backing channel. """ clock = Clock() factory = http.HTTPFactory(reactor=clock) protocol = factory.buildProtocol(None) self.assertEqual(protocol.callLater, clock.callLater) self.assertEqual(protocol._channel.callLater, clock.callLater)
If C{callLater} is patched onto the L{http._GenericHTTPChannelProtocol} then we need to propagate it through to the backing channel.
test_GenericHTTPChannelPropagatesCallLater
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_genericHTTPChannelCallLaterUpgrade(self): """ If C{callLater} is patched onto the L{http._GenericHTTPChannelProtocol} then we need to propagate it across onto a new backing channel after upgrade. """ clock = Clock() factory = http.HTTPFactory(reactor=clock) protocol = factory.buildProtocol(None) self.assertEqual(protocol.callLater, clock.callLater) self.assertEqual(protocol._channel.callLater, clock.callLater) transport = StringTransport() transport.negotiatedProtocol = b'h2' protocol.requestFactory = DummyHTTPHandler protocol.makeConnection(transport) # Send a byte to make it think the handshake is done. protocol.dataReceived(b'P') self.assertEqual(protocol.callLater, clock.callLater) self.assertEqual(protocol._channel.callLater, clock.callLater)
If C{callLater} is patched onto the L{http._GenericHTTPChannelProtocol} then we need to propagate it across onto a new backing channel after upgrade.
test_genericHTTPChannelCallLaterUpgrade
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_unregistersProducer(self): """ The L{_GenericHTTPChannelProtocol} will unregister its proxy channel from the transport if upgrade is negotiated. """ transport = StringTransport() transport.negotiatedProtocol = b'h2' genericProtocol = http._genericHTTPChannelProtocolFactory(b'') genericProtocol.requestFactory = DummyHTTPHandlerProxy genericProtocol.makeConnection(transport) # We expect the transport has a underlying channel registered as # a producer. self.assertIs(transport.producer, genericProtocol._channel) # Force the upgrade. genericProtocol.dataReceived(b'P') # The transport should now have no producer. self.assertIs(transport.producer, None)
The L{_GenericHTTPChannelProtocol} will unregister its proxy channel from the transport if upgrade is negotiated.
test_unregistersProducer
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def _prequest(**headers): """ Make a request with the given request headers for the persistence tests. """ request = http.Request(DummyChannel(), False) for headerName, v in headers.items(): request.requestHeaders.setRawHeaders(networkString(headerName), v) return request
Make a request with the given request headers for the persistence tests.
_prequest
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_http09(self): """ After being used for an I{HTTP/0.9} request, the L{HTTPChannel} is not persistent. """ persist = self.channel.checkPersistence(self.request, b"HTTP/0.9") self.assertFalse(persist) self.assertEqual( [], list(self.request.responseHeaders.getAllRawHeaders()))
After being used for an I{HTTP/0.9} request, the L{HTTPChannel} is not persistent.
test_http09
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_http10(self): """ After being used for an I{HTTP/1.0} request, the L{HTTPChannel} is not persistent. """ persist = self.channel.checkPersistence(self.request, b"HTTP/1.0") self.assertFalse(persist) self.assertEqual( [], list(self.request.responseHeaders.getAllRawHeaders()))
After being used for an I{HTTP/1.0} request, the L{HTTPChannel} is not persistent.
test_http10
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_http11(self): """ After being used for an I{HTTP/1.1} request, the L{HTTPChannel} is persistent. """ persist = self.channel.checkPersistence(self.request, b"HTTP/1.1") self.assertTrue(persist) self.assertEqual( [], list(self.request.responseHeaders.getAllRawHeaders()))
After being used for an I{HTTP/1.1} request, the L{HTTPChannel} is persistent.
test_http11
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_http11Close(self): """ After being used for an I{HTTP/1.1} request with a I{Connection: Close} header, the L{HTTPChannel} is not persistent. """ request = _prequest(connection=[b"close"]) persist = self.channel.checkPersistence(request, b"HTTP/1.1") self.assertFalse(persist) self.assertEqual( [(b"Connection", [b"close"])], list(request.responseHeaders.getAllRawHeaders()))
After being used for an I{HTTP/1.1} request with a I{Connection: Close} header, the L{HTTPChannel} is not persistent.
test_http11Close
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def setUp(self): """ Create an L{_IdentityTransferDecoder} with callbacks hooked up so that calls to them can be inspected. """ self.data = [] self.finish = [] self.contentLength = 10 self.decoder = _IdentityTransferDecoder( self.contentLength, self.data.append, self.finish.append)
Create an L{_IdentityTransferDecoder} with callbacks hooked up so that calls to them can be inspected.
setUp
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_exactAmountReceived(self): """ If L{_IdentityTransferDecoder.dataReceived} is called with a byte string with length equal to the content length passed to L{_IdentityTransferDecoder}'s initializer, the data callback is invoked with that string and the finish callback is invoked with a zero-length string. """ self.decoder.dataReceived(b'x' * self.contentLength) self.assertEqual(self.data, [b'x' * self.contentLength]) self.assertEqual(self.finish, [b''])
If L{_IdentityTransferDecoder.dataReceived} is called with a byte string with length equal to the content length passed to L{_IdentityTransferDecoder}'s initializer, the data callback is invoked with that string and the finish callback is invoked with a zero-length string.
test_exactAmountReceived
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_shortStrings(self): """ If L{_IdentityTransferDecoder.dataReceived} is called multiple times with byte strings which, when concatenated, are as long as the content length provided, the data callback is invoked with each string and the finish callback is invoked only after the second call. """ self.decoder.dataReceived(b'x') self.assertEqual(self.data, [b'x']) self.assertEqual(self.finish, []) self.decoder.dataReceived(b'y' * (self.contentLength - 1)) self.assertEqual(self.data, [b'x', b'y' * (self.contentLength - 1)]) self.assertEqual(self.finish, [b''])
If L{_IdentityTransferDecoder.dataReceived} is called multiple times with byte strings which, when concatenated, are as long as the content length provided, the data callback is invoked with each string and the finish callback is invoked only after the second call.
test_shortStrings
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_longString(self): """ If L{_IdentityTransferDecoder.dataReceived} is called with a byte string with length greater than the provided content length, only the prefix of that string up to the content length is passed to the data callback and the remainder is passed to the finish callback. """ self.decoder.dataReceived(b'x' * self.contentLength + b'y') self.assertEqual(self.data, [b'x' * self.contentLength]) self.assertEqual(self.finish, [b'y'])
If L{_IdentityTransferDecoder.dataReceived} is called with a byte string with length greater than the provided content length, only the prefix of that string up to the content length is passed to the data callback and the remainder is passed to the finish callback.
test_longString
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_rejectDataAfterFinished(self): """ If data is passed to L{_IdentityTransferDecoder.dataReceived} after the finish callback has been invoked, C{RuntimeError} is raised. """ failures = [] def finish(bytes): try: decoder.dataReceived(b'foo') except: failures.append(Failure()) decoder = _IdentityTransferDecoder(5, self.data.append, finish) decoder.dataReceived(b'x' * 4) self.assertEqual(failures, []) decoder.dataReceived(b'y') failures[0].trap(RuntimeError) self.assertEqual( str(failures[0].value), "_IdentityTransferDecoder cannot decode data after finishing")
If data is passed to L{_IdentityTransferDecoder.dataReceived} after the finish callback has been invoked, C{RuntimeError} is raised.
test_rejectDataAfterFinished
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_unknownContentLength(self): """ If L{_IdentityTransferDecoder} is constructed with L{None} for the content length, it passes all data delivered to it through to the data callback. """ data = [] finish = [] decoder = _IdentityTransferDecoder(None, data.append, finish.append) decoder.dataReceived(b'x') self.assertEqual(data, [b'x']) decoder.dataReceived(b'y') self.assertEqual(data, [b'x', b'y']) self.assertEqual(finish, [])
If L{_IdentityTransferDecoder} is constructed with L{None} for the content length, it passes all data delivered to it through to the data callback.
test_unknownContentLength
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def _verifyCallbacksUnreferenced(self, decoder): """ Check the decoder's data and finish callbacks and make sure they are None in order to help avoid references cycles. """ self.assertIdentical(decoder.dataCallback, None) self.assertIdentical(decoder.finishCallback, None)
Check the decoder's data and finish callbacks and make sure they are None in order to help avoid references cycles.
_verifyCallbacksUnreferenced
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_earlyConnectionLose(self): """ L{_IdentityTransferDecoder.noMoreData} raises L{_DataLoss} if it is called and the content length is known but not enough bytes have been delivered. """ self.decoder.dataReceived(b'x' * (self.contentLength - 1)) self.assertRaises(_DataLoss, self.decoder.noMoreData) self._verifyCallbacksUnreferenced(self.decoder)
L{_IdentityTransferDecoder.noMoreData} raises L{_DataLoss} if it is called and the content length is known but not enough bytes have been delivered.
test_earlyConnectionLose
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_unknownContentLengthConnectionLose(self): """ L{_IdentityTransferDecoder.noMoreData} calls the finish callback and raises L{PotentialDataLoss} if it is called and the content length is unknown. """ body = [] finished = [] decoder = _IdentityTransferDecoder(None, body.append, finished.append) self.assertRaises(PotentialDataLoss, decoder.noMoreData) self.assertEqual(body, []) self.assertEqual(finished, [b'']) self._verifyCallbacksUnreferenced(decoder)
L{_IdentityTransferDecoder.noMoreData} calls the finish callback and raises L{PotentialDataLoss} if it is called and the content length is unknown.
test_unknownContentLengthConnectionLose
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_finishedConnectionLose(self): """ L{_IdentityTransferDecoder.noMoreData} does not raise any exception if it is called when the content length is known and that many bytes have been delivered. """ self.decoder.dataReceived(b'x' * self.contentLength) self.decoder.noMoreData() self._verifyCallbacksUnreferenced(self.decoder)
L{_IdentityTransferDecoder.noMoreData} does not raise any exception if it is called when the content length is known and that many bytes have been delivered.
test_finishedConnectionLose
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_decoding(self): """ L{_ChunkedTransferDecoder.dataReceived} decodes chunked-encoded data and passes the result to the specified callback. """ L = [] p = http._ChunkedTransferDecoder(L.append, None) p.dataReceived(b'3\r\nabc\r\n5\r\n12345\r\n') p.dataReceived(b'a\r\n0123456789\r\n') self.assertEqual(L, [b'abc', b'12345', b'0123456789'])
L{_ChunkedTransferDecoder.dataReceived} decodes chunked-encoded data and passes the result to the specified callback.
test_decoding
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_short(self): """ L{_ChunkedTransferDecoder.dataReceived} decodes chunks broken up and delivered in multiple calls. """ L = [] finished = [] p = http._ChunkedTransferDecoder(L.append, finished.append) for s in iterbytes(b'3\r\nabc\r\n5\r\n12345\r\n0\r\n\r\n'): p.dataReceived(s) self.assertEqual(L, [b'a', b'b', b'c', b'1', b'2', b'3', b'4', b'5']) self.assertEqual(finished, [b''])
L{_ChunkedTransferDecoder.dataReceived} decodes chunks broken up and delivered in multiple calls.
test_short
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_newlines(self): """ L{_ChunkedTransferDecoder.dataReceived} doesn't treat CR LF pairs embedded in chunk bodies specially. """ L = [] p = http._ChunkedTransferDecoder(L.append, None) p.dataReceived(b'2\r\n\r\n\r\n') self.assertEqual(L, [b'\r\n'])
L{_ChunkedTransferDecoder.dataReceived} doesn't treat CR LF pairs embedded in chunk bodies specially.
test_newlines
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_extensions(self): """ L{_ChunkedTransferDecoder.dataReceived} disregards chunk-extension fields. """ L = [] p = http._ChunkedTransferDecoder(L.append, None) p.dataReceived(b'3; x-foo=bar\r\nabc\r\n') self.assertEqual(L, [b'abc'])
L{_ChunkedTransferDecoder.dataReceived} disregards chunk-extension fields.
test_extensions
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_finish(self): """ L{_ChunkedTransferDecoder.dataReceived} interprets a zero-length chunk as the end of the chunked data stream and calls the completion callback. """ finished = [] p = http._ChunkedTransferDecoder(None, finished.append) p.dataReceived(b'0\r\n\r\n') self.assertEqual(finished, [b''])
L{_ChunkedTransferDecoder.dataReceived} interprets a zero-length chunk as the end of the chunked data stream and calls the completion callback.
test_finish
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_extra(self): """ L{_ChunkedTransferDecoder.dataReceived} passes any bytes which come after the terminating zero-length chunk to the completion callback. """ finished = [] p = http._ChunkedTransferDecoder(None, finished.append) p.dataReceived(b'0\r\n\r\nhello') self.assertEqual(finished, [b'hello'])
L{_ChunkedTransferDecoder.dataReceived} passes any bytes which come after the terminating zero-length chunk to the completion callback.
test_extra
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_afterFinished(self): """ L{_ChunkedTransferDecoder.dataReceived} raises C{RuntimeError} if it is called after it has seen the last chunk. """ p = http._ChunkedTransferDecoder(None, lambda bytes: None) p.dataReceived(b'0\r\n\r\n') self.assertRaises(RuntimeError, p.dataReceived, b'hello')
L{_ChunkedTransferDecoder.dataReceived} raises C{RuntimeError} if it is called after it has seen the last chunk.
test_afterFinished
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_earlyConnectionLose(self): """ L{_ChunkedTransferDecoder.noMoreData} raises L{_DataLoss} if it is called and the end of the last trailer has not yet been received. """ parser = http._ChunkedTransferDecoder(None, lambda bytes: None) parser.dataReceived(b'0\r\n\r') exc = self.assertRaises(_DataLoss, parser.noMoreData) self.assertEqual( str(exc), "Chunked decoder in 'TRAILER' state, still expecting more data " "to get to 'FINISHED' state.")
L{_ChunkedTransferDecoder.noMoreData} raises L{_DataLoss} if it is called and the end of the last trailer has not yet been received.
test_earlyConnectionLose
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_finishedConnectionLose(self): """ L{_ChunkedTransferDecoder.noMoreData} does not raise any exception if it is called after the terminal zero length chunk is received. """ parser = http._ChunkedTransferDecoder(None, lambda bytes: None) parser.dataReceived(b'0\r\n\r\n') parser.noMoreData()
L{_ChunkedTransferDecoder.noMoreData} does not raise any exception if it is called after the terminal zero length chunk is received.
test_finishedConnectionLose
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_reentrantFinishedNoMoreData(self): """ L{_ChunkedTransferDecoder.noMoreData} can be called from the finished callback without raising an exception. """ errors = [] successes = [] def finished(extra): try: parser.noMoreData() except: errors.append(Failure()) else: successes.append(True) parser = http._ChunkedTransferDecoder(None, finished) parser.dataReceived(b'0\r\n\r\n') self.assertEqual(errors, []) self.assertEqual(successes, [True])
L{_ChunkedTransferDecoder.noMoreData} can be called from the finished callback without raising an exception.
test_reentrantFinishedNoMoreData
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_chunkedResponses(self): """ Test that the L{HTTPChannel} correctly chunks responses when needed. """ trans = StringTransport() channel = http.HTTPChannel() channel.makeConnection(trans) req = http.Request(channel, False) req.setResponseCode(200) req.clientproto = b"HTTP/1.1" req.responseHeaders.setRawHeaders(b"test", [b"lemur"]) req.write(b'Hello') req.write(b'World!') self.assertResponseEquals( trans.value(), [(b"HTTP/1.1 200 OK", b"Test: lemur", b"Transfer-Encoding: chunked", b"5\r\nHello\r\n6\r\nWorld!\r\n")])
Test that the L{HTTPChannel} correctly chunks responses when needed.
test_chunkedResponses
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def runRequest(self, httpRequest, requestFactory=None, success=True, channel=None): """ Execute a web request based on plain text content. @param httpRequest: Content for the request which is processed. @type httpRequest: C{bytes} @param requestFactory: 2-argument callable returning a Request. @type requestFactory: C{callable} @param success: Value to compare against I{self.didRequest}. @type success: C{bool} @param channel: Channel instance over which the request is processed. @type channel: L{HTTPChannel} @return: Returns the channel used for processing the request. @rtype: L{HTTPChannel} """ if not channel: channel = http.HTTPChannel() if requestFactory: channel.requestFactory = _makeRequestProxyFactory(requestFactory) httpRequest = httpRequest.replace(b"\n", b"\r\n") transport = StringTransport() channel.makeConnection(transport) # one byte at a time, to stress it. for byte in iterbytes(httpRequest): if channel.transport.disconnecting: break channel.dataReceived(byte) channel.connectionLost(IOError("all done")) if success: self.assertTrue(self.didRequest) else: self.assertFalse(self.didRequest) return channel
Execute a web request based on plain text content. @param httpRequest: Content for the request which is processed. @type httpRequest: C{bytes} @param requestFactory: 2-argument callable returning a Request. @type requestFactory: C{callable} @param success: Value to compare against I{self.didRequest}. @type success: C{bool} @param channel: Channel instance over which the request is processed. @type channel: L{HTTPChannel} @return: Returns the channel used for processing the request. @rtype: L{HTTPChannel}
runRequest
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_invalidNonAsciiMethod(self): """ When client sends invalid HTTP method containing non-ascii characters HTTP 400 'Bad Request' status will be returned. """ processed = [] class MyRequest(http.Request): def process(self): processed.append(self) self.finish() badRequestLine = b"GE\xc2\xa9 / HTTP/1.1\r\n\r\n" channel = self.runRequest(badRequestLine, MyRequest, 0) self.assertEqual( channel.transport.value(), b"HTTP/1.1 400 Bad Request\r\n\r\n") self.assertTrue(channel.transport.disconnecting) self.assertEqual(processed, [])
When client sends invalid HTTP method containing non-ascii characters HTTP 400 'Bad Request' status will be returned.
test_invalidNonAsciiMethod
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_basicAuth(self): """ L{HTTPChannel} provides username and password information supplied in an I{Authorization} header to the L{Request} which makes it available via its C{getUser} and C{getPassword} methods. """ requests = [] class Request(http.Request): def process(self): self.credentials = (self.getUser(), self.getPassword()) requests.append(self) for u, p in [(b"foo", b"bar"), (b"hello", b"there:z")]: s = base64.encodestring(b":".join((u, p))).strip() f = b"GET / HTTP/1.0\nAuthorization: Basic " + s + b"\n\n" self.runRequest(f, Request, 0) req = requests.pop() self.assertEqual((u, p), req.credentials)
L{HTTPChannel} provides username and password information supplied in an I{Authorization} header to the L{Request} which makes it available via its C{getUser} and C{getPassword} methods.
test_basicAuth
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_headers(self): """ Headers received by L{HTTPChannel} in a request are made available to the L{Request}. """ processed = [] class MyRequest(http.Request): def process(self): processed.append(self) self.finish() requestLines = [ b"GET / HTTP/1.0", b"Foo: bar", b"baz: Quux", b"baz: quux", b"", b""] self.runRequest(b'\n'.join(requestLines), MyRequest, 0) [request] = processed self.assertEqual( request.requestHeaders.getRawHeaders(b'foo'), [b'bar']) self.assertEqual( request.requestHeaders.getRawHeaders(b'bAz'), [b'Quux', b'quux'])
Headers received by L{HTTPChannel} in a request are made available to the L{Request}.
test_headers
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_headersMultiline(self): """ Line folded headers are handled by L{HTTPChannel} by replacing each fold with a single space by the time they are made available to the L{Request}. Any leading whitespace in the folded lines of the header value is preserved. See RFC 7230 section 3.2.4. """ processed = [] class MyRequest(http.Request): def process(self): processed.append(self) self.finish() requestLines = [ b"GET / HTTP/1.0", b"nospace: ", b" nospace\t", b"space:space", b" space", b"spaces: spaces", b" spaces", b" spaces", b"tab: t", b"\ta", b"\tb", b"", b"", ] self.runRequest(b"\n".join(requestLines), MyRequest, 0) [request] = processed # All leading and trailing whitespace is stripped from the # header-value. self.assertEqual( request.requestHeaders.getRawHeaders(b"nospace"), [b"nospace"], ) self.assertEqual( request.requestHeaders.getRawHeaders(b"space"), [b"space space"], ) self.assertEqual( request.requestHeaders.getRawHeaders(b"spaces"), [b"spaces spaces spaces"], ) self.assertEqual( request.requestHeaders.getRawHeaders(b"tab"), [b"t \ta \tb"], )
Line folded headers are handled by L{HTTPChannel} by replacing each fold with a single space by the time they are made available to the L{Request}. Any leading whitespace in the folded lines of the header value is preserved. See RFC 7230 section 3.2.4.
test_headersMultiline
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_tooManyHeaders(self): """ L{HTTPChannel} enforces a limit of C{HTTPChannel.maxHeaders} on the number of headers received per request. """ processed = [] class MyRequest(http.Request): def process(self): processed.append(self) requestLines = [b"GET / HTTP/1.0"] for i in range(http.HTTPChannel.maxHeaders + 2): requestLines.append(networkString("%s: foo" % (i,))) requestLines.extend([b"", b""]) channel = self.runRequest(b"\n".join(requestLines), MyRequest, 0) self.assertEqual(processed, []) self.assertEqual( channel.transport.value(), b"HTTP/1.1 400 Bad Request\r\n\r\n")
L{HTTPChannel} enforces a limit of C{HTTPChannel.maxHeaders} on the number of headers received per request.
test_tooManyHeaders
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_invalidContentLengthHeader(self): """ If a Content-Length header with a non-integer value is received, a 400 (Bad Request) response is sent to the client and the connection is closed. """ processed = [] class MyRequest(http.Request): def process(self): processed.append(self) self.finish() requestLines = [b"GET / HTTP/1.0", b"Content-Length: x", b"", b""] channel = self.runRequest(b"\n".join(requestLines), MyRequest, 0) self.assertEqual( channel.transport.value(), b"HTTP/1.1 400 Bad Request\r\n\r\n") self.assertTrue(channel.transport.disconnecting) self.assertEqual(processed, [])
If a Content-Length header with a non-integer value is received, a 400 (Bad Request) response is sent to the client and the connection is closed.
test_invalidContentLengthHeader
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_invalidHeaderNoColon(self): """ If a header without colon is received a 400 (Bad Request) response is sent to the client and the connection is closed. """ processed = [] class MyRequest(http.Request): def process(self): processed.append(self) self.finish() requestLines = [b"GET / HTTP/1.0", b"HeaderName ", b"", b""] channel = self.runRequest(b"\n".join(requestLines), MyRequest, 0) self.assertEqual( channel.transport.value(), b"HTTP/1.1 400 Bad Request\r\n\r\n") self.assertTrue(channel.transport.disconnecting) self.assertEqual(processed, [])
If a header without colon is received a 400 (Bad Request) response is sent to the client and the connection is closed.
test_invalidHeaderNoColon
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_headerLimitPerRequest(self): """ L{HTTPChannel} enforces the limit of C{HTTPChannel.maxHeaders} per request so that headers received in an earlier request do not count towards the limit when processing a later request. """ processed = [] class MyRequest(http.Request): def process(self): processed.append(self) self.finish() self.patch(http.HTTPChannel, 'maxHeaders', 1) requestLines = [ b"GET / HTTP/1.1", b"Foo: bar", b"", b"", b"GET / HTTP/1.1", b"Bar: baz", b"", b""] channel = self.runRequest(b"\n".join(requestLines), MyRequest, 0) [first, second] = processed self.assertEqual(first.getHeader(b'foo'), b'bar') self.assertEqual(second.getHeader(b'bar'), b'baz') self.assertEqual( channel.transport.value(), b'HTTP/1.1 200 OK\r\n' b'Transfer-Encoding: chunked\r\n' b'\r\n' b'0\r\n' b'\r\n' b'HTTP/1.1 200 OK\r\n' b'Transfer-Encoding: chunked\r\n' b'\r\n' b'0\r\n' b'\r\n')
L{HTTPChannel} enforces the limit of C{HTTPChannel.maxHeaders} per request so that headers received in an earlier request do not count towards the limit when processing a later request.
test_headerLimitPerRequest
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_headersTooBigInitialCommand(self): """ Enforces a limit of C{HTTPChannel.totalHeadersSize} on the size of headers received per request starting from initial command line. """ processed = [] class MyRequest(http.Request): def process(self): processed.append(self) self.finish() channel = http.HTTPChannel() channel.totalHeadersSize = 10 httpRequest = b'GET /path/longer/than/10 HTTP/1.1\n' channel = self.runRequest( httpRequest=httpRequest, requestFactory=MyRequest, channel=channel, success=False ) self.assertEqual(processed, []) self.assertEqual( channel.transport.value(), b"HTTP/1.1 400 Bad Request\r\n\r\n")
Enforces a limit of C{HTTPChannel.totalHeadersSize} on the size of headers received per request starting from initial command line.
test_headersTooBigInitialCommand
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_headersTooBigOtherHeaders(self): """ Enforces a limit of C{HTTPChannel.totalHeadersSize} on the size of headers received per request counting first line and total headers. """ processed = [] class MyRequest(http.Request): def process(self): processed.append(self) self.finish() channel = http.HTTPChannel() channel.totalHeadersSize = 40 httpRequest = ( b'GET /less/than/40 HTTP/1.1\n' b'Some-Header: less-than-40\n' ) channel = self.runRequest( httpRequest=httpRequest, requestFactory=MyRequest, channel=channel, success=False ) self.assertEqual(processed, []) self.assertEqual( channel.transport.value(), b"HTTP/1.1 400 Bad Request\r\n\r\n")
Enforces a limit of C{HTTPChannel.totalHeadersSize} on the size of headers received per request counting first line and total headers.
test_headersTooBigOtherHeaders
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_headersTooBigPerRequest(self): """ Enforces total size of headers per individual request and counter is reset at the end of each request. """ class SimpleRequest(http.Request): def process(self): self.finish() channel = http.HTTPChannel() channel.totalHeadersSize = 60 channel.requestFactory = SimpleRequest httpRequest = ( b'GET / HTTP/1.1\n' b'Some-Header: total-less-than-60\n' b'\n' b'GET / HTTP/1.1\n' b'Some-Header: less-than-60\n' b'\n' ) channel = self.runRequest( httpRequest=httpRequest, channel=channel, success=False) self.assertEqual( channel.transport.value(), b'HTTP/1.1 200 OK\r\n' b'Transfer-Encoding: chunked\r\n' b'\r\n' b'0\r\n' b'\r\n' b'HTTP/1.1 200 OK\r\n' b'Transfer-Encoding: chunked\r\n' b'\r\n' b'0\r\n' b'\r\n' )
Enforces total size of headers per individual request and counter is reset at the end of each request.
test_headersTooBigPerRequest
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def testCookies(self): """ Test cookies parsing and reading. """ httpRequest = b'''\ GET / HTTP/1.0 Cookie: rabbit="eat carrot"; ninja=secret; spam="hey 1=1!" ''' cookies = {} testcase = self class MyRequest(http.Request): def process(self): for name in [b'rabbit', b'ninja', b'spam']: cookies[name] = self.getCookie(name) testcase.didRequest = True self.finish() self.runRequest(httpRequest, MyRequest) self.assertEqual( cookies, { b'rabbit': b'"eat carrot"', b'ninja': b'secret', b'spam': b'"hey 1=1!"'})
Test cookies parsing and reading.
testCookies
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_extraQuestionMark(self): """ While only a single '?' is allowed in an URL, several other servers allow several and pass all after the first through as part of the query arguments. Test that we emulate this behavior. """ httpRequest = b'GET /foo?bar=?&baz=quux HTTP/1.0\n\n' method = [] path = [] args = [] testcase = self class MyRequest(http.Request): def process(self): method.append(self.method) path.append(self.path) args.extend([self.args[b'bar'], self.args[b'baz']]) testcase.didRequest = True self.finish() self.runRequest(httpRequest, MyRequest) self.assertEqual(method, [b'GET']) self.assertEqual(path, [b'/foo']) self.assertEqual(args, [[b'?'], [b'quux']])
While only a single '?' is allowed in an URL, several other servers allow several and pass all after the first through as part of the query arguments. Test that we emulate this behavior.
test_extraQuestionMark
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_formPOSTRequest(self): """ The request body of a I{POST} request with a I{Content-Type} header of I{application/x-www-form-urlencoded} is parsed according to that content type and made available in the C{args} attribute of the request object. The original bytes of the request may still be read from the C{content} attribute. """ query = 'key=value&multiple=two+words&multiple=more%20words&empty=' httpRequest = networkString('''\ POST / HTTP/1.0 Content-Length: %d Content-Type: application/x-www-form-urlencoded %s''' % (len(query), query)) method = [] args = [] content = [] testcase = self class MyRequest(http.Request): def process(self): method.append(self.method) args.extend([ self.args[b'key'], self.args[b'empty'], self.args[b'multiple']]) content.append(self.content.read()) testcase.didRequest = True self.finish() self.runRequest(httpRequest, MyRequest) self.assertEqual(method, [b"POST"]) self.assertEqual( args, [[b"value"], [b""], [b"two words", b"more words"]]) # Reading from the content file-like must produce the entire request # body. self.assertEqual(content, [networkString(query)])
The request body of a I{POST} request with a I{Content-Type} header of I{application/x-www-form-urlencoded} is parsed according to that content type and made available in the C{args} attribute of the request object. The original bytes of the request may still be read from the C{content} attribute.
test_formPOSTRequest
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_missingContentDisposition(self): """ If the C{Content-Disposition} header is missing, the request is denied as a bad request. """ req = b'''\ POST / HTTP/1.0 Content-Type: multipart/form-data; boundary=AaB03x Content-Length: 103 --AaB03x Content-Type: text/plain Content-Transfer-Encoding: quoted-printable abasdfg --AaB03x-- ''' channel = self.runRequest(req, http.Request, success=False) self.assertEqual( channel.transport.value(), b"HTTP/1.1 400 Bad Request\r\n\r\n")
If the C{Content-Disposition} header is missing, the request is denied as a bad request.
test_missingContentDisposition
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_multipartProcessingFailure(self): """ When the multipart processing fails the client gets a 400 Bad Request. """ # The parsing failure is having a UTF-8 boundary -- the spec # says it must be ASCII. req = b'''\ POST / HTTP/1.0 Content-Type: multipart/form-data; boundary=\xe2\x98\x83 Content-Length: 103 --\xe2\x98\x83 Content-Type: text/plain Content-Length: 999999999999999999999999999999999999999999999999999999999999999 Content-Transfer-Encoding: quoted-printable abasdfg --\xe2\x98\x83-- ''' channel = self.runRequest(req, http.Request, success=False) self.assertEqual( channel.transport.value(), b"HTTP/1.1 400 Bad Request\r\n\r\n")
When the multipart processing fails the client gets a 400 Bad Request.
test_multipartProcessingFailure
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_multipartFormData(self): """ If the request has a Content-Type of C{multipart/form-data}, and the form data is parseable, the form arguments will be added to the request's args. """ processed = [] class MyRequest(http.Request): def process(self): processed.append(self) self.write(b"done") self.finish() req = b'''\ POST / HTTP/1.0 Content-Type: multipart/form-data; boundary=AaB03x Content-Length: 149 --AaB03x Content-Type: text/plain Content-Disposition: form-data; name="text" Content-Transfer-Encoding: quoted-printable abasdfg --AaB03x-- ''' channel = self.runRequest(req, MyRequest, success=False) self.assertEqual(channel.transport.value(), b"HTTP/1.0 200 OK\r\n\r\ndone") self.assertEqual(len(processed), 1) self.assertEqual(processed[0].args, {b"text": [b"abasdfg"]})
If the request has a Content-Type of C{multipart/form-data}, and the form data is parseable, the form arguments will be added to the request's args.
test_multipartFormData
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_multipartFileData(self): """ If the request has a Content-Type of C{multipart/form-data}, and the form data is parseable and contains files, the file portions will be added to the request's args. """ processed = [] class MyRequest(http.Request): def process(self): processed.append(self) self.write(b"done") self.finish() body = b"""-----------------------------738837029596785559389649595 Content-Disposition: form-data; name="uploadedfile"; filename="test" Content-Type: application/octet-stream abasdfg -----------------------------738837029596785559389649595-- """ req = '''\ POST / HTTP/1.0 Content-Type: multipart/form-data; boundary=---------------------------738837029596785559389649595 Content-Length: ''' + str(len(body.replace(b"\n", b"\r\n"))) + ''' ''' channel = self.runRequest(req.encode('ascii') + body, MyRequest, success=False) self.assertEqual(channel.transport.value(), b"HTTP/1.0 200 OK\r\n\r\ndone") self.assertEqual(len(processed), 1) self.assertEqual(processed[0].args, {b"uploadedfile": [b"abasdfg"]})
If the request has a Content-Type of C{multipart/form-data}, and the form data is parseable and contains files, the file portions will be added to the request's args.
test_multipartFileData
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_chunkedEncoding(self): """ If a request uses the I{chunked} transfer encoding, the request body is decoded accordingly before it is made available on the request. """ httpRequest = b'''\ GET / HTTP/1.0 Content-Type: text/plain Transfer-Encoding: chunked 6 Hello, 14 spam,eggs spam spam 0 ''' path = [] method = [] content = [] decoder = [] testcase = self class MyRequest(http.Request): def process(self): content.append(self.content.fileno()) content.append(self.content.read()) method.append(self.method) path.append(self.path) decoder.append(self.channel._transferDecoder) testcase.didRequest = True self.finish() self.runRequest(httpRequest, MyRequest) # The tempfile API used to create content returns an # instance of a different type depending on what platform # we're running on. The point here is to verify that the # request body is in a file that's on the filesystem. # Having a fileno method that returns an int is a somewhat # close approximation of this. -exarkun self.assertIsInstance(content[0], int) self.assertEqual(content[1], b'Hello, spam,eggs spam spam') self.assertEqual(method, [b'GET']) self.assertEqual(path, [b'/']) self.assertEqual(decoder, [None])
If a request uses the I{chunked} transfer encoding, the request body is decoded accordingly before it is made available on the request.
test_chunkedEncoding
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_malformedChunkedEncoding(self): """ If a request uses the I{chunked} transfer encoding, but provides an invalid chunk length value, the request fails with a 400 error. """ # See test_chunkedEncoding for the correct form of this request. httpRequest = b'''\ GET / HTTP/1.1 Content-Type: text/plain Transfer-Encoding: chunked MALFORMED_LINE_THIS_SHOULD_BE_'6' Hello, 14 spam,eggs spam spam 0 ''' didRequest = [] class MyRequest(http.Request): def process(self): # This request should fail, so this should never be called. didRequest.append(True) channel = self.runRequest(httpRequest, MyRequest, success=False) self.assertFalse(didRequest, "Request.process called") self.assertEqual( channel.transport.value(), b"HTTP/1.1 400 Bad Request\r\n\r\n") self.assertTrue(channel.transport.disconnecting)
If a request uses the I{chunked} transfer encoding, but provides an invalid chunk length value, the request fails with a 400 error.
test_malformedChunkedEncoding
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_basicAuthException(self): """ A L{Request} that throws an exception processing basic authorization logs an error and uses an empty username and password. """ logObserver = EventLoggingObserver.createWithCleanup( self, globalLogPublisher ) requests = [] class Request(http.Request): def process(self): self.credentials = (self.getUser(), self.getPassword()) requests.append(self) u = b"foo" p = b"bar" s = base64.encodestring(b":".join((u, p))).strip() f = b"GET / HTTP/1.0\nAuthorization: Basic " + s + b"\n\n" self.patch(base64, 'decodestring', lambda x: []) self.runRequest(f, Request, 0) req = requests.pop() self.assertEqual(('', ''), req.credentials) self.assertEquals(1, len(logObserver)) event = logObserver[0] f = event["log_failure"] self.assertIsInstance(f.value, AttributeError) self.flushLoggedErrors(AttributeError)
A L{Request} that throws an exception processing basic authorization logs an error and uses an empty username and password.
test_basicAuthException
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def assertSameParsing(url, decode): """ Verify that C{url} is parsed into the same objects by both L{http.urlparse} and L{urlparse}. """ urlToStandardImplementation = url if decode: urlToStandardImplementation = url.decode('ascii') # stdlib urlparse will give back whatever type we give it. To be # able to compare the values meaningfully, if it gives back unicode, # convert all the values to bytes. standardResult = urlparse(urlToStandardImplementation) if isinstance(standardResult.scheme, unicode): # The choice of encoding is basically irrelevant. The values # are all in ASCII. UTF-8 is, of course, the correct choice. expected = (standardResult.scheme.encode('utf-8'), standardResult.netloc.encode('utf-8'), standardResult.path.encode('utf-8'), standardResult.params.encode('utf-8'), standardResult.query.encode('utf-8'), standardResult.fragment.encode('utf-8')) else: expected = (standardResult.scheme, standardResult.netloc, standardResult.path, standardResult.params, standardResult.query, standardResult.fragment) scheme, netloc, path, params, query, fragment = http.urlparse(url) self.assertEqual( (scheme, netloc, path, params, query, fragment), expected) self.assertIsInstance(scheme, bytes) self.assertIsInstance(netloc, bytes) self.assertIsInstance(path, bytes) self.assertIsInstance(params, bytes) self.assertIsInstance(query, bytes) self.assertIsInstance(fragment, bytes)
Verify that C{url} is parsed into the same objects by both L{http.urlparse} and L{urlparse}.
test_urlparse.assertSameParsing
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_urlparse(self): """ For a given URL, L{http.urlparse} should behave the same as L{urlparse}, except it should always return C{bytes}, never text. """ def urls(): for scheme in (b'http', b'https'): for host in (b'example.com',): for port in (None, 100): for path in (b'', b'path'): if port is not None: host = host + b':' + networkString(str(port)) yield urlunsplit((scheme, host, path, b'', b'')) def assertSameParsing(url, decode): """ Verify that C{url} is parsed into the same objects by both L{http.urlparse} and L{urlparse}. """ urlToStandardImplementation = url if decode: urlToStandardImplementation = url.decode('ascii') # stdlib urlparse will give back whatever type we give it. To be # able to compare the values meaningfully, if it gives back unicode, # convert all the values to bytes. standardResult = urlparse(urlToStandardImplementation) if isinstance(standardResult.scheme, unicode): # The choice of encoding is basically irrelevant. The values # are all in ASCII. UTF-8 is, of course, the correct choice. expected = (standardResult.scheme.encode('utf-8'), standardResult.netloc.encode('utf-8'), standardResult.path.encode('utf-8'), standardResult.params.encode('utf-8'), standardResult.query.encode('utf-8'), standardResult.fragment.encode('utf-8')) else: expected = (standardResult.scheme, standardResult.netloc, standardResult.path, standardResult.params, standardResult.query, standardResult.fragment) scheme, netloc, path, params, query, fragment = http.urlparse(url) self.assertEqual( (scheme, netloc, path, params, query, fragment), expected) self.assertIsInstance(scheme, bytes) self.assertIsInstance(netloc, bytes) self.assertIsInstance(path, bytes) self.assertIsInstance(params, bytes) self.assertIsInstance(query, bytes) self.assertIsInstance(fragment, bytes) # With caching, unicode then str clear_cache() for url in urls(): assertSameParsing(url, True) assertSameParsing(url, False) # With caching, str then unicode clear_cache() for url in urls(): assertSameParsing(url, False) assertSameParsing(url, True) # Without caching for url in urls(): clear_cache() assertSameParsing(url, True) clear_cache() assertSameParsing(url, False)
For a given URL, L{http.urlparse} should behave the same as L{urlparse}, except it should always return C{bytes}, never text.
test_urlparse
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_urlparseRejectsUnicode(self): """ L{http.urlparse} should reject unicode input early. """ self.assertRaises(TypeError, http.urlparse, u'http://example.org/path')
L{http.urlparse} should reject unicode input early.
test_urlparseRejectsUnicode
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def _compatHeadersTest(self, oldName, newName): """ Verify that each of two different attributes which are associated with the same state properly reflect changes made through the other. This is used to test that the C{headers}/C{responseHeaders} and C{received_headers}/C{requestHeaders} pairs interact properly. """ req = http.Request(DummyChannel(), False) getattr(req, newName).setRawHeaders(b"test", [b"lemur"]) self.assertEqual(getattr(req, oldName)[b"test"], b"lemur") setattr(req, oldName, {b"foo": b"bar"}) self.assertEqual( list(getattr(req, newName).getAllRawHeaders()), [(b"Foo", [b"bar"])]) setattr(req, newName, http_headers.Headers()) self.assertEqual(getattr(req, oldName), {})
Verify that each of two different attributes which are associated with the same state properly reflect changes made through the other. This is used to test that the C{headers}/C{responseHeaders} and C{received_headers}/C{requestHeaders} pairs interact properly.
_compatHeadersTest
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_getHeader(self): """ L{http.Request.getHeader} returns the value of the named request header. """ req = http.Request(DummyChannel(), False) req.requestHeaders.setRawHeaders(b"test", [b"lemur"]) self.assertEqual(req.getHeader(b"test"), b"lemur")
L{http.Request.getHeader} returns the value of the named request header.
test_getHeader
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_getHeaderReceivedMultiples(self): """ When there are multiple values for a single request header, L{http.Request.getHeader} returns the last value. """ req = http.Request(DummyChannel(), False) req.requestHeaders.setRawHeaders(b"test", [b"lemur", b"panda"]) self.assertEqual(req.getHeader(b"test"), b"panda")
When there are multiple values for a single request header, L{http.Request.getHeader} returns the last value.
test_getHeaderReceivedMultiples
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_getHeaderNotFound(self): """ L{http.Request.getHeader} returns L{None} when asked for the value of a request header which is not present. """ req = http.Request(DummyChannel(), False) self.assertEqual(req.getHeader(b"test"), None)
L{http.Request.getHeader} returns L{None} when asked for the value of a request header which is not present.
test_getHeaderNotFound
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_getAllHeaders(self): """ L{http.Request.getAllheaders} returns a C{dict} mapping all request header names to their corresponding values. """ req = http.Request(DummyChannel(), False) req.requestHeaders.setRawHeaders(b"test", [b"lemur"]) self.assertEqual(req.getAllHeaders(), {b"test": b"lemur"})
L{http.Request.getAllheaders} returns a C{dict} mapping all request header names to their corresponding values.
test_getAllHeaders
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_getAllHeadersNoHeaders(self): """ L{http.Request.getAllHeaders} returns an empty C{dict} if there are no request headers. """ req = http.Request(DummyChannel(), False) self.assertEqual(req.getAllHeaders(), {})
L{http.Request.getAllHeaders} returns an empty C{dict} if there are no request headers.
test_getAllHeadersNoHeaders
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_getAllHeadersMultipleHeaders(self): """ When there are multiple values for a single request header, L{http.Request.getAllHeaders} returns only the last value. """ req = http.Request(DummyChannel(), False) req.requestHeaders.setRawHeaders(b"test", [b"lemur", b"panda"]) self.assertEqual(req.getAllHeaders(), {b"test": b"panda"})
When there are multiple values for a single request header, L{http.Request.getAllHeaders} returns only the last value.
test_getAllHeadersMultipleHeaders
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_setResponseCode(self): """ L{http.Request.setResponseCode} takes a status code and causes it to be used as the response status. """ channel = DummyChannel() req = http.Request(channel, False) req.setResponseCode(201) req.write(b'') self.assertEqual( channel.transport.written.getvalue().splitlines()[0], b"(no clientproto yet) 201 Created")
L{http.Request.setResponseCode} takes a status code and causes it to be used as the response status.
test_setResponseCode
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_setResponseCodeAndMessage(self): """ L{http.Request.setResponseCode} takes a status code and a message and causes them to be used as the response status. """ channel = DummyChannel() req = http.Request(channel, False) req.setResponseCode(202, b"happily accepted") req.write(b'') self.assertEqual( channel.transport.written.getvalue().splitlines()[0], b'(no clientproto yet) 202 happily accepted')
L{http.Request.setResponseCode} takes a status code and a message and causes them to be used as the response status.
test_setResponseCodeAndMessage
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_setResponseCodeAndMessageNotBytes(self): """ L{http.Request.setResponseCode} accepts C{bytes} for the message parameter and raises L{TypeError} if passed anything else. """ channel = DummyChannel() req = http.Request(channel, False) self.assertRaises(TypeError, req.setResponseCode, 202, u"not happily accepted")
L{http.Request.setResponseCode} accepts C{bytes} for the message parameter and raises L{TypeError} if passed anything else.
test_setResponseCodeAndMessageNotBytes
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_setResponseCodeAcceptsIntegers(self): """ L{http.Request.setResponseCode} accepts C{int} for the code parameter and raises L{TypeError} if passed anything else. """ req = http.Request(DummyChannel(), False) req.setResponseCode(1) self.assertRaises(TypeError, req.setResponseCode, "1")
L{http.Request.setResponseCode} accepts C{int} for the code parameter and raises L{TypeError} if passed anything else.
test_setResponseCodeAcceptsIntegers
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_setResponseCodeAcceptsLongIntegers(self): """ L{http.Request.setResponseCode} accepts C{long} for the code parameter. """ req = http.Request(DummyChannel(), False) req.setResponseCode(long(1))
L{http.Request.setResponseCode} accepts C{long} for the code parameter.
test_setResponseCodeAcceptsLongIntegers
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_setLastModifiedNeverSet(self): """ When no previous value was set and no 'if-modified-since' value was requested, L{http.Request.setLastModified} takes a timestamp in seconds since the epoch and sets the request's lastModified attribute. """ req = http.Request(DummyChannel(), False) req.setLastModified(42) self.assertEqual(req.lastModified, 42)
When no previous value was set and no 'if-modified-since' value was requested, L{http.Request.setLastModified} takes a timestamp in seconds since the epoch and sets the request's lastModified attribute.
test_setLastModifiedNeverSet
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_setLastModifiedUpdate(self): """ If the supplied timestamp is later than the lastModified attribute's value, L{http.Request.setLastModified} updates the lastModifed attribute. """ req = http.Request(DummyChannel(), False) req.setLastModified(0) req.setLastModified(1) self.assertEqual(req.lastModified, 1)
If the supplied timestamp is later than the lastModified attribute's value, L{http.Request.setLastModified} updates the lastModifed attribute.
test_setLastModifiedUpdate
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_setLastModifiedIgnore(self): """ If the supplied timestamp occurs earlier than the current lastModified attribute, L{http.Request.setLastModified} ignores it. """ req = http.Request(DummyChannel(), False) req.setLastModified(1) req.setLastModified(0) self.assertEqual(req.lastModified, 1)
If the supplied timestamp occurs earlier than the current lastModified attribute, L{http.Request.setLastModified} ignores it.
test_setLastModifiedIgnore
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_setLastModifiedCached(self): """ If the resource is older than the if-modified-since date in the request header, L{http.Request.setLastModified} returns L{http.CACHED}. """ req = http.Request(DummyChannel(), False) req.requestHeaders.setRawHeaders( networkString('if-modified-since'), [b'02 Jan 1970 00:00:00 GMT'] ) result = req.setLastModified(42) self.assertEqual(result, http.CACHED)
If the resource is older than the if-modified-since date in the request header, L{http.Request.setLastModified} returns L{http.CACHED}.
test_setLastModifiedCached
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_setLastModifiedNotCached(self): """ If the resource is newer than the if-modified-since date in the request header, L{http.Request.setLastModified} returns None """ req = http.Request(DummyChannel(), False) req.requestHeaders.setRawHeaders( networkString('if-modified-since'), [b'01 Jan 1970 00:00:00 GMT'] ) result = req.setLastModified(1000000) self.assertEqual(result, None)
If the resource is newer than the if-modified-since date in the request header, L{http.Request.setLastModified} returns None
test_setLastModifiedNotCached
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_setLastModifiedTwiceNotCached(self): """ When L{http.Request.setLastModified} is called multiple times, the highest supplied value is honored. If that value is higher than the if-modified-since date in the request header, the method returns None. """ req = http.Request(DummyChannel(), False) req.requestHeaders.setRawHeaders( networkString('if-modified-since'), [b'01 Jan 1970 00:00:01 GMT'] ) req.setLastModified(1000000) result = req.setLastModified(0) self.assertEqual(result, None)
When L{http.Request.setLastModified} is called multiple times, the highest supplied value is honored. If that value is higher than the if-modified-since date in the request header, the method returns None.
test_setLastModifiedTwiceNotCached
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT