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_pauseProducing(self):
"""
L{FileBodyProducer.pauseProducing} temporarily suspends writing bytes
from the input file to the given L{IConsumer}.
"""
expectedResult = b"hello, world"
readSize = 5
output = BytesIO()
consumer = FileConsumer(output)
producer = FileBodyProducer(
BytesIO(expectedResult), self.cooperator, readSize)
complete = producer.startProducing(consumer)
self._scheduled.pop(0)()
self.assertEqual(output.getvalue(), expectedResult[:5])
producer.pauseProducing()
# Sort of depends on an implementation detail of Cooperator: even
# though the only task is paused, there's still a scheduled call. If
# this were to go away because Cooperator became smart enough to cancel
# this call in this case, that would be fine.
self._scheduled.pop(0)()
# Since the producer is paused, no new data should be here.
self.assertEqual(output.getvalue(), expectedResult[:5])
self.assertEqual([], self._scheduled)
self.assertNoResult(complete) | L{FileBodyProducer.pauseProducing} temporarily suspends writing bytes
from the input file to the given L{IConsumer}. | test_pauseProducing | 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_resumeProducing(self):
"""
L{FileBodyProducer.resumeProducing} re-commences writing bytes from the
input file to the given L{IConsumer} after it was previously paused
with L{FileBodyProducer.pauseProducing}.
"""
expectedResult = b"hello, world"
readSize = 5
output = BytesIO()
consumer = FileConsumer(output)
producer = FileBodyProducer(
BytesIO(expectedResult), self.cooperator, readSize)
producer.startProducing(consumer)
self._scheduled.pop(0)()
self.assertEqual(expectedResult[:readSize], output.getvalue())
producer.pauseProducing()
producer.resumeProducing()
self._scheduled.pop(0)()
self.assertEqual(expectedResult[:readSize * 2], output.getvalue()) | L{FileBodyProducer.resumeProducing} re-commences writing bytes from the
input file to the given L{IConsumer} after it was previously paused
with L{FileBodyProducer.pauseProducing}. | test_resumeProducing | 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 createReactor(self):
"""
Create a L{MemoryReactorClock} and give it some hostnames it can
resolve.
@return: a L{MemoryReactorClock}-like object with a slightly limited
interface (only C{advance} and C{tcpClients} in addition to its
formally-declared reactor interfaces), which can resolve a fixed
set of domains.
"""
mrc = MemoryReactorClock()
drr = deterministicResolvingReactor(mrc, hostMap={
u'example.com': [EXAMPLE_COM_IP],
u'ipv6.example.com': [EXAMPLE_COM_V6_IP],
u'example.net': [EXAMPLE_NET_IP],
u'example.org': [EXAMPLE_ORG_IP],
u'foo': [FOO_LOCAL_IP],
u'foo.com': [FOO_COM_IP],
u'127.0.0.7': ['127.0.0.7'],
u'::7': ['::7'],
})
# Lots of tests were written expecting MemoryReactorClock and the
# reactor seen by the SUT to be the same object.
drr.tcpClients = mrc.tcpClients
drr.advance = mrc.advance
return drr | Create a L{MemoryReactorClock} and give it some hostnames it can
resolve.
@return: a L{MemoryReactorClock}-like object with a slightly limited
interface (only C{advance} and C{tcpClients} in addition to its
formally-declared reactor interfaces), which can resolve a fixed
set of domains. | createReactor | 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 nothing():
"""this function does nothing""" | this function does nothing | __init__.nothing | 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, endpoint, testCase):
self.endpoint = endpoint
self.testCase = testCase
def nothing():
"""this function does nothing"""
self.factory = _HTTP11ClientFactory(nothing,
repr(self.endpoint))
self.protocol = StubHTTPProtocol()
self.factory.buildProtocol = lambda addr: self.protocol | this function does nothing | __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 buildAgentForWrapperTest(self, reactor):
"""
Return an Agent suitable for use in tests that wrap the Agent and want
both a fake reactor and StubHTTPProtocol.
"""
agent = client.Agent(reactor)
_oldGetEndpoint = agent._getEndpoint
agent._getEndpoint = lambda *args: (
self.StubEndpoint(_oldGetEndpoint(*args), self))
return agent | Return an Agent suitable for use in tests that wrap the Agent and want
both a fake reactor and StubHTTPProtocol. | buildAgentForWrapperTest | 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 connect(self, factory):
"""
Fake implementation of an endpoint which synchronously
succeeds with an instance of L{StubHTTPProtocol} for ease of
testing.
"""
protocol = StubHTTPProtocol()
protocol.makeConnection(None)
self.protocol = protocol
return succeed(protocol) | Fake implementation of an endpoint which synchronously
succeeds with an instance of L{StubHTTPProtocol} for ease of
testing. | connect | 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_getReturnsNewIfCacheEmpty(self):
"""
If there are no cached connections,
L{HTTPConnectionPool.getConnection} returns a new connection.
"""
self.assertEqual(self.pool._connections, {})
def gotConnection(conn):
self.assertIsInstance(conn, StubHTTPProtocol)
# The new connection is not stored in the pool:
self.assertNotIn(conn, self.pool._connections.values())
unknownKey = 12245
d = self.pool.getConnection(unknownKey, DummyEndpoint())
return d.addCallback(gotConnection) | If there are no cached connections,
L{HTTPConnectionPool.getConnection} returns a new connection. | test_getReturnsNewIfCacheEmpty | 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_putStartsTimeout(self):
"""
If a connection is put back to the pool, a 240-sec timeout is started.
When the timeout hits, the connection is closed and removed from the
pool.
"""
# We start out with one cached connection:
protocol = StubHTTPProtocol()
protocol.makeConnection(StringTransport())
self.pool._putConnection(("http", b"example.com", 80), protocol)
# Connection is in pool, still not closed:
self.assertEqual(protocol.transport.disconnecting, False)
self.assertIn(protocol,
self.pool._connections[("http", b"example.com", 80)])
# Advance 239 seconds, still not closed:
self.fakeReactor.advance(239)
self.assertEqual(protocol.transport.disconnecting, False)
self.assertIn(protocol,
self.pool._connections[("http", b"example.com", 80)])
self.assertIn(protocol, self.pool._timeouts)
# Advance past 240 seconds, connection will be closed:
self.fakeReactor.advance(1.1)
self.assertEqual(protocol.transport.disconnecting, True)
self.assertNotIn(protocol,
self.pool._connections[("http", b"example.com", 80)])
self.assertNotIn(protocol, self.pool._timeouts) | If a connection is put back to the pool, a 240-sec timeout is started.
When the timeout hits, the connection is closed and removed from the
pool. | test_putStartsTimeout | 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_putExceedsMaxPersistent(self):
"""
If an idle connection is put back in the cache and the max number of
persistent connections has been exceeded, one of the connections is
closed and removed from the cache.
"""
pool = self.pool
# We start out with two cached connection, the max:
origCached = [StubHTTPProtocol(), StubHTTPProtocol()]
for p in origCached:
p.makeConnection(StringTransport())
pool._putConnection(("http", b"example.com", 80), p)
self.assertEqual(pool._connections[("http", b"example.com", 80)],
origCached)
timeouts = pool._timeouts.copy()
# Now we add another one:
newProtocol = StubHTTPProtocol()
newProtocol.makeConnection(StringTransport())
pool._putConnection(("http", b"example.com", 80), newProtocol)
# The oldest cached connections will be removed and disconnected:
newCached = pool._connections[("http", b"example.com", 80)]
self.assertEqual(len(newCached), 2)
self.assertEqual(newCached, [origCached[1], newProtocol])
self.assertEqual([p.transport.disconnecting for p in newCached],
[False, False])
self.assertEqual(origCached[0].transport.disconnecting, True)
self.assertTrue(timeouts[origCached[0]].cancelled)
self.assertNotIn(origCached[0], pool._timeouts) | If an idle connection is put back in the cache and the max number of
persistent connections has been exceeded, one of the connections is
closed and removed from the cache. | test_putExceedsMaxPersistent | 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_maxPersistentPerHost(self):
"""
C{maxPersistentPerHost} is enforced per C{(scheme, host, port)}:
different keys have different max connections.
"""
def addProtocol(scheme, host, port):
p = StubHTTPProtocol()
p.makeConnection(StringTransport())
self.pool._putConnection((scheme, host, port), p)
return p
persistent = []
persistent.append(addProtocol("http", b"example.com", 80))
persistent.append(addProtocol("http", b"example.com", 80))
addProtocol("https", b"example.com", 443)
addProtocol("http", b"www2.example.com", 80)
self.assertEqual(
self.pool._connections[("http", b"example.com", 80)], persistent)
self.assertEqual(
len(self.pool._connections[("https", b"example.com", 443)]), 1)
self.assertEqual(
len(self.pool._connections[("http", b"www2.example.com", 80)]), 1) | C{maxPersistentPerHost} is enforced per C{(scheme, host, port)}:
different keys have different max connections. | test_maxPersistentPerHost | 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_getCachedConnection(self):
"""
Getting an address which has a cached connection returns the cached
connection, removes it from the cache and cancels its timeout.
"""
# We start out with one cached connection:
protocol = StubHTTPProtocol()
protocol.makeConnection(StringTransport())
self.pool._putConnection(("http", b"example.com", 80), protocol)
def gotConnection(conn):
# We got the cached connection:
self.assertIdentical(protocol, conn)
self.assertNotIn(
conn, self.pool._connections[("http", b"example.com", 80)])
# And the timeout was cancelled:
self.fakeReactor.advance(241)
self.assertEqual(conn.transport.disconnecting, False)
self.assertNotIn(conn, self.pool._timeouts)
return self.pool.getConnection(("http", b"example.com", 80),
BadEndpoint(),
).addCallback(gotConnection) | Getting an address which has a cached connection returns the cached
connection, removes it from the cache and cancels its timeout. | test_getCachedConnection | 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_newConnection(self):
"""
The pool's C{_newConnection} method constructs a new connection.
"""
# We start out with one cached connection:
protocol = StubHTTPProtocol()
protocol.makeConnection(StringTransport())
key = 12245
self.pool._putConnection(key, protocol)
def gotConnection(newConnection):
# We got a new connection:
self.assertNotIdentical(protocol, newConnection)
# And the old connection is still there:
self.assertIn(protocol, self.pool._connections[key])
# While the new connection is not:
self.assertNotIn(newConnection, self.pool._connections.values())
d = self.pool._newConnection(key, DummyEndpoint())
return d.addCallback(gotConnection) | The pool's C{_newConnection} method constructs a new connection. | test_newConnection | 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_getSkipsDisconnected(self):
"""
When getting connections out of the cache, disconnected connections
are removed and not returned.
"""
pool = self.pool
key = ("http", b"example.com", 80)
# We start out with two cached connection, the max:
origCached = [StubHTTPProtocol(), StubHTTPProtocol()]
for p in origCached:
p.makeConnection(StringTransport())
pool._putConnection(key, p)
self.assertEqual(pool._connections[key], origCached)
# We close the first one:
origCached[0].state = "DISCONNECTED"
# Now, when we retrive connections we should get the *second* one:
result = []
self.pool.getConnection(key,
BadEndpoint()).addCallback(result.append)
self.assertIdentical(result[0], origCached[1])
# And both the disconnected and removed connections should be out of
# the cache:
self.assertEqual(pool._connections[key], [])
self.assertEqual(pool._timeouts, {}) | When getting connections out of the cache, disconnected connections
are removed and not returned. | test_getSkipsDisconnected | 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_putNotQuiescent(self):
"""
If a non-quiescent connection is put back in the cache, an error is
logged.
"""
protocol = StubHTTPProtocol()
# By default state is QUIESCENT
self.assertEqual(protocol.state, "QUIESCENT")
logObserver = EventLoggingObserver.createWithCleanup(
self,
globalLogPublisher
)
protocol.state = "NOTQUIESCENT"
self.pool._putConnection(("http", b"example.com", 80), protocol)
self.assertEquals(1, len(logObserver))
event = logObserver[0]
f = event["log_failure"]
self.assertIsInstance(f.value, RuntimeError)
self.assertEqual(
f.getErrorMessage(),
"BUG: Non-quiescent protocol added to connection pool.")
self.assertIdentical(None, self.pool._connections.get(
("http", b"example.com", 80)))
self.flushLoggedErrors(RuntimeError) | If a non-quiescent connection is put back in the cache, an error is
logged. | test_putNotQuiescent | 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_getUsesQuiescentCallback(self):
"""
When L{HTTPConnectionPool.getConnection} connects, it returns a
C{Deferred} that fires with an instance of L{HTTP11ClientProtocol}
that has the correct quiescent callback attached. When this callback
is called the protocol is returned to the cache correctly, using the
right key.
"""
class StringEndpoint(object):
def connect(self, factory):
p = factory.buildProtocol(None)
p.makeConnection(StringTransport())
return succeed(p)
pool = HTTPConnectionPool(self.fakeReactor, True)
pool.retryAutomatically = False
result = []
key = "a key"
pool.getConnection(
key, StringEndpoint()).addCallback(
result.append)
protocol = result[0]
self.assertIsInstance(protocol, HTTP11ClientProtocol)
# Now that we have protocol instance, lets try to put it back in the
# pool:
protocol._state = "QUIESCENT"
protocol._quiescentCallback(protocol)
# If we try to retrive a connection to same destination again, we
# should get the same protocol, because it should've been added back
# to the pool:
result2 = []
pool.getConnection(
key, StringEndpoint()).addCallback(
result2.append)
self.assertIdentical(result2[0], protocol) | When L{HTTPConnectionPool.getConnection} connects, it returns a
C{Deferred} that fires with an instance of L{HTTP11ClientProtocol}
that has the correct quiescent callback attached. When this callback
is called the protocol is returned to the cache correctly, using the
right key. | test_getUsesQuiescentCallback | 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_closeCachedConnections(self):
"""
L{HTTPConnectionPool.closeCachedConnections} closes all cached
connections and removes them from the cache. It returns a Deferred
that fires when they have all lost their connections.
"""
persistent = []
def addProtocol(scheme, host, port):
p = HTTP11ClientProtocol()
p.makeConnection(StringTransport())
self.pool._putConnection((scheme, host, port), p)
persistent.append(p)
addProtocol("http", b"example.com", 80)
addProtocol("http", b"www2.example.com", 80)
doneDeferred = self.pool.closeCachedConnections()
# Connections have begun disconnecting:
for p in persistent:
self.assertEqual(p.transport.disconnecting, True)
self.assertEqual(self.pool._connections, {})
# All timeouts were cancelled and removed:
for dc in self.fakeReactor.getDelayedCalls():
self.assertEqual(dc.cancelled, True)
self.assertEqual(self.pool._timeouts, {})
# Returned Deferred fires when all connections have been closed:
result = []
doneDeferred.addCallback(result.append)
self.assertEqual(result, [])
persistent[0].connectionLost(Failure(ConnectionDone()))
self.assertEqual(result, [])
persistent[1].connectionLost(Failure(ConnectionDone()))
self.assertEqual(result, [None]) | L{HTTPConnectionPool.closeCachedConnections} closes all cached
connections and removes them from the cache. It returns a Deferred
that fires when they have all lost their connections. | test_closeCachedConnections | 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_cancelGetConnectionCancelsEndpointConnect(self):
"""
Cancelling the C{Deferred} returned from
L{HTTPConnectionPool.getConnection} cancels the C{Deferred} returned
by opening a new connection with the given endpoint.
"""
self.assertEqual(self.pool._connections, {})
connectionResult = Deferred()
class Endpoint:
def connect(self, factory):
return connectionResult
d = self.pool.getConnection(12345, Endpoint())
d.cancel()
self.assertEqual(self.failureResultOf(connectionResult).type,
CancelledError) | Cancelling the C{Deferred} returned from
L{HTTPConnectionPool.getConnection} cancels the C{Deferred} returned
by opening a new connection with the given endpoint. | test_cancelGetConnectionCancelsEndpointConnect | 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_interface(self):
"""
The agent object provides L{IAgent}.
"""
self.assertTrue(verifyObject(IAgent, self.makeAgent())) | The agent object provides L{IAgent}. | test_interface | 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_integrationTestIPv4(self):
"""
L{Agent} works over IPv4.
"""
self.integrationTest(b'example.com', EXAMPLE_COM_IP, IPv4Address) | L{Agent} works over IPv4. | test_integrationTestIPv4 | 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_integrationTestIPv4Address(self):
"""
L{Agent} works over IPv4 when hostname is an IPv4 address.
"""
self.integrationTest(b'127.0.0.7', '127.0.0.7', IPv4Address) | L{Agent} works over IPv4 when hostname is an IPv4 address. | test_integrationTestIPv4Address | 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_integrationTestIPv6(self):
"""
L{Agent} works over IPv6.
"""
self.integrationTest(b'ipv6.example.com', EXAMPLE_COM_V6_IP,
IPv6Address) | L{Agent} works over IPv6. | test_integrationTestIPv6 | 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_integrationTestIPv6Address(self):
"""
L{Agent} works over IPv6 when hostname is an IPv6 address.
"""
self.integrationTest(b'[::7]', '::7', IPv6Address) | L{Agent} works over IPv6 when hostname is an IPv6 address. | test_integrationTestIPv6Address | 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,
serverWrapper=lambda server: server,
createAgent=client.Agent,
scheme=b'http'):
"""
L{Agent} will make a TCP connection, send an HTTP request, and return a
L{Deferred} that fires when the response has been received.
@param hostName: The hostname to interpolate into the URL to be
requested.
@type hostName: L{bytes}
@param expectedAddress: The expected address string.
@type expectedAddress: L{bytes}
@param addressType: The class to construct an address out of.
@type addressType: L{type}
@param serverWrapper: A callable that takes a protocol factory and
returns a protocol factory; used to wrap the server / responder
side in a TLS server.
@type serverWrapper:
serverWrapper(L{twisted.internet.interfaces.IProtocolFactory}) ->
L{twisted.internet.interfaces.IProtocolFactory}
@param createAgent: A callable that takes a reactor and produces an
L{IAgent}; used to construct an agent with an appropriate trust
root for TLS.
@type createAgent: createAgent(reactor) -> L{IAgent}
@param scheme: The scheme to test, C{http} or C{https}
@type scheme: L{bytes}
"""
reactor = self.createReactor()
agent = createAgent(reactor)
deferred = agent.request(b"GET", scheme + b"://" + hostName + b"/")
host, port, factory, timeout, bind = reactor.tcpClients[0]
self.assertEqual(host, expectedAddress)
peerAddress = addressType('TCP', host, port)
clientProtocol = factory.buildProtocol(peerAddress)
clientTransport = FakeTransport(clientProtocol, False,
peerAddress=peerAddress)
clientProtocol.makeConnection(clientTransport)
@Factory.forProtocol
def accumulator():
ap = AccumulatingProtocol()
accumulator.currentProtocol = ap
return ap
accumulator.currentProtocol = None
accumulator.protocolConnectionMade = None
wrapper = serverWrapper(accumulator).buildProtocol(None)
serverTransport = FakeTransport(wrapper, True)
wrapper.makeConnection(serverTransport)
pump = IOPump(clientProtocol, wrapper,
clientTransport, serverTransport, False)
pump.flush()
self.assertNoResult(deferred)
lines = accumulator.currentProtocol.data.split(b"\r\n")
self.assertTrue(lines[0].startswith(b"GET / HTTP"), lines[0])
headers = dict([line.split(b": ", 1) for line in lines[1:] if line])
self.assertEqual(headers[b'Host'], hostName)
self.assertNoResult(deferred)
accumulator.currentProtocol.transport.write(
b"HTTP/1.1 200 OK"
b"\r\nX-An-Header: an-value\r\n"
b"\r\nContent-length: 12\r\n\r\n"
b"hello world!"
)
pump.flush()
response = self.successResultOf(deferred)
self.assertEquals(response.headers.getRawHeaders(b'x-an-header')[0],
b"an-value") | L{Agent} will make a TCP connection, send an HTTP request, and return a
L{Deferred} that fires when the response has been received.
@param hostName: The hostname to interpolate into the URL to be
requested.
@type hostName: L{bytes}
@param expectedAddress: The expected address string.
@type expectedAddress: L{bytes}
@param addressType: The class to construct an address out of.
@type addressType: L{type}
@param serverWrapper: A callable that takes a protocol factory and
returns a protocol factory; used to wrap the server / responder
side in a TLS server.
@type serverWrapper:
serverWrapper(L{twisted.internet.interfaces.IProtocolFactory}) ->
L{twisted.internet.interfaces.IProtocolFactory}
@param createAgent: A callable that takes a reactor and produces an
L{IAgent}; used to construct an agent with an appropriate trust
root for TLS.
@type createAgent: createAgent(reactor) -> L{IAgent}
@param scheme: The scheme to test, C{http} or C{https}
@type scheme: L{bytes} | 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 endpointForURI(self, uri):
"""
Testing implementation.
@param uri: A L{URI}.
@return: C{(scheme, host, port)} of passed in URI; violation of
interface but useful for testing.
@rtype: L{tuple}
"""
return (uri.scheme, uri.host, uri.port) | Testing implementation.
@param uri: A L{URI}.
@return: C{(scheme, host, port)} of passed in URI; violation of
interface but useful for testing.
@rtype: L{tuple} | endpointForURI | 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.Agent} instance
"""
return client.Agent(self.reactor) | @return: a new L{twisted.web.client.Agent} instance | 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 setUp(self):
"""
Create an L{Agent} wrapped around a fake reactor.
"""
self.reactor = self.createReactor()
self.agent = self.makeAgent() | Create an L{Agent} wrapped around a fake reactor. | 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_defaultPool(self):
"""
If no pool is passed in, the L{Agent} creates a non-persistent pool.
"""
agent = client.Agent(self.reactor)
self.assertIsInstance(agent._pool, HTTPConnectionPool)
self.assertEqual(agent._pool.persistent, False)
self.assertIdentical(agent._reactor, agent._pool._reactor) | If no pool is passed in, the L{Agent} creates a non-persistent pool. | test_defaultPool | 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_persistent(self):
"""
If C{persistent} is set to C{True} on the L{HTTPConnectionPool} (the
default), C{Request}s are created with their C{persistent} flag set to
C{True}.
"""
pool = HTTPConnectionPool(self.reactor)
agent = client.Agent(self.reactor, pool=pool)
agent._getEndpoint = lambda *args: self
agent.request(b"GET", b"http://127.0.0.1")
self.assertEqual(self.protocol.requests[0][0].persistent, True) | If C{persistent} is set to C{True} on the L{HTTPConnectionPool} (the
default), C{Request}s are created with their C{persistent} flag set to
C{True}. | test_persistent | 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):
"""
If C{persistent} is set to C{False} when creating the
L{HTTPConnectionPool}, C{Request}s are created with their
C{persistent} flag set to C{False}.
Elsewhere in the tests for the underlying HTTP code we ensure that
this will result in the disconnection of the HTTP protocol once the
request is done, so that the connection will not be returned to the
pool.
"""
pool = HTTPConnectionPool(self.reactor, persistent=False)
agent = client.Agent(self.reactor, pool=pool)
agent._getEndpoint = lambda *args: self
agent.request(b"GET", b"http://127.0.0.1")
self.assertEqual(self.protocol.requests[0][0].persistent, False) | If C{persistent} is set to C{False} when creating the
L{HTTPConnectionPool}, C{Request}s are created with their
C{persistent} flag set to C{False}.
Elsewhere in the tests for the underlying HTTP code we ensure that
this will result in the disconnection of the HTTP protocol once the
request is done, so that the connection will not be returned to the
pool. | 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 Agent, it uses its pool's
C{getConnection} method to do so, with the endpoint returned by
C{self._getEndpoint}. The key used is C{(scheme, host, port)}.
"""
endpoint = DummyEndpoint()
class MyAgent(client.Agent):
def _getEndpoint(this, uri):
self.assertEqual((uri.scheme, uri.host, uri.port),
(b"http", b"foo", 80))
return endpoint
class DummyPool(object):
connected = False
persistent = False
def getConnection(this, key, ep):
this.connected = True
self.assertEqual(ep, endpoint)
# This is the key the default Agent uses, others will have
# different keys:
self.assertEqual(key, (b"http", b"foo", 80))
return defer.succeed(StubHTTPProtocol())
pool = DummyPool()
agent = MyAgent(self.reactor, pool=pool)
self.assertIdentical(pool, agent._pool)
headers = http_headers.Headers()
headers.addRawHeader(b"host", b"foo")
bodyProducer = object()
agent.request(b'GET', b'http://foo/',
bodyProducer=bodyProducer, headers=headers)
self.assertEqual(agent._pool.connected, True) | When a connection is made by the Agent, it uses its pool's
C{getConnection} method to do so, with the endpoint returned by
C{self._getEndpoint}. The key used is C{(scheme, host, port)}. | 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_nonBytesMethod(self):
"""
L{Agent.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{Agent.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_unsupportedScheme(self):
"""
L{Agent.request} returns a L{Deferred} which fails with
L{SchemeNotSupported} if the scheme of the URI passed to it is not
C{'http'}.
"""
return self.assertFailure(
self.agent.request(b'GET', b'mailto:[email protected]'),
SchemeNotSupported) | L{Agent.request} returns a L{Deferred} which fails with
L{SchemeNotSupported} if the scheme of the URI passed to it is not
C{'http'}. | test_unsupportedScheme | 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_connectionFailed(self):
"""
The L{Deferred} returned by L{Agent.request} fires with a L{Failure} if
the TCP connection attempt fails.
"""
result = self.agent.request(b'GET', b'http://foo/')
# Cause the connection to be refused
host, port, factory = self.reactor.tcpClients.pop()[:3]
factory.clientConnectionFailed(None, Failure(ConnectionRefusedError()))
self.reactor.advance(10)
# ^ https://twistedmatrix.com/trac/ticket/8202
self.failureResultOf(result, ConnectionRefusedError) | The L{Deferred} returned by L{Agent.request} fires with a L{Failure} if
the TCP connection attempt fails. | test_connectionFailed | 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_connectHTTP(self):
"""
L{Agent._getEndpoint} return a C{HostnameEndpoint} when passed a scheme
of C{'http'}.
"""
expectedHost = b'example.com'
expectedPort = 1234
endpoint = self.agent._getEndpoint(URI.fromBytes(
b'http://' + expectedHost + b":" + intToBytes(expectedPort)))
self.assertEqual(endpoint._hostStr, "example.com")
self.assertEqual(endpoint._port, expectedPort)
self.assertIsInstance(endpoint, HostnameEndpoint) | L{Agent._getEndpoint} return a C{HostnameEndpoint} when passed a scheme
of C{'http'}. | test_connectHTTP | 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_nonDecodableURI(self):
"""
L{Agent._getEndpoint} when given a non-ASCII decodable URI will raise a
L{ValueError} saying such.
"""
uri = URI.fromBytes(b"http://example.com:80")
uri.host = u'\u2603.com'.encode('utf8')
with self.assertRaises(ValueError) as e:
self.agent._getEndpoint(uri)
self.assertEqual(e.exception.args[0],
("The host of the provided URI ({reprout}) contains "
"non-ASCII octets, it should be ASCII "
"decodable.").format(reprout=repr(uri.host))) | L{Agent._getEndpoint} when given a non-ASCII decodable URI will raise a
L{ValueError} saying such. | test_nonDecodableURI | 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_hostProvided(self):
"""
If L{None} is passed to L{Agent.request} for the C{headers} parameter,
a L{Headers} instance is created for the request and a I{Host} header
added to it.
"""
self.agent._getEndpoint = lambda *args: self
self.agent.request(
b'GET', b'http://example.com/foo?bar')
req, res = self.protocol.requests.pop()
self.assertEqual(req.headers.getRawHeaders(b'host'), [b'example.com']) | If L{None} is passed to L{Agent.request} for the C{headers} parameter,
a L{Headers} instance is created for the request and a I{Host} header
added to it. | test_hostProvided | 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_hostIPv6Bracketed(self):
"""
If an IPv6 address is used in the C{uri} passed to L{Agent.request},
the computed I{Host} header needs to be bracketed.
"""
self.agent._getEndpoint = lambda *args: self
self.agent.request(b'GET', b'http://[::1]/')
req, res = self.protocol.requests.pop()
self.assertEqual(req.headers.getRawHeaders(b'host'), [b'[::1]']) | If an IPv6 address is used in the C{uri} passed to L{Agent.request},
the computed I{Host} header needs to be bracketed. | test_hostIPv6Bracketed | 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_hostOverride(self):
"""
If the headers passed to L{Agent.request} includes a value for the
I{Host} header, that value takes precedence over the one which would
otherwise be automatically provided.
"""
headers = http_headers.Headers({b'foo': [b'bar'], b'host': [b'quux']})
self.agent._getEndpoint = lambda *args: self
self.agent.request(
b'GET', b'http://example.com/foo?bar', headers)
req, res = self.protocol.requests.pop()
self.assertEqual(req.headers.getRawHeaders(b'host'), [b'quux']) | If the headers passed to L{Agent.request} includes a value for the
I{Host} header, that value takes precedence over the one which would
otherwise be automatically provided. | test_hostOverride | 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_headersUnmodified(self):
"""
If a I{Host} header must be added to the request, the L{Headers}
instance passed to L{Agent.request} is not modified.
"""
headers = http_headers.Headers()
self.agent._getEndpoint = lambda *args: self
self.agent.request(
b'GET', b'http://example.com/foo', headers)
protocol = self.protocol
# The request should have been issued.
self.assertEqual(len(protocol.requests), 1)
# And the headers object passed in should not have changed.
self.assertEqual(headers, http_headers.Headers()) | If a I{Host} header must be added to the request, the L{Headers}
instance passed to L{Agent.request} is not modified. | test_headersUnmodified | 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_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 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.