code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
182
| url
stringlengths 46
251
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def test_malformedChunkedEncoding(self):
"""
If a request uses the I{chunked} transfer encoding, but provides an
invalid chunk length value, the request fails with a 400 error.
"""
# See test_chunkedEncoding for the correct form of this request.
httpRequest = b'''\
GET / HTTP/1.1
Content-Type: text/plain
Transfer-Encoding: chunked
MALFORMED_LINE_THIS_SHOULD_BE_'6'
Hello,
14
spam,eggs spam spam
0
'''
didRequest = []
class MyRequest(http.Request):
def process(self):
# This request should fail, so this should never be called.
didRequest.append(True)
channel = self.runRequest(httpRequest, MyRequest, success=False)
self.assertFalse(didRequest, "Request.process called")
self.assertEqual(
channel.transport.value(),
b"HTTP/1.1 400 Bad Request\r\n\r\n")
self.assertTrue(channel.transport.disconnecting) | If a request uses the I{chunked} transfer encoding, but provides an
invalid chunk length value, the request fails with a 400 error. | test_malformedChunkedEncoding | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_basicAuthException(self):
"""
A L{Request} that throws an exception processing basic authorization
logs an error and uses an empty username and password.
"""
logObserver = EventLoggingObserver.createWithCleanup(
self,
globalLogPublisher
)
requests = []
class Request(http.Request):
def process(self):
self.credentials = (self.getUser(), self.getPassword())
requests.append(self)
u = b"foo"
p = b"bar"
s = base64.encodestring(b":".join((u, p))).strip()
f = b"GET / HTTP/1.0\nAuthorization: Basic " + s + b"\n\n"
self.patch(base64, 'decodestring', lambda x: [])
self.runRequest(f, Request, 0)
req = requests.pop()
self.assertEqual(('', ''), req.credentials)
self.assertEquals(1, len(logObserver))
event = logObserver[0]
f = event["log_failure"]
self.assertIsInstance(f.value, AttributeError)
self.flushLoggedErrors(AttributeError) | A L{Request} that throws an exception processing basic authorization
logs an error and uses an empty username and password. | test_basicAuthException | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def assertSameParsing(url, decode):
"""
Verify that C{url} is parsed into the same objects by both
L{http.urlparse} and L{urlparse}.
"""
urlToStandardImplementation = url
if decode:
urlToStandardImplementation = url.decode('ascii')
# stdlib urlparse will give back whatever type we give it. To be
# able to compare the values meaningfully, if it gives back unicode,
# convert all the values to bytes.
standardResult = urlparse(urlToStandardImplementation)
if isinstance(standardResult.scheme, unicode):
# The choice of encoding is basically irrelevant. The values
# are all in ASCII. UTF-8 is, of course, the correct choice.
expected = (standardResult.scheme.encode('utf-8'),
standardResult.netloc.encode('utf-8'),
standardResult.path.encode('utf-8'),
standardResult.params.encode('utf-8'),
standardResult.query.encode('utf-8'),
standardResult.fragment.encode('utf-8'))
else:
expected = (standardResult.scheme,
standardResult.netloc,
standardResult.path,
standardResult.params,
standardResult.query,
standardResult.fragment)
scheme, netloc, path, params, query, fragment = http.urlparse(url)
self.assertEqual(
(scheme, netloc, path, params, query, fragment), expected)
self.assertIsInstance(scheme, bytes)
self.assertIsInstance(netloc, bytes)
self.assertIsInstance(path, bytes)
self.assertIsInstance(params, bytes)
self.assertIsInstance(query, bytes)
self.assertIsInstance(fragment, bytes) | Verify that C{url} is parsed into the same objects by both
L{http.urlparse} and L{urlparse}. | test_urlparse.assertSameParsing | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_urlparse(self):
"""
For a given URL, L{http.urlparse} should behave the same as L{urlparse},
except it should always return C{bytes}, never text.
"""
def urls():
for scheme in (b'http', b'https'):
for host in (b'example.com',):
for port in (None, 100):
for path in (b'', b'path'):
if port is not None:
host = host + b':' + networkString(str(port))
yield urlunsplit((scheme, host, path, b'', b''))
def assertSameParsing(url, decode):
"""
Verify that C{url} is parsed into the same objects by both
L{http.urlparse} and L{urlparse}.
"""
urlToStandardImplementation = url
if decode:
urlToStandardImplementation = url.decode('ascii')
# stdlib urlparse will give back whatever type we give it. To be
# able to compare the values meaningfully, if it gives back unicode,
# convert all the values to bytes.
standardResult = urlparse(urlToStandardImplementation)
if isinstance(standardResult.scheme, unicode):
# The choice of encoding is basically irrelevant. The values
# are all in ASCII. UTF-8 is, of course, the correct choice.
expected = (standardResult.scheme.encode('utf-8'),
standardResult.netloc.encode('utf-8'),
standardResult.path.encode('utf-8'),
standardResult.params.encode('utf-8'),
standardResult.query.encode('utf-8'),
standardResult.fragment.encode('utf-8'))
else:
expected = (standardResult.scheme,
standardResult.netloc,
standardResult.path,
standardResult.params,
standardResult.query,
standardResult.fragment)
scheme, netloc, path, params, query, fragment = http.urlparse(url)
self.assertEqual(
(scheme, netloc, path, params, query, fragment), expected)
self.assertIsInstance(scheme, bytes)
self.assertIsInstance(netloc, bytes)
self.assertIsInstance(path, bytes)
self.assertIsInstance(params, bytes)
self.assertIsInstance(query, bytes)
self.assertIsInstance(fragment, bytes)
# With caching, unicode then str
clear_cache()
for url in urls():
assertSameParsing(url, True)
assertSameParsing(url, False)
# With caching, str then unicode
clear_cache()
for url in urls():
assertSameParsing(url, False)
assertSameParsing(url, True)
# Without caching
for url in urls():
clear_cache()
assertSameParsing(url, True)
clear_cache()
assertSameParsing(url, False) | For a given URL, L{http.urlparse} should behave the same as L{urlparse},
except it should always return C{bytes}, never text. | test_urlparse | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_urlparseRejectsUnicode(self):
"""
L{http.urlparse} should reject unicode input early.
"""
self.assertRaises(TypeError, http.urlparse, u'http://example.org/path') | L{http.urlparse} should reject unicode input early. | test_urlparseRejectsUnicode | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def _compatHeadersTest(self, oldName, newName):
"""
Verify that each of two different attributes which are associated with
the same state properly reflect changes made through the other.
This is used to test that the C{headers}/C{responseHeaders} and
C{received_headers}/C{requestHeaders} pairs interact properly.
"""
req = http.Request(DummyChannel(), False)
getattr(req, newName).setRawHeaders(b"test", [b"lemur"])
self.assertEqual(getattr(req, oldName)[b"test"], b"lemur")
setattr(req, oldName, {b"foo": b"bar"})
self.assertEqual(
list(getattr(req, newName).getAllRawHeaders()),
[(b"Foo", [b"bar"])])
setattr(req, newName, http_headers.Headers())
self.assertEqual(getattr(req, oldName), {}) | Verify that each of two different attributes which are associated with
the same state properly reflect changes made through the other.
This is used to test that the C{headers}/C{responseHeaders} and
C{received_headers}/C{requestHeaders} pairs interact properly. | _compatHeadersTest | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_getHeader(self):
"""
L{http.Request.getHeader} returns the value of the named request
header.
"""
req = http.Request(DummyChannel(), False)
req.requestHeaders.setRawHeaders(b"test", [b"lemur"])
self.assertEqual(req.getHeader(b"test"), b"lemur") | L{http.Request.getHeader} returns the value of the named request
header. | test_getHeader | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_getHeaderReceivedMultiples(self):
"""
When there are multiple values for a single request header,
L{http.Request.getHeader} returns the last value.
"""
req = http.Request(DummyChannel(), False)
req.requestHeaders.setRawHeaders(b"test", [b"lemur", b"panda"])
self.assertEqual(req.getHeader(b"test"), b"panda") | When there are multiple values for a single request header,
L{http.Request.getHeader} returns the last value. | test_getHeaderReceivedMultiples | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_getHeaderNotFound(self):
"""
L{http.Request.getHeader} returns L{None} when asked for the value of a
request header which is not present.
"""
req = http.Request(DummyChannel(), False)
self.assertEqual(req.getHeader(b"test"), None) | L{http.Request.getHeader} returns L{None} when asked for the value of a
request header which is not present. | test_getHeaderNotFound | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_getAllHeaders(self):
"""
L{http.Request.getAllheaders} returns a C{dict} mapping all request
header names to their corresponding values.
"""
req = http.Request(DummyChannel(), False)
req.requestHeaders.setRawHeaders(b"test", [b"lemur"])
self.assertEqual(req.getAllHeaders(), {b"test": b"lemur"}) | L{http.Request.getAllheaders} returns a C{dict} mapping all request
header names to their corresponding values. | test_getAllHeaders | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_getAllHeadersNoHeaders(self):
"""
L{http.Request.getAllHeaders} returns an empty C{dict} if there are no
request headers.
"""
req = http.Request(DummyChannel(), False)
self.assertEqual(req.getAllHeaders(), {}) | L{http.Request.getAllHeaders} returns an empty C{dict} if there are no
request headers. | test_getAllHeadersNoHeaders | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_getAllHeadersMultipleHeaders(self):
"""
When there are multiple values for a single request header,
L{http.Request.getAllHeaders} returns only the last value.
"""
req = http.Request(DummyChannel(), False)
req.requestHeaders.setRawHeaders(b"test", [b"lemur", b"panda"])
self.assertEqual(req.getAllHeaders(), {b"test": b"panda"}) | When there are multiple values for a single request header,
L{http.Request.getAllHeaders} returns only the last value. | test_getAllHeadersMultipleHeaders | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_setResponseCode(self):
"""
L{http.Request.setResponseCode} takes a status code and causes it to be
used as the response status.
"""
channel = DummyChannel()
req = http.Request(channel, False)
req.setResponseCode(201)
req.write(b'')
self.assertEqual(
channel.transport.written.getvalue().splitlines()[0],
b"(no clientproto yet) 201 Created") | L{http.Request.setResponseCode} takes a status code and causes it to be
used as the response status. | test_setResponseCode | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_setResponseCodeAndMessage(self):
"""
L{http.Request.setResponseCode} takes a status code and a message and
causes them to be used as the response status.
"""
channel = DummyChannel()
req = http.Request(channel, False)
req.setResponseCode(202, b"happily accepted")
req.write(b'')
self.assertEqual(
channel.transport.written.getvalue().splitlines()[0],
b'(no clientproto yet) 202 happily accepted') | L{http.Request.setResponseCode} takes a status code and a message and
causes them to be used as the response status. | test_setResponseCodeAndMessage | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_setResponseCodeAndMessageNotBytes(self):
"""
L{http.Request.setResponseCode} accepts C{bytes} for the message
parameter and raises L{TypeError} if passed anything else.
"""
channel = DummyChannel()
req = http.Request(channel, False)
self.assertRaises(TypeError, req.setResponseCode,
202, u"not happily accepted") | L{http.Request.setResponseCode} accepts C{bytes} for the message
parameter and raises L{TypeError} if passed anything else. | test_setResponseCodeAndMessageNotBytes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_setResponseCodeAcceptsIntegers(self):
"""
L{http.Request.setResponseCode} accepts C{int} for the code parameter
and raises L{TypeError} if passed anything else.
"""
req = http.Request(DummyChannel(), False)
req.setResponseCode(1)
self.assertRaises(TypeError, req.setResponseCode, "1") | L{http.Request.setResponseCode} accepts C{int} for the code parameter
and raises L{TypeError} if passed anything else. | test_setResponseCodeAcceptsIntegers | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_setResponseCodeAcceptsLongIntegers(self):
"""
L{http.Request.setResponseCode} accepts C{long} for the code
parameter.
"""
req = http.Request(DummyChannel(), False)
req.setResponseCode(long(1)) | L{http.Request.setResponseCode} accepts C{long} for the code
parameter. | test_setResponseCodeAcceptsLongIntegers | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_setLastModifiedNeverSet(self):
"""
When no previous value was set and no 'if-modified-since' value was
requested, L{http.Request.setLastModified} takes a timestamp in seconds
since the epoch and sets the request's lastModified attribute.
"""
req = http.Request(DummyChannel(), False)
req.setLastModified(42)
self.assertEqual(req.lastModified, 42) | When no previous value was set and no 'if-modified-since' value was
requested, L{http.Request.setLastModified} takes a timestamp in seconds
since the epoch and sets the request's lastModified attribute. | test_setLastModifiedNeverSet | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_setLastModifiedUpdate(self):
"""
If the supplied timestamp is later than the lastModified attribute's
value, L{http.Request.setLastModified} updates the lastModifed
attribute.
"""
req = http.Request(DummyChannel(), False)
req.setLastModified(0)
req.setLastModified(1)
self.assertEqual(req.lastModified, 1) | If the supplied timestamp is later than the lastModified attribute's
value, L{http.Request.setLastModified} updates the lastModifed
attribute. | test_setLastModifiedUpdate | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_setLastModifiedIgnore(self):
"""
If the supplied timestamp occurs earlier than the current lastModified
attribute, L{http.Request.setLastModified} ignores it.
"""
req = http.Request(DummyChannel(), False)
req.setLastModified(1)
req.setLastModified(0)
self.assertEqual(req.lastModified, 1) | If the supplied timestamp occurs earlier than the current lastModified
attribute, L{http.Request.setLastModified} ignores it. | test_setLastModifiedIgnore | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_setLastModifiedCached(self):
"""
If the resource is older than the if-modified-since date in the request
header, L{http.Request.setLastModified} returns L{http.CACHED}.
"""
req = http.Request(DummyChannel(), False)
req.requestHeaders.setRawHeaders(
networkString('if-modified-since'),
[b'02 Jan 1970 00:00:00 GMT']
)
result = req.setLastModified(42)
self.assertEqual(result, http.CACHED) | If the resource is older than the if-modified-since date in the request
header, L{http.Request.setLastModified} returns L{http.CACHED}. | test_setLastModifiedCached | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_setLastModifiedNotCached(self):
"""
If the resource is newer than the if-modified-since date in the request
header, L{http.Request.setLastModified} returns None
"""
req = http.Request(DummyChannel(), False)
req.requestHeaders.setRawHeaders(
networkString('if-modified-since'),
[b'01 Jan 1970 00:00:00 GMT']
)
result = req.setLastModified(1000000)
self.assertEqual(result, None) | If the resource is newer than the if-modified-since date in the request
header, L{http.Request.setLastModified} returns None | test_setLastModifiedNotCached | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_setLastModifiedTwiceNotCached(self):
"""
When L{http.Request.setLastModified} is called multiple times, the
highest supplied value is honored. If that value is higher than the
if-modified-since date in the request header, the method returns None.
"""
req = http.Request(DummyChannel(), False)
req.requestHeaders.setRawHeaders(
networkString('if-modified-since'),
[b'01 Jan 1970 00:00:01 GMT']
)
req.setLastModified(1000000)
result = req.setLastModified(0)
self.assertEqual(result, None) | When L{http.Request.setLastModified} is called multiple times, the
highest supplied value is honored. If that value is higher than the
if-modified-since date in the request header, the method returns None. | test_setLastModifiedTwiceNotCached | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_setLastModifiedTwiceCached(self):
"""
When L{http.Request.setLastModified} is called multiple times, the
highest supplied value is honored. If that value is lower than the
if-modified-since date in the request header, the method returns
L{http.CACHED}.
"""
req = http.Request(DummyChannel(), False)
req.requestHeaders.setRawHeaders(
networkString('if-modified-since'),
[b'01 Jan 1999 00:00:01 GMT']
)
req.setLastModified(1)
result = req.setLastModified(0)
self.assertEqual(result, http.CACHED) | When L{http.Request.setLastModified} is called multiple times, the
highest supplied value is honored. If that value is lower than the
if-modified-since date in the request header, the method returns
L{http.CACHED}. | test_setLastModifiedTwiceCached | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_setHost(self):
"""
L{http.Request.setHost} sets the value of the host request header.
The port should not be added because it is the default.
"""
req = http.Request(DummyChannel(), False)
req.setHost(b"example.com", 80)
self.assertEqual(
req.requestHeaders.getRawHeaders(b"host"), [b"example.com"]) | L{http.Request.setHost} sets the value of the host request header.
The port should not be added because it is the default. | test_setHost | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_setHostNonDefaultPort(self):
"""
L{http.Request.setHost} sets the value of the host request header.
The port should be added because it is not the default.
"""
req = http.Request(DummyChannel(), False)
req.setHost(b"example.com", 81)
self.assertEqual(
req.requestHeaders.getRawHeaders(b"host"), [b"example.com:81"]) | L{http.Request.setHost} sets the value of the host request header.
The port should be added because it is not the default. | test_setHostNonDefaultPort | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_setHeader(self):
"""
L{http.Request.setHeader} sets the value of the given response header.
"""
req = http.Request(DummyChannel(), False)
req.setHeader(b"test", b"lemur")
self.assertEqual(req.responseHeaders.getRawHeaders(b"test"), [b"lemur"]) | L{http.Request.setHeader} sets the value of the given response header. | test_setHeader | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def _checkCookie(self, expectedCookieValue, *args, **kwargs):
"""
Call L{http.Request.addCookie} with C{*args} and C{**kwargs}, and check
that the cookie value is equal to C{expectedCookieValue}.
"""
channel = DummyChannel()
req = http.Request(channel, False)
req.addCookie(*args, **kwargs)
self.assertEqual(req.cookies[0], expectedCookieValue)
# Write nothing to make it produce the headers
req.write(b"")
writtenLines = channel.transport.written.getvalue().split(b"\r\n")
# There should be one Set-Cookie header
addCookieLines = [x for x in writtenLines
if x.startswith(b"Set-Cookie")]
self.assertEqual(len(addCookieLines), 1)
self.assertEqual(addCookieLines[0],
b"Set-Cookie: " + expectedCookieValue) | Call L{http.Request.addCookie} with C{*args} and C{**kwargs}, and check
that the cookie value is equal to C{expectedCookieValue}. | _checkCookie | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_addCookieWithMinimumArgumentsUnicode(self):
"""
L{http.Request.addCookie} adds a new cookie to be sent with the
response, and can be called with just a key and a value. L{unicode}
arguments are encoded using UTF-8.
"""
expectedCookieValue = b"foo=bar"
self._checkCookie(expectedCookieValue, u"foo", u"bar") | L{http.Request.addCookie} adds a new cookie to be sent with the
response, and can be called with just a key and a value. L{unicode}
arguments are encoded using UTF-8. | test_addCookieWithMinimumArgumentsUnicode | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_addCookieWithAllArgumentsUnicode(self):
"""
L{http.Request.addCookie} adds a new cookie to be sent with the
response. L{unicode} arguments are encoded using UTF-8.
"""
expectedCookieValue = (
b"foo=bar; Expires=Fri, 31 Dec 9999 23:59:59 GMT; "
b"Domain=.example.com; Path=/; Max-Age=31536000; "
b"Comment=test; Secure; HttpOnly")
self._checkCookie(expectedCookieValue,
u"foo", u"bar", expires=u"Fri, 31 Dec 9999 23:59:59 GMT",
domain=u".example.com", path=u"/", max_age=u"31536000",
comment=u"test", secure=True, httpOnly=True) | L{http.Request.addCookie} adds a new cookie to be sent with the
response. L{unicode} arguments are encoded using UTF-8. | test_addCookieWithAllArgumentsUnicode | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_addCookieWithMinimumArgumentsBytes(self):
"""
L{http.Request.addCookie} adds a new cookie to be sent with the
response, and can be called with just a key and a value. L{bytes}
arguments are not decoded.
"""
expectedCookieValue = b"foo=bar"
self._checkCookie(expectedCookieValue, b"foo", b"bar") | L{http.Request.addCookie} adds a new cookie to be sent with the
response, and can be called with just a key and a value. L{bytes}
arguments are not decoded. | test_addCookieWithMinimumArgumentsBytes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_addCookieWithAllArgumentsBytes(self):
"""
L{http.Request.addCookie} adds a new cookie to be sent with the
response. L{bytes} arguments are not decoded.
"""
expectedCookieValue = (
b"foo=bar; Expires=Fri, 31 Dec 9999 23:59:59 GMT; "
b"Domain=.example.com; Path=/; Max-Age=31536000; "
b"Comment=test; Secure; HttpOnly")
self._checkCookie(
expectedCookieValue,
b"foo", b"bar", expires=b"Fri, 31 Dec 9999 23:59:59 GMT",
domain=b".example.com", path=b"/", max_age=b"31536000",
comment=b"test", secure=True, httpOnly=True) | L{http.Request.addCookie} adds a new cookie to be sent with the
response. L{bytes} arguments are not decoded. | test_addCookieWithAllArgumentsBytes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_addCookieSanitization(self):
"""
L{http.Request.addCookie} replaces linear whitespace and
semicolons with single spaces.
"""
def cookieValue(key, value):
return b'='.join([key, value])
arguments = [('expires', b'Expires'),
('domain', b'Domain'),
('path', b'Path'),
('max_age', b'Max-Age'),
('comment', b'Comment')]
inputsAndOutputs = list(
zip(textLinearWhitespaceComponents +
bytesLinearWhitespaceComponents,
cycle([sanitizedBytes])))
inputsAndOutputs = [
["Foo; bar", b"Foo bar"],
[b"Foo; bar", b"Foo bar"],
]
for inputValue, outputValue in inputsAndOutputs:
self._checkCookie(cookieValue(outputValue, outputValue),
inputValue, inputValue)
for argument, parameter in arguments:
expected = b"; ".join([
cookieValue(outputValue, outputValue),
cookieValue(parameter, outputValue),
])
self._checkCookie(expected, inputValue, inputValue,
**{argument: inputValue}) | L{http.Request.addCookie} replaces linear whitespace and
semicolons with single spaces. | test_addCookieSanitization | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_addCookieSameSite(self):
"""
L{http.Request.setCookie} supports a C{sameSite} argument.
"""
self._checkCookie(
b"foo=bar; SameSite=lax", b"foo", b"bar", sameSite="lax")
self._checkCookie(
b"foo=bar; SameSite=lax", b"foo", b"bar", sameSite="Lax")
self._checkCookie(
b"foo=bar; SameSite=strict", b"foo", b"bar", sameSite="strict")
self.assertRaises(
ValueError,
self._checkCookie,
b"", b"foo", b"bar", sameSite="anything-else") | L{http.Request.setCookie} supports a C{sameSite} argument. | test_addCookieSameSite | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_firstWrite(self):
"""
For an HTTP 1.0 request, L{http.Request.write} sends an HTTP 1.0
Response-Line and whatever response headers are set.
"""
channel = DummyChannel()
req = http.Request(channel, False)
trans = StringTransport()
channel.transport = trans
req.setResponseCode(200)
req.clientproto = b"HTTP/1.0"
req.responseHeaders.setRawHeaders(b"test", [b"lemur"])
req.write(b'Hello')
self.assertResponseEquals(
trans.value(),
[(b"HTTP/1.0 200 OK",
b"Test: lemur",
b"Hello")]) | For an HTTP 1.0 request, L{http.Request.write} sends an HTTP 1.0
Response-Line and whatever response headers are set. | test_firstWrite | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_firstWriteHTTP11Chunked(self):
"""
For an HTTP 1.1 request, L{http.Request.write} sends an HTTP 1.1
Response-Line, whatever response headers are set, and uses chunked
encoding for the response body.
"""
channel = DummyChannel()
req = http.Request(channel, False)
trans = StringTransport()
channel.transport = trans
req.setResponseCode(200)
req.clientproto = b"HTTP/1.1"
req.responseHeaders.setRawHeaders(b"test", [b"lemur"])
req.write(b'Hello')
req.write(b'World!')
self.assertResponseEquals(
trans.value(),
[(b"HTTP/1.1 200 OK",
b"Test: lemur",
b"Transfer-Encoding: chunked",
b"5\r\nHello\r\n6\r\nWorld!\r\n")]) | For an HTTP 1.1 request, L{http.Request.write} sends an HTTP 1.1
Response-Line, whatever response headers are set, and uses chunked
encoding for the response body. | test_firstWriteHTTP11Chunked | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_firstWriteLastModified(self):
"""
For an HTTP 1.0 request for a resource with a known last modified time,
L{http.Request.write} sends an HTTP Response-Line, whatever response
headers are set, and a last-modified header with that time.
"""
channel = DummyChannel()
req = http.Request(channel, False)
trans = StringTransport()
channel.transport = trans
req.setResponseCode(200)
req.clientproto = b"HTTP/1.0"
req.lastModified = 0
req.responseHeaders.setRawHeaders(b"test", [b"lemur"])
req.write(b'Hello')
self.assertResponseEquals(
trans.value(),
[(b"HTTP/1.0 200 OK",
b"Test: lemur",
b"Last-Modified: Thu, 01 Jan 1970 00:00:00 GMT",
b"Hello")]
) | For an HTTP 1.0 request for a resource with a known last modified time,
L{http.Request.write} sends an HTTP Response-Line, whatever response
headers are set, and a last-modified header with that time. | test_firstWriteLastModified | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_lastModifiedAlreadyWritten(self):
"""
If the last-modified header already exists in the L{http.Request}
response headers, the lastModified attribute is ignored and a message
is logged.
"""
logObserver = EventLoggingObserver.createWithCleanup(
self,
globalLogPublisher
)
channel = DummyChannel()
req = http.Request(channel, False)
trans = StringTransport()
channel.transport = trans
req.setResponseCode(200)
req.clientproto = b"HTTP/1.0"
req.lastModified = 1000000000
req.responseHeaders.setRawHeaders(
b"last-modified",
[b"Thu, 01 Jan 1970 00:00:00 GMT"]
)
req.write(b'Hello')
self.assertResponseEquals(
trans.value(),
[(b"HTTP/1.0 200 OK",
b"Last-Modified: Thu, 01 Jan 1970 00:00:00 GMT",
b"Hello")])
self.assertEquals(1, len(logObserver))
event = logObserver[0]
self.assertEquals(
"Warning: last-modified specified both in"
" header list and lastModified attribute.",
event["log_format"]
) | If the last-modified header already exists in the L{http.Request}
response headers, the lastModified attribute is ignored and a message
is logged. | test_lastModifiedAlreadyWritten | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_receivedCookiesDefault(self):
"""
L{http.Request.received_cookies} defaults to an empty L{dict}.
"""
req = http.Request(DummyChannel(), False)
self.assertEqual(req.received_cookies, {}) | L{http.Request.received_cookies} defaults to an empty L{dict}. | test_receivedCookiesDefault | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_parseCookies(self):
"""
L{http.Request.parseCookies} extracts cookies from C{requestHeaders}
and adds them to C{received_cookies}.
"""
req = http.Request(DummyChannel(), False)
req.requestHeaders.setRawHeaders(
b"cookie", [b'test="lemur"; test2="panda"'])
req.parseCookies()
self.assertEqual(
req.received_cookies, {b"test": b'"lemur"', b"test2": b'"panda"'}) | L{http.Request.parseCookies} extracts cookies from C{requestHeaders}
and adds them to C{received_cookies}. | test_parseCookies | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_parseCookiesMultipleHeaders(self):
"""
L{http.Request.parseCookies} can extract cookies from multiple Cookie
headers.
"""
req = http.Request(DummyChannel(), False)
req.requestHeaders.setRawHeaders(
b"cookie", [b'test="lemur"', b'test2="panda"'])
req.parseCookies()
self.assertEqual(
req.received_cookies, {b"test": b'"lemur"', b"test2": b'"panda"'}) | L{http.Request.parseCookies} can extract cookies from multiple Cookie
headers. | test_parseCookiesMultipleHeaders | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_parseCookiesNoCookie(self):
"""
L{http.Request.parseCookies} can be called on a request without a
cookie header.
"""
req = http.Request(DummyChannel(), False)
req.parseCookies()
self.assertEqual(req.received_cookies, {}) | L{http.Request.parseCookies} can be called on a request without a
cookie header. | test_parseCookiesNoCookie | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_parseCookiesEmptyCookie(self):
"""
L{http.Request.parseCookies} can be called on a request with an
empty cookie header.
"""
req = http.Request(DummyChannel(), False)
req.requestHeaders.setRawHeaders(
b"cookie", [])
req.parseCookies()
self.assertEqual(req.received_cookies, {}) | L{http.Request.parseCookies} can be called on a request with an
empty cookie header. | test_parseCookiesEmptyCookie | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_parseCookiesIgnoreValueless(self):
"""
L{http.Request.parseCookies} ignores cookies which don't have a
value.
"""
req = http.Request(DummyChannel(), False)
req.requestHeaders.setRawHeaders(
b"cookie", [b'foo; bar; baz;'])
req.parseCookies()
self.assertEqual(
req.received_cookies, {}) | L{http.Request.parseCookies} ignores cookies which don't have a
value. | test_parseCookiesIgnoreValueless | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_parseCookiesEmptyValue(self):
"""
L{http.Request.parseCookies} parses cookies with an empty value.
"""
req = http.Request(DummyChannel(), False)
req.requestHeaders.setRawHeaders(
b"cookie", [b'foo='])
req.parseCookies()
self.assertEqual(
req.received_cookies, {b'foo': b''}) | L{http.Request.parseCookies} parses cookies with an empty value. | test_parseCookiesEmptyValue | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_parseCookiesRetainRightSpace(self):
"""
L{http.Request.parseCookies} leaves trailing whitespace in the
cookie value.
"""
req = http.Request(DummyChannel(), False)
req.requestHeaders.setRawHeaders(
b"cookie", [b'foo=bar '])
req.parseCookies()
self.assertEqual(
req.received_cookies, {b'foo': b'bar '}) | L{http.Request.parseCookies} leaves trailing whitespace in the
cookie value. | test_parseCookiesRetainRightSpace | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_parseCookiesStripLeftSpace(self):
"""
L{http.Request.parseCookies} strips leading whitespace in the
cookie key.
"""
req = http.Request(DummyChannel(), False)
req.requestHeaders.setRawHeaders(
b"cookie", [b' foo=bar'])
req.parseCookies()
self.assertEqual(
req.received_cookies, {b'foo': b'bar'}) | L{http.Request.parseCookies} strips leading whitespace in the
cookie key. | test_parseCookiesStripLeftSpace | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_parseCookiesContinueAfterMalformedCookie(self):
"""
L{http.Request.parseCookies} parses valid cookies set before or
after malformed cookies.
"""
req = http.Request(DummyChannel(), False)
req.requestHeaders.setRawHeaders(
b"cookie", [b'12345; test="lemur"; 12345; test2="panda"; 12345'])
req.parseCookies()
self.assertEqual(
req.received_cookies, {b"test": b'"lemur"', b"test2": b'"panda"'}) | L{http.Request.parseCookies} parses valid cookies set before or
after malformed cookies. | test_parseCookiesContinueAfterMalformedCookie | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_connectionLost(self):
"""
L{http.Request.connectionLost} closes L{Request.content} and drops the
reference to the L{HTTPChannel} to assist with garbage collection.
"""
req = http.Request(DummyChannel(), False)
# Cause Request.content to be created at all.
req.gotLength(10)
# Grab a reference to content in case the Request drops it later on.
content = req.content
# Put some bytes into it
req.handleContentChunk(b"hello")
# Then something goes wrong and content should get closed.
req.connectionLost(Failure(ConnectionLost("Finished")))
self.assertTrue(content.closed)
self.assertIdentical(req.channel, None) | L{http.Request.connectionLost} closes L{Request.content} and drops the
reference to the L{HTTPChannel} to assist with garbage collection. | test_connectionLost | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_registerProducerTwiceFails(self):
"""
Calling L{Request.registerProducer} when a producer is already
registered raises ValueError.
"""
req = http.Request(DummyChannel(), False)
req.registerProducer(DummyProducer(), True)
self.assertRaises(
ValueError, req.registerProducer, DummyProducer(), True) | Calling L{Request.registerProducer} when a producer is already
registered raises ValueError. | test_registerProducerTwiceFails | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_registerProducerWhenNotQueuedRegistersPushProducer(self):
"""
Calling L{Request.registerProducer} with an IPushProducer when the
request is not queued registers the producer as a push producer on the
request's transport.
"""
req = http.Request(DummyChannel(), False)
producer = DummyProducer()
req.registerProducer(producer, True)
self.assertEqual([(producer, True)], req.transport.producers) | Calling L{Request.registerProducer} with an IPushProducer when the
request is not queued registers the producer as a push producer on the
request's transport. | test_registerProducerWhenNotQueuedRegistersPushProducer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_registerProducerWhenNotQueuedRegistersPullProducer(self):
"""
Calling L{Request.registerProducer} with an IPullProducer when the
request is not queued registers the producer as a pull producer on the
request's transport.
"""
req = http.Request(DummyChannel(), False)
producer = DummyProducer()
req.registerProducer(producer, False)
self.assertEqual([(producer, False)], req.transport.producers) | Calling L{Request.registerProducer} with an IPullProducer when the
request is not queued registers the producer as a pull producer on the
request's transport. | test_registerProducerWhenNotQueuedRegistersPullProducer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_connectionLostNotification(self):
"""
L{Request.connectionLost} triggers all finish notification Deferreds
and cleans up per-request state.
"""
d = DummyChannel()
request = http.Request(d, True)
finished = request.notifyFinish()
request.connectionLost(Failure(ConnectionLost("Connection done")))
self.assertIdentical(request.channel, None)
return self.assertFailure(finished, ConnectionLost) | L{Request.connectionLost} triggers all finish notification Deferreds
and cleans up per-request state. | test_connectionLostNotification | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_finishNotification(self):
"""
L{Request.finish} triggers all finish notification Deferreds.
"""
request = http.Request(DummyChannel(), False)
finished = request.notifyFinish()
# Force the request to have a non-None content attribute. This is
# probably a bug in Request.
request.gotLength(1)
request.finish()
return finished | L{Request.finish} triggers all finish notification Deferreds. | test_finishNotification | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_writeAfterFinish(self):
"""
Calling L{Request.write} after L{Request.finish} has been called results
in a L{RuntimeError} being raised.
"""
request = http.Request(DummyChannel(), False)
finished = request.notifyFinish()
# Force the request to have a non-None content attribute. This is
# probably a bug in Request.
request.gotLength(1)
request.write(b'foobar')
request.finish()
self.assertRaises(RuntimeError, request.write, b'foobar')
return finished | Calling L{Request.write} after L{Request.finish} has been called results
in a L{RuntimeError} being raised. | test_writeAfterFinish | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_finishAfterConnectionLost(self):
"""
Calling L{Request.finish} after L{Request.connectionLost} has been
called results in a L{RuntimeError} being raised.
"""
channel = DummyChannel()
req = http.Request(channel, False)
req.connectionLost(Failure(ConnectionLost("The end.")))
self.assertRaises(RuntimeError, req.finish) | Calling L{Request.finish} after L{Request.connectionLost} has been
called results in a L{RuntimeError} being raised. | test_finishAfterConnectionLost | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_writeAfterConnectionLost(self):
"""
Calling L{Request.write} after L{Request.connectionLost} has been
called does not raise an exception. L{RuntimeError} will be raised
when finish is called on the request.
"""
channel = DummyChannel()
req = http.Request(channel, False)
req.connectionLost(Failure(ConnectionLost("The end.")))
req.write(b'foobar')
self.assertRaises(RuntimeError, req.finish) | Calling L{Request.write} after L{Request.connectionLost} has been
called does not raise an exception. L{RuntimeError} will be raised
when finish is called on the request. | test_writeAfterConnectionLost | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_reprUninitialized(self):
"""
L{Request.__repr__} returns the class name, object address, and
dummy-place holder values when used on a L{Request} which has not yet
been initialized.
"""
request = http.Request(DummyChannel(), False)
self.assertEqual(
repr(request),
'<Request at 0x%x method=(no method yet) uri=(no uri yet) '
'clientproto=(no clientproto yet)>' % (id(request),)) | L{Request.__repr__} returns the class name, object address, and
dummy-place holder values when used on a L{Request} which has not yet
been initialized. | test_reprUninitialized | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_reprInitialized(self):
"""
L{Request.__repr__} returns, as a L{str}, the class name, object
address, and the method, uri, and client protocol of the HTTP request
it represents. The string is in the form::
<Request at ADDRESS method=METHOD uri=URI clientproto=PROTOCOL>
"""
request = http.Request(DummyChannel(), False)
request.clientproto = b'HTTP/1.0'
request.method = b'GET'
request.uri = b'/foo/bar'
self.assertEqual(
repr(request),
'<Request at 0x%x method=GET uri=/foo/bar '
'clientproto=HTTP/1.0>' % (id(request),)) | L{Request.__repr__} returns, as a L{str}, the class name, object
address, and the method, uri, and client protocol of the HTTP request
it represents. The string is in the form::
<Request at ADDRESS method=METHOD uri=URI clientproto=PROTOCOL> | test_reprInitialized | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_reprSubclass(self):
"""
Subclasses of L{Request} inherit a C{__repr__} implementation which
includes the subclass's name in place of the string C{"Request"}.
"""
class Otherwise(http.Request):
pass
request = Otherwise(DummyChannel(), False)
self.assertEqual(
repr(request),
'<Otherwise at 0x%x method=(no method yet) uri=(no uri yet) '
'clientproto=(no clientproto yet)>' % (id(request),)) | Subclasses of L{Request} inherit a C{__repr__} implementation which
includes the subclass's name in place of the string C{"Request"}. | test_reprSubclass | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_unregisterNonQueuedNonStreamingProducer(self):
"""
L{Request.unregisterProducer} unregisters a non-queued non-streaming
producer from the request and the request's transport.
"""
req = http.Request(DummyChannel(), False)
req.transport = StringTransport()
req.registerProducer(DummyProducer(), False)
req.unregisterProducer()
self.assertEqual((None, None), (req.producer, req.transport.producer)) | L{Request.unregisterProducer} unregisters a non-queued non-streaming
producer from the request and the request's transport. | test_unregisterNonQueuedNonStreamingProducer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_unregisterNonQueuedStreamingProducer(self):
"""
L{Request.unregisterProducer} unregisters a non-queued streaming
producer from the request and the request's transport.
"""
req = http.Request(DummyChannel(), False)
req.transport = StringTransport()
req.registerProducer(DummyProducer(), True)
req.unregisterProducer()
self.assertEqual((None, None), (req.producer, req.transport.producer)) | L{Request.unregisterProducer} unregisters a non-queued streaming
producer from the request and the request's transport. | test_unregisterNonQueuedStreamingProducer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_finishProducesLog(self):
"""
L{http.Request.finish} will call the channel's factory to produce a log
message.
"""
factory = http.HTTPFactory()
factory.timeOut = None
factory._logDateTime = "sometime"
factory._logDateTimeCall = True
factory.startFactory()
factory.logFile = BytesIO()
proto = factory.buildProtocol(None)
val = [
b"GET /path HTTP/1.1\r\n",
b"\r\n\r\n"
]
trans = StringTransport()
proto.makeConnection(trans)
for x in val:
proto.dataReceived(x)
proto._channel.requests[0].finish()
# A log message should be written out
self.assertIn(b'sometime "GET /path HTTP/1.1"',
factory.logFile.getvalue()) | L{http.Request.finish} will call the channel's factory to produce a log
message. | test_finishProducesLog | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_requestBodyTimeoutFromFactory(self):
"""
L{HTTPChannel} timeouts whenever data from a request body is not
delivered to it in time, even when it gets built from a L{HTTPFactory}.
"""
clock = Clock()
factory = http.HTTPFactory(timeout=100, reactor=clock)
factory.startFactory()
protocol = factory.buildProtocol(None)
transport = StringTransport()
protocol = parametrizeTimeoutMixin(protocol, clock)
# Confirm that the timeout is what we think it is.
self.assertEqual(protocol.timeOut, 100)
protocol.makeConnection(transport)
protocol.dataReceived(b'POST / HTTP/1.0\r\nContent-Length: 2\r\n\r\n')
clock.advance(99)
self.assertFalse(transport.disconnecting)
clock.advance(2)
self.assertTrue(transport.disconnecting) | L{HTTPChannel} timeouts whenever data from a request body is not
delivered to it in time, even when it gets built from a L{HTTPFactory}. | test_requestBodyTimeoutFromFactory | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_finishCleansConnection(self):
"""
L{http.Request.finish} will notify the channel that it is finished, and
will put the transport back in the producing state so that the reactor
can close the connection.
"""
factory = http.HTTPFactory()
factory.timeOut = None
factory._logDateTime = "sometime"
factory._logDateTimeCall = True
factory.startFactory()
factory.logFile = BytesIO()
proto = factory.buildProtocol(None)
proto._channel._optimisticEagerReadSize = 0
val = [
b"GET /path HTTP/1.1\r\n",
b"\r\n\r\n"
]
trans = StringTransport()
proto.makeConnection(trans)
self.assertEqual(trans.producerState, 'producing')
for x in val:
proto.dataReceived(x)
proto.dataReceived(b'GET ') # just a few extra bytes to exhaust the
# optimistic buffer size
self.assertEqual(trans.producerState, 'paused')
proto._channel.requests[0].finish()
self.assertEqual(trans.producerState, 'producing') | L{http.Request.finish} will notify the channel that it is finished, and
will put the transport back in the producing state so that the reactor
can close the connection. | test_finishCleansConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_provides_IDeprecatedHTTPChannelToRequestInterface(self):
"""
L{http.Request} provides
L{http._IDeprecatedHTTPChannelToRequestInterface}, which
defines the interface used by L{http.HTTPChannel}.
"""
req = http.Request(DummyChannel(), False)
verifyObject(http._IDeprecatedHTTPChannelToRequestInterface, req) | L{http.Request} provides
L{http._IDeprecatedHTTPChannelToRequestInterface}, which
defines the interface used by L{http.HTTPChannel}. | test_provides_IDeprecatedHTTPChannelToRequestInterface | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_eq(self):
"""
A L{http.Request} is equal to itself.
"""
req = http.Request(DummyChannel(), False)
self.assertEqual(req, req) | A L{http.Request} is equal to itself. | test_eq | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_ne(self):
"""
A L{http.Request} is not equal to another object.
"""
req = http.Request(DummyChannel(), False)
self.assertNotEqual(req, http.Request(DummyChannel(), False)) | A L{http.Request} is not equal to another object. | test_ne | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_hashable(self):
"""
A L{http.Request} is hashable.
"""
req = http.Request(DummyChannel(), False)
hash(req) | A L{http.Request} is hashable. | test_hashable | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_eqWithNonRequest(self):
"""
A L{http.Request} on the left hand side of an equality
comparison to an instance that is not a L{http.Request} hands
the comparison off to that object's C{__eq__} implementation.
"""
eqCalls = []
class _NotARequest(object):
def __eq__(self, other):
eqCalls.append(other)
return True
req = http.Request(DummyChannel(), False)
self.assertEqual(req, _NotARequest())
self.assertEqual(eqCalls, [req]) | A L{http.Request} on the left hand side of an equality
comparison to an instance that is not a L{http.Request} hands
the comparison off to that object's C{__eq__} implementation. | test_eqWithNonRequest | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_neWithNonRequest(self):
"""
A L{http.Request} on the left hand side of an inequality
comparison to an instance that is not a L{http.Request} hands
the comparison off to that object's C{__ne__} implementation.
"""
eqCalls = []
class _NotARequest(object):
def __ne__(self, other):
eqCalls.append(other)
return True
req = http.Request(DummyChannel(), False)
self.assertNotEqual(req, _NotARequest())
self.assertEqual(eqCalls, [req]) | A L{http.Request} on the left hand side of an inequality
comparison to an instance that is not a L{http.Request} hands
the comparison off to that object's C{__ne__} implementation. | test_neWithNonRequest | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_finishProducerStillRegistered(self):
"""
A RuntimeError is logged if a producer is still registered
when an L{http.Request} is finished.
"""
logObserver = EventLoggingObserver.createWithCleanup(
self,
globalLogPublisher
)
request = http.Request(DummyChannel(), False)
request.registerProducer(DummyProducer(), True)
request.finish()
self.assertEquals(1, len(logObserver))
event = logObserver[0]
f = event["log_failure"]
self.assertIsInstance(f.value, RuntimeError)
self.flushLoggedErrors(RuntimeError) | A RuntimeError is logged if a producer is still registered
when an L{http.Request} is finished. | test_finishProducerStillRegistered | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_getClientIPWithIPv4(self):
"""
L{http.Request.getClientIP} returns the host part of the
client's address when connected over IPv4.
"""
request = http.Request(
DummyChannel(peer=address.IPv6Address("TCP", "127.0.0.1", 12344)))
self.assertEqual(request.getClientIP(), "127.0.0.1") | L{http.Request.getClientIP} returns the host part of the
client's address when connected over IPv4. | test_getClientIPWithIPv4 | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_getClientIPWithIPv6(self):
"""
L{http.Request.getClientIP} returns the host part of the
client's address when connected over IPv6.
"""
request = http.Request(
DummyChannel(peer=address.IPv6Address("TCP", "::1", 12344)))
self.assertEqual(request.getClientIP(), "::1") | L{http.Request.getClientIP} returns the host part of the
client's address when connected over IPv6. | test_getClientIPWithIPv6 | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_getClientIPWithNonTCPPeer(self):
"""
L{http.Request.getClientIP} returns L{None} for the client's
IP address when connected over a non-TCP transport.
"""
request = http.Request(
DummyChannel(peer=address.UNIXAddress("/path/to/socket")))
self.assertEqual(request.getClientIP(), None) | L{http.Request.getClientIP} returns L{None} for the client's
IP address when connected over a non-TCP transport. | test_getClientIPWithNonTCPPeer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_getClientAddress(self):
"""
L{http.Request.getClientAddress} returns the client's address
as an L{IAddress} provider.
"""
client = address.UNIXAddress("/path/to/socket")
request = http.Request(DummyChannel(peer=client))
self.assertIs(request.getClientAddress(), client) | L{http.Request.getClientAddress} returns the client's address
as an L{IAddress} provider. | test_getClientAddress | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def setUp(self):
"""
Initialize variables used to verify that the header-processing functions
are getting called.
"""
self.handleHeaderCalled = False
self.handleEndHeadersCalled = False | Initialize variables used to verify that the header-processing functions
are getting called. | setUp | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def ourHandleHeader(self, key, val):
"""
Dummy implementation of L{HTTPClient.handleHeader}.
"""
self.handleHeaderCalled = True
self.assertEqual(val, self.expectedHeaders[key]) | Dummy implementation of L{HTTPClient.handleHeader}. | ourHandleHeader | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def ourHandleEndHeaders(self):
"""
Dummy implementation of L{HTTPClient.handleEndHeaders}.
"""
self.handleEndHeadersCalled = True | Dummy implementation of L{HTTPClient.handleEndHeaders}. | ourHandleEndHeaders | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_extractHeader(self):
"""
A header isn't processed by L{HTTPClient.extractHeader} until it is
confirmed in L{HTTPClient.lineReceived} that the header has been
received completely.
"""
c = ClientDriver()
c.handleHeader = self.ourHandleHeader
c.handleEndHeaders = self.ourHandleEndHeaders
c.lineReceived(b'HTTP/1.0 201')
c.lineReceived(b'Content-Length: 10')
self.assertIdentical(c.length, None)
self.assertFalse(self.handleHeaderCalled)
self.assertFalse(self.handleEndHeadersCalled)
# Signal end of headers.
c.lineReceived(b'')
self.assertTrue(self.handleHeaderCalled)
self.assertTrue(self.handleEndHeadersCalled)
self.assertEqual(c.length, 10) | A header isn't processed by L{HTTPClient.extractHeader} until it is
confirmed in L{HTTPClient.lineReceived} that the header has been
received completely. | test_extractHeader | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_noHeaders(self):
"""
An HTTP request with no headers will not cause any calls to
L{handleHeader} but will cause L{handleEndHeaders} to be called on
L{HTTPClient} subclasses.
"""
c = ClientDriver()
c.handleHeader = self.ourHandleHeader
c.handleEndHeaders = self.ourHandleEndHeaders
c.lineReceived(b'HTTP/1.0 201')
# Signal end of headers.
c.lineReceived(b'')
self.assertFalse(self.handleHeaderCalled)
self.assertTrue(self.handleEndHeadersCalled)
self.assertEqual(c.version, b'HTTP/1.0')
self.assertEqual(c.status, b'201') | An HTTP request with no headers will not cause any calls to
L{handleHeader} but will cause L{handleEndHeaders} to be called on
L{HTTPClient} subclasses. | test_noHeaders | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_multilineHeaders(self):
"""
L{HTTPClient} parses multiline headers by buffering header lines until
an empty line or a line that does not start with whitespace hits
lineReceived, confirming that the header has been received completely.
"""
c = ClientDriver()
c.handleHeader = self.ourHandleHeader
c.handleEndHeaders = self.ourHandleEndHeaders
c.lineReceived(b'HTTP/1.0 201')
c.lineReceived(b'X-Multiline: line-0')
self.assertFalse(self.handleHeaderCalled)
# Start continuing line with a tab.
c.lineReceived(b'\tline-1')
c.lineReceived(b'X-Multiline2: line-2')
# The previous header must be complete, so now it can be processed.
self.assertTrue(self.handleHeaderCalled)
# Start continuing line with a space.
c.lineReceived(b' line-3')
c.lineReceived(b'Content-Length: 10')
# Signal end of headers.
c.lineReceived(b'')
self.assertTrue(self.handleEndHeadersCalled)
self.assertEqual(c.version, b'HTTP/1.0')
self.assertEqual(c.status, b'201')
self.assertEqual(c.length, 10) | L{HTTPClient} parses multiline headers by buffering header lines until
an empty line or a line that does not start with whitespace hits
lineReceived, confirming that the header has been received completely. | test_multilineHeaders | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_HTTP10(self):
"""
HTTP/1.0 requests do not get 100-continue returned, even if 'Expect:
100-continue' is included (RFC 2616 10.1.1).
"""
transport = StringTransport()
channel = http.HTTPChannel()
channel.requestFactory = DummyHTTPHandlerProxy
channel.makeConnection(transport)
channel.dataReceived(b"GET / HTTP/1.0\r\n")
channel.dataReceived(b"Host: www.example.com\r\n")
channel.dataReceived(b"Content-Length: 3\r\n")
channel.dataReceived(b"Expect: 100-continue\r\n")
channel.dataReceived(b"\r\n")
self.assertEqual(transport.value(), b"")
channel.dataReceived(b"abc")
self.assertResponseEquals(
transport.value(),
[(b"HTTP/1.0 200 OK",
b"Command: GET",
b"Content-Length: 13",
b"Version: HTTP/1.0",
b"Request: /",
b"'''\n3\nabc'''\n")]) | HTTP/1.0 requests do not get 100-continue returned, even if 'Expect:
100-continue' is included (RFC 2616 10.1.1). | test_HTTP10 | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_expect100ContinueHeader(self):
"""
If a HTTP/1.1 client sends a 'Expect: 100-continue' header, the server
responds with a 100 response code before handling the request body, if
any. The normal resource rendering code will then be called, which
will send an additional response code.
"""
transport = StringTransport()
channel = http.HTTPChannel()
channel.requestFactory = DummyHTTPHandlerProxy
channel.makeConnection(transport)
channel.dataReceived(b"GET / HTTP/1.1\r\n")
channel.dataReceived(b"Host: www.example.com\r\n")
channel.dataReceived(b"Expect: 100-continue\r\n")
channel.dataReceived(b"Content-Length: 3\r\n")
# The 100 continue response is not sent until all headers are
# received:
self.assertEqual(transport.value(), b"")
channel.dataReceived(b"\r\n")
# The 100 continue response is sent *before* the body is even
# received:
self.assertEqual(transport.value(), b"HTTP/1.1 100 Continue\r\n\r\n")
channel.dataReceived(b"abc")
response = transport.value()
self.assertTrue(
response.startswith(b"HTTP/1.1 100 Continue\r\n\r\n"))
response = response[len(b"HTTP/1.1 100 Continue\r\n\r\n"):]
self.assertResponseEquals(
response,
[(b"HTTP/1.1 200 OK",
b"Command: GET",
b"Content-Length: 13",
b"Version: HTTP/1.1",
b"Request: /",
b"'''\n3\nabc'''\n")]) | If a HTTP/1.1 client sends a 'Expect: 100-continue' header, the server
responds with a 100 response code before handling the request body, if
any. The normal resource rendering code will then be called, which
will send an additional response code. | test_expect100ContinueHeader | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def sub(keys, d):
"""
Create a new dict containing only a subset of the items of an existing
dict.
@param keys: An iterable of the keys which will be added (with values from
C{d}) to the result.
@param d: The existing L{dict} from which to copy items.
@return: The new L{dict} with keys given by C{keys} and values given by the
corresponding values in C{d}.
@rtype: L{dict}
"""
return dict([(k, d[k]) for k in keys]) | Create a new dict containing only a subset of the items of an existing
dict.
@param keys: An iterable of the keys which will be added (with values from
C{d}) to the result.
@param d: The existing L{dict} from which to copy items.
@return: The new L{dict} with keys given by C{keys} and values given by the
corresponding values in C{d}.
@rtype: L{dict} | sub | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_getClientIP(self):
"""
L{Request.getClientIP} is deprecated in favor of
L{Request.getClientAddress}.
"""
request = http.Request(
DummyChannel(peer=address.IPv6Address("TCP", "127.0.0.1", 12345)))
request.gotLength(0)
request.requestReceived(b"GET", b"/", b"HTTP/1.1")
request.getClientIP()
warnings = self.flushWarnings(
offendingFunctions=[self.test_getClientIP])
self.assertEqual(1, len(warnings))
self.assertEqual({
"category": DeprecationWarning,
"message": (
"twisted.web.http.Request.getClientIP was deprecated "
"in Twisted 18.4.0; please use getClientAddress instead")},
sub(["category", "message"], warnings[0])) | L{Request.getClientIP} is deprecated in favor of
L{Request.getClientAddress}. | test_getClientIP | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_noLongerQueued(self):
"""
L{Request.noLongerQueued} is deprecated, as we no longer process
requests simultaneously.
"""
channel = DummyChannel()
request = http.Request(channel)
request.noLongerQueued()
warnings = self.flushWarnings(
offendingFunctions=[self.test_noLongerQueued])
self.assertEqual(1, len(warnings))
self.assertEqual({
"category": DeprecationWarning,
"message": (
"twisted.web.http.Request.noLongerQueued was deprecated "
"in Twisted 16.3.0")},
sub(["category", "message"], warnings[0])) | L{Request.noLongerQueued} is deprecated, as we no longer process
requests simultaneously. | test_noLongerQueued | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def buildChannelAndTransport(self, transport, requestFactory):
"""
Setup a L{HTTPChannel} and a transport and associate them.
@param transport: A transport to back the L{HTTPChannel}
@param requestFactory: An object that can construct L{Request} objects.
@return: A tuple of the channel and the transport.
"""
transport = transport
channel = http.HTTPChannel()
channel.requestFactory = _makeRequestProxyFactory(requestFactory)
channel.makeConnection(transport)
return channel, transport | Setup a L{HTTPChannel} and a transport and associate them.
@param transport: A transport to back the L{HTTPChannel}
@param requestFactory: An object that can construct L{Request} objects.
@return: A tuple of the channel and the transport. | buildChannelAndTransport | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_HTTPChannelIsAProducer(self):
"""
L{HTTPChannel} registers itself as a producer with its transport when a
connection is made.
"""
channel, transport = self.buildChannelAndTransport(
StringTransport(), DummyHTTPHandler
)
self.assertEqual(transport.producer, channel)
self.assertTrue(transport.streaming) | L{HTTPChannel} registers itself as a producer with its transport when a
connection is made. | test_HTTPChannelIsAProducer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_HTTPChannelUnregistersSelfWhenCallingLoseConnection(self):
"""
L{HTTPChannel} unregisters itself when it has loseConnection called.
"""
channel, transport = self.buildChannelAndTransport(
StringTransport(), DummyHTTPHandler
)
channel.loseConnection()
self.assertIs(transport.producer, None)
self.assertIs(transport.streaming, None) | L{HTTPChannel} unregisters itself when it has loseConnection called. | test_HTTPChannelUnregistersSelfWhenCallingLoseConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_HTTPChannelRejectsMultipleProducers(self):
"""
If two producers are registered on a L{HTTPChannel} without the first
being unregistered, a L{RuntimeError} is thrown.
"""
channel, transport = self.buildChannelAndTransport(
StringTransport(), DummyHTTPHandler
)
channel.registerProducer(DummyProducer(), True)
self.assertRaises(
RuntimeError, channel.registerProducer, DummyProducer(), True
) | If two producers are registered on a L{HTTPChannel} without the first
being unregistered, a L{RuntimeError} is thrown. | test_HTTPChannelRejectsMultipleProducers | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_HTTPChannelCanUnregisterWithNoProducer(self):
"""
If there is no producer, the L{HTTPChannel} can still have
C{unregisterProducer} called.
"""
channel, transport = self.buildChannelAndTransport(
StringTransport(), DummyHTTPHandler
)
channel.unregisterProducer()
self.assertIs(channel._requestProducer, None) | If there is no producer, the L{HTTPChannel} can still have
C{unregisterProducer} called. | test_HTTPChannelCanUnregisterWithNoProducer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_HTTPChannelStopWithNoRequestOutstanding(self):
"""
If there is no request producer currently registered, C{stopProducing}
does nothing.
"""
channel, transport = self.buildChannelAndTransport(
StringTransport(), DummyHTTPHandler
)
channel.unregisterProducer()
self.assertIs(channel._requestProducer, None) | If there is no request producer currently registered, C{stopProducing}
does nothing. | test_HTTPChannelStopWithNoRequestOutstanding | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_HTTPChannelStopRequestProducer(self):
"""
If there is a request producer registered with L{HTTPChannel}, calling
C{stopProducing} causes that producer to be stopped as well.
"""
channel, transport = self.buildChannelAndTransport(
StringTransport(), DelayedHTTPHandler
)
# Feed a request in to spawn a Request object, then grab it.
channel.dataReceived(self.request)
request = channel.requests[0].original
# Register a dummy producer.
producer = DummyProducer()
request.registerProducer(producer, True)
# The dummy producer is currently unpaused.
self.assertEqual(producer.events, [])
# The transport now stops production. This stops the request producer.
channel.stopProducing()
self.assertEqual(producer.events, ['stop']) | If there is a request producer registered with L{HTTPChannel}, calling
C{stopProducing} causes that producer to be stopped as well. | test_HTTPChannelStopRequestProducer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_HTTPChannelPropagatesProducingFromTransportToTransport(self):
"""
When L{HTTPChannel} has C{pauseProducing} called on it by the transport
it will call C{pauseProducing} on the transport. When unpaused, the
L{HTTPChannel} will call C{resumeProducing} on its transport.
"""
channel, transport = self.buildChannelAndTransport(
StringTransport(), DummyHTTPHandler
)
# The transport starts in producing state.
self.assertEqual(transport.producerState, 'producing')
# Pause producing. The transport should now be paused as well.
channel.pauseProducing()
self.assertEqual(transport.producerState, 'paused')
# Resume producing. The transport should be unpaused.
channel.resumeProducing()
self.assertEqual(transport.producerState, 'producing') | When L{HTTPChannel} has C{pauseProducing} called on it by the transport
it will call C{pauseProducing} on the transport. When unpaused, the
L{HTTPChannel} will call C{resumeProducing} on its transport. | test_HTTPChannelPropagatesProducingFromTransportToTransport | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_HTTPChannelPropagatesPausedProductionToRequest(self):
"""
If a L{Request} object has registered itself as a producer with a
L{HTTPChannel} object, and the L{HTTPChannel} object is paused, both
the transport and L{Request} objects get paused.
"""
channel, transport = self.buildChannelAndTransport(
StringTransport(), DelayedHTTPHandler
)
channel._optimisticEagerReadSize = 0
# Feed a request in to spawn a Request object, then grab it.
channel.dataReceived(self.request)
# A little extra data to pause the transport.
channel.dataReceived(b'123')
request = channel.requests[0].original
# Register a dummy producer.
producer = DummyProducer()
request.registerProducer(producer, True)
# Note that the transport is paused while it waits for a response.
# The dummy producer, however, is unpaused.
self.assertEqual(transport.producerState, 'paused')
self.assertEqual(producer.events, [])
# The transport now pauses production. This causes the producer to be
# paused. The transport stays paused.
channel.pauseProducing()
self.assertEqual(transport.producerState, 'paused')
self.assertEqual(producer.events, ['pause'])
# The transport has become unblocked and resumes production. This
# unblocks the dummy producer, but leaves the transport blocked.
channel.resumeProducing()
self.assertEqual(transport.producerState, 'paused')
self.assertEqual(producer.events, ['pause', 'resume'])
# Unregister the producer and then complete the response. Because the
# channel is not paused, the transport now gets unpaused.
request.unregisterProducer()
request.delayedProcess()
self.assertEqual(transport.producerState, 'producing') | If a L{Request} object has registered itself as a producer with a
L{HTTPChannel} object, and the L{HTTPChannel} object is paused, both
the transport and L{Request} objects get paused. | test_HTTPChannelPropagatesPausedProductionToRequest | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_HTTPChannelStaysPausedWhenRequestCompletes(self):
"""
If a L{Request} object completes its response while the transport is
paused, the L{HTTPChannel} does not resume the transport.
"""
channel, transport = self.buildChannelAndTransport(
StringTransport(), DelayedHTTPHandler
)
channel._optimisticEagerReadSize = 0
# Feed a request in to spawn a Request object, then grab it.
channel.dataReceived(self.request)
channel.dataReceived(b'extra') # exceed buffer size to pause the
# transport.
request = channel.requests[0].original
# Register a dummy producer.
producer = DummyProducer()
request.registerProducer(producer, True)
# Note that the transport is paused while it waits for a response.
# The dummy producer, however, is unpaused.
self.assertEqual(transport.producerState, 'paused')
self.assertEqual(producer.events, [])
# The transport now pauses production. This causes the producer to be
# paused. The transport stays paused.
channel.pauseProducing()
self.assertEqual(transport.producerState, 'paused')
self.assertEqual(producer.events, ['pause'])
# Unregister the producer and then complete the response. Because the
# channel is still paused, the transport stays paused
request.unregisterProducer()
request.delayedProcess()
self.assertEqual(transport.producerState, 'paused')
# At this point the channel is resumed, and so is the transport.
channel.resumeProducing()
self.assertEqual(transport.producerState, 'producing') | If a L{Request} object completes its response while the transport is
paused, the L{HTTPChannel} does not resume the transport. | test_HTTPChannelStaysPausedWhenRequestCompletes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_HTTPChannelToleratesDataWhenTransportPaused(self):
"""
If the L{HTTPChannel} has paused the transport, it still tolerates
receiving data, and does not attempt to pause the transport again.
"""
class NoDoublePauseTransport(StringTransport):
"""
A version of L{StringTransport} that fails tests if it is paused
while already paused.
"""
def pauseProducing(self):
if self.producerState == 'paused':
raise RuntimeError("Transport was paused twice!")
StringTransport.pauseProducing(self)
# Confirm that pausing a NoDoublePauseTransport twice fails.
transport = NoDoublePauseTransport()
transport.pauseProducing()
self.assertRaises(RuntimeError, transport.pauseProducing)
channel, transport = self.buildChannelAndTransport(
NoDoublePauseTransport(), DummyHTTPHandler
)
# The transport starts in producing state.
self.assertEqual(transport.producerState, 'producing')
# Pause producing. The transport should now be paused as well.
channel.pauseProducing()
self.assertEqual(transport.producerState, 'paused')
# Write in a request, even though the transport is paused.
channel.dataReceived(self.request)
# The transport is still paused, but we have tried to write the
# response out.
self.assertEqual(transport.producerState, 'paused')
self.assertTrue(transport.value().startswith(b'HTTP/1.1 200 OK\r\n'))
# Resume producing. The transport should be unpaused.
channel.resumeProducing()
self.assertEqual(transport.producerState, 'producing') | If the L{HTTPChannel} has paused the transport, it still tolerates
receiving data, and does not attempt to pause the transport again. | test_HTTPChannelToleratesDataWhenTransportPaused | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_HTTPChannelToleratesPullProducers(self):
"""
If the L{HTTPChannel} has a L{IPullProducer} registered with it it can
adapt that producer into an L{IPushProducer}.
"""
channel, transport = self.buildChannelAndTransport(
StringTransport(), DummyPullProducerHandler
)
transport = StringTransport()
channel = http.HTTPChannel()
channel.requestFactory = DummyPullProducerHandlerProxy
channel.makeConnection(transport)
channel.dataReceived(self.request)
request = channel.requests[0].original
responseComplete = request._actualProducer.result
def validate(ign):
responseBody = transport.value().split(b'\r\n\r\n', 1)[1]
expectedResponseBody = (
b'1\r\n0\r\n'
b'1\r\n1\r\n'
b'1\r\n2\r\n'
b'1\r\n3\r\n'
b'1\r\n4\r\n'
b'1\r\n5\r\n'
b'1\r\n6\r\n'
b'1\r\n7\r\n'
b'1\r\n8\r\n'
b'1\r\n9\r\n'
)
self.assertEqual(responseBody, expectedResponseBody)
return responseComplete.addCallback(validate) | If the L{HTTPChannel} has a L{IPullProducer} registered with it it can
adapt that producer into an L{IPushProducer}. | test_HTTPChannelToleratesPullProducers | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
def test_HTTPChannelUnregistersSelfWhenTimingOut(self):
"""
L{HTTPChannel} unregisters itself when it times out a connection.
"""
clock = Clock()
transport = StringTransport()
channel = http.HTTPChannel()
# Patch the channel's callLater method.
channel.timeOut = 100
channel.callLater = clock.callLater
channel.makeConnection(transport)
# Tick the clock forward almost to the timeout.
clock.advance(99)
self.assertIs(transport.producer, channel)
self.assertIs(transport.streaming, True)
# Fire the timeout.
clock.advance(1)
self.assertIs(transport.producer, None)
self.assertIs(transport.streaming, None) | L{HTTPChannel} unregisters itself when it times out a connection. | test_HTTPChannelUnregistersSelfWhenTimingOut | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.