body
stringlengths 26
98.2k
| body_hash
int64 -9,222,864,604,528,158,000
9,221,803,474B
| docstring
stringlengths 1
16.8k
| path
stringlengths 5
230
| name
stringlengths 1
96
| repository_name
stringlengths 7
89
| lang
stringclasses 1
value | body_without_docstring
stringlengths 20
98.2k
|
|---|---|---|---|---|---|---|---|
def test_staticFileDeletedRender(self):
'\n A L{static.File} created for a file which does not exist should render\n its C{childNotFound} page.\n '
staticFile = static.File(self.mktemp())
request = DummyRequest([b'foo.bar'])
request2 = DummyRequest([b'foo.bar'])
d = self._render(staticFile, request)
d2 = self._render(staticFile.childNotFound, request2)
def cbRendered2(ignored):
def cbRendered(ignored):
self.assertEqual(b''.join(request.written), b''.join(request2.written))
d.addCallback(cbRendered)
return d
d2.addCallback(cbRendered2)
return d2
| 8,260,486,273,914,841,000
|
A L{static.File} created for a file which does not exist should render
its C{childNotFound} page.
|
src/twisted/web/test/test_static.py
|
test_staticFileDeletedRender
|
ikingye/twisted
|
python
|
def test_staticFileDeletedRender(self):
'\n A L{static.File} created for a file which does not exist should render\n its C{childNotFound} page.\n '
staticFile = static.File(self.mktemp())
request = DummyRequest([b'foo.bar'])
request2 = DummyRequest([b'foo.bar'])
d = self._render(staticFile, request)
d2 = self._render(staticFile.childNotFound, request2)
def cbRendered2(ignored):
def cbRendered(ignored):
self.assertEqual(b.join(request.written), b.join(request2.written))
d.addCallback(cbRendered)
return d
d2.addCallback(cbRendered2)
return d2
|
def test_getChildChildNotFound_customize(self):
'\n The resource rendered for child not found requests can be customize\n using a class member.\n '
base = FilePath(self.mktemp())
base.setContent(b'')
markerResponse = b'custom-child-not-found-response'
class CustomChildNotFoundResource(resource.Resource):
def render(self, request):
return markerResponse
class CustomStaticFile(static.File):
childNotFound = CustomChildNotFoundResource()
fileResource = CustomStaticFile(base.path)
request = DummyRequest([b'no-child.txt'])
child = fileResource.getChild(b'no-child.txt', request)
result = child.render(request)
self.assertEqual(markerResponse, result)
| 1,055,853,270,083,509,200
|
The resource rendered for child not found requests can be customize
using a class member.
|
src/twisted/web/test/test_static.py
|
test_getChildChildNotFound_customize
|
ikingye/twisted
|
python
|
def test_getChildChildNotFound_customize(self):
'\n The resource rendered for child not found requests can be customize\n using a class member.\n '
base = FilePath(self.mktemp())
base.setContent(b)
markerResponse = b'custom-child-not-found-response'
class CustomChildNotFoundResource(resource.Resource):
def render(self, request):
return markerResponse
class CustomStaticFile(static.File):
childNotFound = CustomChildNotFoundResource()
fileResource = CustomStaticFile(base.path)
request = DummyRequest([b'no-child.txt'])
child = fileResource.getChild(b'no-child.txt', request)
result = child.render(request)
self.assertEqual(markerResponse, result)
|
def test_headRequest(self):
'\n L{static.File.render} returns an empty response body for I{HEAD}\n requests.\n '
path = FilePath(self.mktemp())
path.setContent(b'foo')
file = static.File(path.path)
request = DummyRequest([b''])
request.method = b'HEAD'
d = _render(file, request)
def cbRendered(ignored):
self.assertEqual(b''.join(request.written), b'')
d.addCallback(cbRendered)
return d
| 5,967,143,477,312,165,000
|
L{static.File.render} returns an empty response body for I{HEAD}
requests.
|
src/twisted/web/test/test_static.py
|
test_headRequest
|
ikingye/twisted
|
python
|
def test_headRequest(self):
'\n L{static.File.render} returns an empty response body for I{HEAD}\n requests.\n '
path = FilePath(self.mktemp())
path.setContent(b'foo')
file = static.File(path.path)
request = DummyRequest([b])
request.method = b'HEAD'
d = _render(file, request)
def cbRendered(ignored):
self.assertEqual(b.join(request.written), b)
d.addCallback(cbRendered)
return d
|
def test_processors(self):
"\n If a request is made which encounters a L{File} before a final segment\n which names a file with an extension which is in the L{File}'s\n C{processors} mapping, the processor associated with that extension is\n used to serve the response to the request.\n "
base = FilePath(self.mktemp())
base.makedirs()
base.child('foo.bar').setContent(b"from twisted.web.static import Data\nresource = Data(b'dynamic world', 'text/plain')\n")
file = static.File(base.path)
file.processors = {'.bar': script.ResourceScript}
request = DummyRequest([b'foo.bar'])
child = resource.getChildForRequest(file, request)
d = self._render(child, request)
def cbRendered(ignored):
self.assertEqual(b''.join(request.written), b'dynamic world')
self.assertEqual(request.responseHeaders.getRawHeaders(b'content-length')[0], b'13')
d.addCallback(cbRendered)
return d
| 4,341,430,319,151,045,000
|
If a request is made which encounters a L{File} before a final segment
which names a file with an extension which is in the L{File}'s
C{processors} mapping, the processor associated with that extension is
used to serve the response to the request.
|
src/twisted/web/test/test_static.py
|
test_processors
|
ikingye/twisted
|
python
|
def test_processors(self):
"\n If a request is made which encounters a L{File} before a final segment\n which names a file with an extension which is in the L{File}'s\n C{processors} mapping, the processor associated with that extension is\n used to serve the response to the request.\n "
base = FilePath(self.mktemp())
base.makedirs()
base.child('foo.bar').setContent(b"from twisted.web.static import Data\nresource = Data(b'dynamic world', 'text/plain')\n")
file = static.File(base.path)
file.processors = {'.bar': script.ResourceScript}
request = DummyRequest([b'foo.bar'])
child = resource.getChildForRequest(file, request)
d = self._render(child, request)
def cbRendered(ignored):
self.assertEqual(b.join(request.written), b'dynamic world')
self.assertEqual(request.responseHeaders.getRawHeaders(b'content-length')[0], b'13')
d.addCallback(cbRendered)
return d
|
def test_ignoreExt(self):
'\n The list of ignored extensions can be set by passing a value to\n L{File.__init__} or by calling L{File.ignoreExt} later.\n '
file = static.File(b'.')
self.assertEqual(file.ignoredExts, [])
file.ignoreExt('.foo')
file.ignoreExt('.bar')
self.assertEqual(file.ignoredExts, ['.foo', '.bar'])
file = static.File(b'.', ignoredExts=('.bar', '.baz'))
self.assertEqual(file.ignoredExts, ['.bar', '.baz'])
| -5,866,982,633,577,418,000
|
The list of ignored extensions can be set by passing a value to
L{File.__init__} or by calling L{File.ignoreExt} later.
|
src/twisted/web/test/test_static.py
|
test_ignoreExt
|
ikingye/twisted
|
python
|
def test_ignoreExt(self):
'\n The list of ignored extensions can be set by passing a value to\n L{File.__init__} or by calling L{File.ignoreExt} later.\n '
file = static.File(b'.')
self.assertEqual(file.ignoredExts, [])
file.ignoreExt('.foo')
file.ignoreExt('.bar')
self.assertEqual(file.ignoredExts, ['.foo', '.bar'])
file = static.File(b'.', ignoredExts=('.bar', '.baz'))
self.assertEqual(file.ignoredExts, ['.bar', '.baz'])
|
def test_ignoredExtensionsIgnored(self):
'\n A request for the I{base} child of a L{File} succeeds with a resource\n for the I{base<extension>} file in the path the L{File} was created\n with if such a file exists and the L{File} has been configured to\n ignore the I{<extension>} extension.\n '
base = FilePath(self.mktemp())
base.makedirs()
base.child('foo.bar').setContent(b'baz')
base.child('foo.quux').setContent(b'foobar')
file = static.File(base.path, ignoredExts=('.bar',))
request = DummyRequest([b'foo'])
child = resource.getChildForRequest(file, request)
d = self._render(child, request)
def cbRendered(ignored):
self.assertEqual(b''.join(request.written), b'baz')
d.addCallback(cbRendered)
return d
| -6,533,175,686,496,309,000
|
A request for the I{base} child of a L{File} succeeds with a resource
for the I{base<extension>} file in the path the L{File} was created
with if such a file exists and the L{File} has been configured to
ignore the I{<extension>} extension.
|
src/twisted/web/test/test_static.py
|
test_ignoredExtensionsIgnored
|
ikingye/twisted
|
python
|
def test_ignoredExtensionsIgnored(self):
'\n A request for the I{base} child of a L{File} succeeds with a resource\n for the I{base<extension>} file in the path the L{File} was created\n with if such a file exists and the L{File} has been configured to\n ignore the I{<extension>} extension.\n '
base = FilePath(self.mktemp())
base.makedirs()
base.child('foo.bar').setContent(b'baz')
base.child('foo.quux').setContent(b'foobar')
file = static.File(base.path, ignoredExts=('.bar',))
request = DummyRequest([b'foo'])
child = resource.getChildForRequest(file, request)
d = self._render(child, request)
def cbRendered(ignored):
self.assertEqual(b.join(request.written), b'baz')
d.addCallback(cbRendered)
return d
|
def test_directoryWithoutTrailingSlashRedirects(self):
'\n A request for a path which is a directory but does not have a trailing\n slash will be redirected to a URL which does have a slash by L{File}.\n '
base = FilePath(self.mktemp())
base.makedirs()
base.child('folder').makedirs()
file = static.File(base.path)
request = DummyRequest([b'folder'])
request.uri = b'http://dummy/folder#baz?foo=bar'
child = resource.getChildForRequest(file, request)
self.successResultOf(self._render(child, request))
self.assertEqual(request.responseCode, FOUND)
self.assertEqual(request.responseHeaders.getRawHeaders(b'location'), [b'http://dummy/folder/#baz?foo=bar'])
| 8,908,418,672,911,384,000
|
A request for a path which is a directory but does not have a trailing
slash will be redirected to a URL which does have a slash by L{File}.
|
src/twisted/web/test/test_static.py
|
test_directoryWithoutTrailingSlashRedirects
|
ikingye/twisted
|
python
|
def test_directoryWithoutTrailingSlashRedirects(self):
'\n A request for a path which is a directory but does not have a trailing\n slash will be redirected to a URL which does have a slash by L{File}.\n '
base = FilePath(self.mktemp())
base.makedirs()
base.child('folder').makedirs()
file = static.File(base.path)
request = DummyRequest([b'folder'])
request.uri = b'http://dummy/folder#baz?foo=bar'
child = resource.getChildForRequest(file, request)
self.successResultOf(self._render(child, request))
self.assertEqual(request.responseCode, FOUND)
self.assertEqual(request.responseHeaders.getRawHeaders(b'location'), [b'http://dummy/folder/#baz?foo=bar'])
|
def _makeFilePathWithStringIO(self):
'\n Create a L{File} that when opened for reading, returns a L{StringIO}.\n\n @return: 2-tuple of the opened "file" and the L{File}.\n @rtype: L{tuple}\n '
fakeFile = StringIO()
path = FilePath(self.mktemp())
path.touch()
file = static.File(path.path)
file.open = (lambda : fakeFile)
return (fakeFile, file)
| -4,232,980,466,842,602,500
|
Create a L{File} that when opened for reading, returns a L{StringIO}.
@return: 2-tuple of the opened "file" and the L{File}.
@rtype: L{tuple}
|
src/twisted/web/test/test_static.py
|
_makeFilePathWithStringIO
|
ikingye/twisted
|
python
|
def _makeFilePathWithStringIO(self):
'\n Create a L{File} that when opened for reading, returns a L{StringIO}.\n\n @return: 2-tuple of the opened "file" and the L{File}.\n @rtype: L{tuple}\n '
fakeFile = StringIO()
path = FilePath(self.mktemp())
path.touch()
file = static.File(path.path)
file.open = (lambda : fakeFile)
return (fakeFile, file)
|
def test_HEADClosesFile(self):
'\n A HEAD request opens the file, gets the size, and then closes it after\n the request.\n '
(fakeFile, file) = self._makeFilePathWithStringIO()
request = DummyRequest([''])
request.method = b'HEAD'
self.successResultOf(_render(file, request))
self.assertEqual(b''.join(request.written), b'')
self.assertTrue(fakeFile.closed)
| 829,006,247,321,419,500
|
A HEAD request opens the file, gets the size, and then closes it after
the request.
|
src/twisted/web/test/test_static.py
|
test_HEADClosesFile
|
ikingye/twisted
|
python
|
def test_HEADClosesFile(self):
'\n A HEAD request opens the file, gets the size, and then closes it after\n the request.\n '
(fakeFile, file) = self._makeFilePathWithStringIO()
request = DummyRequest([])
request.method = b'HEAD'
self.successResultOf(_render(file, request))
self.assertEqual(b.join(request.written), b)
self.assertTrue(fakeFile.closed)
|
def test_cachedRequestClosesFile(self):
'\n A GET request that is cached closes the file after the request.\n '
(fakeFile, file) = self._makeFilePathWithStringIO()
request = DummyRequest([''])
request.method = b'GET'
request.setLastModified = (lambda _: http.CACHED)
self.successResultOf(_render(file, request))
self.assertEqual(b''.join(request.written), b'')
self.assertTrue(fakeFile.closed)
| -7,320,467,490,915,870,000
|
A GET request that is cached closes the file after the request.
|
src/twisted/web/test/test_static.py
|
test_cachedRequestClosesFile
|
ikingye/twisted
|
python
|
def test_cachedRequestClosesFile(self):
'\n \n '
(fakeFile, file) = self._makeFilePathWithStringIO()
request = DummyRequest([])
request.method = b'GET'
request.setLastModified = (lambda _: http.CACHED)
self.successResultOf(_render(file, request))
self.assertEqual(b.join(request.written), b)
self.assertTrue(fakeFile.closed)
|
def makeResourceWithContent(self, content, type=None, encoding=None):
'\n Make a L{static.File} resource that has C{content} for its content.\n\n @param content: The L{bytes} to use as the contents of the resource.\n @param type: Optional value for the content type of the resource.\n '
fileName = FilePath(self.mktemp())
fileName.setContent(content)
resource = static.File(fileName._asBytesPath())
resource.encoding = encoding
resource.type = type
return resource
| 6,014,059,087,527,310,000
|
Make a L{static.File} resource that has C{content} for its content.
@param content: The L{bytes} to use as the contents of the resource.
@param type: Optional value for the content type of the resource.
|
src/twisted/web/test/test_static.py
|
makeResourceWithContent
|
ikingye/twisted
|
python
|
def makeResourceWithContent(self, content, type=None, encoding=None):
'\n Make a L{static.File} resource that has C{content} for its content.\n\n @param content: The L{bytes} to use as the contents of the resource.\n @param type: Optional value for the content type of the resource.\n '
fileName = FilePath(self.mktemp())
fileName.setContent(content)
resource = static.File(fileName._asBytesPath())
resource.encoding = encoding
resource.type = type
return resource
|
def contentHeaders(self, request):
"\n Extract the content-* headers from the L{DummyRequest} C{request}.\n\n This returns the subset of C{request.outgoingHeaders} of headers that\n start with 'content-'.\n "
contentHeaders = {}
for (k, v) in request.responseHeaders.getAllRawHeaders():
if k.lower().startswith(b'content-'):
contentHeaders[k.lower()] = v[0]
return contentHeaders
| -6,191,106,567,909,612,000
|
Extract the content-* headers from the L{DummyRequest} C{request}.
This returns the subset of C{request.outgoingHeaders} of headers that
start with 'content-'.
|
src/twisted/web/test/test_static.py
|
contentHeaders
|
ikingye/twisted
|
python
|
def contentHeaders(self, request):
"\n Extract the content-* headers from the L{DummyRequest} C{request}.\n\n This returns the subset of C{request.outgoingHeaders} of headers that\n start with 'content-'.\n "
contentHeaders = {}
for (k, v) in request.responseHeaders.getAllRawHeaders():
if k.lower().startswith(b'content-'):
contentHeaders[k.lower()] = v[0]
return contentHeaders
|
def test_noRangeHeaderGivesNoRangeStaticProducer(self):
'\n makeProducer when no Range header is set returns an instance of\n NoRangeStaticProducer.\n '
resource = self.makeResourceWithContent(b'')
request = DummyRequest([])
with resource.openForReading() as file:
producer = resource.makeProducer(request, file)
self.assertIsInstance(producer, static.NoRangeStaticProducer)
| -3,146,097,848,934,088,700
|
makeProducer when no Range header is set returns an instance of
NoRangeStaticProducer.
|
src/twisted/web/test/test_static.py
|
test_noRangeHeaderGivesNoRangeStaticProducer
|
ikingye/twisted
|
python
|
def test_noRangeHeaderGivesNoRangeStaticProducer(self):
'\n makeProducer when no Range header is set returns an instance of\n NoRangeStaticProducer.\n '
resource = self.makeResourceWithContent(b)
request = DummyRequest([])
with resource.openForReading() as file:
producer = resource.makeProducer(request, file)
self.assertIsInstance(producer, static.NoRangeStaticProducer)
|
def test_noRangeHeaderSets200OK(self):
"\n makeProducer when no Range header is set sets the responseCode on the\n request to 'OK'.\n "
resource = self.makeResourceWithContent(b'')
request = DummyRequest([])
with resource.openForReading() as file:
resource.makeProducer(request, file)
self.assertEqual(http.OK, request.responseCode)
| -8,817,308,023,452,043,000
|
makeProducer when no Range header is set sets the responseCode on the
request to 'OK'.
|
src/twisted/web/test/test_static.py
|
test_noRangeHeaderSets200OK
|
ikingye/twisted
|
python
|
def test_noRangeHeaderSets200OK(self):
"\n makeProducer when no Range header is set sets the responseCode on the\n request to 'OK'.\n "
resource = self.makeResourceWithContent(b)
request = DummyRequest([])
with resource.openForReading() as file:
resource.makeProducer(request, file)
self.assertEqual(http.OK, request.responseCode)
|
def test_noRangeHeaderSetsContentHeaders(self):
'\n makeProducer when no Range header is set sets the Content-* headers\n for the response.\n '
length = 123
contentType = 'text/plain'
contentEncoding = 'gzip'
resource = self.makeResourceWithContent((b'a' * length), type=contentType, encoding=contentEncoding)
request = DummyRequest([])
with resource.openForReading() as file:
resource.makeProducer(request, file)
self.assertEqual({b'content-type': networkString(contentType), b'content-length': (b'%d' % (length,)), b'content-encoding': networkString(contentEncoding)}, self.contentHeaders(request))
| 884,769,670,884,239,400
|
makeProducer when no Range header is set sets the Content-* headers
for the response.
|
src/twisted/web/test/test_static.py
|
test_noRangeHeaderSetsContentHeaders
|
ikingye/twisted
|
python
|
def test_noRangeHeaderSetsContentHeaders(self):
'\n makeProducer when no Range header is set sets the Content-* headers\n for the response.\n '
length = 123
contentType = 'text/plain'
contentEncoding = 'gzip'
resource = self.makeResourceWithContent((b'a' * length), type=contentType, encoding=contentEncoding)
request = DummyRequest([])
with resource.openForReading() as file:
resource.makeProducer(request, file)
self.assertEqual({b'content-type': networkString(contentType), b'content-length': (b'%d' % (length,)), b'content-encoding': networkString(contentEncoding)}, self.contentHeaders(request))
|
def test_singleRangeGivesSingleRangeStaticProducer(self):
'\n makeProducer when the Range header requests a single byte range\n returns an instance of SingleRangeStaticProducer.\n '
request = DummyRequest([])
request.requestHeaders.addRawHeader(b'range', b'bytes=1-3')
resource = self.makeResourceWithContent(b'abcdef')
with resource.openForReading() as file:
producer = resource.makeProducer(request, file)
self.assertIsInstance(producer, static.SingleRangeStaticProducer)
| 8,191,983,018,884,602,000
|
makeProducer when the Range header requests a single byte range
returns an instance of SingleRangeStaticProducer.
|
src/twisted/web/test/test_static.py
|
test_singleRangeGivesSingleRangeStaticProducer
|
ikingye/twisted
|
python
|
def test_singleRangeGivesSingleRangeStaticProducer(self):
'\n makeProducer when the Range header requests a single byte range\n returns an instance of SingleRangeStaticProducer.\n '
request = DummyRequest([])
request.requestHeaders.addRawHeader(b'range', b'bytes=1-3')
resource = self.makeResourceWithContent(b'abcdef')
with resource.openForReading() as file:
producer = resource.makeProducer(request, file)
self.assertIsInstance(producer, static.SingleRangeStaticProducer)
|
def test_singleRangeSets206PartialContent(self):
"\n makeProducer when the Range header requests a single, satisfiable byte\n range sets the response code on the request to 'Partial Content'.\n "
request = DummyRequest([])
request.requestHeaders.addRawHeader(b'range', b'bytes=1-3')
resource = self.makeResourceWithContent(b'abcdef')
with resource.openForReading() as file:
resource.makeProducer(request, file)
self.assertEqual(http.PARTIAL_CONTENT, request.responseCode)
| 5,776,873,039,267,888,000
|
makeProducer when the Range header requests a single, satisfiable byte
range sets the response code on the request to 'Partial Content'.
|
src/twisted/web/test/test_static.py
|
test_singleRangeSets206PartialContent
|
ikingye/twisted
|
python
|
def test_singleRangeSets206PartialContent(self):
"\n makeProducer when the Range header requests a single, satisfiable byte\n range sets the response code on the request to 'Partial Content'.\n "
request = DummyRequest([])
request.requestHeaders.addRawHeader(b'range', b'bytes=1-3')
resource = self.makeResourceWithContent(b'abcdef')
with resource.openForReading() as file:
resource.makeProducer(request, file)
self.assertEqual(http.PARTIAL_CONTENT, request.responseCode)
|
def test_singleRangeSetsContentHeaders(self):
'\n makeProducer when the Range header requests a single, satisfiable byte\n range sets the Content-* headers appropriately.\n '
request = DummyRequest([])
request.requestHeaders.addRawHeader(b'range', b'bytes=1-3')
contentType = 'text/plain'
contentEncoding = 'gzip'
resource = self.makeResourceWithContent(b'abcdef', type=contentType, encoding=contentEncoding)
with resource.openForReading() as file:
resource.makeProducer(request, file)
self.assertEqual({b'content-type': networkString(contentType), b'content-encoding': networkString(contentEncoding), b'content-range': b'bytes 1-3/6', b'content-length': b'3'}, self.contentHeaders(request))
| -5,437,887,611,594,743,000
|
makeProducer when the Range header requests a single, satisfiable byte
range sets the Content-* headers appropriately.
|
src/twisted/web/test/test_static.py
|
test_singleRangeSetsContentHeaders
|
ikingye/twisted
|
python
|
def test_singleRangeSetsContentHeaders(self):
'\n makeProducer when the Range header requests a single, satisfiable byte\n range sets the Content-* headers appropriately.\n '
request = DummyRequest([])
request.requestHeaders.addRawHeader(b'range', b'bytes=1-3')
contentType = 'text/plain'
contentEncoding = 'gzip'
resource = self.makeResourceWithContent(b'abcdef', type=contentType, encoding=contentEncoding)
with resource.openForReading() as file:
resource.makeProducer(request, file)
self.assertEqual({b'content-type': networkString(contentType), b'content-encoding': networkString(contentEncoding), b'content-range': b'bytes 1-3/6', b'content-length': b'3'}, self.contentHeaders(request))
|
def test_singleUnsatisfiableRangeReturnsSingleRangeStaticProducer(self):
'\n makeProducer still returns an instance of L{SingleRangeStaticProducer}\n when the Range header requests a single unsatisfiable byte range.\n '
request = DummyRequest([])
request.requestHeaders.addRawHeader(b'range', b'bytes=4-10')
resource = self.makeResourceWithContent(b'abc')
with resource.openForReading() as file:
producer = resource.makeProducer(request, file)
self.assertIsInstance(producer, static.SingleRangeStaticProducer)
| -7,932,120,498,981,605,000
|
makeProducer still returns an instance of L{SingleRangeStaticProducer}
when the Range header requests a single unsatisfiable byte range.
|
src/twisted/web/test/test_static.py
|
test_singleUnsatisfiableRangeReturnsSingleRangeStaticProducer
|
ikingye/twisted
|
python
|
def test_singleUnsatisfiableRangeReturnsSingleRangeStaticProducer(self):
'\n makeProducer still returns an instance of L{SingleRangeStaticProducer}\n when the Range header requests a single unsatisfiable byte range.\n '
request = DummyRequest([])
request.requestHeaders.addRawHeader(b'range', b'bytes=4-10')
resource = self.makeResourceWithContent(b'abc')
with resource.openForReading() as file:
producer = resource.makeProducer(request, file)
self.assertIsInstance(producer, static.SingleRangeStaticProducer)
|
def test_singleUnsatisfiableRangeSets416ReqestedRangeNotSatisfiable(self):
"\n makeProducer sets the response code of the request to of 'Requested\n Range Not Satisfiable' when the Range header requests a single\n unsatisfiable byte range.\n "
request = DummyRequest([])
request.requestHeaders.addRawHeader(b'range', b'bytes=4-10')
resource = self.makeResourceWithContent(b'abc')
with resource.openForReading() as file:
resource.makeProducer(request, file)
self.assertEqual(http.REQUESTED_RANGE_NOT_SATISFIABLE, request.responseCode)
| -8,704,700,049,519,522,000
|
makeProducer sets the response code of the request to of 'Requested
Range Not Satisfiable' when the Range header requests a single
unsatisfiable byte range.
|
src/twisted/web/test/test_static.py
|
test_singleUnsatisfiableRangeSets416ReqestedRangeNotSatisfiable
|
ikingye/twisted
|
python
|
def test_singleUnsatisfiableRangeSets416ReqestedRangeNotSatisfiable(self):
"\n makeProducer sets the response code of the request to of 'Requested\n Range Not Satisfiable' when the Range header requests a single\n unsatisfiable byte range.\n "
request = DummyRequest([])
request.requestHeaders.addRawHeader(b'range', b'bytes=4-10')
resource = self.makeResourceWithContent(b'abc')
with resource.openForReading() as file:
resource.makeProducer(request, file)
self.assertEqual(http.REQUESTED_RANGE_NOT_SATISFIABLE, request.responseCode)
|
def test_singleUnsatisfiableRangeSetsContentHeaders(self):
'\n makeProducer when the Range header requests a single, unsatisfiable\n byte range sets the Content-* headers appropriately.\n '
request = DummyRequest([])
request.requestHeaders.addRawHeader(b'range', b'bytes=4-10')
contentType = 'text/plain'
resource = self.makeResourceWithContent(b'abc', type=contentType)
with resource.openForReading() as file:
resource.makeProducer(request, file)
self.assertEqual({b'content-type': b'text/plain', b'content-length': b'0', b'content-range': b'bytes */3'}, self.contentHeaders(request))
| 7,437,187,874,531,629,000
|
makeProducer when the Range header requests a single, unsatisfiable
byte range sets the Content-* headers appropriately.
|
src/twisted/web/test/test_static.py
|
test_singleUnsatisfiableRangeSetsContentHeaders
|
ikingye/twisted
|
python
|
def test_singleUnsatisfiableRangeSetsContentHeaders(self):
'\n makeProducer when the Range header requests a single, unsatisfiable\n byte range sets the Content-* headers appropriately.\n '
request = DummyRequest([])
request.requestHeaders.addRawHeader(b'range', b'bytes=4-10')
contentType = 'text/plain'
resource = self.makeResourceWithContent(b'abc', type=contentType)
with resource.openForReading() as file:
resource.makeProducer(request, file)
self.assertEqual({b'content-type': b'text/plain', b'content-length': b'0', b'content-range': b'bytes */3'}, self.contentHeaders(request))
|
def test_singlePartiallyOverlappingRangeSetsContentHeaders(self):
'\n makeProducer when the Range header requests a single byte range that\n partly overlaps the resource sets the Content-* headers appropriately.\n '
request = DummyRequest([])
request.requestHeaders.addRawHeader(b'range', b'bytes=2-10')
contentType = 'text/plain'
resource = self.makeResourceWithContent(b'abc', type=contentType)
with resource.openForReading() as file:
resource.makeProducer(request, file)
self.assertEqual({b'content-type': b'text/plain', b'content-length': b'1', b'content-range': b'bytes 2-2/3'}, self.contentHeaders(request))
| 7,817,529,316,703,571,000
|
makeProducer when the Range header requests a single byte range that
partly overlaps the resource sets the Content-* headers appropriately.
|
src/twisted/web/test/test_static.py
|
test_singlePartiallyOverlappingRangeSetsContentHeaders
|
ikingye/twisted
|
python
|
def test_singlePartiallyOverlappingRangeSetsContentHeaders(self):
'\n makeProducer when the Range header requests a single byte range that\n partly overlaps the resource sets the Content-* headers appropriately.\n '
request = DummyRequest([])
request.requestHeaders.addRawHeader(b'range', b'bytes=2-10')
contentType = 'text/plain'
resource = self.makeResourceWithContent(b'abc', type=contentType)
with resource.openForReading() as file:
resource.makeProducer(request, file)
self.assertEqual({b'content-type': b'text/plain', b'content-length': b'1', b'content-range': b'bytes 2-2/3'}, self.contentHeaders(request))
|
def test_multipleRangeGivesMultipleRangeStaticProducer(self):
'\n makeProducer when the Range header requests a single byte range\n returns an instance of MultipleRangeStaticProducer.\n '
request = DummyRequest([])
request.requestHeaders.addRawHeader(b'range', b'bytes=1-3,5-6')
resource = self.makeResourceWithContent(b'abcdef')
with resource.openForReading() as file:
producer = resource.makeProducer(request, file)
self.assertIsInstance(producer, static.MultipleRangeStaticProducer)
| 8,088,635,840,996,636,000
|
makeProducer when the Range header requests a single byte range
returns an instance of MultipleRangeStaticProducer.
|
src/twisted/web/test/test_static.py
|
test_multipleRangeGivesMultipleRangeStaticProducer
|
ikingye/twisted
|
python
|
def test_multipleRangeGivesMultipleRangeStaticProducer(self):
'\n makeProducer when the Range header requests a single byte range\n returns an instance of MultipleRangeStaticProducer.\n '
request = DummyRequest([])
request.requestHeaders.addRawHeader(b'range', b'bytes=1-3,5-6')
resource = self.makeResourceWithContent(b'abcdef')
with resource.openForReading() as file:
producer = resource.makeProducer(request, file)
self.assertIsInstance(producer, static.MultipleRangeStaticProducer)
|
def test_multipleRangeSets206PartialContent(self):
"\n makeProducer when the Range header requests a multiple satisfiable\n byte ranges sets the response code on the request to 'Partial\n Content'.\n "
request = DummyRequest([])
request.requestHeaders.addRawHeader(b'range', b'bytes=1-3,5-6')
resource = self.makeResourceWithContent(b'abcdef')
with resource.openForReading() as file:
resource.makeProducer(request, file)
self.assertEqual(http.PARTIAL_CONTENT, request.responseCode)
| 1,134,091,184,371,823,100
|
makeProducer when the Range header requests a multiple satisfiable
byte ranges sets the response code on the request to 'Partial
Content'.
|
src/twisted/web/test/test_static.py
|
test_multipleRangeSets206PartialContent
|
ikingye/twisted
|
python
|
def test_multipleRangeSets206PartialContent(self):
"\n makeProducer when the Range header requests a multiple satisfiable\n byte ranges sets the response code on the request to 'Partial\n Content'.\n "
request = DummyRequest([])
request.requestHeaders.addRawHeader(b'range', b'bytes=1-3,5-6')
resource = self.makeResourceWithContent(b'abcdef')
with resource.openForReading() as file:
resource.makeProducer(request, file)
self.assertEqual(http.PARTIAL_CONTENT, request.responseCode)
|
def test_mutipleRangeSetsContentHeaders(self):
'\n makeProducer when the Range header requests a single, satisfiable byte\n range sets the Content-* headers appropriately.\n '
request = DummyRequest([])
request.requestHeaders.addRawHeader(b'range', b'bytes=1-3,5-6')
resource = self.makeResourceWithContent(b'abcdefghijkl', encoding='gzip')
with resource.openForReading() as file:
producer = resource.makeProducer(request, file)
contentHeaders = self.contentHeaders(request)
self.assertEqual(set([b'content-length', b'content-type']), set(contentHeaders.keys()))
expectedLength = 5
for (boundary, offset, size) in producer.rangeInfo:
expectedLength += len(boundary)
self.assertEqual((b'%d' % (expectedLength,)), contentHeaders[b'content-length'])
self.assertIn(b'content-type', contentHeaders)
contentType = contentHeaders[b'content-type']
self.assertNotIdentical(None, re.match(b'multipart/byteranges; boundary="[^"]*"\\Z', contentType))
self.assertNotIn(b'content-encoding', contentHeaders)
| -1,230,654,409,265,250,600
|
makeProducer when the Range header requests a single, satisfiable byte
range sets the Content-* headers appropriately.
|
src/twisted/web/test/test_static.py
|
test_mutipleRangeSetsContentHeaders
|
ikingye/twisted
|
python
|
def test_mutipleRangeSetsContentHeaders(self):
'\n makeProducer when the Range header requests a single, satisfiable byte\n range sets the Content-* headers appropriately.\n '
request = DummyRequest([])
request.requestHeaders.addRawHeader(b'range', b'bytes=1-3,5-6')
resource = self.makeResourceWithContent(b'abcdefghijkl', encoding='gzip')
with resource.openForReading() as file:
producer = resource.makeProducer(request, file)
contentHeaders = self.contentHeaders(request)
self.assertEqual(set([b'content-length', b'content-type']), set(contentHeaders.keys()))
expectedLength = 5
for (boundary, offset, size) in producer.rangeInfo:
expectedLength += len(boundary)
self.assertEqual((b'%d' % (expectedLength,)), contentHeaders[b'content-length'])
self.assertIn(b'content-type', contentHeaders)
contentType = contentHeaders[b'content-type']
self.assertNotIdentical(None, re.match(b'multipart/byteranges; boundary="[^"]*"\\Z', contentType))
self.assertNotIn(b'content-encoding', contentHeaders)
|
def test_multipleUnsatisfiableRangesReturnsMultipleRangeStaticProducer(self):
'\n makeProducer still returns an instance of L{SingleRangeStaticProducer}\n when the Range header requests multiple ranges, none of which are\n satisfiable.\n '
request = DummyRequest([])
request.requestHeaders.addRawHeader(b'range', b'bytes=10-12,15-20')
resource = self.makeResourceWithContent(b'abc')
with resource.openForReading() as file:
producer = resource.makeProducer(request, file)
self.assertIsInstance(producer, static.MultipleRangeStaticProducer)
| 8,250,657,927,533,788,000
|
makeProducer still returns an instance of L{SingleRangeStaticProducer}
when the Range header requests multiple ranges, none of which are
satisfiable.
|
src/twisted/web/test/test_static.py
|
test_multipleUnsatisfiableRangesReturnsMultipleRangeStaticProducer
|
ikingye/twisted
|
python
|
def test_multipleUnsatisfiableRangesReturnsMultipleRangeStaticProducer(self):
'\n makeProducer still returns an instance of L{SingleRangeStaticProducer}\n when the Range header requests multiple ranges, none of which are\n satisfiable.\n '
request = DummyRequest([])
request.requestHeaders.addRawHeader(b'range', b'bytes=10-12,15-20')
resource = self.makeResourceWithContent(b'abc')
with resource.openForReading() as file:
producer = resource.makeProducer(request, file)
self.assertIsInstance(producer, static.MultipleRangeStaticProducer)
|
def test_multipleUnsatisfiableRangesSets416ReqestedRangeNotSatisfiable(self):
"\n makeProducer sets the response code of the request to of 'Requested\n Range Not Satisfiable' when the Range header requests multiple ranges,\n none of which are satisfiable.\n "
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)
| 489,461,435,045,998,500
|
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.
|
src/twisted/web/test/test_static.py
|
test_multipleUnsatisfiableRangesSets416ReqestedRangeNotSatisfiable
|
ikingye/twisted
|
python
|
def test_multipleUnsatisfiableRangesSets416ReqestedRangeNotSatisfiable(self):
"\n makeProducer sets the response code of the request to of 'Requested\n Range Not Satisfiable' when the Range header requests multiple ranges,\n none of which are satisfiable.\n "
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)
|
def test_multipleUnsatisfiableRangeSetsContentHeaders(self):
'\n makeProducer when the Range header requests multiple ranges, none of\n which are satisfiable, sets the Content-* headers appropriately.\n '
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))
| -9,090,289,868,403,047,000
|
makeProducer when the Range header requests multiple ranges, none of
which are satisfiable, sets the Content-* headers appropriately.
|
src/twisted/web/test/test_static.py
|
test_multipleUnsatisfiableRangeSetsContentHeaders
|
ikingye/twisted
|
python
|
def test_multipleUnsatisfiableRangeSetsContentHeaders(self):
'\n makeProducer when the Range header requests multiple ranges, none of\n which are satisfiable, sets the Content-* headers appropriately.\n '
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))
|
def test_oneSatisfiableRangeIsEnough(self):
"\n makeProducer when the Range header requests multiple ranges, at least\n one of which matches, sets the response code to 'Partial Content'.\n "
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)
| -8,784,242,700,428,044,000
|
makeProducer when the Range header requests multiple ranges, at least
one of which matches, sets the response code to 'Partial Content'.
|
src/twisted/web/test/test_static.py
|
test_oneSatisfiableRangeIsEnough
|
ikingye/twisted
|
python
|
def test_oneSatisfiableRangeIsEnough(self):
"\n makeProducer when the Range header requests multiple ranges, at least\n one of which matches, sets the response code to 'Partial Content'.\n "
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)
|
def test_stopProducingClosesFile(self):
'\n L{StaticProducer.stopProducing} closes the file object the producer is\n producing data from.\n '
fileObject = StringIO()
producer = static.StaticProducer(None, fileObject)
producer.stopProducing()
self.assertTrue(fileObject.closed)
| 8,419,424,758,739,213,000
|
L{StaticProducer.stopProducing} closes the file object the producer is
producing data from.
|
src/twisted/web/test/test_static.py
|
test_stopProducingClosesFile
|
ikingye/twisted
|
python
|
def test_stopProducingClosesFile(self):
'\n L{StaticProducer.stopProducing} closes the file object the producer is\n producing data from.\n '
fileObject = StringIO()
producer = static.StaticProducer(None, fileObject)
producer.stopProducing()
self.assertTrue(fileObject.closed)
|
def test_stopProducingSetsRequestToNone(self):
"\n L{StaticProducer.stopProducing} sets the request instance variable to\n None, which indicates to subclasses' resumeProducing methods that no\n more data should be produced.\n "
fileObject = StringIO()
producer = static.StaticProducer(DummyRequest([]), fileObject)
producer.stopProducing()
self.assertIdentical(None, producer.request)
| 5,446,413,294,597,400,000
|
L{StaticProducer.stopProducing} sets the request instance variable to
None, which indicates to subclasses' resumeProducing methods that no
more data should be produced.
|
src/twisted/web/test/test_static.py
|
test_stopProducingSetsRequestToNone
|
ikingye/twisted
|
python
|
def test_stopProducingSetsRequestToNone(self):
"\n L{StaticProducer.stopProducing} sets the request instance variable to\n None, which indicates to subclasses' resumeProducing methods that no\n more data should be produced.\n "
fileObject = StringIO()
producer = static.StaticProducer(DummyRequest([]), fileObject)
producer.stopProducing()
self.assertIdentical(None, producer.request)
|
def test_implementsIPullProducer(self):
'\n L{NoRangeStaticProducer} implements L{IPullProducer}.\n '
verifyObject(interfaces.IPullProducer, static.NoRangeStaticProducer(None, None))
| 6,275,865,730,282,266,000
|
L{NoRangeStaticProducer} implements L{IPullProducer}.
|
src/twisted/web/test/test_static.py
|
test_implementsIPullProducer
|
ikingye/twisted
|
python
|
def test_implementsIPullProducer(self):
'\n \n '
verifyObject(interfaces.IPullProducer, static.NoRangeStaticProducer(None, None))
|
def test_resumeProducingProducesContent(self):
'\n L{NoRangeStaticProducer.resumeProducing} writes content from the\n resource to the request.\n '
request = DummyRequest([])
content = b'abcdef'
producer = static.NoRangeStaticProducer(request, StringIO(content))
producer.start()
self.assertEqual(content, b''.join(request.written))
| 6,436,079,115,757,809,000
|
L{NoRangeStaticProducer.resumeProducing} writes content from the
resource to the request.
|
src/twisted/web/test/test_static.py
|
test_resumeProducingProducesContent
|
ikingye/twisted
|
python
|
def test_resumeProducingProducesContent(self):
'\n L{NoRangeStaticProducer.resumeProducing} writes content from the\n resource to the request.\n '
request = DummyRequest([])
content = b'abcdef'
producer = static.NoRangeStaticProducer(request, StringIO(content))
producer.start()
self.assertEqual(content, b.join(request.written))
|
def test_resumeProducingBuffersOutput(self):
'\n L{NoRangeStaticProducer.start} writes at most\n C{abstract.FileDescriptor.bufferSize} bytes of content from the\n resource to the request at once.\n '
request = DummyRequest([])
bufferSize = abstract.FileDescriptor.bufferSize
content = (b'a' * ((2 * bufferSize) + 1))
producer = static.NoRangeStaticProducer(request, StringIO(content))
producer.start()
expected = [content[0:bufferSize], content[bufferSize:(2 * bufferSize)], content[(2 * bufferSize):]]
self.assertEqual(expected, request.written)
| 6,262,488,206,969,006,000
|
L{NoRangeStaticProducer.start} writes at most
C{abstract.FileDescriptor.bufferSize} bytes of content from the
resource to the request at once.
|
src/twisted/web/test/test_static.py
|
test_resumeProducingBuffersOutput
|
ikingye/twisted
|
python
|
def test_resumeProducingBuffersOutput(self):
'\n L{NoRangeStaticProducer.start} writes at most\n C{abstract.FileDescriptor.bufferSize} bytes of content from the\n resource to the request at once.\n '
request = DummyRequest([])
bufferSize = abstract.FileDescriptor.bufferSize
content = (b'a' * ((2 * bufferSize) + 1))
producer = static.NoRangeStaticProducer(request, StringIO(content))
producer.start()
expected = [content[0:bufferSize], content[bufferSize:(2 * bufferSize)], content[(2 * bufferSize):]]
self.assertEqual(expected, request.written)
|
def test_finishCalledWhenDone(self):
'\n L{NoRangeStaticProducer.resumeProducing} calls finish() on the request\n after it is done producing content.\n '
request = DummyRequest([])
finishDeferred = request.notifyFinish()
callbackList = []
finishDeferred.addCallback(callbackList.append)
producer = static.NoRangeStaticProducer(request, StringIO(b'abcdef'))
producer.start()
self.assertEqual([None], callbackList)
| 2,211,219,624,418,289,400
|
L{NoRangeStaticProducer.resumeProducing} calls finish() on the request
after it is done producing content.
|
src/twisted/web/test/test_static.py
|
test_finishCalledWhenDone
|
ikingye/twisted
|
python
|
def test_finishCalledWhenDone(self):
'\n L{NoRangeStaticProducer.resumeProducing} calls finish() on the request\n after it is done producing content.\n '
request = DummyRequest([])
finishDeferred = request.notifyFinish()
callbackList = []
finishDeferred.addCallback(callbackList.append)
producer = static.NoRangeStaticProducer(request, StringIO(b'abcdef'))
producer.start()
self.assertEqual([None], callbackList)
|
def test_implementsIPullProducer(self):
'\n L{SingleRangeStaticProducer} implements L{IPullProducer}.\n '
verifyObject(interfaces.IPullProducer, static.SingleRangeStaticProducer(None, None, None, None))
| -5,223,490,809,204,682,000
|
L{SingleRangeStaticProducer} implements L{IPullProducer}.
|
src/twisted/web/test/test_static.py
|
test_implementsIPullProducer
|
ikingye/twisted
|
python
|
def test_implementsIPullProducer(self):
'\n \n '
verifyObject(interfaces.IPullProducer, static.SingleRangeStaticProducer(None, None, None, None))
|
def test_resumeProducingProducesContent(self):
'\n L{SingleRangeStaticProducer.resumeProducing} writes the given amount\n of content, starting at the given offset, from the resource to the\n request.\n '
request = DummyRequest([])
content = b'abcdef'
producer = static.SingleRangeStaticProducer(request, StringIO(content), 1, 3)
producer.start()
self.assertEqual(content[1:4], b''.join(request.written))
| 3,195,439,568,948,067,000
|
L{SingleRangeStaticProducer.resumeProducing} writes the given amount
of content, starting at the given offset, from the resource to the
request.
|
src/twisted/web/test/test_static.py
|
test_resumeProducingProducesContent
|
ikingye/twisted
|
python
|
def test_resumeProducingProducesContent(self):
'\n L{SingleRangeStaticProducer.resumeProducing} writes the given amount\n of content, starting at the given offset, from the resource to the\n request.\n '
request = DummyRequest([])
content = b'abcdef'
producer = static.SingleRangeStaticProducer(request, StringIO(content), 1, 3)
producer.start()
self.assertEqual(content[1:4], b.join(request.written))
|
def test_resumeProducingBuffersOutput(self):
'\n L{SingleRangeStaticProducer.start} writes at most\n C{abstract.FileDescriptor.bufferSize} bytes of content from the\n resource to the request at once.\n '
request = DummyRequest([])
bufferSize = abstract.FileDescriptor.bufferSize
content = (b'abc' * bufferSize)
producer = static.SingleRangeStaticProducer(request, StringIO(content), 1, (bufferSize + 10))
producer.start()
expected = [content[1:(bufferSize + 1)], content[(bufferSize + 1):(bufferSize + 11)]]
self.assertEqual(expected, request.written)
| -8,965,505,298,795,356,000
|
L{SingleRangeStaticProducer.start} writes at most
C{abstract.FileDescriptor.bufferSize} bytes of content from the
resource to the request at once.
|
src/twisted/web/test/test_static.py
|
test_resumeProducingBuffersOutput
|
ikingye/twisted
|
python
|
def test_resumeProducingBuffersOutput(self):
'\n L{SingleRangeStaticProducer.start} writes at most\n C{abstract.FileDescriptor.bufferSize} bytes of content from the\n resource to the request at once.\n '
request = DummyRequest([])
bufferSize = abstract.FileDescriptor.bufferSize
content = (b'abc' * bufferSize)
producer = static.SingleRangeStaticProducer(request, StringIO(content), 1, (bufferSize + 10))
producer.start()
expected = [content[1:(bufferSize + 1)], content[(bufferSize + 1):(bufferSize + 11)]]
self.assertEqual(expected, request.written)
|
def test_finishCalledWhenDone(self):
'\n L{SingleRangeStaticProducer.resumeProducing} calls finish() on the\n request after it is done producing content.\n '
request = DummyRequest([])
finishDeferred = request.notifyFinish()
callbackList = []
finishDeferred.addCallback(callbackList.append)
producer = static.SingleRangeStaticProducer(request, StringIO(b'abcdef'), 1, 1)
producer.start()
self.assertEqual([None], callbackList)
| -7,405,512,406,198,084,000
|
L{SingleRangeStaticProducer.resumeProducing} calls finish() on the
request after it is done producing content.
|
src/twisted/web/test/test_static.py
|
test_finishCalledWhenDone
|
ikingye/twisted
|
python
|
def test_finishCalledWhenDone(self):
'\n L{SingleRangeStaticProducer.resumeProducing} calls finish() on the\n request after it is done producing content.\n '
request = DummyRequest([])
finishDeferred = request.notifyFinish()
callbackList = []
finishDeferred.addCallback(callbackList.append)
producer = static.SingleRangeStaticProducer(request, StringIO(b'abcdef'), 1, 1)
producer.start()
self.assertEqual([None], callbackList)
|
def test_implementsIPullProducer(self):
'\n L{MultipleRangeStaticProducer} implements L{IPullProducer}.\n '
verifyObject(interfaces.IPullProducer, static.MultipleRangeStaticProducer(None, None, None))
| 7,842,647,734,957,226,000
|
L{MultipleRangeStaticProducer} implements L{IPullProducer}.
|
src/twisted/web/test/test_static.py
|
test_implementsIPullProducer
|
ikingye/twisted
|
python
|
def test_implementsIPullProducer(self):
'\n \n '
verifyObject(interfaces.IPullProducer, static.MultipleRangeStaticProducer(None, None, None))
|
def test_resumeProducingProducesContent(self):
'\n L{MultipleRangeStaticProducer.resumeProducing} writes the requested\n chunks of content from the resource to the request, with the supplied\n boundaries in between each chunk.\n '
request = DummyRequest([])
content = b'abcdef'
producer = static.MultipleRangeStaticProducer(request, StringIO(content), [(b'1', 1, 3), (b'2', 5, 1)])
producer.start()
self.assertEqual(b'1bcd2f', b''.join(request.written))
| 2,154,517,942,630,779,400
|
L{MultipleRangeStaticProducer.resumeProducing} writes the requested
chunks of content from the resource to the request, with the supplied
boundaries in between each chunk.
|
src/twisted/web/test/test_static.py
|
test_resumeProducingProducesContent
|
ikingye/twisted
|
python
|
def test_resumeProducingProducesContent(self):
'\n L{MultipleRangeStaticProducer.resumeProducing} writes the requested\n chunks of content from the resource to the request, with the supplied\n boundaries in between each chunk.\n '
request = DummyRequest([])
content = b'abcdef'
producer = static.MultipleRangeStaticProducer(request, StringIO(content), [(b'1', 1, 3), (b'2', 5, 1)])
producer.start()
self.assertEqual(b'1bcd2f', b.join(request.written))
|
def test_resumeProducingBuffersOutput(self):
"\n L{MultipleRangeStaticProducer.start} writes about\n C{abstract.FileDescriptor.bufferSize} bytes of content from the\n resource to the request at once.\n\n To be specific about the 'about' above: it can write slightly more,\n for example in the case where the first boundary plus the first chunk\n is less than C{bufferSize} but first boundary plus the first chunk\n plus the second boundary is more, but this is unimportant as in\n practice the boundaries are fairly small. On the other side, it is\n important for performance to bundle up several small chunks into one\n call to request.write.\n "
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
producer.start()
expected = [(((b'a' + content[0:2]) + b'b') + content[5:11]), (content[11:15] + b'c')]
self.assertEqual(expected, request.written)
| -905,546,181,750,821,400
|
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.
|
src/twisted/web/test/test_static.py
|
test_resumeProducingBuffersOutput
|
ikingye/twisted
|
python
|
def test_resumeProducingBuffersOutput(self):
"\n L{MultipleRangeStaticProducer.start} writes about\n C{abstract.FileDescriptor.bufferSize} bytes of content from the\n resource to the request at once.\n\n To be specific about the 'about' above: it can write slightly more,\n for example in the case where the first boundary plus the first chunk\n is less than C{bufferSize} but first boundary plus the first chunk\n plus the second boundary is more, but this is unimportant as in\n practice the boundaries are fairly small. On the other side, it is\n important for performance to bundle up several small chunks into one\n call to request.write.\n "
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
producer.start()
expected = [(((b'a' + content[0:2]) + b'b') + content[5:11]), (content[11:15] + b'c')]
self.assertEqual(expected, request.written)
|
def test_finishCalledWhenDone(self):
'\n L{MultipleRangeStaticProducer.resumeProducing} calls finish() on the\n request after it is done producing content.\n '
request = DummyRequest([])
finishDeferred = request.notifyFinish()
callbackList = []
finishDeferred.addCallback(callbackList.append)
producer = static.MultipleRangeStaticProducer(request, StringIO(b'abcdef'), [(b'', 1, 2)])
producer.start()
self.assertEqual([None], callbackList)
| -6,132,423,272,888,084,000
|
L{MultipleRangeStaticProducer.resumeProducing} calls finish() on the
request after it is done producing content.
|
src/twisted/web/test/test_static.py
|
test_finishCalledWhenDone
|
ikingye/twisted
|
python
|
def test_finishCalledWhenDone(self):
'\n L{MultipleRangeStaticProducer.resumeProducing} calls finish() on the\n request after it is done producing content.\n '
request = DummyRequest([])
finishDeferred = request.notifyFinish()
callbackList = []
finishDeferred.addCallback(callbackList.append)
producer = static.MultipleRangeStaticProducer(request, StringIO(b'abcdef'), [(b, 1, 2)])
producer.start()
self.assertEqual([None], callbackList)
|
def setUp(self):
'\n Create a temporary file with a fixed payload of 64 bytes. Create a\n resource for that file and create a request which will be for that\n resource. Each test can set a different range header to test different\n aspects of the implementation.\n '
path = FilePath(self.mktemp())
self.payload = b'\xf8u\xf3E\x8c7\xce\x00\x9e\xb6a0y0S\xf0\xef\xac\xb7\xbe\xb5\x17M\x1e\x136k{\x1e\xbe\x0c\x07\x07\t\xd0\xbckY\xf5I\x0b\xb8\x88oZ\x1d\x85b\x1a\xcdk\xf2\x1d&\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)
| 6,316,311,734,255,176,000
|
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.
|
src/twisted/web/test/test_static.py
|
setUp
|
ikingye/twisted
|
python
|
def setUp(self):
'\n Create a temporary file with a fixed payload of 64 bytes. Create a\n resource for that file and create a request which will be for that\n resource. Each test can set a different range header to test different\n aspects of the implementation.\n '
path = FilePath(self.mktemp())
self.payload = b'\xf8u\xf3E\x8c7\xce\x00\x9e\xb6a0y0S\xf0\xef\xac\xb7\xbe\xb5\x17M\x1e\x136k{\x1e\xbe\x0c\x07\x07\t\xd0\xbckY\xf5I\x0b\xb8\x88oZ\x1d\x85b\x1a\xcdk\xf2\x1d&\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)
|
def tearDown(self):
'\n Clean up the resource file and the log observer.\n '
self.file.close()
log.removeObserver(self.catcher.append)
| 3,586,183,210,272,889,000
|
Clean up the resource file and the log observer.
|
src/twisted/web/test/test_static.py
|
tearDown
|
ikingye/twisted
|
python
|
def tearDown(self):
'\n \n '
self.file.close()
log.removeObserver(self.catcher.append)
|
def _assertLogged(self, expected):
'\n Asserts that a given log message occurred with an expected message.\n '
logItem = self.catcher.pop()
self.assertEqual(logItem['message'][0], expected)
self.assertEqual(self.catcher, [], ('An additional log occurred: %r' % (logItem,)))
| -5,044,695,461,327,398,000
|
Asserts that a given log message occurred with an expected message.
|
src/twisted/web/test/test_static.py
|
_assertLogged
|
ikingye/twisted
|
python
|
def _assertLogged(self, expected):
'\n \n '
logItem = self.catcher.pop()
self.assertEqual(logItem['message'][0], expected)
self.assertEqual(self.catcher, [], ('An additional log occurred: %r' % (logItem,)))
|
def test_invalidRanges(self):
'\n L{File._parseRangeHeader} raises L{ValueError} when passed\n syntactically invalid byte ranges.\n '
f = self.resource._parseRangeHeader
self.assertRaises(ValueError, f, b'bytes')
self.assertRaises(ValueError, f, b'unknown=1-2')
self.assertRaises(ValueError, f, b'bytes=3')
self.assertRaises(ValueError, f, b'bytes=-')
self.assertRaises(ValueError, f, b'bytes=foo-')
self.assertRaises(ValueError, f, b'bytes=-foo')
self.assertRaises(ValueError, f, b'bytes=5-4')
| -6,036,859,627,763,585,000
|
L{File._parseRangeHeader} raises L{ValueError} when passed
syntactically invalid byte ranges.
|
src/twisted/web/test/test_static.py
|
test_invalidRanges
|
ikingye/twisted
|
python
|
def test_invalidRanges(self):
'\n L{File._parseRangeHeader} raises L{ValueError} when passed\n syntactically invalid byte ranges.\n '
f = self.resource._parseRangeHeader
self.assertRaises(ValueError, f, b'bytes')
self.assertRaises(ValueError, f, b'unknown=1-2')
self.assertRaises(ValueError, f, b'bytes=3')
self.assertRaises(ValueError, f, b'bytes=-')
self.assertRaises(ValueError, f, b'bytes=foo-')
self.assertRaises(ValueError, f, b'bytes=-foo')
self.assertRaises(ValueError, f, b'bytes=5-4')
|
def test_rangeMissingStop(self):
'\n A single bytes range without an explicit stop position is parsed into a\n two-tuple giving the start position and L{None}.\n '
self.assertEqual(self.resource._parseRangeHeader(b'bytes=0-'), [(0, None)])
| -1,044,061,674,528,578,700
|
A single bytes range without an explicit stop position is parsed into a
two-tuple giving the start position and L{None}.
|
src/twisted/web/test/test_static.py
|
test_rangeMissingStop
|
ikingye/twisted
|
python
|
def test_rangeMissingStop(self):
'\n A single bytes range without an explicit stop position is parsed into a\n two-tuple giving the start position and L{None}.\n '
self.assertEqual(self.resource._parseRangeHeader(b'bytes=0-'), [(0, None)])
|
def test_rangeMissingStart(self):
'\n A single bytes range without an explicit start position is parsed into\n a two-tuple of L{None} and the end position.\n '
self.assertEqual(self.resource._parseRangeHeader(b'bytes=-3'), [(None, 3)])
| 6,925,129,249,024,071,000
|
A single bytes range without an explicit start position is parsed into
a two-tuple of L{None} and the end position.
|
src/twisted/web/test/test_static.py
|
test_rangeMissingStart
|
ikingye/twisted
|
python
|
def test_rangeMissingStart(self):
'\n A single bytes range without an explicit start position is parsed into\n a two-tuple of L{None} and the end position.\n '
self.assertEqual(self.resource._parseRangeHeader(b'bytes=-3'), [(None, 3)])
|
def test_range(self):
'\n A single bytes range with explicit start and stop positions is parsed\n into a two-tuple of those positions.\n '
self.assertEqual(self.resource._parseRangeHeader(b'bytes=2-5'), [(2, 5)])
| 9,205,609,228,488,359,000
|
A single bytes range with explicit start and stop positions is parsed
into a two-tuple of those positions.
|
src/twisted/web/test/test_static.py
|
test_range
|
ikingye/twisted
|
python
|
def test_range(self):
'\n A single bytes range with explicit start and stop positions is parsed\n into a two-tuple of those positions.\n '
self.assertEqual(self.resource._parseRangeHeader(b'bytes=2-5'), [(2, 5)])
|
def test_rangeWithSpace(self):
'\n A single bytes range with whitespace in allowed places is parsed in\n the same way as it would be without the whitespace.\n '
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)])
| -8,428,409,773,720,505,000
|
A single bytes range with whitespace in allowed places is parsed in
the same way as it would be without the whitespace.
|
src/twisted/web/test/test_static.py
|
test_rangeWithSpace
|
ikingye/twisted
|
python
|
def test_rangeWithSpace(self):
'\n A single bytes range with whitespace in allowed places is parsed in\n the same way as it would be without the whitespace.\n '
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)])
|
def test_nullRangeElements(self):
'\n If there are multiple byte ranges but only one is non-null, the\n non-null range is parsed and its start and stop returned.\n '
self.assertEqual(self.resource._parseRangeHeader(b'bytes=1-2,\r\n, ,\t'), [(1, 2)])
| 7,235,197,918,962,922,000
|
If there are multiple byte ranges but only one is non-null, the
non-null range is parsed and its start and stop returned.
|
src/twisted/web/test/test_static.py
|
test_nullRangeElements
|
ikingye/twisted
|
python
|
def test_nullRangeElements(self):
'\n If there are multiple byte ranges but only one is non-null, the\n non-null range is parsed and its start and stop returned.\n '
self.assertEqual(self.resource._parseRangeHeader(b'bytes=1-2,\r\n, ,\t'), [(1, 2)])
|
def test_multipleRanges(self):
'\n If multiple byte ranges are specified their starts and stops are\n returned.\n '
self.assertEqual(self.resource._parseRangeHeader(b'bytes=1-2,3-4'), [(1, 2), (3, 4)])
| -3,362,049,809,075,947,000
|
If multiple byte ranges are specified their starts and stops are
returned.
|
src/twisted/web/test/test_static.py
|
test_multipleRanges
|
ikingye/twisted
|
python
|
def test_multipleRanges(self):
'\n If multiple byte ranges are specified their starts and stops are\n returned.\n '
self.assertEqual(self.resource._parseRangeHeader(b'bytes=1-2,3-4'), [(1, 2), (3, 4)])
|
def test_bodyLength(self):
'\n A correct response to a range request is as long as the length of the\n requested range.\n '
self.request.requestHeaders.addRawHeader(b'range', b'bytes=0-43')
self.resource.render(self.request)
self.assertEqual(len(b''.join(self.request.written)), 44)
| -8,546,746,440,599,878,000
|
A correct response to a range request is as long as the length of the
requested range.
|
src/twisted/web/test/test_static.py
|
test_bodyLength
|
ikingye/twisted
|
python
|
def test_bodyLength(self):
'\n A correct response to a range request is as long as the length of the\n requested range.\n '
self.request.requestHeaders.addRawHeader(b'range', b'bytes=0-43')
self.resource.render(self.request)
self.assertEqual(len(b.join(self.request.written)), 44)
|
def test_invalidRangeRequest(self):
"\n An incorrect range request (RFC 2616 defines a correct range request as\n a Bytes-Unit followed by a '=' character followed by a specific range.\n Only 'bytes' is defined) results in the range header value being logged\n and a normal 200 response being sent.\n "
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], (b'%d' % (len(self.payload),)))
| -8,286,954,473,496,117,000
|
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.
|
src/twisted/web/test/test_static.py
|
test_invalidRangeRequest
|
ikingye/twisted
|
python
|
def test_invalidRangeRequest(self):
"\n An incorrect range request (RFC 2616 defines a correct range request as\n a Bytes-Unit followed by a '=' character followed by a specific range.\n Only 'bytes' is defined) results in the range header value being logged\n and a normal 200 response being sent.\n "
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], (b'%d' % (len(self.payload),)))
|
def parseMultipartBody(self, body, boundary):
'\n Parse C{body} as a multipart MIME response separated by C{boundary}.\n\n Note that this with fail the calling test on certain syntactic\n problems.\n '
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
| -3,703,157,553,750,491,000
|
Parse C{body} as a multipart MIME response separated by C{boundary}.
Note that this with fail the calling test on certain syntactic
problems.
|
src/twisted/web/test/test_static.py
|
parseMultipartBody
|
ikingye/twisted
|
python
|
def parseMultipartBody(self, body, boundary):
'\n Parse C{body} as a multipart MIME response separated by C{boundary}.\n\n Note that this with fail the calling test on certain syntactic\n problems.\n '
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
|
def test_multipleRangeRequest(self):
'\n The response to a request for multiple bytes ranges is a MIME-ish\n multipart response.\n '
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'])
| -1,234,887,928,790,036,000
|
The response to a request for multiple bytes ranges is a MIME-ish
multipart response.
|
src/twisted/web/test/test_static.py
|
test_multipleRangeRequest
|
ikingye/twisted
|
python
|
def test_multipleRangeRequest(self):
'\n The response to a request for multiple bytes ranges is a MIME-ish\n multipart response.\n '
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'])
|
def test_multipleRangeRequestWithRangeOverlappingEnd(self):
'\n The response to a request for multiple bytes ranges is a MIME-ish\n multipart response, even when one of the ranged falls off the end of\n the resource.\n '
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'])
| 5,544,368,812,457,158,000
|
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.
|
src/twisted/web/test/test_static.py
|
test_multipleRangeRequestWithRangeOverlappingEnd
|
ikingye/twisted
|
python
|
def test_multipleRangeRequestWithRangeOverlappingEnd(self):
'\n The response to a request for multiple bytes ranges is a MIME-ish\n multipart response, even when one of the ranged falls off the end of\n the resource.\n '
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'])
|
def test_implicitEnd(self):
'\n If the end byte position is omitted, then it is treated as if the\n length of the resource was specified by the end byte position.\n '
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')
| -6,203,704,777,043,995,000
|
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.
|
src/twisted/web/test/test_static.py
|
test_implicitEnd
|
ikingye/twisted
|
python
|
def test_implicitEnd(self):
'\n If the end byte position is omitted, then it is treated as if the\n length of the resource was specified by the end byte position.\n '
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')
|
def test_implicitStart(self):
'\n If the start byte position is omitted but the end byte position is\n supplied, then the range is treated as requesting the last -N bytes of\n the resource, where N is the end byte position.\n '
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')
| 2,494,607,885,007,411,700
|
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.
|
src/twisted/web/test/test_static.py
|
test_implicitStart
|
ikingye/twisted
|
python
|
def test_implicitStart(self):
'\n If the start byte position is omitted but the end byte position is\n supplied, then the range is treated as requesting the last -N bytes of\n the resource, where N is the end byte position.\n '
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')
|
def test_explicitRange(self):
"\n A correct response to a bytes range header request from A to B starts\n with the A'th byte and ends with (including) the B'th byte. The first\n byte of a page is numbered with 0.\n "
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((b'%d' % (len(written),)), self.request.responseHeaders.getRawHeaders(b'content-length')[0])
| -4,606,723,982,345,162,000
|
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.
|
src/twisted/web/test/test_static.py
|
test_explicitRange
|
ikingye/twisted
|
python
|
def test_explicitRange(self):
"\n A correct response to a bytes range header request from A to B starts\n with the A'th byte and ends with (including) the B'th byte. The first\n byte of a page is numbered with 0.\n "
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((b'%d' % (len(written),)), self.request.responseHeaders.getRawHeaders(b'content-length')[0])
|
def test_explicitRangeOverlappingEnd(self):
"\n A correct response to a bytes range header request from A to B when B\n is past the end of the resource starts with the A'th byte and ends\n with the last byte of the resource. The first byte of a page is\n numbered with 0.\n "
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((b'%d' % (len(written),)), self.request.responseHeaders.getRawHeaders(b'content-length')[0])
| 423,770,989,585,533,200
|
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.
|
src/twisted/web/test/test_static.py
|
test_explicitRangeOverlappingEnd
|
ikingye/twisted
|
python
|
def test_explicitRangeOverlappingEnd(self):
"\n A correct response to a bytes range header request from A to B when B\n is past the end of the resource starts with the A'th byte and ends\n with the last byte of the resource. The first byte of a page is\n numbered with 0.\n "
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((b'%d' % (len(written),)), self.request.responseHeaders.getRawHeaders(b'content-length')[0])
|
def test_statusCodeRequestedRangeNotSatisfiable(self):
'\n If a range is syntactically invalid due to the start being greater than\n the end, the range header is ignored (the request is responded to as if\n it were not present).\n '
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], (b'%d' % (len(self.payload),)))
| -87,484,699,623,276,370
|
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).
|
src/twisted/web/test/test_static.py
|
test_statusCodeRequestedRangeNotSatisfiable
|
ikingye/twisted
|
python
|
def test_statusCodeRequestedRangeNotSatisfiable(self):
'\n If a range is syntactically invalid due to the start being greater than\n the end, the range header is ignored (the request is responded to as if\n it were not present).\n '
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], (b'%d' % (len(self.payload),)))
|
def test_invalidStartBytePos(self):
'\n If a range is unsatisfiable due to the start not being less than the\n length of the resource, the response is 416 (Requested range not\n satisfiable) and no data is written to the response body (RFC 2616,\n section 14.35.1).\n '
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')
self.assertEqual(self.request.responseHeaders.getRawHeaders(b'content-range')[0], networkString(('bytes */%d' % (len(self.payload),))))
| -5,199,343,923,952,654,000
|
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).
|
src/twisted/web/test/test_static.py
|
test_invalidStartBytePos
|
ikingye/twisted
|
python
|
def test_invalidStartBytePos(self):
'\n If a range is unsatisfiable due to the start not being less than the\n length of the resource, the response is 416 (Requested range not\n satisfiable) and no data is written to the response body (RFC 2616,\n section 14.35.1).\n '
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')
self.assertEqual(self.request.responseHeaders.getRawHeaders(b'content-range')[0], networkString(('bytes */%d' % (len(self.payload),))))
|
def test_renderHeader(self):
'\n L{static.DirectoryLister} prints the request uri as header of the\n rendered content.\n '
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)
| 1,704,634,193,810,319,600
|
L{static.DirectoryLister} prints the request uri as header of the
rendered content.
|
src/twisted/web/test/test_static.py
|
test_renderHeader
|
ikingye/twisted
|
python
|
def test_renderHeader(self):
'\n L{static.DirectoryLister} prints the request uri as header of the\n rendered content.\n '
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)
|
def test_renderUnquoteHeader(self):
'\n L{static.DirectoryLister} unquote the request uri before printing it.\n '
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)
| -2,939,546,999,535,782,000
|
L{static.DirectoryLister} unquote the request uri before printing it.
|
src/twisted/web/test/test_static.py
|
test_renderUnquoteHeader
|
ikingye/twisted
|
python
|
def test_renderUnquoteHeader(self):
'\n \n '
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)
|
def test_escapeHeader(self):
'\n L{static.DirectoryLister} escape "&", "<" and ">" after unquoting the\n request uri.\n '
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&bar</h1>', data)
self.assertIn(b'<title>Directory listing for foo&bar</title>', data)
| -6,775,586,662,256,715,000
|
L{static.DirectoryLister} escape "&", "<" and ">" after unquoting the
request uri.
|
src/twisted/web/test/test_static.py
|
test_escapeHeader
|
ikingye/twisted
|
python
|
def test_escapeHeader(self):
'\n L{static.DirectoryLister} escape "&", "<" and ">" after unquoting the\n request uri.\n '
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&bar</h1>', data)
self.assertIn(b'<title>Directory listing for foo&bar</title>', data)
|
def test_renderFiles(self):
'\n L{static.DirectoryLister} is able to list all the files inside a\n directory.\n '
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">\n <td><a href="file1">file1</a></td>\n <td>8B</td>\n <td>[text/html]</td>\n <td></td>\n</tr>\n<tr class="even">\n <td><a href="file2">file2</a></td>\n <td>7K</td>\n <td>[text/html]</td>\n <td></td>\n</tr>'
self.assertIn(body, data)
| -4,695,931,111,386,863,000
|
L{static.DirectoryLister} is able to list all the files inside a
directory.
|
src/twisted/web/test/test_static.py
|
test_renderFiles
|
ikingye/twisted
|
python
|
def test_renderFiles(self):
'\n L{static.DirectoryLister} is able to list all the files inside a\n directory.\n '
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">\n <td><a href="file1">file1</a></td>\n <td>8B</td>\n <td>[text/html]</td>\n <td></td>\n</tr>\n<tr class="even">\n <td><a href="file2">file2</a></td>\n <td>7K</td>\n <td>[text/html]</td>\n <td></td>\n</tr>'
self.assertIn(body, data)
|
def test_renderDirectories(self):
'\n L{static.DirectoryLister} is able to list all the directories inside\n a directory.\n '
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">\n <td><a href="dir1/">dir1/</a></td>\n <td></td>\n <td>[Directory]</td>\n <td></td>\n</tr>\n<tr class="even">\n <td><a href="dir2%20%26%203/">dir2 & 3/</a></td>\n <td></td>\n <td>[Directory]</td>\n <td></td>\n</tr>'
self.assertIn(body, data)
| -8,469,718,515,438,374,000
|
L{static.DirectoryLister} is able to list all the directories inside
a directory.
|
src/twisted/web/test/test_static.py
|
test_renderDirectories
|
ikingye/twisted
|
python
|
def test_renderDirectories(self):
'\n L{static.DirectoryLister} is able to list all the directories inside\n a directory.\n '
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">\n <td><a href="dir1/">dir1/</a></td>\n <td></td>\n <td>[Directory]</td>\n <td></td>\n</tr>\n<tr class="even">\n <td><a href="dir2%20%26%203/">dir2 & 3/</a></td>\n <td></td>\n <td>[Directory]</td>\n <td></td>\n</tr>'
self.assertIn(body, data)
|
def test_renderFiltered(self):
'\n L{static.DirectoryLister} takes an optional C{dirs} argument that\n filter out the list of directories and files printed.\n '
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">\n <td><a href="dir1/">dir1/</a></td>\n <td></td>\n <td>[Directory]</td>\n <td></td>\n</tr>\n<tr class="even">\n <td><a href="dir3/">dir3/</a></td>\n <td></td>\n <td>[Directory]</td>\n <td></td>\n</tr>'
self.assertIn(body, data)
| 7,056,062,431,907,018,000
|
L{static.DirectoryLister} takes an optional C{dirs} argument that
filter out the list of directories and files printed.
|
src/twisted/web/test/test_static.py
|
test_renderFiltered
|
ikingye/twisted
|
python
|
def test_renderFiltered(self):
'\n L{static.DirectoryLister} takes an optional C{dirs} argument that\n filter out the list of directories and files printed.\n '
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">\n <td><a href="dir1/">dir1/</a></td>\n <td></td>\n <td>[Directory]</td>\n <td></td>\n</tr>\n<tr class="even">\n <td><a href="dir3/">dir3/</a></td>\n <td></td>\n <td>[Directory]</td>\n <td></td>\n</tr>'
self.assertIn(body, data)
|
def test_oddAndEven(self):
'\n L{static.DirectoryLister} gives an alternate class for each odd and\n even rows in the table.\n '
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">'))
| 8,501,426,598,190,716,000
|
L{static.DirectoryLister} gives an alternate class for each odd and
even rows in the table.
|
src/twisted/web/test/test_static.py
|
test_oddAndEven
|
ikingye/twisted
|
python
|
def test_oddAndEven(self):
'\n L{static.DirectoryLister} gives an alternate class for each odd and\n even rows in the table.\n '
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">'))
|
def test_contentType(self):
'\n L{static.DirectoryLister} produces a MIME-type that indicates that it is\n HTML, and includes its charset (UTF-8).\n '
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')
| -6,052,789,141,766,044,000
|
L{static.DirectoryLister} produces a MIME-type that indicates that it is
HTML, and includes its charset (UTF-8).
|
src/twisted/web/test/test_static.py
|
test_contentType
|
ikingye/twisted
|
python
|
def test_contentType(self):
'\n L{static.DirectoryLister} produces a MIME-type that indicates that it is\n HTML, and includes its charset (UTF-8).\n '
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')
|
def test_mimeTypeAndEncodings(self):
'\n L{static.DirectoryLister} is able to detect mimetype and encoding of\n listed files.\n '
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]'}])
| -795,609,005,526,907,400
|
L{static.DirectoryLister} is able to detect mimetype and encoding of
listed files.
|
src/twisted/web/test/test_static.py
|
test_mimeTypeAndEncodings
|
ikingye/twisted
|
python
|
def test_mimeTypeAndEncodings(self):
'\n L{static.DirectoryLister} is able to detect mimetype and encoding of\n listed files.\n '
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]'}])
|
@skipIf((not platform._supportsSymlinks()), 'No symlink support')
def test_brokenSymlink(self):
'\n If on the file in the listing points to a broken symlink, it should not\n be returned by L{static.DirectoryLister._getFilesAndDirectories}.\n '
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, [])
| 6,083,747,401,319,551,000
|
If on the file in the listing points to a broken symlink, it should not
be returned by L{static.DirectoryLister._getFilesAndDirectories}.
|
src/twisted/web/test/test_static.py
|
test_brokenSymlink
|
ikingye/twisted
|
python
|
@skipIf((not platform._supportsSymlinks()), 'No symlink support')
def test_brokenSymlink(self):
'\n If on the file in the listing points to a broken symlink, it should not\n be returned by L{static.DirectoryLister._getFilesAndDirectories}.\n '
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, [])
|
def test_childrenNotFound(self):
'\n Any child resource of L{static.DirectoryLister} renders an HTTP\n I{NOT FOUND} response code.\n '
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
| -4,267,932,203,475,147,300
|
Any child resource of L{static.DirectoryLister} renders an HTTP
I{NOT FOUND} response code.
|
src/twisted/web/test/test_static.py
|
test_childrenNotFound
|
ikingye/twisted
|
python
|
def test_childrenNotFound(self):
'\n Any child resource of L{static.DirectoryLister} renders an HTTP\n I{NOT FOUND} response code.\n '
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
|
def test_repr(self):
'\n L{static.DirectoryLister.__repr__} gives the path of the lister.\n '
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,)))
| -1,958,118,648,294,807,600
|
L{static.DirectoryLister.__repr__} gives the path of the lister.
|
src/twisted/web/test/test_static.py
|
test_repr
|
ikingye/twisted
|
python
|
def test_repr(self):
'\n \n '
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,)))
|
def test_formatFileSize(self):
'\n L{static.formatFileSize} format an amount of bytes into a more readable\n format.\n '
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')
| -2,353,880,983,155,626,000
|
L{static.formatFileSize} format an amount of bytes into a more readable
format.
|
src/twisted/web/test/test_static.py
|
test_formatFileSize
|
ikingye/twisted
|
python
|
def test_formatFileSize(self):
'\n L{static.formatFileSize} format an amount of bytes into a more readable\n format.\n '
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')
|
def _fakeInit(self, paths):
'\n A mock L{mimetypes.init} that records the value of the passed C{paths}\n argument.\n\n @param paths: The paths that will be recorded.\n '
self.paths = paths
| 5,062,677,809,623,193,000
|
A mock L{mimetypes.init} that records the value of the passed C{paths}
argument.
@param paths: The paths that will be recorded.
|
src/twisted/web/test/test_static.py
|
_fakeInit
|
ikingye/twisted
|
python
|
def _fakeInit(self, paths):
'\n A mock L{mimetypes.init} that records the value of the passed C{paths}\n argument.\n\n @param paths: The paths that will be recorded.\n '
self.paths = paths
|
def test_defaultArgumentIsNone(self):
'\n By default, L{None} is passed to C{mimetypes.init}.\n '
static.loadMimeTypes(init=self._fakeInit)
self.assertIdentical(self.paths, None)
| 4,742,965,784,926,496,000
|
By default, L{None} is passed to C{mimetypes.init}.
|
src/twisted/web/test/test_static.py
|
test_defaultArgumentIsNone
|
ikingye/twisted
|
python
|
def test_defaultArgumentIsNone(self):
'\n \n '
static.loadMimeTypes(init=self._fakeInit)
self.assertIdentical(self.paths, None)
|
def test_extraLocationsWork(self):
'\n Passed MIME type files are passed to C{mimetypes.init}.\n '
paths = ['x', 'y', 'z']
static.loadMimeTypes(paths, init=self._fakeInit)
self.assertIdentical(self.paths, paths)
| -974,519,116,068,292,500
|
Passed MIME type files are passed to C{mimetypes.init}.
|
src/twisted/web/test/test_static.py
|
test_extraLocationsWork
|
ikingye/twisted
|
python
|
def test_extraLocationsWork(self):
'\n \n '
paths = ['x', 'y', 'z']
static.loadMimeTypes(paths, init=self._fakeInit)
self.assertIdentical(self.paths, paths)
|
def test_usesGlobalInitFunction(self):
'\n By default, C{mimetypes.init} is called.\n '
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)
| 945,141,539,896,150,300
|
By default, C{mimetypes.init} is called.
|
src/twisted/web/test/test_static.py
|
test_usesGlobalInitFunction
|
ikingye/twisted
|
python
|
def test_usesGlobalInitFunction(self):
'\n \n '
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)
|
def test_addSlashDeprecated(self):
'\n L{twisted.web.static.addSlash} is deprecated.\n '
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')
| 3,913,914,040,382,188,500
|
L{twisted.web.static.addSlash} is deprecated.
|
src/twisted/web/test/test_static.py
|
test_addSlashDeprecated
|
ikingye/twisted
|
python
|
def test_addSlashDeprecated(self):
'\n \n '
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')
|
def rank_genes_groups(adata, groupby, groups='all', group_reference=None, n_genes=100, compute_distribution=False, only_positive=True, copy=False):
'Rank genes according to differential expression [Wolf17]_.\n\n Rank genes by differential expression. By default, a t-test-like ranking is\n used, in which means are normalized with variances. Soon, a Wilcoxon-rank\n test and other alternatives will be provided.\n\n Parameters\n ----------\n adata : `AnnData`\n Annotated data matrix.\n groupby : `str`\n The key of the sample grouping to consider.\n groups : `str`, `list`, optional (default: `\'all\'`)\n Subset of groups, e.g. `[\'g1\', \'g2\', \'g3\']`, to which comparison shall\n be restricted. If not passed, a ranking will be generated for all\n groups.\n group_reference : `str` or `None`, optional (default: `None`)\n If `None`, compare each group to the union of the rest of the group. If\n a group identifier, the comparison will be with respect to this group.\n n_genes : `int` (default: 100)\n How many genes to rank by default.\n compute_distribution : `bool`\n If `True`, also computes the distribution for top-ranked genes, which\n can be visualized using `sc.pl.rank_genes_groups_violin(adata)`.\n\n Returns\n -------\n rank_genes_groups_gene_zscores : np.ndarray of dtype float (adata.add)\n Array of shape (number of comparisons) × (number of genes) storing the\n zscore of the each gene for each test.\n rank_genes_groups_gene_names : np.ndarray of dtype str (adata.add)\n Array of shape (number of comparisons). Stores the labels for each comparison,\n for example "C1 vs. C2" when comparing category \'C1\' with \'C2\'.\n '
logg.info('find differentially expressed genes', r=True)
adata = (adata.copy() if copy else adata)
n_genes_user = n_genes
utils.check_adata(adata)
groups_order = groups
if (isinstance(groups_order, list) and isinstance(groups_order[0], int)):
groups_order = [str(n) for n in groups_order]
if ((group_reference is not None) and (group_reference not in set(groups_order))):
groups_order += [group_reference]
if ((group_reference is not None) and (group_reference not in set(adata.add[(groupby + '_order')]))):
raise ValueError('group_reference = {} needs to be one of groupby = {}.'.format(group_reference, groupby))
(groups_order, groups_masks) = utils.select_groups(adata, groups_order, groupby)
adata.add['rank_genes_groups'] = groupby
adata.add['rank_genes_groups_order'] = groups_order
X = adata.X
n_groups = groups_masks.shape[0]
n_genes = X.shape[1]
means = np.zeros((n_groups, n_genes))
vars = np.zeros((n_groups, n_genes))
ns = np.zeros(n_groups, dtype=int)
for (imask, mask) in enumerate(groups_masks):
(means[imask], vars[imask]) = simple._get_mean_var(X[mask])
ns[imask] = np.where(mask)[0].size
logg.info('... consider "{}":'.format(groupby), groups_order, 'with sample numbers', ns)
if (group_reference is not None):
ireference = np.where((groups_order == group_reference))[0][0]
rankings_gene_zscores = []
rankings_gene_names = []
reference_indices = np.arange(adata.n_vars, dtype=int)
for igroup in range(n_groups):
if (group_reference is None):
mask_rest = (~ groups_masks[igroup])
elif (igroup == ireference):
continue
else:
mask_rest = groups_masks[ireference]
(mean_rest, var_rest) = simple._get_mean_var(X[mask_rest])
ns_rest = np.where(mask_rest)[0].size
denominator = np.sqrt(((vars[igroup] / ns[igroup]) + (var_rest / ns_rest)))
denominator[np.flatnonzero((denominator == 0))] = np.nan
zscores = ((means[igroup] - mean_rest) / denominator)
zscores[np.isnan(zscores)] = 0
zscores = (zscores if only_positive else np.abs(zscores))
partition = np.argpartition(zscores, (- n_genes_user))[(- n_genes_user):]
partial_indices = np.argsort(zscores[partition])[::(- 1)]
global_indices = reference_indices[partition][partial_indices]
rankings_gene_zscores.append(zscores[global_indices])
rankings_gene_names.append(adata.var_names[global_indices])
if compute_distribution:
mask = groups_masks[igroup]
for gene_counter in range(n_genes_user):
gene_idx = global_indices[gene_counter]
X_col = X[(mask, gene_idx)]
if issparse(X):
X_col = X_col.toarray()[:, 0]
identifier = _build_identifier(groupby, groups_order[igroup], gene_counter, adata.var_names[gene_idx])
full_col = np.empty(adata.n_smps)
full_col[:] = np.nan
full_col[mask] = ((X_col - mean_rest[gene_idx]) / denominator[gene_idx])
adata.smp[identifier] = full_col
groups_order_save = groups_order
if (group_reference is not None):
groups_order_save = [g for g in groups_order if (g != group_reference)]
adata.add['rank_genes_groups_gene_scores'] = np.rec.fromarrays([n for n in rankings_gene_zscores], dtype=[(rn, 'float32') for rn in groups_order_save])
adata.add['rank_genes_groups_gene_names'] = np.rec.fromarrays([n for n in rankings_gene_names], dtype=[(rn, 'U50') for rn in groups_order_save])
logg.m(' finished', t=True, end=' ')
logg.m('and added\n "rank_genes_groups_gene_names", np.recarray to be indexed by the `groups` (adata.add)\n "rank_genes_groups_gene_zscores", the scores (adata.add)\n "rank_genes_...", distributions of top-ranked genes (adata.smp)')
return (adata if copy else None)
| 8,561,619,984,092,934,000
|
Rank genes according to differential expression [Wolf17]_.
Rank genes by differential expression. By default, a t-test-like ranking is
used, in which means are normalized with variances. Soon, a Wilcoxon-rank
test and other alternatives will be provided.
Parameters
----------
adata : `AnnData`
Annotated data matrix.
groupby : `str`
The key of the sample grouping to consider.
groups : `str`, `list`, optional (default: `'all'`)
Subset of groups, e.g. `['g1', 'g2', 'g3']`, to which comparison shall
be restricted. If not passed, a ranking will be generated for all
groups.
group_reference : `str` or `None`, optional (default: `None`)
If `None`, compare each group to the union of the rest of the group. If
a group identifier, the comparison will be with respect to this group.
n_genes : `int` (default: 100)
How many genes to rank by default.
compute_distribution : `bool`
If `True`, also computes the distribution for top-ranked genes, which
can be visualized using `sc.pl.rank_genes_groups_violin(adata)`.
Returns
-------
rank_genes_groups_gene_zscores : np.ndarray of dtype float (adata.add)
Array of shape (number of comparisons) × (number of genes) storing the
zscore of the each gene for each test.
rank_genes_groups_gene_names : np.ndarray of dtype str (adata.add)
Array of shape (number of comparisons). Stores the labels for each comparison,
for example "C1 vs. C2" when comparing category 'C1' with 'C2'.
|
scanpy/tools/rank_genes_groups.py
|
rank_genes_groups
|
gioelelm/scanpy
|
python
|
def rank_genes_groups(adata, groupby, groups='all', group_reference=None, n_genes=100, compute_distribution=False, only_positive=True, copy=False):
'Rank genes according to differential expression [Wolf17]_.\n\n Rank genes by differential expression. By default, a t-test-like ranking is\n used, in which means are normalized with variances. Soon, a Wilcoxon-rank\n test and other alternatives will be provided.\n\n Parameters\n ----------\n adata : `AnnData`\n Annotated data matrix.\n groupby : `str`\n The key of the sample grouping to consider.\n groups : `str`, `list`, optional (default: `\'all\'`)\n Subset of groups, e.g. `[\'g1\', \'g2\', \'g3\']`, to which comparison shall\n be restricted. If not passed, a ranking will be generated for all\n groups.\n group_reference : `str` or `None`, optional (default: `None`)\n If `None`, compare each group to the union of the rest of the group. If\n a group identifier, the comparison will be with respect to this group.\n n_genes : `int` (default: 100)\n How many genes to rank by default.\n compute_distribution : `bool`\n If `True`, also computes the distribution for top-ranked genes, which\n can be visualized using `sc.pl.rank_genes_groups_violin(adata)`.\n\n Returns\n -------\n rank_genes_groups_gene_zscores : np.ndarray of dtype float (adata.add)\n Array of shape (number of comparisons) × (number of genes) storing the\n zscore of the each gene for each test.\n rank_genes_groups_gene_names : np.ndarray of dtype str (adata.add)\n Array of shape (number of comparisons). Stores the labels for each comparison,\n for example "C1 vs. C2" when comparing category \'C1\' with \'C2\'.\n '
logg.info('find differentially expressed genes', r=True)
adata = (adata.copy() if copy else adata)
n_genes_user = n_genes
utils.check_adata(adata)
groups_order = groups
if (isinstance(groups_order, list) and isinstance(groups_order[0], int)):
groups_order = [str(n) for n in groups_order]
if ((group_reference is not None) and (group_reference not in set(groups_order))):
groups_order += [group_reference]
if ((group_reference is not None) and (group_reference not in set(adata.add[(groupby + '_order')]))):
raise ValueError('group_reference = {} needs to be one of groupby = {}.'.format(group_reference, groupby))
(groups_order, groups_masks) = utils.select_groups(adata, groups_order, groupby)
adata.add['rank_genes_groups'] = groupby
adata.add['rank_genes_groups_order'] = groups_order
X = adata.X
n_groups = groups_masks.shape[0]
n_genes = X.shape[1]
means = np.zeros((n_groups, n_genes))
vars = np.zeros((n_groups, n_genes))
ns = np.zeros(n_groups, dtype=int)
for (imask, mask) in enumerate(groups_masks):
(means[imask], vars[imask]) = simple._get_mean_var(X[mask])
ns[imask] = np.where(mask)[0].size
logg.info('... consider "{}":'.format(groupby), groups_order, 'with sample numbers', ns)
if (group_reference is not None):
ireference = np.where((groups_order == group_reference))[0][0]
rankings_gene_zscores = []
rankings_gene_names = []
reference_indices = np.arange(adata.n_vars, dtype=int)
for igroup in range(n_groups):
if (group_reference is None):
mask_rest = (~ groups_masks[igroup])
elif (igroup == ireference):
continue
else:
mask_rest = groups_masks[ireference]
(mean_rest, var_rest) = simple._get_mean_var(X[mask_rest])
ns_rest = np.where(mask_rest)[0].size
denominator = np.sqrt(((vars[igroup] / ns[igroup]) + (var_rest / ns_rest)))
denominator[np.flatnonzero((denominator == 0))] = np.nan
zscores = ((means[igroup] - mean_rest) / denominator)
zscores[np.isnan(zscores)] = 0
zscores = (zscores if only_positive else np.abs(zscores))
partition = np.argpartition(zscores, (- n_genes_user))[(- n_genes_user):]
partial_indices = np.argsort(zscores[partition])[::(- 1)]
global_indices = reference_indices[partition][partial_indices]
rankings_gene_zscores.append(zscores[global_indices])
rankings_gene_names.append(adata.var_names[global_indices])
if compute_distribution:
mask = groups_masks[igroup]
for gene_counter in range(n_genes_user):
gene_idx = global_indices[gene_counter]
X_col = X[(mask, gene_idx)]
if issparse(X):
X_col = X_col.toarray()[:, 0]
identifier = _build_identifier(groupby, groups_order[igroup], gene_counter, adata.var_names[gene_idx])
full_col = np.empty(adata.n_smps)
full_col[:] = np.nan
full_col[mask] = ((X_col - mean_rest[gene_idx]) / denominator[gene_idx])
adata.smp[identifier] = full_col
groups_order_save = groups_order
if (group_reference is not None):
groups_order_save = [g for g in groups_order if (g != group_reference)]
adata.add['rank_genes_groups_gene_scores'] = np.rec.fromarrays([n for n in rankings_gene_zscores], dtype=[(rn, 'float32') for rn in groups_order_save])
adata.add['rank_genes_groups_gene_names'] = np.rec.fromarrays([n for n in rankings_gene_names], dtype=[(rn, 'U50') for rn in groups_order_save])
logg.m(' finished', t=True, end=' ')
logg.m('and added\n "rank_genes_groups_gene_names", np.recarray to be indexed by the `groups` (adata.add)\n "rank_genes_groups_gene_zscores", the scores (adata.add)\n "rank_genes_...", distributions of top-ranked genes (adata.smp)')
return (adata if copy else None)
|
def connect(self, receiver=None, **kwargs):
'\n Support decorator syntax:\n\n >>> @signal.connect(sender=type)\n >>> def my_receiver(**kwargs):\n >>> pass\n\n '
def wrapped(func):
return super(BetterSignal, self).connect(func, **kwargs)
if (receiver is None):
return wrapped
return wraps(receiver)(wrapped(receiver))
| 5,741,615,033,492,212,000
|
Support decorator syntax:
>>> @signal.connect(sender=type)
>>> def my_receiver(**kwargs):
>>> pass
|
src/sentry/signals.py
|
connect
|
ChadKillingsworth/sentry
|
python
|
def connect(self, receiver=None, **kwargs):
'\n Support decorator syntax:\n\n >>> @signal.connect(sender=type)\n >>> def my_receiver(**kwargs):\n >>> pass\n\n '
def wrapped(func):
return super(BetterSignal, self).connect(func, **kwargs)
if (receiver is None):
return wrapped
return wraps(receiver)(wrapped(receiver))
|
def calc_wetted_fraction(canopyStore, canopyStore_max, gamma):
' Calculate the wetted fraction of the canopy\n\n Parameters\n ----------\n canopyStore : int or float\n Canopy Interception storage [mm]\n canopyStore_max : int or float\n Maximum non-drainable canopy interception storage [mm]\n gamma : float\n Parameter to account for the non-linearity in the wetted fraction of the canopy\n\n Returns\n -------\n wetFrac: float\n Wetted fraction of the canopy\n '
if (canopyStore < canopyStore_max):
wetFrac = ((canopyStore / canopyStore_max) ** gamma)
else:
wetFrac = 1.0
return wetFrac
| -8,737,017,222,261,279,000
|
Calculate the wetted fraction of the canopy
Parameters
----------
canopyStore : int or float
Canopy Interception storage [mm]
canopyStore_max : int or float
Maximum non-drainable canopy interception storage [mm]
gamma : float
Parameter to account for the non-linearity in the wetted fraction of the canopy
Returns
-------
wetFrac: float
Wetted fraction of the canopy
|
flux_param.py
|
calc_wetted_fraction
|
aelkouk/rainfall_runoff
|
python
|
def calc_wetted_fraction(canopyStore, canopyStore_max, gamma):
' Calculate the wetted fraction of the canopy\n\n Parameters\n ----------\n canopyStore : int or float\n Canopy Interception storage [mm]\n canopyStore_max : int or float\n Maximum non-drainable canopy interception storage [mm]\n gamma : float\n Parameter to account for the non-linearity in the wetted fraction of the canopy\n\n Returns\n -------\n wetFrac: float\n Wetted fraction of the canopy\n '
if (canopyStore < canopyStore_max):
wetFrac = ((canopyStore / canopyStore_max) ** gamma)
else:
wetFrac = 1.0
return wetFrac
|
def calc_canopy_evaporation(pet, wetFrac):
' Calculate the evaporation from canopy interception storage\n\n Parameters\n ----------\n pet : int or float\n Potential evapotranspiration [mm day^-1]\n wetFrac : float\n Wetted fraction of the canopy\n\n Returns\n -------\n canopyEvap: float\n Evaporation from canopy interception storage [mm day^-1]\n '
canopyEvap = (pet * wetFrac)
return canopyEvap
| 6,483,015,903,107,830,000
|
Calculate the evaporation from canopy interception storage
Parameters
----------
pet : int or float
Potential evapotranspiration [mm day^-1]
wetFrac : float
Wetted fraction of the canopy
Returns
-------
canopyEvap: float
Evaporation from canopy interception storage [mm day^-1]
|
flux_param.py
|
calc_canopy_evaporation
|
aelkouk/rainfall_runoff
|
python
|
def calc_canopy_evaporation(pet, wetFrac):
' Calculate the evaporation from canopy interception storage\n\n Parameters\n ----------\n pet : int or float\n Potential evapotranspiration [mm day^-1]\n wetFrac : float\n Wetted fraction of the canopy\n\n Returns\n -------\n canopyEvap: float\n Evaporation from canopy interception storage [mm day^-1]\n '
canopyEvap = (pet * wetFrac)
return canopyEvap
|
def calc_throughfall_flux(precip, canopyStore, canopyStore_max):
' Calculate the throughfall flux from canopy interception storage\n\n Parameters\n ----------\n precip : int or float\n Precipitation flux [mm day^-1]\n canopyStore : int or float\n Canopy Interception storage [mm]\n canopyStore_max : int or float\n Maximum non-drainable canopy interception storage [mm]\n\n Returns\n -------\n throughfall : int or float\n Throughfall flux [mm day^-1]\n '
if (canopyStore < canopyStore_max):
throughfall = (precip * (canopyStore / canopyStore_max))
else:
throughfall = precip
return throughfall
| -8,531,380,039,885,947,000
|
Calculate the throughfall flux from canopy interception storage
Parameters
----------
precip : int or float
Precipitation flux [mm day^-1]
canopyStore : int or float
Canopy Interception storage [mm]
canopyStore_max : int or float
Maximum non-drainable canopy interception storage [mm]
Returns
-------
throughfall : int or float
Throughfall flux [mm day^-1]
|
flux_param.py
|
calc_throughfall_flux
|
aelkouk/rainfall_runoff
|
python
|
def calc_throughfall_flux(precip, canopyStore, canopyStore_max):
' Calculate the throughfall flux from canopy interception storage\n\n Parameters\n ----------\n precip : int or float\n Precipitation flux [mm day^-1]\n canopyStore : int or float\n Canopy Interception storage [mm]\n canopyStore_max : int or float\n Maximum non-drainable canopy interception storage [mm]\n\n Returns\n -------\n throughfall : int or float\n Throughfall flux [mm day^-1]\n '
if (canopyStore < canopyStore_max):
throughfall = (precip * (canopyStore / canopyStore_max))
else:
throughfall = precip
return throughfall
|
def calc_canopy_drainage_flux(canopyStore, canopyStore_max, k_can):
' Calculate the canopy drainage flux from canopy interception storage\n\n Parameters\n ----------\n canopyStore : int or float\n Canopy Interception storage [mm]\n canopyStore_max : int or float\n Maximum non-drainable canopy interception storage [mm]\n k_can: float\n Canopy drainage coe\x0ecient [day^-1]\n\n Returns\n -------\n canopyDrain : int or float\n Canopy drainage flux [mm day^-1]\n '
if (canopyStore < canopyStore_max):
canopyDrain = 0.0
else:
canopyDrain = (k_can * (canopyStore - canopyStore_max))
return canopyDrain
| 3,481,565,100,862,882,000
|
Calculate the canopy drainage flux from canopy interception storage
Parameters
----------
canopyStore : int or float
Canopy Interception storage [mm]
canopyStore_max : int or float
Maximum non-drainable canopy interception storage [mm]
k_can: float
Canopy drainage coecient [day^-1]
Returns
-------
canopyDrain : int or float
Canopy drainage flux [mm day^-1]
|
flux_param.py
|
calc_canopy_drainage_flux
|
aelkouk/rainfall_runoff
|
python
|
def calc_canopy_drainage_flux(canopyStore, canopyStore_max, k_can):
' Calculate the canopy drainage flux from canopy interception storage\n\n Parameters\n ----------\n canopyStore : int or float\n Canopy Interception storage [mm]\n canopyStore_max : int or float\n Maximum non-drainable canopy interception storage [mm]\n k_can: float\n Canopy drainage coe\x0ecient [day^-1]\n\n Returns\n -------\n canopyDrain : int or float\n Canopy drainage flux [mm day^-1]\n '
if (canopyStore < canopyStore_max):
canopyDrain = 0.0
else:
canopyDrain = (k_can * (canopyStore - canopyStore_max))
return canopyDrain
|
def calc_precipitation_excess(throughfall, canopyDrain):
' Calculate excess precipitation (the sum of throughfall and canopy drainage)\n\n Parameters\n ----------\n throughfall : int or float\n Throughfall flux [mm day^-1]\n canopyDrain : int or float\n Canopy drainage flux [mm day^-1]\n Returns\n -------\n precipExcess : int or float\n Excess precipitation [mm day^-1]\n '
precipExcess = (throughfall + canopyDrain)
return precipExcess
| -4,112,685,920,751,450,600
|
Calculate excess precipitation (the sum of throughfall and canopy drainage)
Parameters
----------
throughfall : int or float
Throughfall flux [mm day^-1]
canopyDrain : int or float
Canopy drainage flux [mm day^-1]
Returns
-------
precipExcess : int or float
Excess precipitation [mm day^-1]
|
flux_param.py
|
calc_precipitation_excess
|
aelkouk/rainfall_runoff
|
python
|
def calc_precipitation_excess(throughfall, canopyDrain):
' Calculate excess precipitation (the sum of throughfall and canopy drainage)\n\n Parameters\n ----------\n throughfall : int or float\n Throughfall flux [mm day^-1]\n canopyDrain : int or float\n Canopy drainage flux [mm day^-1]\n Returns\n -------\n precipExcess : int or float\n Excess precipitation [mm day^-1]\n '
precipExcess = (throughfall + canopyDrain)
return precipExcess
|
def calc_saturated_fraction(unsatStore, unsatStore_max, alpha):
' Calculate the saturated fraction of the unsaturated zone\n\n Parameters\n ----------\n unsatStore : int or float\n Storage in the unsaturated zone [mm]\n unsatStore_max : int or float\n Maximum storage in the unsaturated zone [mm]\n alpha : float\n Parameter to account for the non-linearity in the variable source area for saturation-excess runoff\n\n Returns\n -------\n satFrac: float\n Saturated fraction of the unsaturated zone\n '
if (unsatStore < unsatStore_max):
satFrac = (1 - ((1 - (unsatStore / unsatStore_max)) ** alpha))
else:
satFrac = 1
return satFrac
| -1,440,228,671,100,922,600
|
Calculate the saturated fraction of the unsaturated zone
Parameters
----------
unsatStore : int or float
Storage in the unsaturated zone [mm]
unsatStore_max : int or float
Maximum storage in the unsaturated zone [mm]
alpha : float
Parameter to account for the non-linearity in the variable source area for saturation-excess runoff
Returns
-------
satFrac: float
Saturated fraction of the unsaturated zone
|
flux_param.py
|
calc_saturated_fraction
|
aelkouk/rainfall_runoff
|
python
|
def calc_saturated_fraction(unsatStore, unsatStore_max, alpha):
' Calculate the saturated fraction of the unsaturated zone\n\n Parameters\n ----------\n unsatStore : int or float\n Storage in the unsaturated zone [mm]\n unsatStore_max : int or float\n Maximum storage in the unsaturated zone [mm]\n alpha : float\n Parameter to account for the non-linearity in the variable source area for saturation-excess runoff\n\n Returns\n -------\n satFrac: float\n Saturated fraction of the unsaturated zone\n '
if (unsatStore < unsatStore_max):
satFrac = (1 - ((1 - (unsatStore / unsatStore_max)) ** alpha))
else:
satFrac = 1
return satFrac
|
def calc_unsaturated_evaporation(pet, unsatStore, fieldCap, wetFrac):
' Calculate evaporation from the unsaturated zone\n\n Parameters\n ----------\n pet : int or float\n Potential evapotranspiration [mm day^-1]\n unsatStore : int or float\n Storage in the unsaturated zone [mm]\n fieldCap : int or float\n Field capacity [mm]\n wetFrac : float\n Wetted fraction of the canopy\n\n Returns\n -------\n unsatEvap : float\n Evaporation from the unsaturated zone [mm day^-1]\n '
if (unsatStore < fieldCap):
unsatEvap = ((pet * (unsatStore / fieldCap)) * (1 - wetFrac))
else:
unsatEvap = (pet * (1 - wetFrac))
return unsatEvap
| -2,068,569,744,580,078,300
|
Calculate evaporation from the unsaturated zone
Parameters
----------
pet : int or float
Potential evapotranspiration [mm day^-1]
unsatStore : int or float
Storage in the unsaturated zone [mm]
fieldCap : int or float
Field capacity [mm]
wetFrac : float
Wetted fraction of the canopy
Returns
-------
unsatEvap : float
Evaporation from the unsaturated zone [mm day^-1]
|
flux_param.py
|
calc_unsaturated_evaporation
|
aelkouk/rainfall_runoff
|
python
|
def calc_unsaturated_evaporation(pet, unsatStore, fieldCap, wetFrac):
' Calculate evaporation from the unsaturated zone\n\n Parameters\n ----------\n pet : int or float\n Potential evapotranspiration [mm day^-1]\n unsatStore : int or float\n Storage in the unsaturated zone [mm]\n fieldCap : int or float\n Field capacity [mm]\n wetFrac : float\n Wetted fraction of the canopy\n\n Returns\n -------\n unsatEvap : float\n Evaporation from the unsaturated zone [mm day^-1]\n '
if (unsatStore < fieldCap):
unsatEvap = ((pet * (unsatStore / fieldCap)) * (1 - wetFrac))
else:
unsatEvap = (pet * (1 - wetFrac))
return unsatEvap
|
def calc_overland_flow(precipExcess, satFrac):
' Calculate overland flow (surface runoff)\n\n Parameters\n ----------\n precipExcess : int or float\n Excess precipitation [mm day^-1]\n satFrac : float\n Saturated fraction of the unsaturated zone\n Returns\n -------\n overlandFlow : float\n Overland flow (surface runoff) [mm day^-1]\n '
overlandFlow = (precipExcess * satFrac)
return overlandFlow
| 5,386,441,397,117,047,000
|
Calculate overland flow (surface runoff)
Parameters
----------
precipExcess : int or float
Excess precipitation [mm day^-1]
satFrac : float
Saturated fraction of the unsaturated zone
Returns
-------
overlandFlow : float
Overland flow (surface runoff) [mm day^-1]
|
flux_param.py
|
calc_overland_flow
|
aelkouk/rainfall_runoff
|
python
|
def calc_overland_flow(precipExcess, satFrac):
' Calculate overland flow (surface runoff)\n\n Parameters\n ----------\n precipExcess : int or float\n Excess precipitation [mm day^-1]\n satFrac : float\n Saturated fraction of the unsaturated zone\n Returns\n -------\n overlandFlow : float\n Overland flow (surface runoff) [mm day^-1]\n '
overlandFlow = (precipExcess * satFrac)
return overlandFlow
|
def calc_percolation_flux(unsatStore, unsatStore_max, fieldCap, k_sat, beta):
' Calculate the percolation flux from the unsaturated to the saturated zone\n\n Parameters\n ----------\n unsatStore : int or float\n Storage in the unsaturated zone [mm]\n unsatStore_max : int or float\n Maximum storage in the unsaturated zone [mm]\n fieldCap : int or float\n Field capacity [mm]\n k_sat : int or float\n Maximum percolation rate [mm day^-1]\n beta : int or float\n Parameter to account for percolation non-linearity\n\n Returns\n -------\n percolation : int or float\n Percolation flux [mm day^-1]\n '
if (unsatStore < fieldCap):
percolation = 0.0
else:
percolation = (k_sat * (((unsatStore - fieldCap) / (unsatStore_max - fieldCap)) ** beta))
return percolation
| -3,688,662,267,747,456,000
|
Calculate the percolation flux from the unsaturated to the saturated zone
Parameters
----------
unsatStore : int or float
Storage in the unsaturated zone [mm]
unsatStore_max : int or float
Maximum storage in the unsaturated zone [mm]
fieldCap : int or float
Field capacity [mm]
k_sat : int or float
Maximum percolation rate [mm day^-1]
beta : int or float
Parameter to account for percolation non-linearity
Returns
-------
percolation : int or float
Percolation flux [mm day^-1]
|
flux_param.py
|
calc_percolation_flux
|
aelkouk/rainfall_runoff
|
python
|
def calc_percolation_flux(unsatStore, unsatStore_max, fieldCap, k_sat, beta):
' Calculate the percolation flux from the unsaturated to the saturated zone\n\n Parameters\n ----------\n unsatStore : int or float\n Storage in the unsaturated zone [mm]\n unsatStore_max : int or float\n Maximum storage in the unsaturated zone [mm]\n fieldCap : int or float\n Field capacity [mm]\n k_sat : int or float\n Maximum percolation rate [mm day^-1]\n beta : int or float\n Parameter to account for percolation non-linearity\n\n Returns\n -------\n percolation : int or float\n Percolation flux [mm day^-1]\n '
if (unsatStore < fieldCap):
percolation = 0.0
else:
percolation = (k_sat * (((unsatStore - fieldCap) / (unsatStore_max - fieldCap)) ** beta))
return percolation
|
def calc_baseflow(satStore, k_sz):
' Calculate baseflow from the saturated zone\n\n Parameters\n ----------\n satStore : int or float\n Storage in the saturated zone [mm]\n k_sz : float\n Runoff coefficient for the saturated zone [day^-1]\n\n Returns\n -------\n baseflow : float\n Baseflow from the saturated zone [mm day^-1]\n '
baseflow = (satStore * k_sz)
return baseflow
| -2,345,098,295,040,265,700
|
Calculate baseflow from the saturated zone
Parameters
----------
satStore : int or float
Storage in the saturated zone [mm]
k_sz : float
Runoff coefficient for the saturated zone [day^-1]
Returns
-------
baseflow : float
Baseflow from the saturated zone [mm day^-1]
|
flux_param.py
|
calc_baseflow
|
aelkouk/rainfall_runoff
|
python
|
def calc_baseflow(satStore, k_sz):
' Calculate baseflow from the saturated zone\n\n Parameters\n ----------\n satStore : int or float\n Storage in the saturated zone [mm]\n k_sz : float\n Runoff coefficient for the saturated zone [day^-1]\n\n Returns\n -------\n baseflow : float\n Baseflow from the saturated zone [mm day^-1]\n '
baseflow = (satStore * k_sz)
return baseflow
|
def render_nodelist(nodes):
'\n render a nodelist out of all nodes found\n '
all_nodes = []
for node in nodes.values():
all_nodes.append(node.nodelist())
return {'version': '1.0.0', 'updated_at': NOW_TIMESTAMP.isoformat(), 'nodes': all_nodes}
| 7,375,901,422,494,012,000
|
render a nodelist out of all nodes found
|
roles/ffbsee-robin-exporter/files/robin_prometheus.py
|
render_nodelist
|
ffbsee/ffbsee-ansible
|
python
|
def render_nodelist(nodes):
'\n \n '
all_nodes = []
for node in nodes.values():
all_nodes.append(node.nodelist())
return {'version': '1.0.0', 'updated_at': NOW_TIMESTAMP.isoformat(), 'nodes': all_nodes}
|
def load_nodes(path):
'\n load nodes from storage file\n '
nodes = {}
with open(path, 'rb') as file:
nodes = pickle.load(file)
for node in nodes.values():
node.online = False
node.index = None
node.clientcount = 0
return nodes
| 8,085,006,938,907,111,000
|
load nodes from storage file
|
roles/ffbsee-robin-exporter/files/robin_prometheus.py
|
load_nodes
|
ffbsee/ffbsee-ansible
|
python
|
def load_nodes(path):
'\n \n '
nodes = {}
with open(path, 'rb') as file:
nodes = pickle.load(file)
for node in nodes.values():
node.online = False
node.index = None
node.clientcount = 0
return nodes
|
def save_nodes(path, nodes):
'\n save nodes to storage file\n '
with open(path, 'wb') as file:
pickle.dump(nodes, file)
| 3,547,771,320,046,375,400
|
save nodes to storage file
|
roles/ffbsee-robin-exporter/files/robin_prometheus.py
|
save_nodes
|
ffbsee/ffbsee-ansible
|
python
|
def save_nodes(path, nodes):
'\n \n '
with open(path, 'wb') as file:
pickle.dump(nodes, file)
|
def remove_old_nodes(nodes, delta):
'\n remove nodes older than a certain limit\n '
limit = (NOW_TIMESTAMP - delta)
old_keys = []
for (key, node) in nodes.items():
if (node.lastseen < limit):
old_keys.append(key)
count = 0
for key in old_keys:
del nodes[key]
count += 1
print('Removed {} old nodes'.format(count))
| 2,316,065,004,767,788,500
|
remove nodes older than a certain limit
|
roles/ffbsee-robin-exporter/files/robin_prometheus.py
|
remove_old_nodes
|
ffbsee/ffbsee-ansible
|
python
|
def remove_old_nodes(nodes, delta):
'\n \n '
limit = (NOW_TIMESTAMP - delta)
old_keys = []
for (key, node) in nodes.items():
if (node.lastseen < limit):
old_keys.append(key)
count = 0
for key in old_keys:
del nodes[key]
count += 1
print('Removed {} old nodes'.format(count))
|
def is_file(path):
'\n just check whether there is a file on given path\n '
return (path and os.path.isfile(path))
| -1,608,553,595,138,983,400
|
just check whether there is a file on given path
|
roles/ffbsee-robin-exporter/files/robin_prometheus.py
|
is_file
|
ffbsee/ffbsee-ansible
|
python
|
def is_file(path):
'\n \n '
return (path and os.path.isfile(path))
|
def main():
'\n main function collecting data from input file/storage and serving prometheus data\n '
import argparse
parser = argparse.ArgumentParser(description='Convert data received from alfred and provide them as prometheus-service')
parser.add_argument('-m', '--maps', default='robin.txt', help='input file containing data collected by alfred')
parser.add_argument('--storage', default='nodes_backup.bin', help='store old data between calls e.g. to remember node lastseen values')
parser.add_argument('-p', '--port', default=8000, help='the port this service should listen to')
args = parser.parse_args()
nodes = {}
if is_file(args.storage):
nodes = load_nodes(args.storage)
remove_old_nodes(nodes, datetime.timedelta(days=7))
try:
with open(args.maps, 'r') as maps:
for line in maps.readlines():
try:
AlfredParser.parse_line(line.strip(), nodes)
except:
import traceback
print(line)
traceback.print_exc()
continue
nodes_json = render_nodelist(nodes)
except IOError:
exit((('File ' + args.maps) + ' not accessible'))
if args.storage:
save_nodes(args.storage, nodes)
global GLOBAL_NODES
GLOBAL_NODES = nodes_json
global PORT_NUMBER
try:
PORT_NUMBER = int(args.port)
except ValueError:
exit((('Error: ' + args.port) + ' is not a valid port-number'))
| 8,121,735,286,831,113,000
|
main function collecting data from input file/storage and serving prometheus data
|
roles/ffbsee-robin-exporter/files/robin_prometheus.py
|
main
|
ffbsee/ffbsee-ansible
|
python
|
def main():
'\n \n '
import argparse
parser = argparse.ArgumentParser(description='Convert data received from alfred and provide them as prometheus-service')
parser.add_argument('-m', '--maps', default='robin.txt', help='input file containing data collected by alfred')
parser.add_argument('--storage', default='nodes_backup.bin', help='store old data between calls e.g. to remember node lastseen values')
parser.add_argument('-p', '--port', default=8000, help='the port this service should listen to')
args = parser.parse_args()
nodes = {}
if is_file(args.storage):
nodes = load_nodes(args.storage)
remove_old_nodes(nodes, datetime.timedelta(days=7))
try:
with open(args.maps, 'r') as maps:
for line in maps.readlines():
try:
AlfredParser.parse_line(line.strip(), nodes)
except:
import traceback
print(line)
traceback.print_exc()
continue
nodes_json = render_nodelist(nodes)
except IOError:
exit((('File ' + args.maps) + ' not accessible'))
if args.storage:
save_nodes(args.storage, nodes)
global GLOBAL_NODES
GLOBAL_NODES = nodes_json
global PORT_NUMBER
try:
PORT_NUMBER = int(args.port)
except ValueError:
exit((('Error: ' + args.port) + ' is not a valid port-number'))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.