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_multipleUnsatisfiableRangesSets416ReqestedRangeNotSatisfiable(self): """ makeProducer sets the response code of the request to of 'Requested Range Not Satisfiable' when the Range header requests multiple ranges, none of which are satisfiable. """ request = DummyRequest([]) request.requestHeaders.addRawHeader(b'range', b'bytes=10-12,15-20') resource = self.makeResourceWithContent(b'abc') with resource.openForReading() as file: resource.makeProducer(request, file) self.assertEqual( http.REQUESTED_RANGE_NOT_SATISFIABLE, request.responseCode)
makeProducer sets the response code of the request to of 'Requested Range Not Satisfiable' when the Range header requests multiple ranges, none of which are satisfiable.
test_multipleUnsatisfiableRangesSets416ReqestedRangeNotSatisfiable
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_multipleUnsatisfiableRangeSetsContentHeaders(self): """ makeProducer when the Range header requests multiple ranges, none of which are satisfiable, sets the Content-* headers appropriately. """ request = DummyRequest([]) request.requestHeaders.addRawHeader(b'range', b'bytes=4-10') contentType = "text/plain" request.requestHeaders.addRawHeader(b'range', b'bytes=10-12,15-20') resource = self.makeResourceWithContent(b'abc', type=contentType) with resource.openForReading() as file: resource.makeProducer(request, file) self.assertEqual( {b'content-length': b'0', b'content-range': b'bytes */3', b'content-type': b'text/plain'}, self.contentHeaders(request))
makeProducer when the Range header requests multiple ranges, none of which are satisfiable, sets the Content-* headers appropriately.
test_multipleUnsatisfiableRangeSetsContentHeaders
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_oneSatisfiableRangeIsEnough(self): """ makeProducer when the Range header requests multiple ranges, at least one of which matches, sets the response code to 'Partial Content'. """ request = DummyRequest([]) request.requestHeaders.addRawHeader(b'range', b'bytes=1-3,100-200') resource = self.makeResourceWithContent(b'abcdef') with resource.openForReading() as file: resource.makeProducer(request, file) self.assertEqual( http.PARTIAL_CONTENT, request.responseCode)
makeProducer when the Range header requests multiple ranges, at least one of which matches, sets the response code to 'Partial Content'.
test_oneSatisfiableRangeIsEnough
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_stopProducingClosesFile(self): """ L{StaticProducer.stopProducing} closes the file object the producer is producing data from. """ fileObject = StringIO() producer = static.StaticProducer(None, fileObject) producer.stopProducing() self.assertTrue(fileObject.closed)
L{StaticProducer.stopProducing} closes the file object the producer is producing data from.
test_stopProducingClosesFile
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_stopProducingSetsRequestToNone(self): """ L{StaticProducer.stopProducing} sets the request instance variable to None, which indicates to subclasses' resumeProducing methods that no more data should be produced. """ fileObject = StringIO() producer = static.StaticProducer(DummyRequest([]), fileObject) producer.stopProducing() self.assertIdentical(None, producer.request)
L{StaticProducer.stopProducing} sets the request instance variable to None, which indicates to subclasses' resumeProducing methods that no more data should be produced.
test_stopProducingSetsRequestToNone
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_implementsIPullProducer(self): """ L{NoRangeStaticProducer} implements L{IPullProducer}. """ verifyObject( interfaces.IPullProducer, static.NoRangeStaticProducer(None, None))
L{NoRangeStaticProducer} implements L{IPullProducer}.
test_implementsIPullProducer
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_resumeProducingProducesContent(self): """ L{NoRangeStaticProducer.resumeProducing} writes content from the resource to the request. """ request = DummyRequest([]) content = b'abcdef' producer = static.NoRangeStaticProducer( request, StringIO(content)) # start calls registerProducer on the DummyRequest, which pulls all # output from the producer and so we just need this one call. producer.start() self.assertEqual(content, b''.join(request.written))
L{NoRangeStaticProducer.resumeProducing} writes content from the resource to the request.
test_resumeProducingProducesContent
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_resumeProducingBuffersOutput(self): """ L{NoRangeStaticProducer.start} writes at most C{abstract.FileDescriptor.bufferSize} bytes of content from the resource to the request at once. """ request = DummyRequest([]) bufferSize = abstract.FileDescriptor.bufferSize content = b'a' * (2*bufferSize + 1) producer = static.NoRangeStaticProducer( request, StringIO(content)) # start calls registerProducer on the DummyRequest, which pulls all # output from the producer and so we just need this one call. producer.start() expected = [ content[0:bufferSize], content[bufferSize:2*bufferSize], content[2*bufferSize:] ] self.assertEqual(expected, request.written)
L{NoRangeStaticProducer.start} writes at most C{abstract.FileDescriptor.bufferSize} bytes of content from the resource to the request at once.
test_resumeProducingBuffersOutput
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_finishCalledWhenDone(self): """ L{NoRangeStaticProducer.resumeProducing} calls finish() on the request after it is done producing content. """ request = DummyRequest([]) finishDeferred = request.notifyFinish() callbackList = [] finishDeferred.addCallback(callbackList.append) producer = static.NoRangeStaticProducer( request, StringIO(b'abcdef')) # start calls registerProducer on the DummyRequest, which pulls all # output from the producer and so we just need this one call. producer.start() self.assertEqual([None], callbackList)
L{NoRangeStaticProducer.resumeProducing} calls finish() on the request after it is done producing content.
test_finishCalledWhenDone
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_implementsIPullProducer(self): """ L{SingleRangeStaticProducer} implements L{IPullProducer}. """ verifyObject( interfaces.IPullProducer, static.SingleRangeStaticProducer(None, None, None, None))
L{SingleRangeStaticProducer} implements L{IPullProducer}.
test_implementsIPullProducer
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_resumeProducingProducesContent(self): """ L{SingleRangeStaticProducer.resumeProducing} writes the given amount of content, starting at the given offset, from the resource to the request. """ request = DummyRequest([]) content = b'abcdef' producer = static.SingleRangeStaticProducer( request, StringIO(content), 1, 3) # DummyRequest.registerProducer pulls all output from the producer, so # we just need to call start. producer.start() self.assertEqual(content[1:4], b''.join(request.written))
L{SingleRangeStaticProducer.resumeProducing} writes the given amount of content, starting at the given offset, from the resource to the request.
test_resumeProducingProducesContent
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_resumeProducingBuffersOutput(self): """ L{SingleRangeStaticProducer.start} writes at most C{abstract.FileDescriptor.bufferSize} bytes of content from the resource to the request at once. """ request = DummyRequest([]) bufferSize = abstract.FileDescriptor.bufferSize content = b'abc' * bufferSize producer = static.SingleRangeStaticProducer( request, StringIO(content), 1, bufferSize+10) # DummyRequest.registerProducer pulls all output from the producer, so # we just need to call start. producer.start() expected = [ content[1:bufferSize+1], content[bufferSize+1:bufferSize+11], ] self.assertEqual(expected, request.written)
L{SingleRangeStaticProducer.start} writes at most C{abstract.FileDescriptor.bufferSize} bytes of content from the resource to the request at once.
test_resumeProducingBuffersOutput
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_finishCalledWhenDone(self): """ L{SingleRangeStaticProducer.resumeProducing} calls finish() on the request after it is done producing content. """ request = DummyRequest([]) finishDeferred = request.notifyFinish() callbackList = [] finishDeferred.addCallback(callbackList.append) producer = static.SingleRangeStaticProducer( request, StringIO(b'abcdef'), 1, 1) # start calls registerProducer on the DummyRequest, which pulls all # output from the producer and so we just need this one call. producer.start() self.assertEqual([None], callbackList)
L{SingleRangeStaticProducer.resumeProducing} calls finish() on the request after it is done producing content.
test_finishCalledWhenDone
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_implementsIPullProducer(self): """ L{MultipleRangeStaticProducer} implements L{IPullProducer}. """ verifyObject( interfaces.IPullProducer, static.MultipleRangeStaticProducer(None, None, None))
L{MultipleRangeStaticProducer} implements L{IPullProducer}.
test_implementsIPullProducer
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_resumeProducingProducesContent(self): """ L{MultipleRangeStaticProducer.resumeProducing} writes the requested chunks of content from the resource to the request, with the supplied boundaries in between each chunk. """ request = DummyRequest([]) content = b'abcdef' producer = static.MultipleRangeStaticProducer( request, StringIO(content), [(b'1', 1, 3), (b'2', 5, 1)]) # DummyRequest.registerProducer pulls all output from the producer, so # we just need to call start. producer.start() self.assertEqual(b'1bcd2f', b''.join(request.written))
L{MultipleRangeStaticProducer.resumeProducing} writes the requested chunks of content from the resource to the request, with the supplied boundaries in between each chunk.
test_resumeProducingProducesContent
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_resumeProducingBuffersOutput(self): """ L{MultipleRangeStaticProducer.start} writes about C{abstract.FileDescriptor.bufferSize} bytes of content from the resource to the request at once. To be specific about the 'about' above: it can write slightly more, for example in the case where the first boundary plus the first chunk is less than C{bufferSize} but first boundary plus the first chunk plus the second boundary is more, but this is unimportant as in practice the boundaries are fairly small. On the other side, it is important for performance to bundle up several small chunks into one call to request.write. """ request = DummyRequest([]) content = b'0123456789' * 2 producer = static.MultipleRangeStaticProducer( request, StringIO(content), [(b'a', 0, 2), (b'b', 5, 10), (b'c', 0, 0)]) producer.bufferSize = 10 # DummyRequest.registerProducer pulls all output from the producer, so # we just need to call start. producer.start() expected = [ b'a' + content[0:2] + b'b' + content[5:11], content[11:15] + b'c', ] self.assertEqual(expected, request.written)
L{MultipleRangeStaticProducer.start} writes about C{abstract.FileDescriptor.bufferSize} bytes of content from the resource to the request at once. To be specific about the 'about' above: it can write slightly more, for example in the case where the first boundary plus the first chunk is less than C{bufferSize} but first boundary plus the first chunk plus the second boundary is more, but this is unimportant as in practice the boundaries are fairly small. On the other side, it is important for performance to bundle up several small chunks into one call to request.write.
test_resumeProducingBuffersOutput
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_finishCalledWhenDone(self): """ L{MultipleRangeStaticProducer.resumeProducing} calls finish() on the request after it is done producing content. """ request = DummyRequest([]) finishDeferred = request.notifyFinish() callbackList = [] finishDeferred.addCallback(callbackList.append) producer = static.MultipleRangeStaticProducer( request, StringIO(b'abcdef'), [(b'', 1, 2)]) # start calls registerProducer on the DummyRequest, which pulls all # output from the producer and so we just need this one call. producer.start() self.assertEqual([None], callbackList)
L{MultipleRangeStaticProducer.resumeProducing} calls finish() on the request after it is done producing content.
test_finishCalledWhenDone
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def setUp(self): """ Create a temporary file with a fixed payload of 64 bytes. Create a resource for that file and create a request which will be for that resource. Each test can set a different range header to test different aspects of the implementation. """ path = FilePath(self.mktemp()) # This is just a jumble of random stuff. It's supposed to be a good # set of data for this test, particularly in order to avoid # accidentally seeing the right result by having a byte sequence # repeated at different locations or by having byte values which are # somehow correlated with their position in the string. self.payload = (b'\xf8u\xf3E\x8c7\xce\x00\x9e\xb6a0y0S\xf0\xef\xac\xb7' b'\xbe\xb5\x17M\x1e\x136k{\x1e\xbe\x0c\x07\x07\t\xd0' b'\xbckY\xf5I\x0b\xb8\x88oZ\x1d\x85b\x1a\xcdk\xf2\x1d' b'&\xfd%\xdd\x82q/A\x10Y\x8b') path.setContent(self.payload) self.file = path.open() self.resource = static.File(self.file.name) self.resource.isLeaf = 1 self.request = DummyRequest([b'']) self.request.uri = self.file.name self.catcher = [] log.addObserver(self.catcher.append)
Create a temporary file with a fixed payload of 64 bytes. Create a resource for that file and create a request which will be for that resource. Each test can set a different range header to test different aspects of the implementation.
setUp
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def tearDown(self): """ Clean up the resource file and the log observer. """ self.file.close() log.removeObserver(self.catcher.append)
Clean up the resource file and the log observer.
tearDown
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def _assertLogged(self, expected): """ Asserts that a given log message occurred with an expected message. """ logItem = self.catcher.pop() self.assertEqual(logItem["message"][0], expected) self.assertEqual( self.catcher, [], "An additional log occurred: %r" % (logItem,))
Asserts that a given log message occurred with an expected message.
_assertLogged
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_invalidRanges(self): """ L{File._parseRangeHeader} raises L{ValueError} when passed syntactically invalid byte ranges. """ f = self.resource._parseRangeHeader # there's no = self.assertRaises(ValueError, f, b'bytes') # unknown isn't a valid Bytes-Unit self.assertRaises(ValueError, f, b'unknown=1-2') # there's no - in =stuff self.assertRaises(ValueError, f, b'bytes=3') # both start and end are empty self.assertRaises(ValueError, f, b'bytes=-') # start isn't an integer self.assertRaises(ValueError, f, b'bytes=foo-') # end isn't an integer self.assertRaises(ValueError, f, b'bytes=-foo') # end isn't equal to or greater than start self.assertRaises(ValueError, f, b'bytes=5-4')
L{File._parseRangeHeader} raises L{ValueError} when passed syntactically invalid byte ranges.
test_invalidRanges
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_rangeMissingStop(self): """ A single bytes range without an explicit stop position is parsed into a two-tuple giving the start position and L{None}. """ self.assertEqual( self.resource._parseRangeHeader(b'bytes=0-'), [(0, None)])
A single bytes range without an explicit stop position is parsed into a two-tuple giving the start position and L{None}.
test_rangeMissingStop
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_rangeMissingStart(self): """ A single bytes range without an explicit start position is parsed into a two-tuple of L{None} and the end position. """ self.assertEqual( self.resource._parseRangeHeader(b'bytes=-3'), [(None, 3)])
A single bytes range without an explicit start position is parsed into a two-tuple of L{None} and the end position.
test_rangeMissingStart
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_range(self): """ A single bytes range with explicit start and stop positions is parsed into a two-tuple of those positions. """ self.assertEqual( self.resource._parseRangeHeader(b'bytes=2-5'), [(2, 5)])
A single bytes range with explicit start and stop positions is parsed into a two-tuple of those positions.
test_range
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_rangeWithSpace(self): """ A single bytes range with whitespace in allowed places is parsed in the same way as it would be without the whitespace. """ self.assertEqual( self.resource._parseRangeHeader(b' bytes=1-2 '), [(1, 2)]) self.assertEqual( self.resource._parseRangeHeader(b'bytes =1-2 '), [(1, 2)]) self.assertEqual( self.resource._parseRangeHeader(b'bytes= 1-2'), [(1, 2)]) self.assertEqual( self.resource._parseRangeHeader(b'bytes=1 -2'), [(1, 2)]) self.assertEqual( self.resource._parseRangeHeader(b'bytes=1- 2'), [(1, 2)]) self.assertEqual( self.resource._parseRangeHeader(b'bytes=1-2 '), [(1, 2)])
A single bytes range with whitespace in allowed places is parsed in the same way as it would be without the whitespace.
test_rangeWithSpace
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_nullRangeElements(self): """ If there are multiple byte ranges but only one is non-null, the non-null range is parsed and its start and stop returned. """ self.assertEqual( self.resource._parseRangeHeader(b'bytes=1-2,\r\n, ,\t'), [(1, 2)])
If there are multiple byte ranges but only one is non-null, the non-null range is parsed and its start and stop returned.
test_nullRangeElements
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_multipleRanges(self): """ If multiple byte ranges are specified their starts and stops are returned. """ self.assertEqual( self.resource._parseRangeHeader(b'bytes=1-2,3-4'), [(1, 2), (3, 4)])
If multiple byte ranges are specified their starts and stops are returned.
test_multipleRanges
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_bodyLength(self): """ A correct response to a range request is as long as the length of the requested range. """ self.request.requestHeaders.addRawHeader(b'range', b'bytes=0-43') self.resource.render(self.request) self.assertEqual(len(b''.join(self.request.written)), 44)
A correct response to a range request is as long as the length of the requested range.
test_bodyLength
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_invalidRangeRequest(self): """ An incorrect range request (RFC 2616 defines a correct range request as a Bytes-Unit followed by a '=' character followed by a specific range. Only 'bytes' is defined) results in the range header value being logged and a normal 200 response being sent. """ range = b'foobar=0-43' self.request.requestHeaders.addRawHeader(b'range', range) self.resource.render(self.request) expected = "Ignoring malformed Range header %r" % (range.decode(),) self._assertLogged(expected) self.assertEqual(b''.join(self.request.written), self.payload) self.assertEqual(self.request.responseCode, http.OK) self.assertEqual( self.request.responseHeaders.getRawHeaders(b'content-length')[0], intToBytes(len(self.payload)))
An incorrect range request (RFC 2616 defines a correct range request as a Bytes-Unit followed by a '=' character followed by a specific range. Only 'bytes' is defined) results in the range header value being logged and a normal 200 response being sent.
test_invalidRangeRequest
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def parseMultipartBody(self, body, boundary): """ Parse C{body} as a multipart MIME response separated by C{boundary}. Note that this with fail the calling test on certain syntactic problems. """ sep = b"\r\n--" + boundary parts = body.split(sep) self.assertEqual(b'', parts[0]) self.assertEqual(b'--\r\n', parts[-1]) parsed_parts = [] for part in parts[1:-1]: before, header1, header2, blank, partBody = part.split(b'\r\n', 4) headers = header1 + b'\n' + header2 self.assertEqual(b'', before) self.assertEqual(b'', blank) partContentTypeValue = re.search( b'^content-type: (.*)$', headers, re.I|re.M).group(1) start, end, size = re.search( b'^content-range: bytes ([0-9]+)-([0-9]+)/([0-9]+)$', headers, re.I|re.M).groups() parsed_parts.append( {b'contentType': partContentTypeValue, b'contentRange': (start, end, size), b'body': partBody}) return parsed_parts
Parse C{body} as a multipart MIME response separated by C{boundary}. Note that this with fail the calling test on certain syntactic problems.
parseMultipartBody
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_multipleRangeRequest(self): """ The response to a request for multiple bytes ranges is a MIME-ish multipart response. """ startEnds = [(0, 2), (20, 30), (40, 50)] rangeHeaderValue = b','.join([networkString("%s-%s" % (s,e)) for (s, e) in startEnds]) self.request.requestHeaders.addRawHeader(b'range', b'bytes=' + rangeHeaderValue) self.resource.render(self.request) self.assertEqual(self.request.responseCode, http.PARTIAL_CONTENT) boundary = re.match( b'^multipart/byteranges; boundary="(.*)"$', self.request.responseHeaders.getRawHeaders(b'content-type')[0]).group(1) parts = self.parseMultipartBody(b''.join(self.request.written), boundary) self.assertEqual(len(startEnds), len(parts)) for part, (s, e) in zip(parts, startEnds): self.assertEqual(networkString(self.resource.type), part[b'contentType']) start, end, size = part[b'contentRange'] self.assertEqual(int(start), s) self.assertEqual(int(end), e) self.assertEqual(int(size), self.resource.getFileSize()) self.assertEqual(self.payload[s:e+1], part[b'body'])
The response to a request for multiple bytes ranges is a MIME-ish multipart response.
test_multipleRangeRequest
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_multipleRangeRequestWithRangeOverlappingEnd(self): """ The response to a request for multiple bytes ranges is a MIME-ish multipart response, even when one of the ranged falls off the end of the resource. """ startEnds = [(0, 2), (40, len(self.payload) + 10)] rangeHeaderValue = b','.join([networkString("%s-%s" % (s,e)) for (s, e) in startEnds]) self.request.requestHeaders.addRawHeader(b'range', b'bytes=' + rangeHeaderValue) self.resource.render(self.request) self.assertEqual(self.request.responseCode, http.PARTIAL_CONTENT) boundary = re.match( b'^multipart/byteranges; boundary="(.*)"$', self.request.responseHeaders.getRawHeaders(b'content-type')[0]).group(1) parts = self.parseMultipartBody(b''.join(self.request.written), boundary) self.assertEqual(len(startEnds), len(parts)) for part, (s, e) in zip(parts, startEnds): self.assertEqual(networkString(self.resource.type), part[b'contentType']) start, end, size = part[b'contentRange'] self.assertEqual(int(start), s) self.assertEqual(int(end), min(e, self.resource.getFileSize()-1)) self.assertEqual(int(size), self.resource.getFileSize()) self.assertEqual(self.payload[s:e+1], part[b'body'])
The response to a request for multiple bytes ranges is a MIME-ish multipart response, even when one of the ranged falls off the end of the resource.
test_multipleRangeRequestWithRangeOverlappingEnd
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_implicitEnd(self): """ If the end byte position is omitted, then it is treated as if the length of the resource was specified by the end byte position. """ self.request.requestHeaders.addRawHeader(b'range', b'bytes=23-') self.resource.render(self.request) self.assertEqual(b''.join(self.request.written), self.payload[23:]) self.assertEqual(len(b''.join(self.request.written)), 41) self.assertEqual(self.request.responseCode, http.PARTIAL_CONTENT) self.assertEqual( self.request.responseHeaders.getRawHeaders(b'content-range')[0], b'bytes 23-63/64') self.assertEqual( self.request.responseHeaders.getRawHeaders(b'content-length')[0], b'41')
If the end byte position is omitted, then it is treated as if the length of the resource was specified by the end byte position.
test_implicitEnd
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_implicitStart(self): """ If the start byte position is omitted but the end byte position is supplied, then the range is treated as requesting the last -N bytes of the resource, where N is the end byte position. """ self.request.requestHeaders.addRawHeader(b'range', b'bytes=-17') self.resource.render(self.request) self.assertEqual(b''.join(self.request.written), self.payload[-17:]) self.assertEqual(len(b''.join(self.request.written)), 17) self.assertEqual(self.request.responseCode, http.PARTIAL_CONTENT) self.assertEqual( self.request.responseHeaders.getRawHeaders(b'content-range')[0], b'bytes 47-63/64') self.assertEqual( self.request.responseHeaders.getRawHeaders(b'content-length')[0], b'17')
If the start byte position is omitted but the end byte position is supplied, then the range is treated as requesting the last -N bytes of the resource, where N is the end byte position.
test_implicitStart
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_explicitRange(self): """ A correct response to a bytes range header request from A to B starts with the A'th byte and ends with (including) the B'th byte. The first byte of a page is numbered with 0. """ self.request.requestHeaders.addRawHeader(b'range', b'bytes=3-43') self.resource.render(self.request) written = b''.join(self.request.written) self.assertEqual(written, self.payload[3:44]) self.assertEqual(self.request.responseCode, http.PARTIAL_CONTENT) self.assertEqual( self.request.responseHeaders.getRawHeaders(b'content-range')[0], b'bytes 3-43/64') self.assertEqual( intToBytes(len(written)), self.request.responseHeaders.getRawHeaders(b'content-length')[0])
A correct response to a bytes range header request from A to B starts with the A'th byte and ends with (including) the B'th byte. The first byte of a page is numbered with 0.
test_explicitRange
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_explicitRangeOverlappingEnd(self): """ A correct response to a bytes range header request from A to B when B is past the end of the resource starts with the A'th byte and ends with the last byte of the resource. The first byte of a page is numbered with 0. """ self.request.requestHeaders.addRawHeader(b'range', b'bytes=40-100') self.resource.render(self.request) written = b''.join(self.request.written) self.assertEqual(written, self.payload[40:]) self.assertEqual(self.request.responseCode, http.PARTIAL_CONTENT) self.assertEqual( self.request.responseHeaders.getRawHeaders(b'content-range')[0], b'bytes 40-63/64') self.assertEqual( intToBytes(len(written)), self.request.responseHeaders.getRawHeaders(b'content-length')[0])
A correct response to a bytes range header request from A to B when B is past the end of the resource starts with the A'th byte and ends with the last byte of the resource. The first byte of a page is numbered with 0.
test_explicitRangeOverlappingEnd
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_statusCodeRequestedRangeNotSatisfiable(self): """ If a range is syntactically invalid due to the start being greater than the end, the range header is ignored (the request is responded to as if it were not present). """ self.request.requestHeaders.addRawHeader(b'range', b'bytes=20-13') self.resource.render(self.request) self.assertEqual(self.request.responseCode, http.OK) self.assertEqual(b''.join(self.request.written), self.payload) self.assertEqual( self.request.responseHeaders.getRawHeaders(b'content-length')[0], intToBytes(len(self.payload)))
If a range is syntactically invalid due to the start being greater than the end, the range header is ignored (the request is responded to as if it were not present).
test_statusCodeRequestedRangeNotSatisfiable
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_invalidStartBytePos(self): """ If a range is unsatisfiable due to the start not being less than the length of the resource, the response is 416 (Requested range not satisfiable) and no data is written to the response body (RFC 2616, section 14.35.1). """ self.request.requestHeaders.addRawHeader(b'range', b'bytes=67-108') self.resource.render(self.request) self.assertEqual( self.request.responseCode, http.REQUESTED_RANGE_NOT_SATISFIABLE) self.assertEqual(b''.join(self.request.written), b'') self.assertEqual( self.request.responseHeaders.getRawHeaders(b'content-length')[0], b'0') # Sections 10.4.17 and 14.16 self.assertEqual( self.request.responseHeaders.getRawHeaders(b'content-range')[0], networkString('bytes */%d' % (len(self.payload),)))
If a range is unsatisfiable due to the start not being less than the length of the resource, the response is 416 (Requested range not satisfiable) and no data is written to the response body (RFC 2616, section 14.35.1).
test_invalidStartBytePos
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_renderHeader(self): """ L{static.DirectoryLister} prints the request uri as header of the rendered content. """ path = FilePath(self.mktemp()) path.makedirs() lister = static.DirectoryLister(path.path) data = lister.render(self._request(b'foo')) self.assertIn(b"<h1>Directory listing for foo</h1>", data) self.assertIn(b"<title>Directory listing for foo</title>", data)
L{static.DirectoryLister} prints the request uri as header of the rendered content.
test_renderHeader
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_renderUnquoteHeader(self): """ L{static.DirectoryLister} unquote the request uri before printing it. """ path = FilePath(self.mktemp()) path.makedirs() lister = static.DirectoryLister(path.path) data = lister.render(self._request(b'foo%20bar')) self.assertIn(b"<h1>Directory listing for foo bar</h1>", data) self.assertIn(b"<title>Directory listing for foo bar</title>", data)
L{static.DirectoryLister} unquote the request uri before printing it.
test_renderUnquoteHeader
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_escapeHeader(self): """ L{static.DirectoryLister} escape "&", "<" and ">" after unquoting the request uri. """ path = FilePath(self.mktemp()) path.makedirs() lister = static.DirectoryLister(path.path) data = lister.render(self._request(b'foo%26bar')) self.assertIn(b"<h1>Directory listing for foo&amp;bar</h1>", data) self.assertIn(b"<title>Directory listing for foo&amp;bar</title>", data)
L{static.DirectoryLister} escape "&", "<" and ">" after unquoting the request uri.
test_escapeHeader
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_renderFiles(self): """ L{static.DirectoryLister} is able to list all the files inside a directory. """ path = FilePath(self.mktemp()) path.makedirs() path.child('file1').setContent(b"content1") path.child('file2').setContent(b"content2" * 1000) lister = static.DirectoryLister(path.path) data = lister.render(self._request(b'foo')) body = b"""<tr class="odd"> <td><a href="file1">file1</a></td> <td>8B</td> <td>[text/html]</td> <td></td> </tr> <tr class="even"> <td><a href="file2">file2</a></td> <td>7K</td> <td>[text/html]</td> <td></td> </tr>""" self.assertIn(body, data)
L{static.DirectoryLister} is able to list all the files inside a directory.
test_renderFiles
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_renderDirectories(self): """ L{static.DirectoryLister} is able to list all the directories inside a directory. """ path = FilePath(self.mktemp()) path.makedirs() path.child('dir1').makedirs() path.child('dir2 & 3').makedirs() lister = static.DirectoryLister(path.path) data = lister.render(self._request(b'foo')) body = b"""<tr class="odd"> <td><a href="dir1/">dir1/</a></td> <td></td> <td>[Directory]</td> <td></td> </tr> <tr class="even"> <td><a href="dir2%20%26%203/">dir2 &amp; 3/</a></td> <td></td> <td>[Directory]</td> <td></td> </tr>""" self.assertIn(body, data)
L{static.DirectoryLister} is able to list all the directories inside a directory.
test_renderDirectories
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_renderFiltered(self): """ L{static.DirectoryLister} takes an optional C{dirs} argument that filter out the list of directories and files printed. """ path = FilePath(self.mktemp()) path.makedirs() path.child('dir1').makedirs() path.child('dir2').makedirs() path.child('dir3').makedirs() lister = static.DirectoryLister(path.path, dirs=["dir1", "dir3"]) data = lister.render(self._request(b'foo')) body = b"""<tr class="odd"> <td><a href="dir1/">dir1/</a></td> <td></td> <td>[Directory]</td> <td></td> </tr> <tr class="even"> <td><a href="dir3/">dir3/</a></td> <td></td> <td>[Directory]</td> <td></td> </tr>""" self.assertIn(body, data)
L{static.DirectoryLister} takes an optional C{dirs} argument that filter out the list of directories and files printed.
test_renderFiltered
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_oddAndEven(self): """ L{static.DirectoryLister} gives an alternate class for each odd and even rows in the table. """ lister = static.DirectoryLister(None) elements = [{"href": "", "text": "", "size": "", "type": "", "encoding": ""} for i in range(5)] content = lister._buildTableContent(elements) self.assertEqual(len(content), 5) self.assertTrue(content[0].startswith('<tr class="odd">')) self.assertTrue(content[1].startswith('<tr class="even">')) self.assertTrue(content[2].startswith('<tr class="odd">')) self.assertTrue(content[3].startswith('<tr class="even">')) self.assertTrue(content[4].startswith('<tr class="odd">'))
L{static.DirectoryLister} gives an alternate class for each odd and even rows in the table.
test_oddAndEven
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_contentType(self): """ L{static.DirectoryLister} produces a MIME-type that indicates that it is HTML, and includes its charset (UTF-8). """ path = FilePath(self.mktemp()) path.makedirs() lister = static.DirectoryLister(path.path) req = self._request(b'') lister.render(req) self.assertEqual(req.responseHeaders.getRawHeaders(b'content-type')[0], b"text/html; charset=utf-8")
L{static.DirectoryLister} produces a MIME-type that indicates that it is HTML, and includes its charset (UTF-8).
test_contentType
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_mimeTypeAndEncodings(self): """ L{static.DirectoryLister} is able to detect mimetype and encoding of listed files. """ path = FilePath(self.mktemp()) path.makedirs() path.child('file1.txt').setContent(b"file1") path.child('file2.py').setContent(b"python") path.child('file3.conf.gz').setContent(b"conf compressed") path.child('file4.diff.bz2').setContent(b"diff compressed") directory = os.listdir(path.path) directory.sort() contentTypes = { ".txt": "text/plain", ".py": "text/python", ".conf": "text/configuration", ".diff": "text/diff" } lister = static.DirectoryLister(path.path, contentTypes=contentTypes) dirs, files = lister._getFilesAndDirectories(directory) self.assertEqual(dirs, []) self.assertEqual(files, [ {'encoding': '', 'href': 'file1.txt', 'size': '5B', 'text': 'file1.txt', 'type': '[text/plain]'}, {'encoding': '', 'href': 'file2.py', 'size': '6B', 'text': 'file2.py', 'type': '[text/python]'}, {'encoding': '[gzip]', 'href': 'file3.conf.gz', 'size': '15B', 'text': 'file3.conf.gz', 'type': '[text/configuration]'}, {'encoding': '[bzip2]', 'href': 'file4.diff.bz2', 'size': '15B', 'text': 'file4.diff.bz2', 'type': '[text/diff]'}])
L{static.DirectoryLister} is able to detect mimetype and encoding of listed files.
test_mimeTypeAndEncodings
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_brokenSymlink(self): """ If on the file in the listing points to a broken symlink, it should not be returned by L{static.DirectoryLister._getFilesAndDirectories}. """ path = FilePath(self.mktemp()) path.makedirs() file1 = path.child('file1') file1.setContent(b"file1") file1.linkTo(path.child("file2")) file1.remove() lister = static.DirectoryLister(path.path) directory = os.listdir(path.path) directory.sort() dirs, files = lister._getFilesAndDirectories(directory) self.assertEqual(dirs, []) self.assertEqual(files, [])
If on the file in the listing points to a broken symlink, it should not be returned by L{static.DirectoryLister._getFilesAndDirectories}.
test_brokenSymlink
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_childrenNotFound(self): """ Any child resource of L{static.DirectoryLister} renders an HTTP I{NOT FOUND} response code. """ path = FilePath(self.mktemp()) path.makedirs() lister = static.DirectoryLister(path.path) request = self._request(b'') child = resource.getChildForRequest(lister, request) result = _render(child, request) def cbRendered(ignored): self.assertEqual(request.responseCode, http.NOT_FOUND) result.addCallback(cbRendered) return result
Any child resource of L{static.DirectoryLister} renders an HTTP I{NOT FOUND} response code.
test_childrenNotFound
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_repr(self): """ L{static.DirectoryLister.__repr__} gives the path of the lister. """ path = FilePath(self.mktemp()) lister = static.DirectoryLister(path.path) self.assertEqual(repr(lister), "<DirectoryLister of %r>" % (path.path,)) self.assertEqual(str(lister), "<DirectoryLister of %r>" % (path.path,))
L{static.DirectoryLister.__repr__} gives the path of the lister.
test_repr
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_formatFileSize(self): """ L{static.formatFileSize} format an amount of bytes into a more readable format. """ self.assertEqual(static.formatFileSize(0), "0B") self.assertEqual(static.formatFileSize(123), "123B") self.assertEqual(static.formatFileSize(4567), "4K") self.assertEqual(static.formatFileSize(8900000), "8M") self.assertEqual(static.formatFileSize(1234000000), "1G") self.assertEqual(static.formatFileSize(1234567890000), "1149G")
L{static.formatFileSize} format an amount of bytes into a more readable format.
test_formatFileSize
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def _fakeInit(self, paths): """ A mock L{mimetypes.init} that records the value of the passed C{paths} argument. @param paths: The paths that will be recorded. """ self.paths = paths
A mock L{mimetypes.init} that records the value of the passed C{paths} argument. @param paths: The paths that will be recorded.
_fakeInit
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_defaultArgumentIsNone(self): """ By default, L{None} is passed to C{mimetypes.init}. """ static.loadMimeTypes(init=self._fakeInit) self.assertIdentical(self.paths, None)
By default, L{None} is passed to C{mimetypes.init}.
test_defaultArgumentIsNone
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_extraLocationsWork(self): """ Passed MIME type files are passed to C{mimetypes.init}. """ paths = ["x", "y", "z"] static.loadMimeTypes(paths, init=self._fakeInit) self.assertIdentical(self.paths, paths)
Passed MIME type files are passed to C{mimetypes.init}.
test_extraLocationsWork
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_usesGlobalInitFunction(self): """ By default, C{mimetypes.init} is called. """ # Checking mimetypes.inited doesn't always work, because # something, somewhere, calls mimetypes.init. Yay global # mutable state :) if getattr(inspect, "signature", None): signature = inspect.signature(static.loadMimeTypes) self.assertIs(signature.parameters["init"].default, mimetypes.init) else: args, _, _, defaults = inspect.getargspec(static.loadMimeTypes) defaultInit = defaults[args.index("init")] self.assertIs(defaultInit, mimetypes.init)
By default, C{mimetypes.init} is called.
test_usesGlobalInitFunction
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_addSlashDeprecated(self): """ L{twisted.web.static.addSlash} is deprecated. """ from twisted.web.static import addSlash addSlash(DummyRequest([b''])) warnings = self.flushWarnings([self.test_addSlashDeprecated]) self.assertEqual(len(warnings), 1) self.assertEqual(warnings[0]['message'], "twisted.web.static.addSlash was deprecated in Twisted 16.0.0")
L{twisted.web.static.addSlash} is deprecated.
test_addSlashDeprecated
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_static.py
MIT
def test_constants(self): """ All constants besides C{RESPONSES} defined in L{_response} are integers and are keys in C{RESPONSES}. """ for sym in dir(_responses): if sym == 'RESPONSES': continue if all((c == '_' or c in string.ascii_uppercase) for c in sym): val = getattr(_responses, sym) self.assertIsInstance(val, int) self.assertIn(val, _responses.RESPONSES)
All constants besides C{RESPONSES} defined in L{_response} are integers and are keys in C{RESPONSES}.
test_constants
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_web__responses.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_web__responses.py
MIT
def buildPushPromiseFrame(self, streamID, promisedStreamID, headers, flags=[]): """ Builds a single Push Promise frame. """ f = hyperframe.frame.PushPromiseFrame(streamID) f.promised_stream_id = promisedStreamID f.data = self.encoder.encode(headers) f.flags = set(flags) f.flags.add('END_HEADERS') return f
Builds a single Push Promise frame.
buildPushPromiseFrame
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def buildRequestFrames(headers, data, frameFactory=None, streamID=1): """ Provides a sequence of HTTP/2 frames that encode a single HTTP request. This should be used when you want to control the serialization yourself, e.g. because you want to interleave other frames with these. If that's not necessary, prefer L{buildRequestBytes}. @param headers: The HTTP/2 headers to send. @type headers: L{list} of L{tuple} of L{bytes} @param data: The HTTP data to send. Each list entry will be sent in its own frame. @type data: L{list} of L{bytes} @param frameFactory: The L{FrameFactory} that will be used to construct the frames. @type frameFactory: L{FrameFactory} @param streamID: The ID of the stream on which to send the request. @type streamID: L{int} """ if frameFactory is None: frameFactory = FrameFactory() frames = [] frames.append( frameFactory.buildHeadersFrame(headers=headers, streamID=streamID) ) frames.extend( frameFactory.buildDataFrame(chunk, streamID=streamID) for chunk in data ) frames[-1].flags.add('END_STREAM') return frames
Provides a sequence of HTTP/2 frames that encode a single HTTP request. This should be used when you want to control the serialization yourself, e.g. because you want to interleave other frames with these. If that's not necessary, prefer L{buildRequestBytes}. @param headers: The HTTP/2 headers to send. @type headers: L{list} of L{tuple} of L{bytes} @param data: The HTTP data to send. Each list entry will be sent in its own frame. @type data: L{list} of L{bytes} @param frameFactory: The L{FrameFactory} that will be used to construct the frames. @type frameFactory: L{FrameFactory} @param streamID: The ID of the stream on which to send the request. @type streamID: L{int}
buildRequestFrames
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def buildRequestBytes(headers, data, frameFactory=None, streamID=1): """ Provides the byte sequence for a collection of HTTP/2 frames representing the provided request. @param headers: The HTTP/2 headers to send. @type headers: L{list} of L{tuple} of L{bytes} @param data: The HTTP data to send. Each list entry will be sent in its own frame. @type data: L{list} of L{bytes} @param frameFactory: The L{FrameFactory} that will be used to construct the frames. @type frameFactory: L{FrameFactory} @param streamID: The ID of the stream on which to send the request. @type streamID: L{int} """ frames = buildRequestFrames(headers, data, frameFactory, streamID) return b''.join(f.serialize() for f in frames)
Provides the byte sequence for a collection of HTTP/2 frames representing the provided request. @param headers: The HTTP/2 headers to send. @type headers: L{list} of L{tuple} of L{bytes} @param data: The HTTP data to send. Each list entry will be sent in its own frame. @type data: L{list} of L{bytes} @param frameFactory: The L{FrameFactory} that will be used to construct the frames. @type frameFactory: L{FrameFactory} @param streamID: The ID of the stream on which to send the request. @type streamID: L{int}
buildRequestBytes
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def framesFromBytes(data): """ Given a sequence of bytes, decodes them into frames. Note that this method should almost always be called only once, before making some assertions. This is because decoding HTTP/2 frames is extremely stateful, and this function doesn't preserve any of that state between calls. @param data: The serialized HTTP/2 frames. @type data: L{bytes} @returns: A list of HTTP/2 frames. @rtype: L{list} of L{hyperframe.frame.Frame} subclasses. """ buffer = FrameBuffer() buffer.receiveData(data) return list(buffer)
Given a sequence of bytes, decodes them into frames. Note that this method should almost always be called only once, before making some assertions. This is because decoding HTTP/2 frames is extremely stateful, and this function doesn't preserve any of that state between calls. @param data: The serialized HTTP/2 frames. @type data: L{bytes} @returns: A list of HTTP/2 frames. @rtype: L{list} of L{hyperframe.frame.Frame} subclasses.
framesFromBytes
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def acceptData(self): """ Start the data pipe. """ self.channel.resumeProducing()
Start the data pipe.
acceptData
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def acceptData(self): """ Start and then immediately stop the data pipe. """ self.channel.resumeProducing() self.channel.stopProducing()
Start and then immediately stop the data pipe.
acceptData
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def assertAllStreamsBlocked(self, connection): """ Confirm that all streams are blocked: that is, the priority tree believes that none of the streams have data ready to send. """ self.assertRaises(priority.DeadlockError, next, connection.priority)
Confirm that all streams are blocked: that is, the priority tree believes that none of the streams have data ready to send.
assertAllStreamsBlocked
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def connectAndReceive(self, connection, headers, body): """ Takes a single L{H2Connection} object and connects it to a L{StringTransport} using a brand new L{FrameFactory}. @param connection: The L{H2Connection} object to connect. @type connection: L{H2Connection} @param headers: The headers to send on the first request. @type headers: L{Iterable} of L{tuple} of C{(bytes, bytes)} @param body: Chunks of body to send, if any. @type body: L{Iterable} of L{bytes} @return: A tuple of L{FrameFactory}, L{StringTransport} """ frameFactory = FrameFactory() transport = StringTransport() requestBytes = frameFactory.clientConnectionPreface() requestBytes += buildRequestBytes(headers, body, frameFactory) connection.makeConnection(transport) # One byte at a time, to stress the implementation. for byte in iterbytes(requestBytes): connection.dataReceived(byte) return frameFactory, transport
Takes a single L{H2Connection} object and connects it to a L{StringTransport} using a brand new L{FrameFactory}. @param connection: The L{H2Connection} object to connect. @type connection: L{H2Connection} @param headers: The headers to send on the first request. @type headers: L{Iterable} of L{tuple} of C{(bytes, bytes)} @param body: Chunks of body to send, if any. @type body: L{Iterable} of L{bytes} @return: A tuple of L{FrameFactory}, L{StringTransport}
connectAndReceive
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_basicRequest(self): """ Send request over a TCP connection and confirm that we get back the expected data in the order and style we expect. """ # This test is complex because it validates the data very closely: it # specifically checks frame ordering and type. connection = H2Connection() connection.requestFactory = DummyHTTPHandlerProxy _, transport = self.connectAndReceive( connection, self.getRequestHeaders, [] ) def validate(streamID): frames = framesFromBytes(transport.value()) self.assertEqual(len(frames), 4) self.assertTrue(all(f.stream_id == 1 for f in frames[1:])) self.assertTrue( isinstance(frames[1], hyperframe.frame.HeadersFrame) ) self.assertTrue(isinstance(frames[2], hyperframe.frame.DataFrame)) self.assertTrue(isinstance(frames[3], hyperframe.frame.DataFrame)) self.assertEqual( dict(frames[1].data), dict(self.getResponseHeaders) ) self.assertEqual(frames[2].data, self.getResponseData) self.assertEqual(frames[3].data, b'') self.assertTrue('END_STREAM' in frames[3].flags) return connection._streamCleanupCallbacks[1].addCallback(validate)
Send request over a TCP connection and confirm that we get back the expected data in the order and style we expect.
test_basicRequest
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_postRequest(self): """ Send a POST request and confirm that the data is safely transferred. """ connection = H2Connection() connection.requestFactory = DummyHTTPHandlerProxy _, transport = self.connectAndReceive( connection, self.postRequestHeaders, self.postRequestData ) def validate(streamID): frames = framesFromBytes(transport.value()) # One Settings frame, one Headers frame and two Data frames. self.assertEqual(len(frames), 4) self.assertTrue(all(f.stream_id == 1 for f in frames[-3:])) self.assertTrue( isinstance(frames[-3], hyperframe.frame.HeadersFrame) ) self.assertTrue(isinstance(frames[-2], hyperframe.frame.DataFrame)) self.assertTrue(isinstance(frames[-1], hyperframe.frame.DataFrame)) self.assertEqual( dict(frames[-3].data), dict(self.postResponseHeaders) ) self.assertEqual(frames[-2].data, self.postResponseData) self.assertEqual(frames[-1].data, b'') self.assertTrue('END_STREAM' in frames[-1].flags) return connection._streamCleanupCallbacks[1].addCallback(validate)
Send a POST request and confirm that the data is safely transferred.
test_postRequest
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_postRequestNoLength(self): """ Send a POST request without length and confirm that the data is safely transferred. """ postResponseHeaders = [ (b':status', b'200'), (b'request', b'/post_endpoint'), (b'command', b'POST'), (b'version', b'HTTP/2'), (b'content-length', b'38'), ] postResponseData = b"'''\nNone\nhello world, it's http/2!'''\n" # Strip the content-length header. postRequestHeaders = [ (x, y) for x, y in self.postRequestHeaders if x != b'content-length' ] connection = H2Connection() connection.requestFactory = DummyHTTPHandlerProxy _, transport = self.connectAndReceive( connection, postRequestHeaders, self.postRequestData ) def validate(streamID): frames = framesFromBytes(transport.value()) # One Settings frame, one Headers frame, and two Data frames self.assertEqual(len(frames), 4) self.assertTrue(all(f.stream_id == 1 for f in frames[-3:])) self.assertTrue( isinstance(frames[-3], hyperframe.frame.HeadersFrame) ) self.assertTrue(isinstance(frames[-2], hyperframe.frame.DataFrame)) self.assertTrue(isinstance(frames[-1], hyperframe.frame.DataFrame)) self.assertEqual( dict(frames[-3].data), dict(postResponseHeaders) ) self.assertEqual(frames[-2].data, postResponseData) self.assertEqual(frames[-1].data, b'') self.assertTrue('END_STREAM' in frames[-1].flags) return connection._streamCleanupCallbacks[1].addCallback(validate)
Send a POST request without length and confirm that the data is safely transferred.
test_postRequestNoLength
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_interleavedRequests(self): """ Many interleaved POST requests all get received and responded to appropriately. """ # Unfortunately this test is pretty complex. REQUEST_COUNT = 40 f = FrameFactory() b = StringTransport() a = H2Connection() a.requestFactory = DummyHTTPHandlerProxy # Stream IDs are always odd numbers. streamIDs = list(range(1, REQUEST_COUNT * 2, 2)) frames = [ buildRequestFrames( self.postRequestHeaders, self.postRequestData, f, streamID ) for streamID in streamIDs ] requestBytes = f.clientConnectionPreface() # Interleave the frames. That is, send one frame from each stream at a # time. This wacky line lets us do that. frames = itertools.chain.from_iterable(zip(*frames)) requestBytes += b''.join(frame.serialize() for frame in frames) a.makeConnection(b) # one byte at a time, to stress the implementation. for byte in iterbytes(requestBytes): a.dataReceived(byte) def validate(results): frames = framesFromBytes(b.value()) # We expect 1 Settings frame for the connection, and then 3 frames # *per stream* (1 Headers frame, 2 Data frames). This doesn't send # enough data to trigger a window update. self.assertEqual(len(frames), 1 + (3 * 40)) # Let's check the data is ok. We need the non-WindowUpdate frames # for each stream. for streamID in streamIDs: streamFrames = [ f for f in frames if f.stream_id == streamID and not isinstance(f, hyperframe.frame.WindowUpdateFrame) ] self.assertEqual(len(streamFrames), 3) self.assertEqual( dict(streamFrames[0].data), dict(self.postResponseHeaders) ) self.assertEqual(streamFrames[1].data, self.postResponseData) self.assertEqual(streamFrames[2].data, b'') self.assertTrue('END_STREAM' in streamFrames[2].flags) return defer.DeferredList( list(a._streamCleanupCallbacks.values()) ).addCallback(validate)
Many interleaved POST requests all get received and responded to appropriately.
test_interleavedRequests
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_sendAccordingToPriority(self): """ Data in responses is interleaved according to HTTP/2 priorities. """ # We want to start three parallel GET requests that will each return # four chunks of data. These chunks will be interleaved according to # HTTP/2 priorities. Stream 1 will be set to weight 64, Stream 3 to # weight 32, and Stream 5 to weight 16 but dependent on Stream 1. # That will cause data frames for these streams to be emitted in this # order: 1, 3, 1, 1, 3, 1, 1, 3, 5, 3, 5, 3, 5, 5, 5. # # The reason there are so many frames is because the implementation # interleaves stream completion according to priority order as well, # because it is sent on a Data frame. # # This doesn't fully test priority, but tests *almost* enough of it to # be worthwhile. f = FrameFactory() b = StringTransport() a = H2Connection() a.requestFactory = ChunkedHTTPHandlerProxy getRequestHeaders = self.getRequestHeaders getRequestHeaders[2] = (':path', '/chunked/4') frames = [ buildRequestFrames(getRequestHeaders, [], f, streamID) for streamID in [1, 3, 5] ] # Set the priorities. The first two will use their HEADERS frame, the # third will have a PRIORITY frame sent before the headers. frames[0][0].flags.add('PRIORITY') frames[0][0].stream_weight = 64 frames[1][0].flags.add('PRIORITY') frames[1][0].stream_weight = 32 priorityFrame = f.buildPriorityFrame( streamID=5, weight=16, dependsOn=1, exclusive=True, ) frames[2].insert(0, priorityFrame) frames = itertools.chain.from_iterable(frames) requestBytes = f.clientConnectionPreface() requestBytes += b''.join(frame.serialize() for frame in frames) a.makeConnection(b) # one byte at a time, to stress the implementation. for byte in iterbytes(requestBytes): a.dataReceived(byte) def validate(results): frames = framesFromBytes(b.value()) # We expect 1 Settings frame for the connection, and then 6 frames # per stream (1 Headers frame, 5 data frames), for a total of 19. self.assertEqual(len(frames), 19) streamIDs = [ f.stream_id for f in frames if isinstance(f, hyperframe.frame.DataFrame) ] expectedOrder = [1, 3, 1, 1, 3, 1, 1, 3, 5, 3, 5, 3, 5, 5, 5] self.assertEqual(streamIDs, expectedOrder) return defer.DeferredList( list(a._streamCleanupCallbacks.values()) ).addCallback(validate)
Data in responses is interleaved according to HTTP/2 priorities.
test_sendAccordingToPriority
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_protocolErrorTerminatesConnection(self): """ A protocol error from the remote peer terminates the connection. """ f = FrameFactory() b = StringTransport() a = H2Connection() a.requestFactory = DummyHTTPHandlerProxy # We're going to open a stream and then send a PUSH_PROMISE frame, # which is forbidden. requestBytes = f.clientConnectionPreface() requestBytes += buildRequestBytes(self.getRequestHeaders, [], f) requestBytes += f.buildPushPromiseFrame( streamID=1, promisedStreamID=2, headers=self.getRequestHeaders, flags=['END_HEADERS'], ).serialize() a.makeConnection(b) # one byte at a time, to stress the implementation. for byte in iterbytes(requestBytes): a.dataReceived(byte) # Check whether the transport got shut down: if it did, stop # sending more data. if b.disconnecting: break frames = framesFromBytes(b.value()) # The send loop never gets to terminate the stream, but *some* data # does get sent. We get a Settings frame, a Headers frame, and then the # GoAway frame. self.assertEqual(len(frames), 3) self.assertTrue( isinstance(frames[-1], hyperframe.frame.GoAwayFrame) ) self.assertTrue(b.disconnecting)
A protocol error from the remote peer terminates the connection.
test_protocolErrorTerminatesConnection
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_streamProducingData(self): """ The H2Stream data implements IPushProducer, and can have its data production controlled by the Request if the Request chooses to. """ connection = H2Connection() connection.requestFactory = ConsumerDummyHandlerProxy _, transport = self.connectAndReceive( connection, self.postRequestHeaders, self.postRequestData ) # At this point no data should have been received by the request *or* # the response. We need to dig the request out of the tree of objects. request = connection.streams[1]._request.original self.assertFalse(request._requestReceived) # We should have only received the Settings frame. It's important that # the WindowUpdate frames don't land before data is delivered to the # Request. frames = framesFromBytes(transport.value()) self.assertEqual(len(frames), 1) # At this point, we can kick off the producing. This will force the # H2Stream object to deliver the request data all at once, so check # that it was delivered correctly. request.acceptData() self.assertTrue(request._requestReceived) self.assertTrue(request._data, b"hello world, it's http/2!") # *That* will have also caused the H2Connection object to emit almost # all the data it needs. That'll be a Headers frame, as well as the # original SETTINGS frame. frames = framesFromBytes(transport.value()) self.assertEqual(len(frames), 2) def validate(streamID): # Confirm that the response is ok. frames = framesFromBytes(transport.value()) # The only new frames here are the two Data frames. self.assertEqual(len(frames), 4) self.assertTrue('END_STREAM' in frames[-1].flags) return connection._streamCleanupCallbacks[1].addCallback(validate)
The H2Stream data implements IPushProducer, and can have its data production controlled by the Request if the Request chooses to.
test_streamProducingData
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_abortStreamProducingData(self): """ The H2Stream data implements IPushProducer, and can have its data production controlled by the Request if the Request chooses to. When the production is stopped, that causes the stream connection to be lost. """ f = FrameFactory() b = StringTransport() a = H2Connection() a.requestFactory = AbortingConsumerDummyHandlerProxy # We're going to send in a POST request. frames = buildRequestFrames( self.postRequestHeaders, self.postRequestData, f ) frames[-1].flags = set() # Remove END_STREAM flag. requestBytes = f.clientConnectionPreface() requestBytes += b''.join(f.serialize() for f in frames) a.makeConnection(b) # one byte at a time, to stress the implementation. for byte in iterbytes(requestBytes): a.dataReceived(byte) # At this point no data should have been received by the request *or* # the response. We need to dig the request out of the tree of objects. request = a.streams[1]._request.original self.assertFalse(request._requestReceived) # Save off the cleanup deferred now, it'll be removed when the # RstStream frame is sent. cleanupCallback = a._streamCleanupCallbacks[1] # At this point, we can kick off the production and immediate abort. request.acceptData() # The stream will now have been aborted. def validate(streamID): # Confirm that the response is ok. frames = framesFromBytes(b.value()) # We expect a Settings frame and a RstStream frame. self.assertEqual(len(frames), 2) self.assertTrue( isinstance(frames[-1], hyperframe.frame.RstStreamFrame) ) self.assertEqual(frames[-1].stream_id, 1) return cleanupCallback.addCallback(validate)
The H2Stream data implements IPushProducer, and can have its data production controlled by the Request if the Request chooses to. When the production is stopped, that causes the stream connection to be lost.
test_abortStreamProducingData
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_terminatedRequest(self): """ When a RstStream frame is received, the L{H2Connection} and L{H2Stream} objects tear down the L{http.Request} and swallow all outstanding writes. """ # Here we want to use the DummyProducerHandler primarily for the side # effect it has of not writing to the connection. That means we can # delay some writes until *after* the RstStream frame is received. connection = H2Connection() connection.requestFactory = DummyProducerHandlerProxy frameFactory, transport = self.connectAndReceive( connection, self.getRequestHeaders, [] ) # Get the request object. request = connection.streams[1]._request.original # Send two writes in. request.write(b"first chunk") request.write(b"second chunk") # Save off the cleanup deferred now, it'll be removed when the # RstStream frame is received. cleanupCallback = connection._streamCleanupCallbacks[1] # Now fire the RstStream frame. connection.dataReceived( frameFactory.buildRstStreamFrame(1, errorCode=1).serialize() ) # This should have cancelled the request. self.assertTrue(request._disconnected) self.assertTrue(request.channel is None) # This should not raise an exception, the function will just return # immediately, and do nothing request.write(b"third chunk") # Check that everything is fine. # We expect that only the Settings and Headers frames will have been # emitted. The two writes are lost because the delayed call never had # another chance to execute before the RstStream frame got processed. def validate(streamID): frames = framesFromBytes(transport.value()) self.assertEqual(len(frames), 2) self.assertEqual(frames[1].stream_id, 1) self.assertTrue( isinstance(frames[1], hyperframe.frame.HeadersFrame) ) return cleanupCallback.addCallback(validate)
When a RstStream frame is received, the L{H2Connection} and L{H2Stream} objects tear down the L{http.Request} and swallow all outstanding writes.
test_terminatedRequest
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_terminatedConnection(self): """ When a GoAway frame is received, the L{H2Connection} and L{H2Stream} objects tear down all outstanding L{http.Request} objects and stop all writing. """ # Here we want to use the DummyProducerHandler primarily for the side # effect it has of not writing to the connection. That means we can # delay some writes until *after* the GoAway frame is received. connection = H2Connection() connection.requestFactory = DummyProducerHandlerProxy frameFactory, transport = self.connectAndReceive( connection, self.getRequestHeaders, [] ) # Get the request object. request = connection.streams[1]._request.original # Send two writes in. request.write(b"first chunk") request.write(b"second chunk") # Save off the cleanup deferred now, it'll be removed when the # GoAway frame is received. cleanupCallback = connection._streamCleanupCallbacks[1] # Now fire the GoAway frame. connection.dataReceived( frameFactory.buildGoAwayFrame(lastStreamID=0).serialize() ) # This should have cancelled the request. self.assertTrue(request._disconnected) self.assertTrue(request.channel is None) # It should also have cancelled the sending loop. self.assertFalse(connection._stillProducing) # Check that everything is fine. # We expect that only the Settings and Headers frames will have been # emitted. The writes are lost because the callLater never had # a chance to execute before the GoAway frame got processed. def validate(streamID): frames = framesFromBytes(transport.value()) self.assertEqual(len(frames), 2) self.assertEqual(frames[1].stream_id, 1) self.assertTrue( isinstance(frames[1], hyperframe.frame.HeadersFrame) ) return cleanupCallback.addCallback(validate)
When a GoAway frame is received, the L{H2Connection} and L{H2Stream} objects tear down all outstanding L{http.Request} objects and stop all writing.
test_terminatedConnection
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_respondWith100Continue(self): """ Requests containing Expect: 100-continue cause provisional 100 responses to be emitted. """ connection = H2Connection() connection.requestFactory = DummyHTTPHandlerProxy # Add Expect: 100-continue for this request. headers = self.getRequestHeaders + [(b'expect', b'100-continue')] _, transport = self.connectAndReceive(connection, headers, []) # We expect 5 frames now: Settings, two Headers frames, and two Data # frames. We're only really interested in validating the first Headers # frame which contains the 100. def validate(streamID): frames = framesFromBytes(transport.value()) self.assertEqual(len(frames), 5) self.assertTrue(all(f.stream_id == 1 for f in frames[1:])) self.assertTrue( isinstance(frames[1], hyperframe.frame.HeadersFrame) ) self.assertEqual( frames[1].data, [(b':status', b'100')] ) self.assertTrue('END_STREAM' in frames[-1].flags) return connection._streamCleanupCallbacks[1].addCallback(validate)
Requests containing Expect: 100-continue cause provisional 100 responses to be emitted.
test_respondWith100Continue
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_respondWith400(self): """ Triggering the call to L{H2Stream._respondToBadRequestAndDisconnect} leads to a 400 error being sent automatically and the stream being torn down. """ # The only "natural" way to trigger this in the current codebase is to # send a multipart/form-data request that the cgi module doesn't like. # That's absurdly hard, so instead we'll just call it ourselves. For # this reason we use the DummyProducerHandler, which doesn't write the # headers straight away. connection = H2Connection() connection.requestFactory = DummyProducerHandlerProxy _, transport = self.connectAndReceive( connection, self.getRequestHeaders, [] ) # Grab the request and the completion callback. stream = connection.streams[1] request = stream._request.original cleanupCallback = connection._streamCleanupCallbacks[1] # Abort the stream. stream._respondToBadRequestAndDisconnect() # This should have cancelled the request. self.assertTrue(request._disconnected) self.assertTrue(request.channel is None) # We expect 2 frames Settings and the 400 Headers. def validate(streamID): frames = framesFromBytes(transport.value()) self.assertEqual(len(frames), 2) self.assertTrue( isinstance(frames[1], hyperframe.frame.HeadersFrame) ) self.assertEqual( frames[1].data, [(b':status', b'400')] ) self.assertTrue('END_STREAM' in frames[-1].flags) return cleanupCallback.addCallback(validate)
Triggering the call to L{H2Stream._respondToBadRequestAndDisconnect} leads to a 400 error being sent automatically and the stream being torn down.
test_respondWith400
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_loseH2StreamConnection(self): """ Calling L{Request.loseConnection} causes all data that has previously been sent to be flushed, and then the stream cleanly closed. """ # Here we again want to use the DummyProducerHandler because it doesn't # close the connection on its own. connection = H2Connection() connection.requestFactory = DummyProducerHandlerProxy _, transport = self.connectAndReceive( connection, self.getRequestHeaders, [] ) # Grab the request. stream = connection.streams[1] request = stream._request.original # Send in some writes. dataChunks = [b'hello', b'world', b'here', b'are', b'some', b'writes'] for chunk in dataChunks: request.write(chunk) # Now lose the connection. request.loseConnection() # Check that the data was all written out correctly and that the stream # state is cleaned up. def validate(streamID): frames = framesFromBytes(transport.value()) # Settings, Headers, 7 Data frames. self.assertEqual(len(frames), 9) self.assertTrue(all(f.stream_id == 1 for f in frames[1:])) self.assertTrue( isinstance(frames[1], hyperframe.frame.HeadersFrame) ) self.assertTrue('END_STREAM' in frames[-1].flags) receivedDataChunks = [ f.data for f in frames if isinstance(f, hyperframe.frame.DataFrame) ] self.assertEqual( receivedDataChunks, dataChunks + [b""], ) return connection._streamCleanupCallbacks[1].addCallback(validate)
Calling L{Request.loseConnection} causes all data that has previously been sent to be flushed, and then the stream cleanly closed.
test_loseH2StreamConnection
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_cannotRegisterTwoProducers(self): """ The L{H2Stream} object forbids registering two producers. """ connection = H2Connection() connection.requestFactory = DummyProducerHandlerProxy self.connectAndReceive(connection, self.getRequestHeaders, []) # Grab the request. stream = connection.streams[1] request = stream._request.original self.assertRaises(ValueError, stream.registerProducer, request, True)
The L{H2Stream} object forbids registering two producers.
test_cannotRegisterTwoProducers
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_handlesPullProducer(self): """ L{Request} objects that have registered pull producers get blocked and unblocked according to HTTP/2 flow control. """ connection = H2Connection() connection.requestFactory = DummyPullProducerHandlerProxy _, transport = self.connectAndReceive( connection, self.getRequestHeaders, [] ) # Get the producer completion deferred and ensure we call # request.finish. stream = connection.streams[1] request = stream._request.original producerComplete = request._actualProducer.result producerComplete.addCallback(lambda x: request.finish()) # Check that the sending loop sends all the appropriate data. def validate(streamID): frames = framesFromBytes(transport.value()) # Check that the stream is correctly terminated. self.assertTrue('END_STREAM' in frames[-1].flags) # Grab the data from the frames. dataChunks = [ f.data for f in frames if isinstance(f, hyperframe.frame.DataFrame) ] self.assertEqual( dataChunks, [ b"0", b"1", b"2", b"3", b"4", b"5", b"6", b"7", b"8", b"9", b"" ] ) return connection._streamCleanupCallbacks[1].addCallback(validate)
L{Request} objects that have registered pull producers get blocked and unblocked according to HTTP/2 flow control.
test_handlesPullProducer
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_isSecureWorksProperly(self): """ L{Request} objects can correctly ask isSecure on HTTP/2. """ connection = H2Connection() connection.requestFactory = DelayedHTTPHandlerProxy self.connectAndReceive(connection, self.getRequestHeaders, []) request = connection.streams[1]._request.original self.assertFalse(request.isSecure()) connection.streams[1].abortConnection()
L{Request} objects can correctly ask isSecure on HTTP/2.
test_isSecureWorksProperly
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_lateCompletionWorks(self): """ L{H2Connection} correctly unblocks when a stream is ended. """ connection = H2Connection() connection.requestFactory = DelayedHTTPHandlerProxy _, transport = self.connectAndReceive( connection, self.getRequestHeaders, [] ) # Delay a call to end request, forcing the connection to block because # it has no data to send. request = connection.streams[1]._request.original reactor.callLater(0.01, request.finish) def validateComplete(*args): frames = framesFromBytes(transport.value()) # Check that the stream is correctly terminated. self.assertEqual(len(frames), 3) self.assertTrue('END_STREAM' in frames[-1].flags) return connection._streamCleanupCallbacks[1].addCallback( validateComplete )
L{H2Connection} correctly unblocks when a stream is ended.
test_lateCompletionWorks
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_writeSequenceForChannels(self): """ L{H2Stream} objects can send a series of frames via C{writeSequence}. """ connection = H2Connection() connection.requestFactory = DelayedHTTPHandlerProxy _, transport = self.connectAndReceive( connection, self.getRequestHeaders, [] ) stream = connection.streams[1] request = stream._request.original request.setResponseCode(200) stream.writeSequence([b'Hello', b',', b'world!']) request.finish() completionDeferred = connection._streamCleanupCallbacks[1] def validate(streamID): frames = framesFromBytes(transport.value()) # Check that the stream is correctly terminated. self.assertTrue('END_STREAM' in frames[-1].flags) # Grab the data from the frames. dataChunks = [ f.data for f in frames if isinstance(f, hyperframe.frame.DataFrame) ] self.assertEqual( dataChunks, [ b"Hello", b",", b"world!", b"" ] ) return completionDeferred.addCallback(validate)
L{H2Stream} objects can send a series of frames via C{writeSequence}.
test_writeSequenceForChannels
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_delayWrites(self): """ Delaying writes from L{Request} causes the L{H2Connection} to block on sending until data is available. However, data is *not* sent if there's no room in the flow control window. """ # Here we again want to use the DummyProducerHandler because it doesn't # close the connection on its own. f = FrameFactory() b = StringTransport() a = H2Connection() a.requestFactory = DelayedHTTPHandlerProxy requestBytes = f.clientConnectionPreface() requestBytes += f.buildSettingsFrame( {h2.settings.SettingCodes.INITIAL_WINDOW_SIZE: 5} ).serialize() requestBytes += buildRequestBytes( self.getRequestHeaders, [], f ) a.makeConnection(b) # one byte at a time, to stress the implementation. for byte in iterbytes(requestBytes): a.dataReceived(byte) # Grab the request. stream = a.streams[1] request = stream._request.original # Write the first 5 bytes. request.write(b'fiver') dataChunks = [b'here', b'are', b'some', b'writes'] def write_chunks(): # Send in some writes. for chunk in dataChunks: request.write(chunk) request.finish() d = task.deferLater(reactor, 0.01, write_chunks) d.addCallback( lambda *args: a.dataReceived( f.buildWindowUpdateFrame(streamID=1, increment=50).serialize() ) ) # Check that the data was all written out correctly and that the stream # state is cleaned up. def validate(streamID): frames = framesFromBytes(b.value()) # 2 Settings, Headers, 7 Data frames. self.assertEqual(len(frames), 9) self.assertTrue(all(f.stream_id == 1 for f in frames[2:])) self.assertTrue( isinstance(frames[2], hyperframe.frame.HeadersFrame) ) self.assertTrue('END_STREAM' in frames[-1].flags) receivedDataChunks = [ f.data for f in frames if isinstance(f, hyperframe.frame.DataFrame) ] self.assertEqual( receivedDataChunks, [b"fiver"] + dataChunks + [b""], ) return a._streamCleanupCallbacks[1].addCallback(validate)
Delaying writes from L{Request} causes the L{H2Connection} to block on sending until data is available. However, data is *not* sent if there's no room in the flow control window.
test_delayWrites
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_resetAfterBody(self): """ A client that immediately resets after sending the body causes Twisted to send no response. """ frameFactory = FrameFactory() transport = StringTransport() a = H2Connection() a.requestFactory = DummyHTTPHandlerProxy requestBytes = frameFactory.clientConnectionPreface() requestBytes += buildRequestBytes( headers=self.getRequestHeaders, data=[], frameFactory=frameFactory ) requestBytes += frameFactory.buildRstStreamFrame( streamID=1 ).serialize() a.makeConnection(transport) a.dataReceived(requestBytes) frames = framesFromBytes(transport.value()) self.assertEqual(len(frames), 1) self.assertNotIn(1, a._streamCleanupCallbacks)
A client that immediately resets after sending the body causes Twisted to send no response.
test_resetAfterBody
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_RequestRequiringFactorySiteInConstructor(self): """ A custom L{Request} subclass that requires the site and factory in the constructor is able to get them. """ d = defer.Deferred() class SuperRequest(DummyHTTPHandler): def __init__(self, *args, **kwargs): DummyHTTPHandler.__init__(self, *args, **kwargs) d.callback((self.channel.site, self.channel.factory)) connection = H2Connection() httpFactory = http.HTTPFactory() connection.requestFactory = _makeRequestProxyFactory(SuperRequest) # Create some sentinels to look for. connection.factory = httpFactory connection.site = object() self.connectAndReceive(connection, self.getRequestHeaders, []) def validateFactoryAndSite(args): site, factory = args self.assertIs(site, connection.site) self.assertIs(factory, connection.factory) d.addCallback(validateFactoryAndSite) # We need to wait for the stream cleanup callback to drain the # response. cleanupCallback = connection._streamCleanupCallbacks[1] return defer.gatherResults([d, cleanupCallback])
A custom L{Request} subclass that requires the site and factory in the constructor is able to get them.
test_RequestRequiringFactorySiteInConstructor
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_notifyOnCompleteRequest(self): """ A request sent to a HTTP/2 connection fires the L{http.Request.notifyFinish} callback with a L{None} value. """ connection = H2Connection() connection.requestFactory = NotifyingRequestFactory(DummyHTTPHandler) _, transport = self.connectAndReceive( connection, self.getRequestHeaders, [] ) deferreds = connection.requestFactory.results self.assertEqual(len(deferreds), 1) def validate(result): self.assertIsNone(result) d = deferreds[0] d.addCallback(validate) # We need to wait for the stream cleanup callback to drain the # response. cleanupCallback = connection._streamCleanupCallbacks[1] return defer.gatherResults([d, cleanupCallback])
A request sent to a HTTP/2 connection fires the L{http.Request.notifyFinish} callback with a L{None} value.
test_notifyOnCompleteRequest
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_notifyOnResetStream(self): """ A HTTP/2 reset stream fires the L{http.Request.notifyFinish} deferred with L{ConnectionLost}. """ connection = H2Connection() connection.requestFactory = NotifyingRequestFactory(DelayedHTTPHandler) frameFactory, transport = self.connectAndReceive( connection, self.getRequestHeaders, [] ) deferreds = connection.requestFactory.results self.assertEqual(len(deferreds), 1) # We need this to errback with a Failure indicating the RSTSTREAM # frame. def callback(ign): self.fail("Didn't errback, called back instead") def errback(reason): self.assertIsInstance(reason, failure.Failure) self.assertIs(reason.type, error.ConnectionLost) return None # Trap the error d = deferreds[0] d.addCallbacks(callback, errback) # Now send the RSTSTREAM frame. invalidData = frameFactory.buildRstStreamFrame(streamID=1).serialize() connection.dataReceived(invalidData) return d
A HTTP/2 reset stream fires the L{http.Request.notifyFinish} deferred with L{ConnectionLost}.
test_notifyOnResetStream
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_failWithProtocolError(self): """ A HTTP/2 protocol error triggers the L{http.Request.notifyFinish} deferred for all outstanding requests with a Failure that contains the underlying exception. """ # We need to set up two requests concurrently so that we can validate # that these all fail. connectAndReceive will set up one: we will need # to manually send the rest. connection = H2Connection() connection.requestFactory = NotifyingRequestFactory(DelayedHTTPHandler) frameFactory, transport = self.connectAndReceive( connection, self.getRequestHeaders, [] ) secondRequest = buildRequestBytes( self.getRequestHeaders, [], frameFactory=frameFactory, streamID=3 ) connection.dataReceived(secondRequest) # Now we want to grab the deferreds from the notifying factory. deferreds = connection.requestFactory.results self.assertEqual(len(deferreds), 2) # We need these to errback with a Failure representing the # ProtocolError. def callback(ign): self.fail("Didn't errback, called back instead") def errback(reason): self.assertIsInstance(reason, failure.Failure) self.assertIsInstance(reason.value, h2.exceptions.ProtocolError) return None # Trap the error for d in deferreds: d.addCallbacks(callback, errback) # Now trigger the protocol error. The easiest protocol error to trigger # is to send a data frame for a non-existent stream. invalidData = frameFactory.buildDataFrame( data=b'yo', streamID=0xF0 ).serialize() connection.dataReceived(invalidData) return defer.gatherResults(deferreds)
A HTTP/2 protocol error triggers the L{http.Request.notifyFinish} deferred for all outstanding requests with a Failure that contains the underlying exception.
test_failWithProtocolError
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_failOnGoaway(self): """ A HTTP/2 GoAway triggers the L{http.Request.notifyFinish} deferred for all outstanding requests with a Failure that contains a RemoteGoAway error. """ # We need to set up two requests concurrently so that we can validate # that these all fail. connectAndReceive will set up one: we will need # to manually send the rest. connection = H2Connection() connection.requestFactory = NotifyingRequestFactory(DelayedHTTPHandler) frameFactory, transport = self.connectAndReceive( connection, self.getRequestHeaders, [] ) secondRequest = buildRequestBytes( self.getRequestHeaders, [], frameFactory=frameFactory, streamID=3 ) connection.dataReceived(secondRequest) # Now we want to grab the deferreds from the notifying factory. deferreds = connection.requestFactory.results self.assertEqual(len(deferreds), 2) # We need these to errback with a Failure indicating the GOAWAY frame. def callback(ign): self.fail("Didn't errback, called back instead") def errback(reason): self.assertIsInstance(reason, failure.Failure) self.assertIs(reason.type, error.ConnectionLost) return None # Trap the error for d in deferreds: d.addCallbacks(callback, errback) # Now send the GoAway frame. invalidData = frameFactory.buildGoAwayFrame(lastStreamID=3).serialize() connection.dataReceived(invalidData) return defer.gatherResults(deferreds)
A HTTP/2 GoAway triggers the L{http.Request.notifyFinish} deferred for all outstanding requests with a Failure that contains a RemoteGoAway error.
test_failOnGoaway
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_failOnStopProducing(self): """ The transport telling the HTTP/2 connection to stop producing will fire all L{http.Request.notifyFinish} errbacks with L{error.} """ # We need to set up two requests concurrently so that we can validate # that these all fail. connectAndReceive will set up one: we will need # to manually send the rest. connection = H2Connection() connection.requestFactory = NotifyingRequestFactory(DelayedHTTPHandler) frameFactory, transport = self.connectAndReceive( connection, self.getRequestHeaders, [] ) secondRequest = buildRequestBytes( self.getRequestHeaders, [], frameFactory=frameFactory, streamID=3 ) connection.dataReceived(secondRequest) # Now we want to grab the deferreds from the notifying factory. deferreds = connection.requestFactory.results self.assertEqual(len(deferreds), 2) # We need these to errback with a Failure indicating the consumer # aborted our data production. def callback(ign): self.fail("Didn't errback, called back instead") def errback(reason): self.assertIsInstance(reason, failure.Failure) self.assertIs(reason.type, error.ConnectionLost) return None # Trap the error for d in deferreds: d.addCallbacks(callback, errback) # Now call stopProducing. connection.stopProducing() return defer.gatherResults(deferreds)
The transport telling the HTTP/2 connection to stop producing will fire all L{http.Request.notifyFinish} errbacks with L{error.}
test_failOnStopProducing
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_notifyOnFast400(self): """ A HTTP/2 stream that has had _respondToBadRequestAndDisconnect called on it from a request handler calls the L{http.Request.notifyFinish} errback with L{ConnectionLost}. """ connection = H2Connection() connection.requestFactory = NotifyingRequestFactory(DelayedHTTPHandler) frameFactory, transport = self.connectAndReceive( connection, self.getRequestHeaders, [] ) deferreds = connection.requestFactory.results self.assertEqual(len(deferreds), 1) # We need this to errback with a Failure indicating the loss of the # connection. def callback(ign): self.fail("Didn't errback, called back instead") def errback(reason): self.assertIsInstance(reason, failure.Failure) self.assertIs(reason.type, error.ConnectionLost) return None # Trap the error d = deferreds[0] d.addCallbacks(callback, errback) # Abort the stream. The only "natural" way to trigger this in the # current codebase is to send a multipart/form-data request that the # cgi module doesn't like. # That's absurdly hard, so instead we'll just call it ourselves. For # this reason we use the DummyProducerHandler, which doesn't write the # headers straight away. stream = connection.streams[1] stream._respondToBadRequestAndDisconnect() return d
A HTTP/2 stream that has had _respondToBadRequestAndDisconnect called on it from a request handler calls the L{http.Request.notifyFinish} errback with L{ConnectionLost}.
test_notifyOnFast400
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_bufferExcessData(self): """ When a L{Request} object is not using C{IProducer} to generate data and so is not having backpressure exerted on it, the L{H2Stream} object will buffer data until the flow control window is opened. """ f = FrameFactory() b = StringTransport() a = H2Connection() a.requestFactory = DummyHTTPHandlerProxy # Shrink the window to 5 bytes, then send the request. requestBytes = f.clientConnectionPreface() requestBytes += f.buildSettingsFrame( {h2.settings.SettingCodes.INITIAL_WINDOW_SIZE: 5} ).serialize() requestBytes += buildRequestBytes( self.getRequestHeaders, [], f ) a.makeConnection(b) # one byte at a time, to stress the implementation. for byte in iterbytes(requestBytes): a.dataReceived(byte) # Send in WindowUpdate frames that open the window one byte at a time, # to repeatedly temporarily unbuffer data. 5 bytes will have already # been sent. bonusFrames = len(self.getResponseData) - 5 for _ in range(bonusFrames): frame = f.buildWindowUpdateFrame(streamID=1, increment=1) a.dataReceived(frame.serialize()) # Give the sending loop a chance to catch up! def validate(streamID): frames = framesFromBytes(b.value()) # Check that the stream is correctly terminated. self.assertTrue('END_STREAM' in frames[-1].flags) # Put the Data frames together to confirm we're all good. actualResponseData = b''.join( f.data for f in frames if isinstance(f, hyperframe.frame.DataFrame) ) self.assertEqual(self.getResponseData, actualResponseData) return a._streamCleanupCallbacks[1].addCallback(validate)
When a L{Request} object is not using C{IProducer} to generate data and so is not having backpressure exerted on it, the L{H2Stream} object will buffer data until the flow control window is opened.
test_bufferExcessData
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_producerBlockingUnblocking(self): """ L{Request} objects that have registered producers get blocked and unblocked according to HTTP/2 flow control. """ f = FrameFactory() b = StringTransport() a = H2Connection() a.requestFactory = DummyProducerHandlerProxy # Shrink the window to 5 bytes, then send the request. requestBytes = f.clientConnectionPreface() requestBytes += f.buildSettingsFrame( {h2.settings.SettingCodes.INITIAL_WINDOW_SIZE: 5} ).serialize() requestBytes += buildRequestBytes( self.getRequestHeaders, [], f ) a.makeConnection(b) # one byte at a time, to stress the implementation. for byte in iterbytes(requestBytes): a.dataReceived(byte) # Grab the request object. stream = a.streams[1] request = stream._request.original # Confirm that the stream believes the producer is producing. self.assertTrue(stream._producerProducing) # Write 10 bytes to the connection. request.write(b"helloworld") # The producer should have been paused. self.assertFalse(stream._producerProducing) self.assertEqual(request.producer.events, ['pause']) # Open the flow control window by 5 bytes. This should not unpause the # producer. a.dataReceived( f.buildWindowUpdateFrame(streamID=1, increment=5).serialize() ) self.assertFalse(stream._producerProducing) self.assertEqual(request.producer.events, ['pause']) # Open the connection window by 5 bytes as well. This should also not # unpause the producer. a.dataReceived( f.buildWindowUpdateFrame(streamID=0, increment=5).serialize() ) self.assertFalse(stream._producerProducing) self.assertEqual(request.producer.events, ['pause']) # Open it by five more bytes. This should unpause the producer. a.dataReceived( f.buildWindowUpdateFrame(streamID=1, increment=5).serialize() ) self.assertTrue(stream._producerProducing) self.assertEqual(request.producer.events, ['pause', 'resume']) # Write another 10 bytes, which should force us to pause again. When # written this chunk will be sent as one lot, simply because of the # fact that the sending loop is not currently running. request.write(b"helloworld") self.assertFalse(stream._producerProducing) self.assertEqual(request.producer.events, ['pause', 'resume', 'pause']) # Open the window wide and then complete the request. a.dataReceived( f.buildWindowUpdateFrame(streamID=1, increment=50).serialize() ) self.assertTrue(stream._producerProducing) self.assertEqual( request.producer.events, ['pause', 'resume', 'pause', 'resume'] ) request.unregisterProducer() request.finish() # Check that the sending loop sends all the appropriate data. def validate(streamID): frames = framesFromBytes(b.value()) # Check that the stream is correctly terminated. self.assertTrue('END_STREAM' in frames[-1].flags) # Grab the data from the frames. dataChunks = [ f.data for f in frames if isinstance(f, hyperframe.frame.DataFrame) ] self.assertEqual( dataChunks, [b"helloworld", b"helloworld", b""] ) return a._streamCleanupCallbacks[1].addCallback(validate)
L{Request} objects that have registered producers get blocked and unblocked according to HTTP/2 flow control.
test_producerBlockingUnblocking
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_flowControlExact(self): """ Exactly filling the flow control window still blocks producers. """ f = FrameFactory() b = StringTransport() a = H2Connection() a.requestFactory = DummyProducerHandlerProxy # Shrink the window to 5 bytes, then send the request. requestBytes = f.clientConnectionPreface() requestBytes += f.buildSettingsFrame( {h2.settings.SettingCodes.INITIAL_WINDOW_SIZE: 5} ).serialize() requestBytes += buildRequestBytes( self.getRequestHeaders, [], f ) a.makeConnection(b) # one byte at a time, to stress the implementation. for byte in iterbytes(requestBytes): a.dataReceived(byte) # Grab the request object. stream = a.streams[1] request = stream._request.original # Confirm that the stream believes the producer is producing. self.assertTrue(stream._producerProducing) # Write 10 bytes to the connection. This should block the producer # immediately. request.write(b"helloworld") self.assertFalse(stream._producerProducing) self.assertEqual(request.producer.events, ['pause']) # Despite the producer being blocked, write one more byte. This should # not get sent or force any other data to be sent. request.write(b"h") # Open the window wide and then complete the request. We do this by # means of callLater to ensure that the sending loop has time to run. def window_open(): a.dataReceived( f.buildWindowUpdateFrame(streamID=1, increment=50).serialize() ) self.assertTrue(stream._producerProducing) self.assertEqual( request.producer.events, ['pause', 'resume'] ) request.unregisterProducer() request.finish() windowDefer = task.deferLater(reactor, 0, window_open) # Check that the sending loop sends all the appropriate data. def validate(streamID): frames = framesFromBytes(b.value()) # Check that the stream is correctly terminated. self.assertTrue('END_STREAM' in frames[-1].flags) # Grab the data from the frames. dataChunks = [ f.data for f in frames if isinstance(f, hyperframe.frame.DataFrame) ] self.assertEqual(dataChunks, [b"hello", b"world", b"h", b""]) validateDefer = a._streamCleanupCallbacks[1].addCallback(validate) return defer.DeferredList([windowDefer, validateDefer])
Exactly filling the flow control window still blocks producers.
test_flowControlExact
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_endingBlockedStream(self): """ L{Request} objects that end a stream that is currently blocked behind flow control can still end the stream and get cleaned up. """ f = FrameFactory() b = StringTransport() a = H2Connection() a.requestFactory = DummyProducerHandlerProxy # Shrink the window to 5 bytes, then send the request. requestBytes = f.clientConnectionPreface() requestBytes += f.buildSettingsFrame( {h2.settings.SettingCodes.INITIAL_WINDOW_SIZE: 5} ).serialize() requestBytes += buildRequestBytes( self.getRequestHeaders, [], f ) a.makeConnection(b) # one byte at a time, to stress the implementation. for byte in iterbytes(requestBytes): a.dataReceived(byte) # Grab the request object. stream = a.streams[1] request = stream._request.original # Confirm that the stream believes the producer is producing. self.assertTrue(stream._producerProducing) # Write 10 bytes to the connection, then complete the connection. request.write(b"helloworld") request.unregisterProducer() request.finish() # This should have completed the request. self.assertTrue(request.finished) # Open the window wide and then complete the request. reactor.callLater( 0, a.dataReceived, f.buildWindowUpdateFrame(streamID=1, increment=50).serialize() ) # Check that the sending loop sends all the appropriate data. def validate(streamID): frames = framesFromBytes(b.value()) # Check that the stream is correctly terminated. self.assertTrue('END_STREAM' in frames[-1].flags) # Grab the data from the frames. dataChunks = [ f.data for f in frames if isinstance(f, hyperframe.frame.DataFrame) ] self.assertEqual( dataChunks, [b"hello", b"world", b""] ) return a._streamCleanupCallbacks[1].addCallback(validate)
L{Request} objects that end a stream that is currently blocked behind flow control can still end the stream and get cleaned up.
test_endingBlockedStream
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_responseWithoutBody(self): """ We safely handle responses without bodies. """ f = FrameFactory() b = StringTransport() a = H2Connection() # We use the DummyProducerHandler just because we can guarantee that it # doesn't end up with a body. a.requestFactory = DummyProducerHandlerProxy # Send the request. requestBytes = f.clientConnectionPreface() requestBytes += buildRequestBytes( self.getRequestHeaders, [], f ) a.makeConnection(b) # one byte at a time, to stress the implementation. for byte in iterbytes(requestBytes): a.dataReceived(byte) # Grab the request object and the stream completion callback. stream = a.streams[1] request = stream._request.original cleanupCallback = a._streamCleanupCallbacks[1] # Complete the connection immediately. request.unregisterProducer() request.finish() # This should have completed the request. self.assertTrue(request.finished) # Check that the sending loop sends all the appropriate data. def validate(streamID): frames = framesFromBytes(b.value()) self.assertEqual(len(frames), 3) # Check that the stream is correctly terminated. self.assertTrue('END_STREAM' in frames[-1].flags) # Grab the data from the frames. dataChunks = [ f.data for f in frames if isinstance(f, hyperframe.frame.DataFrame) ] self.assertEqual( dataChunks, [b""], ) return cleanupCallback.addCallback(validate)
We safely handle responses without bodies.
test_responseWithoutBody
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_windowUpdateForCompleteStream(self): """ WindowUpdate frames received after we've completed the stream are safely handled. """ # To test this with the data sending loop working the way it does, we # need to send *no* body on the response. That's unusual, but fine. f = FrameFactory() b = StringTransport() a = H2Connection() # We use the DummyProducerHandler just because we can guarantee that it # doesn't end up with a body. a.requestFactory = DummyProducerHandlerProxy # Send the request. requestBytes = f.clientConnectionPreface() requestBytes += buildRequestBytes( self.getRequestHeaders, [], f ) a.makeConnection(b) # one byte at a time, to stress the implementation. for byte in iterbytes(requestBytes): a.dataReceived(byte) # Grab the request object and the stream completion callback. stream = a.streams[1] request = stream._request.original cleanupCallback = a._streamCleanupCallbacks[1] # Complete the connection immediately. request.unregisterProducer() request.finish() # This should have completed the request. self.assertTrue(request.finished) # Now open the flow control window a bit. This should cause no # problems. a.dataReceived( f.buildWindowUpdateFrame(streamID=1, increment=50).serialize() ) # Check that the sending loop sends all the appropriate data. def validate(streamID): frames = framesFromBytes(b.value()) self.assertEqual(len(frames), 3) # Check that the stream is correctly terminated. self.assertTrue('END_STREAM' in frames[-1].flags) # Grab the data from the frames. dataChunks = [ f.data for f in frames if isinstance(f, hyperframe.frame.DataFrame) ] self.assertEqual( dataChunks, [b""], ) return cleanupCallback.addCallback(validate)
WindowUpdate frames received after we've completed the stream are safely handled.
test_windowUpdateForCompleteStream
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_producerUnblocked(self): """ L{Request} objects that have registered producers that are not blocked behind flow control do not have their producer notified. """ f = FrameFactory() b = StringTransport() a = H2Connection() a.requestFactory = DummyProducerHandlerProxy # Shrink the window to 5 bytes, then send the request. requestBytes = f.clientConnectionPreface() requestBytes += f.buildSettingsFrame( {h2.settings.SettingCodes.INITIAL_WINDOW_SIZE: 5} ).serialize() requestBytes += buildRequestBytes( self.getRequestHeaders, [], f ) a.makeConnection(b) # one byte at a time, to stress the implementation. for byte in iterbytes(requestBytes): a.dataReceived(byte) # Grab the request object. stream = a.streams[1] request = stream._request.original # Confirm that the stream believes the producer is producing. self.assertTrue(stream._producerProducing) # Write 4 bytes to the connection, leaving space in the window. request.write(b"word") # The producer should not have been paused. self.assertTrue(stream._producerProducing) self.assertEqual(request.producer.events, []) # Open the flow control window by 5 bytes. This should not notify the # producer. a.dataReceived( f.buildWindowUpdateFrame(streamID=1, increment=5).serialize() ) self.assertTrue(stream._producerProducing) self.assertEqual(request.producer.events, []) # Open the window wide complete the request. request.unregisterProducer() request.finish() # Check that the sending loop sends all the appropriate data. def validate(streamID): frames = framesFromBytes(b.value()) # Check that the stream is correctly terminated. self.assertTrue('END_STREAM' in frames[-1].flags) # Grab the data from the frames. dataChunks = [ f.data for f in frames if isinstance(f, hyperframe.frame.DataFrame) ] self.assertEqual( dataChunks, [b"word", b""] ) return a._streamCleanupCallbacks[1].addCallback(validate)
L{Request} objects that have registered producers that are not blocked behind flow control do not have their producer notified.
test_producerUnblocked
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT
def test_unnecessaryWindowUpdate(self): """ When a WindowUpdate frame is received for the whole connection but no data is currently waiting, nothing exciting happens. """ f = FrameFactory() b = StringTransport() a = H2Connection() a.requestFactory = DummyHTTPHandlerProxy # Send the request. frames = buildRequestFrames( self.postRequestHeaders, self.postRequestData, f ) frames.insert(1, f.buildWindowUpdateFrame(streamID=0, increment=5)) requestBytes = f.clientConnectionPreface() requestBytes += b''.join(f.serialize() for f in frames) a.makeConnection(b) # one byte at a time, to stress the implementation. for byte in iterbytes(requestBytes): a.dataReceived(byte) # Give the sending loop a chance to catch up! def validate(streamID): frames = framesFromBytes(b.value()) # Check that the stream is correctly terminated. self.assertTrue('END_STREAM' in frames[-1].flags) # Put the Data frames together to confirm we're all good. actualResponseData = b''.join( f.data for f in frames if isinstance(f, hyperframe.frame.DataFrame) ) self.assertEqual(self.postResponseData, actualResponseData) return a._streamCleanupCallbacks[1].addCallback(validate)
When a WindowUpdate frame is received for the whole connection but no data is currently waiting, nothing exciting happens.
test_unnecessaryWindowUpdate
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http2.py
MIT