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
182
| url
stringlengths 46
251
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def test_hostValueStandardHTTP(self):
"""
When passed a scheme of C{'http'} and a port of C{80},
L{Agent._computeHostValue} returns a string giving just
the host name passed to it.
"""
self.assertEqual(
self.agent._computeHostValue(b'http', b'example.com', 80),
b'example.com') | When passed a scheme of C{'http'} and a port of C{80},
L{Agent._computeHostValue} returns a string giving just
the host name passed to it. | test_hostValueStandardHTTP | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_hostValueNonStandardHTTP(self):
"""
When passed a scheme of C{'http'} and a port other than C{80},
L{Agent._computeHostValue} returns a string giving the
host passed to it joined together with the port number by C{":"}.
"""
self.assertEqual(
self.agent._computeHostValue(b'http', b'example.com', 54321),
b'example.com:54321') | When passed a scheme of C{'http'} and a port other than C{80},
L{Agent._computeHostValue} returns a string giving the
host passed to it joined together with the port number by C{":"}. | test_hostValueNonStandardHTTP | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_hostValueStandardHTTPS(self):
"""
When passed a scheme of C{'https'} and a port of C{443},
L{Agent._computeHostValue} returns a string giving just
the host name passed to it.
"""
self.assertEqual(
self.agent._computeHostValue(b'https', b'example.com', 443),
b'example.com') | When passed a scheme of C{'https'} and a port of C{443},
L{Agent._computeHostValue} returns a string giving just
the host name passed to it. | test_hostValueStandardHTTPS | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_hostValueNonStandardHTTPS(self):
"""
When passed a scheme of C{'https'} and a port other than C{443},
L{Agent._computeHostValue} returns a string giving the
host passed to it joined together with the port number by C{":"}.
"""
self.assertEqual(
self.agent._computeHostValue(b'https', b'example.com', 54321),
b'example.com:54321') | When passed a scheme of C{'https'} and a port other than C{443},
L{Agent._computeHostValue} returns a string giving the
host passed to it joined together with the port number by C{":"}. | test_hostValueNonStandardHTTPS | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_request(self):
"""
L{Agent.request} establishes a new connection to the host indicated by
the host part of the URI passed to it and issues a request using the
method, the path portion of the URI, the headers, and the body producer
passed to it. It returns a L{Deferred} which fires with an
L{IResponse} from the server.
"""
self.agent._getEndpoint = lambda *args: self
headers = http_headers.Headers({b'foo': [b'bar']})
# Just going to check the body for identity, so it doesn't need to be
# real.
body = object()
self.agent.request(
b'GET', b'http://example.com:1234/foo?bar', headers, body)
protocol = self.protocol
# The request should be issued.
self.assertEqual(len(protocol.requests), 1)
req, res = protocol.requests.pop()
self.assertIsInstance(req, Request)
self.assertEqual(req.method, b'GET')
self.assertEqual(req.uri, b'/foo?bar')
self.assertEqual(
req.headers,
http_headers.Headers({b'foo': [b'bar'],
b'host': [b'example.com:1234']}))
self.assertIdentical(req.bodyProducer, body) | L{Agent.request} establishes a new connection to the host indicated by
the host part of the URI passed to it and issues a request using the
method, the path portion of the URI, the headers, and the body producer
passed to it. It returns a L{Deferred} which fires with an
L{IResponse} from the server. | test_request | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_connectTimeout(self):
"""
L{Agent} takes a C{connectTimeout} argument which is forwarded to the
following C{connectTCP} agent.
"""
agent = client.Agent(self.reactor, connectTimeout=5)
agent.request(b'GET', b'http://foo/')
timeout = self.reactor.tcpClients.pop()[3]
self.assertEqual(5, timeout) | L{Agent} takes a C{connectTimeout} argument which is forwarded to the
following C{connectTCP} agent. | test_connectTimeout | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_connectTimeoutHTTPS(self):
"""
L{Agent} takes a C{connectTimeout} argument which is forwarded to the
following C{connectTCP} call.
"""
agent = client.Agent(self.reactor, connectTimeout=5)
agent.request(b'GET', b'https://foo/')
timeout = self.reactor.tcpClients.pop()[3]
self.assertEqual(5, timeout) | L{Agent} takes a C{connectTimeout} argument which is forwarded to the
following C{connectTCP} call. | test_connectTimeoutHTTPS | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_bindAddress(self):
"""
L{Agent} takes a C{bindAddress} argument which is forwarded to the
following C{connectTCP} call.
"""
agent = client.Agent(self.reactor, bindAddress='192.168.0.1')
agent.request(b'GET', b'http://foo/')
address = self.reactor.tcpClients.pop()[4]
self.assertEqual('192.168.0.1', address) | L{Agent} takes a C{bindAddress} argument which is forwarded to the
following C{connectTCP} call. | test_bindAddress | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_bindAddressSSL(self):
"""
L{Agent} takes a C{bindAddress} argument which is forwarded to the
following C{connectSSL} call.
"""
agent = client.Agent(self.reactor, bindAddress='192.168.0.1')
agent.request(b'GET', b'https://foo/')
address = self.reactor.tcpClients.pop()[4]
self.assertEqual('192.168.0.1', address) | L{Agent} takes a C{bindAddress} argument which is forwarded to the
following C{connectSSL} call. | test_bindAddressSSL | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_responseIncludesRequest(self):
"""
L{Response}s returned by L{Agent.request} have a reference to the
L{Request} that was originally issued.
"""
uri = b'http://example.com/'
agent = self.buildAgentForWrapperTest(self.reactor)
d = agent.request(b'GET', uri)
# The request should be issued.
self.assertEqual(len(self.protocol.requests), 1)
req, res = self.protocol.requests.pop()
self.assertIsInstance(req, Request)
resp = client.Response._construct(
(b'HTTP', 1, 1),
200,
b'OK',
client.Headers({}),
None,
req)
res.callback(resp)
response = self.successResultOf(d)
self.assertEqual(
(response.request.method, response.request.absoluteURI,
response.request.headers),
(req.method, req.absoluteURI, req.headers)) | L{Response}s returned by L{Agent.request} have a reference to the
L{Request} that was originally issued. | test_responseIncludesRequest | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_requestAbsoluteURI(self):
"""
L{Request.absoluteURI} is the absolute URI of the request.
"""
uri = b'http://example.com/foo;1234?bar#frag'
agent = self.buildAgentForWrapperTest(self.reactor)
agent.request(b'GET', uri)
# The request should be issued.
self.assertEqual(len(self.protocol.requests), 1)
req, res = self.protocol.requests.pop()
self.assertIsInstance(req, Request)
self.assertEqual(req.absoluteURI, uri) | L{Request.absoluteURI} is the absolute URI of the request. | test_requestAbsoluteURI | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_requestMissingAbsoluteURI(self):
"""
L{Request.absoluteURI} is L{None} if L{Request._parsedURI} is L{None}.
"""
request = client.Request(b'FOO', b'/', client.Headers(), None)
self.assertIdentical(request.absoluteURI, None) | L{Request.absoluteURI} is L{None} if L{Request._parsedURI} is L{None}. | test_requestMissingAbsoluteURI | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_endpointFactory(self):
"""
L{Agent.usingEndpointFactory} creates an L{Agent} that uses the given
factory to create endpoints.
"""
factory = StubEndpointFactory()
agent = client.Agent.usingEndpointFactory(
None, endpointFactory=factory)
uri = URI.fromBytes(b'http://example.com/')
returnedEndpoint = agent._getEndpoint(uri)
self.assertEqual(returnedEndpoint, (b"http", b"example.com", 80)) | L{Agent.usingEndpointFactory} creates an L{Agent} that uses the given
factory to create endpoints. | test_endpointFactory | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_endpointFactoryDefaultPool(self):
"""
If no pool is passed in to L{Agent.usingEndpointFactory}, a default
pool is constructed with no persistent connections.
"""
agent = client.Agent.usingEndpointFactory(
self.reactor, StubEndpointFactory())
pool = agent._pool
self.assertEqual((pool.__class__, pool.persistent, pool._reactor),
(HTTPConnectionPool, False, agent._reactor)) | If no pool is passed in to L{Agent.usingEndpointFactory}, a default
pool is constructed with no persistent connections. | test_endpointFactoryDefaultPool | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_endpointFactoryPool(self):
"""
If a pool is passed in to L{Agent.usingEndpointFactory} it is used as
the L{Agent} pool.
"""
pool = object()
agent = client.Agent.usingEndpointFactory(
self.reactor, StubEndpointFactory(), pool)
self.assertIs(pool, agent._pool) | If a pool is passed in to L{Agent.usingEndpointFactory} it is used as
the L{Agent} pool. | test_endpointFactoryPool | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def attemptRequestWithMaliciousMethod(self, method):
"""
Attempt a request with the provided method.
@param method: see L{MethodInjectionTestsMixin}
"""
agent = client.Agent(self.createReactor())
uri = b"http://twisted.invalid"
agent.request(method, uri, client.Headers(), None) | Attempt a request with the provided method.
@param method: see L{MethodInjectionTestsMixin} | attemptRequestWithMaliciousMethod | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def attemptRequestWithMaliciousURI(self, uri):
"""
Attempt a request with the provided method.
@param uri: see L{URIInjectionTestsMixin}
"""
agent = client.Agent(self.createReactor())
method = b"GET"
agent.request(method, uri, client.Headers(), None) | Attempt a request with the provided method.
@param uri: see L{URIInjectionTestsMixin} | attemptRequestWithMaliciousURI | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def makeEndpoint(self, host=b'example.com', port=443):
"""
Create an L{Agent} with an https scheme and return its endpoint
created according to the arguments.
@param host: The host for the endpoint.
@type host: L{bytes}
@param port: The port for the endpoint.
@type port: L{int}
@return: An endpoint of an L{Agent} constructed according to args.
@rtype: L{SSL4ClientEndpoint}
"""
return client.Agent(self.createReactor())._getEndpoint(
URI.fromBytes(b'https://' + host + b":" + intToBytes(port) + b"/")) | Create an L{Agent} with an https scheme and return its endpoint
created according to the arguments.
@param host: The host for the endpoint.
@type host: L{bytes}
@param port: The port for the endpoint.
@type port: L{int}
@return: An endpoint of an L{Agent} constructed according to args.
@rtype: L{SSL4ClientEndpoint} | makeEndpoint | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_endpointType(self):
"""
L{Agent._getEndpoint} return a L{SSL4ClientEndpoint} when passed a
scheme of C{'https'}.
"""
from twisted.internet.endpoints import _WrapperEndpoint
endpoint = self.makeEndpoint()
self.assertIsInstance(endpoint, _WrapperEndpoint)
self.assertIsInstance(endpoint._wrappedEndpoint, HostnameEndpoint) | L{Agent._getEndpoint} return a L{SSL4ClientEndpoint} when passed a
scheme of C{'https'}. | test_endpointType | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_hostArgumentIsRespected(self):
"""
If a host is passed, the endpoint respects it.
"""
endpoint = self.makeEndpoint(host=b"example.com")
self.assertEqual(endpoint._wrappedEndpoint._hostStr, "example.com") | If a host is passed, the endpoint respects it. | test_hostArgumentIsRespected | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_portArgumentIsRespected(self):
"""
If a port is passed, the endpoint respects it.
"""
expectedPort = 4321
endpoint = self.makeEndpoint(port=expectedPort)
self.assertEqual(endpoint._wrappedEndpoint._port, expectedPort) | If a port is passed, the endpoint respects it. | test_portArgumentIsRespected | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_contextFactoryType(self):
"""
L{Agent} wraps its connection creator creator and uses modern TLS APIs.
"""
endpoint = self.makeEndpoint()
contextFactory = endpoint._wrapperFactory(None)._connectionCreator
self.assertIsInstance(contextFactory, ClientTLSOptions)
self.assertEqual(contextFactory._hostname, u"example.com") | L{Agent} wraps its connection creator creator and uses modern TLS APIs. | test_contextFactoryType | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def do_handshake(self):
"""
The handshake started. Record that fact.
"""
self.handshakeStarted = True | The handshake started. Record that fact. | test_connectHTTPSCustomConnectionCreator.do_handshake | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def set_connect_state(self):
"""
The connection started. Record that fact.
"""
self.connectState = True | The connection started. Record that fact. | test_connectHTTPSCustomConnectionCreator.set_connect_state | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def clientConnectionForTLS(self, tlsProtocol):
"""
Implement L{IOpenSSLClientConnectionCreator}.
@param tlsProtocol: The TLS protocol.
@type tlsProtocol: L{TLSMemoryBIOProtocol}
@return: C{expectedConnection}
"""
contextArgs.append((tlsProtocol, self.hostname, self.port))
return expectedConnection | Implement L{IOpenSSLClientConnectionCreator}.
@param tlsProtocol: The TLS protocol.
@type tlsProtocol: L{TLSMemoryBIOProtocol}
@return: C{expectedConnection} | test_connectHTTPSCustomConnectionCreator.clientConnectionForTLS | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def creatorForNetloc(self, hostname, port):
"""
Emulate L{BrowserLikePolicyForHTTPS}.
@param hostname: The hostname to verify.
@type hostname: L{bytes}
@param port: The port number.
@type port: L{int}
@return: a stub L{IOpenSSLClientConnectionCreator}
@rtype: L{JustEnoughCreator}
"""
return JustEnoughCreator(hostname, port) | Emulate L{BrowserLikePolicyForHTTPS}.
@param hostname: The hostname to verify.
@type hostname: L{bytes}
@param port: The port number.
@type port: L{int}
@return: a stub L{IOpenSSLClientConnectionCreator}
@rtype: L{JustEnoughCreator} | test_connectHTTPSCustomConnectionCreator.creatorForNetloc | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_connectHTTPSCustomConnectionCreator(self):
"""
If a custom L{WebClientConnectionCreator}-like object is passed to
L{Agent.__init__} it will be used to determine the SSL parameters for
HTTPS requests. When an HTTPS request is made, the hostname and port
number of the request URL will be passed to the connection creator's
C{creatorForNetloc} method. The resulting context object will be used
to establish the SSL connection.
"""
expectedHost = b'example.org'
expectedPort = 20443
class JustEnoughConnection(object):
handshakeStarted = False
connectState = False
def do_handshake(self):
"""
The handshake started. Record that fact.
"""
self.handshakeStarted = True
def set_connect_state(self):
"""
The connection started. Record that fact.
"""
self.connectState = True
contextArgs = []
@implementer(IOpenSSLClientConnectionCreator)
class JustEnoughCreator(object):
def __init__(self, hostname, port):
self.hostname = hostname
self.port = port
def clientConnectionForTLS(self, tlsProtocol):
"""
Implement L{IOpenSSLClientConnectionCreator}.
@param tlsProtocol: The TLS protocol.
@type tlsProtocol: L{TLSMemoryBIOProtocol}
@return: C{expectedConnection}
"""
contextArgs.append((tlsProtocol, self.hostname, self.port))
return expectedConnection
expectedConnection = JustEnoughConnection()
@implementer(IPolicyForHTTPS)
class StubBrowserLikePolicyForHTTPS(object):
def creatorForNetloc(self, hostname, port):
"""
Emulate L{BrowserLikePolicyForHTTPS}.
@param hostname: The hostname to verify.
@type hostname: L{bytes}
@param port: The port number.
@type port: L{int}
@return: a stub L{IOpenSSLClientConnectionCreator}
@rtype: L{JustEnoughCreator}
"""
return JustEnoughCreator(hostname, port)
expectedCreatorCreator = StubBrowserLikePolicyForHTTPS()
reactor = self.createReactor()
agent = client.Agent(reactor, expectedCreatorCreator)
endpoint = agent._getEndpoint(URI.fromBytes(
b'https://' + expectedHost + b":" + intToBytes(expectedPort)))
endpoint.connect(Factory.forProtocol(Protocol))
tlsFactory = reactor.tcpClients[-1][2]
tlsProtocol = tlsFactory.buildProtocol(None)
tlsProtocol.makeConnection(StringTransport())
tls = contextArgs[0][0]
self.assertIsInstance(tls, TLSMemoryBIOProtocol)
self.assertEqual(contextArgs[0][1:], (expectedHost, expectedPort))
self.assertTrue(expectedConnection.handshakeStarted)
self.assertTrue(expectedConnection.connectState) | If a custom L{WebClientConnectionCreator}-like object is passed to
L{Agent.__init__} it will be used to determine the SSL parameters for
HTTPS requests. When an HTTPS request is made, the hostname and port
number of the request URL will be passed to the connection creator's
C{creatorForNetloc} method. The resulting context object will be used
to establish the SSL connection. | test_connectHTTPSCustomConnectionCreator | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_deprecatedDuckPolicy(self):
"""
Passing something that duck-types I{like} a L{web client context
factory <twisted.web.client.WebClientContextFactory>} - something that
does not provide L{IPolicyForHTTPS} - to L{Agent} emits a
L{DeprecationWarning} even if you don't actually C{import
WebClientContextFactory} to do it.
"""
def warnMe():
client.Agent(deterministicResolvingReactor(MemoryReactorClock()),
"does-not-provide-IPolicyForHTTPS")
warnMe()
warnings = self.flushWarnings([warnMe])
self.assertEqual(len(warnings), 1)
[warning] = warnings
self.assertEqual(warning['category'], DeprecationWarning)
self.assertEqual(
warning['message'],
"'does-not-provide-IPolicyForHTTPS' was passed as the HTTPS "
"policy for an Agent, but it does not provide IPolicyForHTTPS. "
"Since Twisted 14.0, you must pass a provider of IPolicyForHTTPS."
) | Passing something that duck-types I{like} a L{web client context
factory <twisted.web.client.WebClientContextFactory>} - something that
does not provide L{IPolicyForHTTPS} - to L{Agent} emits a
L{DeprecationWarning} even if you don't actually C{import
WebClientContextFactory} to do it. | test_deprecatedDuckPolicy | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_alternateTrustRoot(self):
"""
L{BrowserLikePolicyForHTTPS.creatorForNetloc} returns an
L{IOpenSSLClientConnectionCreator} provider which will add certificates
from the given trust root.
"""
trustRoot = CustomOpenSSLTrustRoot()
policy = BrowserLikePolicyForHTTPS(trustRoot=trustRoot)
creator = policy.creatorForNetloc(b"thingy", 4321)
self.assertTrue(trustRoot.called)
connection = creator.clientConnectionForTLS(None)
self.assertIs(trustRoot.context, connection.get_context()) | L{BrowserLikePolicyForHTTPS.creatorForNetloc} returns an
L{IOpenSSLClientConnectionCreator} provider which will add certificates
from the given trust root. | test_alternateTrustRoot | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def integrationTest(self, hostName, expectedAddress, addressType):
"""
Wrap L{AgentTestsMixin.integrationTest} with TLS.
"""
certHostName = hostName.strip(b'[]')
authority, server = certificatesForAuthorityAndServer(certHostName
.decode('ascii'))
def tlsify(serverFactory):
return TLSMemoryBIOFactory(server.options(), False, serverFactory)
def tlsagent(reactor):
from twisted.web.iweb import IPolicyForHTTPS
from zope.interface import implementer
@implementer(IPolicyForHTTPS)
class Policy(object):
def creatorForNetloc(self, hostname, port):
return optionsForClientTLS(hostname.decode("ascii"),
trustRoot=authority)
return client.Agent(reactor, contextFactory=Policy())
(super(AgentHTTPSTests, self)
.integrationTest(hostName, expectedAddress, addressType,
serverWrapper=tlsify,
createAgent=tlsagent,
scheme=b'https')) | Wrap L{AgentTestsMixin.integrationTest} with TLS. | integrationTest | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def setUp(self):
"""
Get WebClientContextFactory while quashing its deprecation warning.
"""
from twisted.web.client import WebClientContextFactory
self.warned = self.flushWarnings([WebClientContextFactoryTests.setUp])
self.webClientContextFactory = WebClientContextFactory | Get WebClientContextFactory while quashing its deprecation warning. | setUp | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_deprecated(self):
"""
L{twisted.web.client.WebClientContextFactory} is deprecated. Importing
it displays a warning.
"""
self.assertEqual(len(self.warned), 1)
[warning] = self.warned
self.assertEqual(warning['category'], DeprecationWarning)
self.assertEqual(
warning['message'],
getDeprecationWarningString(
self.webClientContextFactory, Version("Twisted", 14, 0, 0),
replacement=BrowserLikePolicyForHTTPS,
)
# See https://twistedmatrix.com/trac/ticket/7242
.replace(";", ":")
) | L{twisted.web.client.WebClientContextFactory} is deprecated. Importing
it displays a warning. | test_deprecated | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_missingSSL(self):
"""
If C{getContext} is called and SSL is not available, raise
L{NotImplementedError}.
"""
self.assertRaises(
NotImplementedError,
self.webClientContextFactory().getContext,
b'example.com', 443,
) | If C{getContext} is called and SSL is not available, raise
L{NotImplementedError}. | test_missingSSL | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_returnsContext(self):
"""
If SSL is present, C{getContext} returns a L{OpenSSL.SSL.Context}.
"""
ctx = self.webClientContextFactory().getContext('example.com', 443)
self.assertIsInstance(ctx, ssl.SSL.Context) | If SSL is present, C{getContext} returns a L{OpenSSL.SSL.Context}. | test_returnsContext | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_setsTrustRootOnContextToDefaultTrustRoot(self):
"""
The L{CertificateOptions} has C{trustRoot} set to the default trust
roots.
"""
ctx = self.webClientContextFactory()
certificateOptions = ctx._getCertificateOptions('example.com', 443)
self.assertIsInstance(
certificateOptions.trustRoot, ssl.OpenSSLDefaultPaths) | The L{CertificateOptions} has C{trustRoot} set to the default trust
roots. | test_setsTrustRootOnContextToDefaultTrustRoot | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_onlyRetryIdempotentMethods(self):
"""
Only GET, HEAD, OPTIONS, TRACE, DELETE methods cause a retry.
"""
pool = client.HTTPConnectionPool(None)
connection = client._RetryingHTTP11ClientProtocol(None, pool)
self.assertTrue(connection._shouldRetry(
b"GET", RequestNotSent(), None))
self.assertTrue(connection._shouldRetry(
b"HEAD", RequestNotSent(), None))
self.assertTrue(connection._shouldRetry(
b"OPTIONS", RequestNotSent(), None))
self.assertTrue(connection._shouldRetry(
b"TRACE", RequestNotSent(), None))
self.assertTrue(connection._shouldRetry(
b"DELETE", RequestNotSent(), None))
self.assertFalse(connection._shouldRetry(
b"POST", RequestNotSent(), None))
self.assertFalse(connection._shouldRetry(
b"MYMETHOD", RequestNotSent(), None)) | Only GET, HEAD, OPTIONS, TRACE, DELETE methods cause a retry. | test_onlyRetryIdempotentMethods | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_onlyRetryIfNoResponseReceived(self):
"""
Only L{RequestNotSent}, L{RequestTransmissionFailed} and
L{ResponseNeverReceived} exceptions cause a retry.
"""
pool = client.HTTPConnectionPool(None)
connection = client._RetryingHTTP11ClientProtocol(None, pool)
self.assertTrue(connection._shouldRetry(
b"GET", RequestNotSent(), None))
self.assertTrue(connection._shouldRetry(
b"GET", RequestTransmissionFailed([]), None))
self.assertTrue(connection._shouldRetry(
b"GET", ResponseNeverReceived([]),None))
self.assertFalse(connection._shouldRetry(
b"GET", ResponseFailed([]), None))
self.assertFalse(connection._shouldRetry(
b"GET", ConnectionRefusedError(), None)) | Only L{RequestNotSent}, L{RequestTransmissionFailed} and
L{ResponseNeverReceived} exceptions cause a retry. | test_onlyRetryIfNoResponseReceived | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_dontRetryIfFailedDueToCancel(self):
"""
If a request failed due to the operation being cancelled,
C{_shouldRetry} returns C{False} to indicate the request should not be
retried.
"""
pool = client.HTTPConnectionPool(None)
connection = client._RetryingHTTP11ClientProtocol(None, pool)
exception = ResponseNeverReceived([Failure(defer.CancelledError())])
self.assertFalse(connection._shouldRetry(b"GET", exception, None)) | If a request failed due to the operation being cancelled,
C{_shouldRetry} returns C{False} to indicate the request should not be
retried. | test_dontRetryIfFailedDueToCancel | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_retryIfFailedDueToNonCancelException(self):
"""
If a request failed with L{ResponseNeverReceived} due to some
arbitrary exception, C{_shouldRetry} returns C{True} to indicate the
request should be retried.
"""
pool = client.HTTPConnectionPool(None)
connection = client._RetryingHTTP11ClientProtocol(None, pool)
self.assertTrue(connection._shouldRetry(
b"GET", ResponseNeverReceived([Failure(Exception())]), None)) | If a request failed with L{ResponseNeverReceived} due to some
arbitrary exception, C{_shouldRetry} returns C{True} to indicate the
request should be retried. | test_retryIfFailedDueToNonCancelException | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_wrappedOnPersistentReturned(self):
"""
If L{client.HTTPConnectionPool.getConnection} returns a previously
cached connection, it will get wrapped in a
L{client._RetryingHTTP11ClientProtocol}.
"""
pool = client.HTTPConnectionPool(Clock())
# Add a connection to the cache:
protocol = StubHTTPProtocol()
protocol.makeConnection(StringTransport())
pool._putConnection(123, protocol)
# Retrieve it, it should come back wrapped in a
# _RetryingHTTP11ClientProtocol:
d = pool.getConnection(123, DummyEndpoint())
def gotConnection(connection):
self.assertIsInstance(connection,
client._RetryingHTTP11ClientProtocol)
self.assertIdentical(connection._clientProtocol, protocol)
return d.addCallback(gotConnection) | If L{client.HTTPConnectionPool.getConnection} returns a previously
cached connection, it will get wrapped in a
L{client._RetryingHTTP11ClientProtocol}. | test_wrappedOnPersistentReturned | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_notWrappedOnNewReturned(self):
"""
If L{client.HTTPConnectionPool.getConnection} returns a new
connection, it will be returned as is.
"""
pool = client.HTTPConnectionPool(None)
d = pool.getConnection(123, DummyEndpoint())
def gotConnection(connection):
# Don't want to use isinstance since potentially the wrapper might
# subclass it at some point:
self.assertIdentical(connection.__class__, HTTP11ClientProtocol)
return d.addCallback(gotConnection) | If L{client.HTTPConnectionPool.getConnection} returns a new
connection, it will be returned as is. | test_notWrappedOnNewReturned | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def retryAttempt(self, willWeRetry):
"""
Fail a first request, possibly retrying depending on argument.
"""
protocols = []
def newProtocol():
protocol = StubHTTPProtocol()
protocols.append(protocol)
return defer.succeed(protocol)
bodyProducer = object()
request = client.Request(b"FOO", b"/", client.Headers(), bodyProducer,
persistent=True)
newProtocol()
protocol = protocols[0]
retrier = client._RetryingHTTP11ClientProtocol(protocol, newProtocol)
def _shouldRetry(m, e, bp):
self.assertEqual(m, b"FOO")
self.assertIdentical(bp, bodyProducer)
self.assertIsInstance(e, (RequestNotSent, ResponseNeverReceived))
return willWeRetry
retrier._shouldRetry = _shouldRetry
d = retrier.request(request)
# So far, one request made:
self.assertEqual(len(protocols), 1)
self.assertEqual(len(protocols[0].requests), 1)
# Fail the first request:
protocol.requests[0][1].errback(RequestNotSent())
return d, protocols | Fail a first request, possibly retrying depending on argument. | retryAttempt | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_retryIfShouldRetryReturnsTrue(self):
"""
L{client._RetryingHTTP11ClientProtocol} retries when
L{client._RetryingHTTP11ClientProtocol._shouldRetry} returns C{True}.
"""
d, protocols = self.retryAttempt(True)
# We retried!
self.assertEqual(len(protocols), 2)
response = object()
protocols[1].requests[0][1].callback(response)
return d.addCallback(self.assertIdentical, response) | L{client._RetryingHTTP11ClientProtocol} retries when
L{client._RetryingHTTP11ClientProtocol._shouldRetry} returns C{True}. | test_retryIfShouldRetryReturnsTrue | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_dontRetryIfShouldRetryReturnsFalse(self):
"""
L{client._RetryingHTTP11ClientProtocol} does not retry when
L{client._RetryingHTTP11ClientProtocol._shouldRetry} returns C{False}.
"""
d, protocols = self.retryAttempt(False)
# We did not retry:
self.assertEqual(len(protocols), 1)
return self.assertFailure(d, RequestNotSent) | L{client._RetryingHTTP11ClientProtocol} does not retry when
L{client._RetryingHTTP11ClientProtocol._shouldRetry} returns C{False}. | test_dontRetryIfShouldRetryReturnsFalse | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_onlyRetryWithoutBody(self):
"""
L{_RetryingHTTP11ClientProtocol} only retries queries that don't have
a body.
This is an implementation restriction; if the restriction is fixed,
this test should be removed and PUT added to list of methods that
support retries.
"""
pool = client.HTTPConnectionPool(None)
connection = client._RetryingHTTP11ClientProtocol(None, pool)
self.assertTrue(connection._shouldRetry(b"GET", RequestNotSent(), None))
self.assertFalse(connection._shouldRetry(b"GET", RequestNotSent(), object())) | L{_RetryingHTTP11ClientProtocol} only retries queries that don't have
a body.
This is an implementation restriction; if the restriction is fixed,
this test should be removed and PUT added to list of methods that
support retries. | test_onlyRetryWithoutBody | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_onlyRetryOnce(self):
"""
If a L{client._RetryingHTTP11ClientProtocol} fails more than once on
an idempotent query before a response is received, it will not retry.
"""
d, protocols = self.retryAttempt(True)
self.assertEqual(len(protocols), 2)
# Fail the second request too:
protocols[1].requests[0][1].errback(ResponseNeverReceived([]))
# We didn't retry again:
self.assertEqual(len(protocols), 2)
return self.assertFailure(d, ResponseNeverReceived) | If a L{client._RetryingHTTP11ClientProtocol} fails more than once on
an idempotent query before a response is received, it will not retry. | test_onlyRetryOnce | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_dontRetryIfRetryAutomaticallyFalse(self):
"""
If L{HTTPConnectionPool.retryAutomatically} is set to C{False}, don't
wrap connections with retrying logic.
"""
pool = client.HTTPConnectionPool(Clock())
pool.retryAutomatically = False
# Add a connection to the cache:
protocol = StubHTTPProtocol()
protocol.makeConnection(StringTransport())
pool._putConnection(123, protocol)
# Retrieve it, it should come back unwrapped:
d = pool.getConnection(123, DummyEndpoint())
def gotConnection(connection):
self.assertIdentical(connection, protocol)
return d.addCallback(gotConnection) | If L{HTTPConnectionPool.retryAutomatically} is set to C{False}, don't
wrap connections with retrying logic. | test_dontRetryIfRetryAutomaticallyFalse | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_retryWithNewConnection(self):
"""
L{client.HTTPConnectionPool} creates
{client._RetryingHTTP11ClientProtocol} with a new connection factory
method that creates a new connection using the same key and endpoint
as the wrapped connection.
"""
pool = client.HTTPConnectionPool(Clock())
key = 123
endpoint = DummyEndpoint()
newConnections = []
# Override the pool's _newConnection:
def newConnection(k, e):
newConnections.append((k, e))
pool._newConnection = newConnection
# Add a connection to the cache:
protocol = StubHTTPProtocol()
protocol.makeConnection(StringTransport())
pool._putConnection(key, protocol)
# Retrieve it, it should come back wrapped in a
# _RetryingHTTP11ClientProtocol:
d = pool.getConnection(key, endpoint)
def gotConnection(connection):
self.assertIsInstance(connection,
client._RetryingHTTP11ClientProtocol)
self.assertIdentical(connection._clientProtocol, protocol)
# Verify that the _newConnection method on retrying connection
# calls _newConnection on the pool:
self.assertEqual(newConnections, [])
connection._newConnection()
self.assertEqual(len(newConnections), 1)
self.assertEqual(newConnections[0][0], key)
self.assertIdentical(newConnections[0][1], endpoint)
return d.addCallback(gotConnection) | L{client.HTTPConnectionPool} creates
{client._RetryingHTTP11ClientProtocol} with a new connection factory
method that creates a new connection using the same key and endpoint
as the wrapped connection. | test_retryWithNewConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def addCookies(self, cookieJar, uri, cookies):
"""
Add a cookie to a cookie jar.
"""
response = client._FakeUrllib2Response(
client.Response(
(b'HTTP', 1, 1),
200,
b'OK',
client.Headers({b'Set-Cookie': cookies}),
None))
request = client._FakeUrllib2Request(uri)
cookieJar.extract_cookies(response, request)
return request, response | Add a cookie to a cookie jar. | addCookies | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def makeCookieJar(self):
"""
@return: a C{cookielib.CookieJar} with some sample cookies
"""
cookieJar = cookielib.CookieJar()
reqres = self.addCookies(
cookieJar,
b'http://example.com:1234/foo?bar',
[b'foo=1; cow=moo; Path=/foo; Comment=hello',
b'bar=2; Comment=goodbye'])
return cookieJar, reqres | @return: a C{cookielib.CookieJar} with some sample cookies | makeCookieJar | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_extractCookies(self):
"""
L{cookielib.CookieJar.extract_cookies} extracts cookie information from
fake urllib2 response instances.
"""
jar = self.makeCookieJar()[0]
cookies = dict([(c.name, c) for c in jar])
cookie = cookies['foo']
self.assertEqual(cookie.version, 0)
self.assertEqual(cookie.name, 'foo')
self.assertEqual(cookie.value, '1')
self.assertEqual(cookie.path, '/foo')
self.assertEqual(cookie.comment, 'hello')
self.assertEqual(cookie.get_nonstandard_attr('cow'), 'moo')
cookie = cookies['bar']
self.assertEqual(cookie.version, 0)
self.assertEqual(cookie.name, 'bar')
self.assertEqual(cookie.value, '2')
self.assertEqual(cookie.path, '/')
self.assertEqual(cookie.comment, 'goodbye')
self.assertIdentical(cookie.get_nonstandard_attr('cow'), None) | L{cookielib.CookieJar.extract_cookies} extracts cookie information from
fake urllib2 response instances. | test_extractCookies | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_sendCookie(self):
"""
L{cookielib.CookieJar.add_cookie_header} adds a cookie header to a fake
urllib2 request instance.
"""
jar, (request, response) = self.makeCookieJar()
self.assertIdentical(
request.get_header('Cookie', None),
None)
jar.add_cookie_header(request)
self.assertEqual(
request.get_header('Cookie', None),
'foo=1; bar=2') | L{cookielib.CookieJar.add_cookie_header} adds a cookie header to a fake
urllib2 request instance. | test_sendCookie | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def makeAgent(self):
"""
@return: a new L{twisted.web.client.CookieAgent}
"""
return client.CookieAgent(
self.buildAgentForWrapperTest(self.reactor),
cookielib.CookieJar()) | @return: a new L{twisted.web.client.CookieAgent} | makeAgent | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_emptyCookieJarRequest(self):
"""
L{CookieAgent.request} does not insert any C{'Cookie'} header into the
L{Request} object if there is no cookie in the cookie jar for the URI
being requested. Cookies are extracted from the response and stored in
the cookie jar.
"""
cookieJar = cookielib.CookieJar()
self.assertEqual(list(cookieJar), [])
agent = self.buildAgentForWrapperTest(self.reactor)
cookieAgent = client.CookieAgent(agent, cookieJar)
d = cookieAgent.request(
b'GET', b'http://example.com:1234/foo?bar')
def _checkCookie(ignored):
cookies = list(cookieJar)
self.assertEqual(len(cookies), 1)
self.assertEqual(cookies[0].name, 'foo')
self.assertEqual(cookies[0].value, '1')
d.addCallback(_checkCookie)
req, res = self.protocol.requests.pop()
self.assertIdentical(req.headers.getRawHeaders(b'cookie'), None)
resp = client.Response(
(b'HTTP', 1, 1),
200,
b'OK',
client.Headers({b'Set-Cookie': [b'foo=1',]}),
None)
res.callback(resp)
return d | L{CookieAgent.request} does not insert any C{'Cookie'} header into the
L{Request} object if there is no cookie in the cookie jar for the URI
being requested. Cookies are extracted from the response and stored in
the cookie jar. | test_emptyCookieJarRequest | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_requestWithCookie(self):
"""
L{CookieAgent.request} inserts a C{'Cookie'} header into the L{Request}
object when there is a cookie matching the request URI in the cookie
jar.
"""
uri = b'http://example.com:1234/foo?bar'
cookie = b'foo=1'
cookieJar = cookielib.CookieJar()
self.addCookies(cookieJar, uri, [cookie])
self.assertEqual(len(list(cookieJar)), 1)
agent = self.buildAgentForWrapperTest(self.reactor)
cookieAgent = client.CookieAgent(agent, cookieJar)
cookieAgent.request(b'GET', uri)
req, res = self.protocol.requests.pop()
self.assertEqual(req.headers.getRawHeaders(b'cookie'), [cookie]) | L{CookieAgent.request} inserts a C{'Cookie'} header into the L{Request}
object when there is a cookie matching the request URI in the cookie
jar. | test_requestWithCookie | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_secureCookie(self):
"""
L{CookieAgent} is able to handle secure cookies, ie cookies which
should only be handled over https.
"""
uri = b'https://example.com:1234/foo?bar'
cookie = b'foo=1;secure'
cookieJar = cookielib.CookieJar()
self.addCookies(cookieJar, uri, [cookie])
self.assertEqual(len(list(cookieJar)), 1)
agent = self.buildAgentForWrapperTest(self.reactor)
cookieAgent = client.CookieAgent(agent, cookieJar)
cookieAgent.request(b'GET', uri)
req, res = self.protocol.requests.pop()
self.assertEqual(req.headers.getRawHeaders(b'cookie'), [b'foo=1']) | L{CookieAgent} is able to handle secure cookies, ie cookies which
should only be handled over https. | test_secureCookie | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_secureCookieOnInsecureConnection(self):
"""
If a cookie is setup as secure, it won't be sent with the request if
it's not over HTTPS.
"""
uri = b'http://example.com/foo?bar'
cookie = b'foo=1;secure'
cookieJar = cookielib.CookieJar()
self.addCookies(cookieJar, uri, [cookie])
self.assertEqual(len(list(cookieJar)), 1)
agent = self.buildAgentForWrapperTest(self.reactor)
cookieAgent = client.CookieAgent(agent, cookieJar)
cookieAgent.request(b'GET', uri)
req, res = self.protocol.requests.pop()
self.assertIdentical(None, req.headers.getRawHeaders(b'cookie')) | If a cookie is setup as secure, it won't be sent with the request if
it's not over HTTPS. | test_secureCookieOnInsecureConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_portCookie(self):
"""
L{CookieAgent} supports cookies which enforces the port number they
need to be transferred upon.
"""
uri = b'http://example.com:1234/foo?bar'
cookie = b'foo=1;port=1234'
cookieJar = cookielib.CookieJar()
self.addCookies(cookieJar, uri, [cookie])
self.assertEqual(len(list(cookieJar)), 1)
agent = self.buildAgentForWrapperTest(self.reactor)
cookieAgent = client.CookieAgent(agent, cookieJar)
cookieAgent.request(b'GET', uri)
req, res = self.protocol.requests.pop()
self.assertEqual(req.headers.getRawHeaders(b'cookie'), [b'foo=1']) | L{CookieAgent} supports cookies which enforces the port number they
need to be transferred upon. | test_portCookie | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_portCookieOnWrongPort(self):
"""
When creating a cookie with a port directive, it won't be added to the
L{cookie.CookieJar} if the URI is on a different port.
"""
uri = b'http://example.com:4567/foo?bar'
cookie = b'foo=1;port=1234'
cookieJar = cookielib.CookieJar()
self.addCookies(cookieJar, uri, [cookie])
self.assertEqual(len(list(cookieJar)), 0) | When creating a cookie with a port directive, it won't be added to the
L{cookie.CookieJar} if the URI is on a different port. | test_portCookieOnWrongPort | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def makeAgent(self):
"""
@return: a new L{twisted.web.client.ContentDecoderAgent}
"""
return client.ContentDecoderAgent(self.agent, []) | @return: a new L{twisted.web.client.ContentDecoderAgent} | makeAgent | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_acceptHeaders(self):
"""
L{client.ContentDecoderAgent} sets the I{Accept-Encoding} header to the
names of the available decoder objects.
"""
agent = client.ContentDecoderAgent(
self.agent, [(b'decoder1', Decoder1), (b'decoder2', Decoder2)])
agent.request(b'GET', b'http://example.com/foo')
protocol = self.protocol
self.assertEqual(len(protocol.requests), 1)
req, res = protocol.requests.pop()
self.assertEqual(req.headers.getRawHeaders(b'accept-encoding'),
[b'decoder1,decoder2']) | L{client.ContentDecoderAgent} sets the I{Accept-Encoding} header to the
names of the available decoder objects. | test_acceptHeaders | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_existingHeaders(self):
"""
If there are existing I{Accept-Encoding} fields,
L{client.ContentDecoderAgent} creates a new field for the decoders it
knows about.
"""
headers = http_headers.Headers({b'foo': [b'bar'],
b'accept-encoding': [b'fizz']})
agent = client.ContentDecoderAgent(
self.agent, [(b'decoder1', Decoder1), (b'decoder2', Decoder2)])
agent.request(b'GET', b'http://example.com/foo', headers=headers)
protocol = self.protocol
self.assertEqual(len(protocol.requests), 1)
req, res = protocol.requests.pop()
self.assertEqual(
list(sorted(req.headers.getAllRawHeaders())),
[(b'Accept-Encoding', [b'fizz', b'decoder1,decoder2']),
(b'Foo', [b'bar']),
(b'Host', [b'example.com'])]) | If there are existing I{Accept-Encoding} fields,
L{client.ContentDecoderAgent} creates a new field for the decoders it
knows about. | test_existingHeaders | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_plainEncodingResponse(self):
"""
If the response is not encoded despited the request I{Accept-Encoding}
headers, L{client.ContentDecoderAgent} simply forwards the response.
"""
agent = client.ContentDecoderAgent(
self.agent, [(b'decoder1', Decoder1), (b'decoder2', Decoder2)])
deferred = agent.request(b'GET', b'http://example.com/foo')
req, res = self.protocol.requests.pop()
response = Response((b'HTTP', 1, 1), 200, b'OK', http_headers.Headers(),
None)
res.callback(response)
return deferred.addCallback(self.assertIdentical, response) | If the response is not encoded despited the request I{Accept-Encoding}
headers, L{client.ContentDecoderAgent} simply forwards the response. | test_plainEncodingResponse | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_unsupportedEncoding(self):
"""
If an encoding unknown to the L{client.ContentDecoderAgent} is found,
the response is unchanged.
"""
agent = client.ContentDecoderAgent(
self.agent, [(b'decoder1', Decoder1), (b'decoder2', Decoder2)])
deferred = agent.request(b'GET', b'http://example.com/foo')
req, res = self.protocol.requests.pop()
headers = http_headers.Headers({b'foo': [b'bar'],
b'content-encoding': [b'fizz']})
response = Response((b'HTTP', 1, 1), 200, b'OK', headers, None)
res.callback(response)
return deferred.addCallback(self.assertIdentical, response) | If an encoding unknown to the L{client.ContentDecoderAgent} is found,
the response is unchanged. | test_unsupportedEncoding | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_unknownEncoding(self):
"""
When L{client.ContentDecoderAgent} encounters a decoder it doesn't know
about, it stops decoding even if another encoding is known afterwards.
"""
agent = client.ContentDecoderAgent(
self.agent, [(b'decoder1', Decoder1), (b'decoder2', Decoder2)])
deferred = agent.request(b'GET', b'http://example.com/foo')
req, res = self.protocol.requests.pop()
headers = http_headers.Headers({b'foo': [b'bar'],
b'content-encoding':
[b'decoder1,fizz,decoder2']})
response = Response((b'HTTP', 1, 1), 200, b'OK', headers, None)
res.callback(response)
def check(result):
self.assertNotIdentical(response, result)
self.assertIsInstance(result, Decoder2)
self.assertEqual([b'decoder1,fizz'],
result.headers.getRawHeaders(b'content-encoding'))
return deferred.addCallback(check) | When L{client.ContentDecoderAgent} encounters a decoder it doesn't know
about, it stops decoding even if another encoding is known afterwards. | test_unknownEncoding | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_gzipEncodingResponse(self):
"""
If the response has a C{gzip} I{Content-Encoding} header,
L{GzipDecoder} wraps the response to return uncompressed data to the
user.
"""
deferred = self.agent.request(b'GET', b'http://example.com/foo')
req, res = self.protocol.requests.pop()
headers = http_headers.Headers({b'foo': [b'bar'],
b'content-encoding': [b'gzip']})
transport = StringTransport()
response = Response((b'HTTP', 1, 1), 200, b'OK', headers, transport)
response.length = 12
res.callback(response)
compressor = zlib.compressobj(2, zlib.DEFLATED, 16 + zlib.MAX_WBITS)
data = (compressor.compress(b'x' * 6) + compressor.compress(b'y' * 4) +
compressor.flush())
def checkResponse(result):
self.assertNotIdentical(result, response)
self.assertEqual(result.version, (b'HTTP', 1, 1))
self.assertEqual(result.code, 200)
self.assertEqual(result.phrase, b'OK')
self.assertEqual(list(result.headers.getAllRawHeaders()),
[(b'Foo', [b'bar'])])
self.assertEqual(result.length, UNKNOWN_LENGTH)
self.assertRaises(AttributeError, getattr, result, 'unknown')
response._bodyDataReceived(data[:5])
response._bodyDataReceived(data[5:])
response._bodyDataFinished()
protocol = SimpleAgentProtocol()
result.deliverBody(protocol)
self.assertEqual(protocol.received, [b'x' * 6 + b'y' * 4])
return defer.gatherResults([protocol.made, protocol.finished])
deferred.addCallback(checkResponse)
return deferred | If the response has a C{gzip} I{Content-Encoding} header,
L{GzipDecoder} wraps the response to return uncompressed data to the
user. | test_gzipEncodingResponse | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_brokenContent(self):
"""
If the data received by the L{GzipDecoder} isn't valid gzip-compressed
data, the call to C{deliverBody} fails with a C{zlib.error}.
"""
deferred = self.agent.request(b'GET', b'http://example.com/foo')
req, res = self.protocol.requests.pop()
headers = http_headers.Headers({b'foo': [b'bar'],
b'content-encoding': [b'gzip']})
transport = StringTransport()
response = Response((b'HTTP', 1, 1), 200, b'OK', headers, transport)
response.length = 12
res.callback(response)
data = b"not gzipped content"
def checkResponse(result):
response._bodyDataReceived(data)
result.deliverBody(Protocol())
deferred.addCallback(checkResponse)
self.assertFailure(deferred, client.ResponseFailed)
def checkFailure(error):
error.reasons[0].trap(zlib.error)
self.assertIsInstance(error.response, Response)
return deferred.addCallback(checkFailure) | If the data received by the L{GzipDecoder} isn't valid gzip-compressed
data, the call to C{deliverBody} fails with a C{zlib.error}. | test_brokenContent | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_flushData(self):
"""
When the connection with the server is lost, the gzip protocol calls
C{flush} on the zlib decompressor object to get uncompressed data which
may have been buffered.
"""
class decompressobj(object):
def __init__(self, wbits):
pass
def decompress(self, data):
return b'x'
def flush(self):
return b'y'
oldDecompressObj = zlib.decompressobj
zlib.decompressobj = decompressobj
self.addCleanup(setattr, zlib, 'decompressobj', oldDecompressObj)
deferred = self.agent.request(b'GET', b'http://example.com/foo')
req, res = self.protocol.requests.pop()
headers = http_headers.Headers({b'content-encoding': [b'gzip']})
transport = StringTransport()
response = Response((b'HTTP', 1, 1), 200, b'OK', headers, transport)
res.callback(response)
def checkResponse(result):
response._bodyDataReceived(b'data')
response._bodyDataFinished()
protocol = SimpleAgentProtocol()
result.deliverBody(protocol)
self.assertEqual(protocol.received, [b'x', b'y'])
return defer.gatherResults([protocol.made, protocol.finished])
deferred.addCallback(checkResponse)
return deferred | When the connection with the server is lost, the gzip protocol calls
C{flush} on the zlib decompressor object to get uncompressed data which
may have been buffered. | test_flushData | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_flushError(self):
"""
If the C{flush} call in C{connectionLost} fails, the C{zlib.error}
exception is caught and turned into a L{ResponseFailed}.
"""
class decompressobj(object):
def __init__(self, wbits):
pass
def decompress(self, data):
return b'x'
def flush(self):
raise zlib.error()
oldDecompressObj = zlib.decompressobj
zlib.decompressobj = decompressobj
self.addCleanup(setattr, zlib, 'decompressobj', oldDecompressObj)
deferred = self.agent.request(b'GET', b'http://example.com/foo')
req, res = self.protocol.requests.pop()
headers = http_headers.Headers({b'content-encoding': [b'gzip']})
transport = StringTransport()
response = Response((b'HTTP', 1, 1), 200, b'OK', headers, transport)
res.callback(response)
def checkResponse(result):
response._bodyDataReceived(b'data')
response._bodyDataFinished()
protocol = SimpleAgentProtocol()
result.deliverBody(protocol)
self.assertEqual(protocol.received, [b'x', b'y'])
return defer.gatherResults([protocol.made, protocol.finished])
deferred.addCallback(checkResponse)
self.assertFailure(deferred, client.ResponseFailed)
def checkFailure(error):
error.reasons[1].trap(zlib.error)
self.assertIsInstance(error.response, Response)
return deferred.addCallback(checkFailure) | If the C{flush} call in C{connectionLost} fails, the C{zlib.error}
exception is caught and turned into a L{ResponseFailed}. | test_flushError | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def makeAgent(self):
"""
@return: a new L{twisted.web.client.ProxyAgent}
"""
return client.ProxyAgent(
TCP4ClientEndpoint(self.reactor, "127.0.0.1", 1234),
self.reactor) | @return: a new L{twisted.web.client.ProxyAgent} | makeAgent | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_nonBytesMethod(self):
"""
L{ProxyAgent.request} raises L{TypeError} when the C{method} argument
isn't L{bytes}.
"""
self.assertRaises(TypeError, self.agent.request,
u'GET', b'http://foo.example/') | L{ProxyAgent.request} raises L{TypeError} when the C{method} argument
isn't L{bytes}. | test_nonBytesMethod | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_proxyRequest(self):
"""
L{client.ProxyAgent} issues an HTTP request against the proxy, with the
full URI as path, when C{request} is called.
"""
headers = http_headers.Headers({b'foo': [b'bar']})
# Just going to check the body for identity, so it doesn't need to be
# real.
body = object()
self.agent.request(
b'GET', b'http://example.com:1234/foo?bar', headers, body)
host, port, factory = self.reactor.tcpClients.pop()[:3]
self.assertEqual(host, "bar")
self.assertEqual(port, 5678)
self.assertIsInstance(factory._wrappedFactory,
client._HTTP11ClientFactory)
protocol = self.protocol
# The request should be issued.
self.assertEqual(len(protocol.requests), 1)
req, res = protocol.requests.pop()
self.assertIsInstance(req, Request)
self.assertEqual(req.method, b'GET')
self.assertEqual(req.uri, b'http://example.com:1234/foo?bar')
self.assertEqual(
req.headers,
http_headers.Headers({b'foo': [b'bar'],
b'host': [b'example.com:1234']}))
self.assertIdentical(req.bodyProducer, body) | L{client.ProxyAgent} issues an HTTP request against the proxy, with the
full URI as path, when C{request} is called. | test_proxyRequest | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_nonPersistent(self):
"""
C{ProxyAgent} connections are not persistent by default.
"""
self.assertEqual(self.agent._pool.persistent, False) | C{ProxyAgent} connections are not persistent by default. | test_nonPersistent | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_connectUsesConnectionPool(self):
"""
When a connection is made by the C{ProxyAgent}, it uses its pool's
C{getConnection} method to do so, with the endpoint it was constructed
with and a key of C{("http-proxy", endpoint)}.
"""
endpoint = DummyEndpoint()
class DummyPool(object):
connected = False
persistent = False
def getConnection(this, key, ep):
this.connected = True
self.assertIdentical(ep, endpoint)
# The key is *not* tied to the final destination, but only to
# the address of the proxy, since that's where *we* are
# connecting:
self.assertEqual(key, ("http-proxy", endpoint))
return defer.succeed(StubHTTPProtocol())
pool = DummyPool()
agent = client.ProxyAgent(endpoint, self.reactor, pool=pool)
self.assertIdentical(pool, agent._pool)
agent.request(b'GET', b'http://foo/')
self.assertEqual(agent._pool.connected, True) | When a connection is made by the C{ProxyAgent}, it uses its pool's
C{getConnection} method to do so, with the endpoint it was constructed
with and a key of C{("http-proxy", endpoint)}. | test_connectUsesConnectionPool | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_noRedirect(self):
"""
L{client.RedirectAgent} behaves like L{client.Agent} if the response
doesn't contain a redirect.
"""
deferred = self.agent.request(b'GET', b'http://example.com/foo')
req, res = self.protocol.requests.pop()
headers = http_headers.Headers()
response = Response((b'HTTP', 1, 1), 200, b'OK', headers, None)
res.callback(response)
self.assertEqual(0, len(self.protocol.requests))
result = self.successResultOf(deferred)
self.assertIdentical(response, result)
self.assertIdentical(result.previousResponse, None) | L{client.RedirectAgent} behaves like L{client.Agent} if the response
doesn't contain a redirect. | test_noRedirect | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def _testRedirectDefault(self, code):
"""
When getting a redirect, L{client.RedirectAgent} follows the URL
specified in the L{Location} header field and make a new request.
@param code: HTTP status code.
"""
self.agent.request(b'GET', b'http://example.com/foo')
host, port = self.reactor.tcpClients.pop()[:2]
self.assertEqual(EXAMPLE_COM_IP, host)
self.assertEqual(80, port)
req, res = self.protocol.requests.pop()
# If possible (i.e.: SSL support is present), run the test with a
# cross-scheme redirect to verify that the scheme is honored; if not,
# let's just make sure it works at all.
if ssl is None:
scheme = b'http'
expectedPort = 80
else:
scheme = b'https'
expectedPort = 443
headers = http_headers.Headers(
{b'location': [scheme + b'://example.com/bar']})
response = Response((b'HTTP', 1, 1), code, b'OK', headers, None)
res.callback(response)
req2, res2 = self.protocol.requests.pop()
self.assertEqual(b'GET', req2.method)
self.assertEqual(b'/bar', req2.uri)
host, port = self.reactor.tcpClients.pop()[:2]
self.assertEqual(EXAMPLE_COM_IP, host)
self.assertEqual(expectedPort, port) | When getting a redirect, L{client.RedirectAgent} follows the URL
specified in the L{Location} header field and make a new request.
@param code: HTTP status code. | _testRedirectDefault | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_redirect301(self):
"""
L{client.RedirectAgent} follows redirects on status code 301.
"""
self._testRedirectDefault(301) | L{client.RedirectAgent} follows redirects on status code 301. | test_redirect301 | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_redirect302(self):
"""
L{client.RedirectAgent} follows redirects on status code 302.
"""
self._testRedirectDefault(302) | L{client.RedirectAgent} follows redirects on status code 302. | test_redirect302 | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_redirect307(self):
"""
L{client.RedirectAgent} follows redirects on status code 307.
"""
self._testRedirectDefault(307) | L{client.RedirectAgent} follows redirects on status code 307. | test_redirect307 | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def _testRedirectToGet(self, code, method):
"""
L{client.RedirectAgent} changes the method to I{GET} when getting
a redirect on a non-I{GET} request.
@param code: HTTP status code.
@param method: HTTP request method.
"""
self.agent.request(method, b'http://example.com/foo')
req, res = self.protocol.requests.pop()
headers = http_headers.Headers(
{b'location': [b'http://example.com/bar']})
response = Response((b'HTTP', 1, 1), code, b'OK', headers, None)
res.callback(response)
req2, res2 = self.protocol.requests.pop()
self.assertEqual(b'GET', req2.method)
self.assertEqual(b'/bar', req2.uri) | L{client.RedirectAgent} changes the method to I{GET} when getting
a redirect on a non-I{GET} request.
@param code: HTTP status code.
@param method: HTTP request method. | _testRedirectToGet | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_redirect303(self):
"""
L{client.RedirectAgent} changes the method to I{GET} when getting a 303
redirect on a I{POST} request.
"""
self._testRedirectToGet(303, b'POST') | L{client.RedirectAgent} changes the method to I{GET} when getting a 303
redirect on a I{POST} request. | test_redirect303 | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_noLocationField(self):
"""
If no L{Location} header field is found when getting a redirect,
L{client.RedirectAgent} fails with a L{ResponseFailed} error wrapping a
L{error.RedirectWithNoLocation} exception.
"""
deferred = self.agent.request(b'GET', b'http://example.com/foo')
req, res = self.protocol.requests.pop()
headers = http_headers.Headers()
response = Response((b'HTTP', 1, 1), 301, b'OK', headers, None)
res.callback(response)
fail = self.failureResultOf(deferred, client.ResponseFailed)
fail.value.reasons[0].trap(error.RedirectWithNoLocation)
self.assertEqual(b'http://example.com/foo',
fail.value.reasons[0].value.uri)
self.assertEqual(301, fail.value.response.code) | If no L{Location} header field is found when getting a redirect,
L{client.RedirectAgent} fails with a L{ResponseFailed} error wrapping a
L{error.RedirectWithNoLocation} exception. | test_noLocationField | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def _testPageRedirectFailure(self, code, method):
"""
When getting a redirect on an unsupported request method,
L{client.RedirectAgent} fails with a L{ResponseFailed} error wrapping
a L{error.PageRedirect} exception.
@param code: HTTP status code.
@param method: HTTP request method.
"""
deferred = self.agent.request(method, b'http://example.com/foo')
req, res = self.protocol.requests.pop()
headers = http_headers.Headers()
response = Response((b'HTTP', 1, 1), code, b'OK', headers, None)
res.callback(response)
fail = self.failureResultOf(deferred, client.ResponseFailed)
fail.value.reasons[0].trap(error.PageRedirect)
self.assertEqual(b'http://example.com/foo',
fail.value.reasons[0].value.location)
self.assertEqual(code, fail.value.response.code) | When getting a redirect on an unsupported request method,
L{client.RedirectAgent} fails with a L{ResponseFailed} error wrapping
a L{error.PageRedirect} exception.
@param code: HTTP status code.
@param method: HTTP request method. | _testPageRedirectFailure | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_307OnPost(self):
"""
When getting a 307 redirect on a I{POST} request,
L{client.RedirectAgent} fails with a L{ResponseFailed} error wrapping
a L{error.PageRedirect} exception.
"""
self._testPageRedirectFailure(307, b'POST') | When getting a 307 redirect on a I{POST} request,
L{client.RedirectAgent} fails with a L{ResponseFailed} error wrapping
a L{error.PageRedirect} exception. | test_307OnPost | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_redirectLimit(self):
"""
If the limit of redirects specified to L{client.RedirectAgent} is
reached, the deferred fires with L{ResponseFailed} error wrapping
a L{InfiniteRedirection} exception.
"""
agent = self.buildAgentForWrapperTest(self.reactor)
redirectAgent = client.RedirectAgent(agent, 1)
deferred = redirectAgent.request(b'GET', b'http://example.com/foo')
req, res = self.protocol.requests.pop()
headers = http_headers.Headers(
{b'location': [b'http://example.com/bar']})
response = Response((b'HTTP', 1, 1), 302, b'OK', headers, None)
res.callback(response)
req2, res2 = self.protocol.requests.pop()
response2 = Response((b'HTTP', 1, 1), 302, b'OK', headers, None)
res2.callback(response2)
fail = self.failureResultOf(deferred, client.ResponseFailed)
fail.value.reasons[0].trap(error.InfiniteRedirection)
self.assertEqual(b'http://example.com/foo',
fail.value.reasons[0].value.location)
self.assertEqual(302, fail.value.response.code) | If the limit of redirects specified to L{client.RedirectAgent} is
reached, the deferred fires with L{ResponseFailed} error wrapping
a L{InfiniteRedirection} exception. | test_redirectLimit | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def _testRedirectURI(self, uri, location, finalURI):
"""
When L{client.RedirectAgent} encounters a relative redirect I{URI}, it
is resolved against the request I{URI} before following the redirect.
@param uri: Request URI.
@param location: I{Location} header redirect URI.
@param finalURI: Expected final URI.
"""
self.agent.request(b'GET', uri)
req, res = self.protocol.requests.pop()
headers = http_headers.Headers(
{b'location': [location]})
response = Response((b'HTTP', 1, 1), 302, b'OK', headers, None)
res.callback(response)
req2, res2 = self.protocol.requests.pop()
self.assertEqual(b'GET', req2.method)
self.assertEqual(finalURI, req2.absoluteURI) | When L{client.RedirectAgent} encounters a relative redirect I{URI}, it
is resolved against the request I{URI} before following the redirect.
@param uri: Request URI.
@param location: I{Location} header redirect URI.
@param finalURI: Expected final URI. | _testRedirectURI | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_relativeURI(self):
"""
L{client.RedirectAgent} resolves and follows relative I{URI}s in
redirects, preserving query strings.
"""
self._testRedirectURI(
b'http://example.com/foo/bar', b'baz',
b'http://example.com/foo/baz')
self._testRedirectURI(
b'http://example.com/foo/bar', b'/baz',
b'http://example.com/baz')
self._testRedirectURI(
b'http://example.com/foo/bar', b'/baz?a',
b'http://example.com/baz?a') | L{client.RedirectAgent} resolves and follows relative I{URI}s in
redirects, preserving query strings. | test_relativeURI | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_relativeURIPreserveFragments(self):
"""
L{client.RedirectAgent} resolves and follows relative I{URI}s in
redirects, preserving fragments in way that complies with the HTTP 1.1
bis draft.
@see: U{https://tools.ietf.org/html/draft-ietf-httpbis-p2-semantics-22#section-7.1.2}
"""
self._testRedirectURI(
b'http://example.com/foo/bar#frag', b'/baz?a',
b'http://example.com/baz?a#frag')
self._testRedirectURI(
b'http://example.com/foo/bar', b'/baz?a#frag2',
b'http://example.com/baz?a#frag2') | L{client.RedirectAgent} resolves and follows relative I{URI}s in
redirects, preserving fragments in way that complies with the HTTP 1.1
bis draft.
@see: U{https://tools.ietf.org/html/draft-ietf-httpbis-p2-semantics-22#section-7.1.2} | test_relativeURIPreserveFragments | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_relativeURISchemeRelative(self):
"""
L{client.RedirectAgent} resolves and follows scheme relative I{URI}s in
redirects, replacing the hostname and port when required.
"""
self._testRedirectURI(
b'http://example.com/foo/bar', b'//foo.com/baz',
b'http://foo.com/baz')
self._testRedirectURI(
b'http://example.com/foo/bar', b'//foo.com:81/baz',
b'http://foo.com:81/baz') | L{client.RedirectAgent} resolves and follows scheme relative I{URI}s in
redirects, replacing the hostname and port when required. | test_relativeURISchemeRelative | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_responseHistory(self):
"""
L{Response.response} references the previous L{Response} from
a redirect, or L{None} if there was no previous response.
"""
agent = self.buildAgentForWrapperTest(self.reactor)
redirectAgent = client.RedirectAgent(agent)
deferred = redirectAgent.request(b'GET', b'http://example.com/foo')
redirectReq, redirectRes = self.protocol.requests.pop()
headers = http_headers.Headers(
{b'location': [b'http://example.com/bar']})
redirectResponse = Response((b'HTTP', 1, 1), 302, b'OK', headers, None)
redirectRes.callback(redirectResponse)
req, res = self.protocol.requests.pop()
response = Response((b'HTTP', 1, 1), 200, b'OK', headers, None)
res.callback(response)
finalResponse = self.successResultOf(deferred)
self.assertIdentical(finalResponse.previousResponse, redirectResponse)
self.assertIdentical(redirectResponse.previousResponse, None) | L{Response.response} references the previous L{Response} from
a redirect, or L{None} if there was no previous response. | test_responseHistory | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def makeAgent(self):
"""
@return: a new L{twisted.web.client.RedirectAgent}
"""
return client.RedirectAgent(
self.buildAgentForWrapperTest(self.reactor)) | @return: a new L{twisted.web.client.RedirectAgent} | makeAgent | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_301OnPost(self):
"""
When getting a 301 redirect on a I{POST} request,
L{client.RedirectAgent} fails with a L{ResponseFailed} error wrapping
a L{error.PageRedirect} exception.
"""
self._testPageRedirectFailure(301, b'POST') | When getting a 301 redirect on a I{POST} request,
L{client.RedirectAgent} fails with a L{ResponseFailed} error wrapping
a L{error.PageRedirect} exception. | test_301OnPost | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_302OnPost(self):
"""
When getting a 302 redirect on a I{POST} request,
L{client.RedirectAgent} fails with a L{ResponseFailed} error wrapping
a L{error.PageRedirect} exception.
"""
self._testPageRedirectFailure(302, b'POST') | When getting a 302 redirect on a I{POST} request,
L{client.RedirectAgent} fails with a L{ResponseFailed} error wrapping
a L{error.PageRedirect} exception. | test_302OnPost | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def makeAgent(self):
"""
@return: a new L{twisted.web.client.BrowserLikeRedirectAgent}
"""
return client.BrowserLikeRedirectAgent(
self.buildAgentForWrapperTest(self.reactor)) | @return: a new L{twisted.web.client.BrowserLikeRedirectAgent} | makeAgent | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_redirectToGet301(self):
"""
L{client.BrowserLikeRedirectAgent} changes the method to I{GET} when
getting a 302 redirect on a I{POST} request.
"""
self._testRedirectToGet(301, b'POST') | L{client.BrowserLikeRedirectAgent} changes the method to I{GET} when
getting a 302 redirect on a I{POST} request. | test_redirectToGet301 | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def __init__(self, headers=None, transportFactory=AbortableStringTransport):
"""
@param headers: The headers for this response. If L{None}, an empty
L{Headers} instance will be used.
@type headers: L{Headers}
@param transportFactory: A callable used to construct the transport.
"""
if headers is None:
headers = Headers()
self.headers = headers
self.transport = transportFactory() | @param headers: The headers for this response. If L{None}, an empty
L{Headers} instance will be used.
@type headers: L{Headers}
@param transportFactory: A callable used to construct the transport. | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def deliverBody(self, protocol):
"""
Record the given protocol and use it to make a connection with
L{DummyResponse.transport}.
"""
self.protocol = protocol
self.protocol.makeConnection(self.transport) | Record the given protocol and use it to make a connection with
L{DummyResponse.transport}. | deliverBody | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def deliverBody(self, protocol):
"""
Make the connection, then remove the transport.
"""
self.protocol = protocol
self.protocol.makeConnection(self.transport)
self.protocol.transport = None | Make the connection, then remove the transport. | deliverBody | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_success(self):
"""
L{client.readBody} returns a L{Deferred} which fires with the complete
body of the L{IResponse} provider passed to it.
"""
response = DummyResponse()
d = client.readBody(response)
response.protocol.dataReceived(b"first")
response.protocol.dataReceived(b"second")
response.protocol.connectionLost(Failure(ResponseDone()))
self.assertEqual(self.successResultOf(d), b"firstsecond") | L{client.readBody} returns a L{Deferred} which fires with the complete
body of the L{IResponse} provider passed to it. | test_success | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_cancel(self):
"""
When cancelling the L{Deferred} returned by L{client.readBody}, the
connection to the server will be aborted.
"""
response = DummyResponse()
deferred = client.readBody(response)
deferred.cancel()
self.failureResultOf(deferred, defer.CancelledError)
self.assertTrue(response.transport.aborting) | When cancelling the L{Deferred} returned by L{client.readBody}, the
connection to the server will be aborted. | test_cancel | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.