code
stringlengths
26
870k
docstring
stringlengths
1
65.6k
func_name
stringlengths
1
194
language
stringclasses
1 value
repo
stringlengths
8
68
path
stringlengths
5
182
url
stringlengths
46
251
license
stringclasses
4 values
def test_requestResponseCodeMessage(self): """ The response code and message can be set by the request object passed to a distributed resource's C{render} method. """ class SetResponseCode(resource.Resource): def render(self, request): request.setResponseCode(200, b"some-message") return "" request = self._requestAgentTest(SetResponseCode()) def cbRequested(result): self.assertEqual(result[0].data, b"") self.assertEqual(result[1].code, 200) self.assertEqual(result[1].phrase, b"some-message") request.addCallback(cbRequested) return request
The response code and message can be set by the request object passed to a distributed resource's C{render} method.
test_requestResponseCodeMessage
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
MIT
def test_largeWrite(self): """ If a string longer than the Banana size limit is passed to the L{distrib.Request} passed to the remote resource, it is broken into smaller strings to be transported over the PB connection. """ class LargeWrite(resource.Resource): def render(self, request): request.write(b'x' * SIZE_LIMIT + b'y') request.finish() return server.NOT_DONE_YET request = self._requestTest(LargeWrite()) request.addCallback(self.assertEqual, b'x' * SIZE_LIMIT + b'y') return request
If a string longer than the Banana size limit is passed to the L{distrib.Request} passed to the remote resource, it is broken into smaller strings to be transported over the PB connection.
test_largeWrite
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
MIT
def test_largeReturn(self): """ Like L{test_largeWrite}, but for the case where C{render} returns a long string rather than explicitly passing it to L{Request.write}. """ class LargeReturn(resource.Resource): def render(self, request): return b'x' * SIZE_LIMIT + b'y' request = self._requestTest(LargeReturn()) request.addCallback(self.assertEqual, b'x' * SIZE_LIMIT + b'y') return request
Like L{test_largeWrite}, but for the case where C{render} returns a long string rather than explicitly passing it to L{Request.write}.
test_largeReturn
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
MIT
def test_connectionLost(self): """ If there is an error issuing the request to the remote publisher, an error response is returned. """ # Using pb.Root as a publisher will cause request calls to fail with an # error every time. Just what we want to test. self.f1 = serverFactory = PBServerFactory(pb.Root()) self.port1 = serverPort = reactor.listenTCP(0, serverFactory) self.sub = subscription = distrib.ResourceSubscription( "127.0.0.1", serverPort.getHost().port) request = DummyRequest([b'']) d = _render(subscription, request) def cbRendered(ignored): self.assertEqual(request.responseCode, 500) # This is the error we caused the request to fail with. It should # have been logged. errors = self.flushLoggedErrors(pb.NoSuchMethod) self.assertEqual(len(errors), 1) # The error page is rendered as HTML. expected = [ b'', b'<html>', b' <head><title>500 - Server Connection Lost</title></head>', b' <body>', b' <h1>Server Connection Lost</h1>', b' <p>Connection to distributed server lost:' b'<pre>' b'[Failure instance: Traceback from remote host -- ' b'twisted.spread.flavors.NoSuchMethod: ' b'No such method: remote_request', b']</pre></p>', b' </body>', b'</html>', b'' ] self.assertEqual([b'\n'.join(expected)], request.written) d.addCallback(cbRendered) return d
If there is an error issuing the request to the remote publisher, an error response is returned.
test_connectionLost
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
MIT
def test_logFailed(self): """ When a request fails, the string form of the failure is logged. """ logObserver = proto_helpers.EventLoggingObserver.createWithCleanup( self, globalLogPublisher ) f = failure.Failure(ArbitraryError()) request = DummyRequest([b'']) issue = distrib.Issue(request) issue.failed(f) self.assertEquals(1, len(logObserver)) self.assertIn( "Failure instance", logObserver[0]["log_format"] )
When a request fails, the string form of the failure is logged.
test_logFailed
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
MIT
def test_requestFail(self): """ When L{twisted.web.distrib.Request}'s fail is called, the failure is logged. """ logObserver = proto_helpers.EventLoggingObserver.createWithCleanup( self, globalLogPublisher ) err = ArbitraryError() f = failure.Failure(err) req = distrib.Request(DummyChannel()) req.fail(f) self.flushLoggedErrors(ArbitraryError) self.assertEquals(1, len(logObserver)) self.assertIs(logObserver[0]["log_failure"], f)
When L{twisted.web.distrib.Request}'s fail is called, the failure is logged.
test_requestFail
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
MIT
def test_interface(self): """ L{UserDirectory} instances provide L{resource.IResource}. """ self.assertTrue(verifyObject(resource.IResource, self.directory))
L{UserDirectory} instances provide L{resource.IResource}.
test_interface
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
MIT
def _404Test(self, name): """ Verify that requesting the C{name} child of C{self.directory} results in a 404 response. """ request = DummyRequest([name]) result = self.directory.getChild(name, request) d = _render(result, request) def cbRendered(ignored): self.assertEqual(request.responseCode, 404) d.addCallback(cbRendered) return d
Verify that requesting the C{name} child of C{self.directory} results in a 404 response.
_404Test
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
MIT
def test_getInvalidUser(self): """ L{UserDirectory.getChild} returns a resource which renders a 404 response when passed a string which does not correspond to any known user. """ return self._404Test('carol')
L{UserDirectory.getChild} returns a resource which renders a 404 response when passed a string which does not correspond to any known user.
test_getInvalidUser
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
MIT
def test_getUserWithoutResource(self): """ L{UserDirectory.getChild} returns a resource which renders a 404 response when passed a string which corresponds to a known user who has neither a user directory nor a user distrib socket. """ return self._404Test('alice')
L{UserDirectory.getChild} returns a resource which renders a 404 response when passed a string which corresponds to a known user who has neither a user directory nor a user distrib socket.
test_getUserWithoutResource
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
MIT
def test_getPublicHTMLChild(self): """ L{UserDirectory.getChild} returns a L{static.File} instance when passed the name of a user with a home directory containing a I{public_html} directory. """ home = filepath.FilePath(self.bob[-2]) public_html = home.child('public_html') public_html.makedirs() request = DummyRequest(['bob']) result = self.directory.getChild('bob', request) self.assertIsInstance(result, static.File) self.assertEqual(result.path, public_html.path)
L{UserDirectory.getChild} returns a L{static.File} instance when passed the name of a user with a home directory containing a I{public_html} directory.
test_getPublicHTMLChild
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
MIT
def test_getDistribChild(self): """ L{UserDirectory.getChild} returns a L{ResourceSubscription} instance when passed the name of a user suffixed with C{".twistd"} who has a home directory containing a I{.twistd-web-pb} socket. """ home = filepath.FilePath(self.bob[-2]) home.makedirs() web = home.child('.twistd-web-pb') request = DummyRequest(['bob']) result = self.directory.getChild('bob.twistd', request) self.assertIsInstance(result, distrib.ResourceSubscription) self.assertEqual(result.host, 'unix') self.assertEqual(abspath(result.port), web.path)
L{UserDirectory.getChild} returns a L{ResourceSubscription} instance when passed the name of a user suffixed with C{".twistd"} who has a home directory containing a I{.twistd-web-pb} socket.
test_getDistribChild
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
MIT
def test_invalidMethod(self): """ L{UserDirectory.render} raises L{UnsupportedMethod} in response to a non-I{GET} request. """ request = DummyRequest(['']) request.method = 'POST' self.assertRaises( server.UnsupportedMethod, self.directory.render, request)
L{UserDirectory.render} raises L{UnsupportedMethod} in response to a non-I{GET} request.
test_invalidMethod
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
MIT
def test_render(self): """ L{UserDirectory} renders a list of links to available user content in response to a I{GET} request. """ public_html = filepath.FilePath(self.alice[-2]).child('public_html') public_html.makedirs() web = filepath.FilePath(self.bob[-2]) web.makedirs() # This really only works if it's a unix socket, but the implementation # doesn't currently check for that. It probably should someday, and # then skip users with non-sockets. web.child('.twistd-web-pb').setContent(b"") request = DummyRequest(['']) result = _render(self.directory, request) def cbRendered(ignored): document = parseString(b''.join(request.written)) # Each user should have an li with a link to their page. [alice, bob] = document.getElementsByTagName('li') self.assertEqual(alice.firstChild.tagName, 'a') self.assertEqual(alice.firstChild.getAttribute('href'), 'alice/') self.assertEqual(alice.firstChild.firstChild.data, 'Alice (file)') self.assertEqual(bob.firstChild.tagName, 'a') self.assertEqual(bob.firstChild.getAttribute('href'), 'bob.twistd/') self.assertEqual(bob.firstChild.firstChild.data, 'Bob (twistd)') result.addCallback(cbRendered) return result
L{UserDirectory} renders a list of links to available user content in response to a I{GET} request.
test_render
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
MIT
def test_passwordDatabase(self): """ If L{UserDirectory} is instantiated with no arguments, it uses the L{pwd} module as its password database. """ directory = distrib.UserDirectory() self.assertIdentical(directory._pwd, pwd)
If L{UserDirectory} is instantiated with no arguments, it uses the L{pwd} module as its password database.
test_passwordDatabase
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
MIT
def test_protectedServerAndDate(self): """ If the CGI script emits a I{Server} or I{Date} header, these are ignored. """ cgiFilename = self.writeCGI(SPECIAL_HEADER_CGI) portnum = self.startServer(cgiFilename) url = "http://localhost:%d/cgi" % (portnum,) url = url.encode("ascii") agent = client.Agent(reactor) d = agent.request(b"GET", url) d.addCallback(discardBody) def checkResponse(response): self.assertNotIn('monkeys', response.headers.getRawHeaders('server')) self.assertNotIn('last year', response.headers.getRawHeaders('date')) d.addCallback(checkResponse) return d
If the CGI script emits a I{Server} or I{Date} header, these are ignored.
test_protectedServerAndDate
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
MIT
def test_noDuplicateContentTypeHeaders(self): """ If the CGI script emits a I{content-type} header, make sure that the server doesn't add an additional (duplicate) one, as per ticket 4786. """ cgiFilename = self.writeCGI(NO_DUPLICATE_CONTENT_TYPE_HEADER_CGI) portnum = self.startServer(cgiFilename) url = "http://localhost:%d/cgi" % (portnum,) url = url.encode("ascii") agent = client.Agent(reactor) d = agent.request(b"GET", url) d.addCallback(discardBody) def checkResponse(response): self.assertEqual( response.headers.getRawHeaders('content-type'), ['text/cgi-duplicate-test']) return response d.addCallback(checkResponse) return d
If the CGI script emits a I{content-type} header, make sure that the server doesn't add an additional (duplicate) one, as per ticket 4786.
test_noDuplicateContentTypeHeaders
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
MIT
def test_noProxyPassthrough(self): """ The CGI script is never called with the Proxy header passed through. """ cgiFilename = self.writeCGI(HEADER_OUTPUT_CGI) portnum = self.startServer(cgiFilename) url = "http://localhost:%d/cgi" % (portnum,) url = url.encode("ascii") agent = client.Agent(reactor) headers = http_headers.Headers({b"Proxy": [b"foo"], b"X-Innocent-Header": [b"bar"]}) d = agent.request(b"GET", url, headers=headers) def checkResponse(response): headers = json.loads(response.decode("ascii")) self.assertEqual( set(headers.keys()), {"HTTP_HOST", "HTTP_CONNECTION", "HTTP_X_INNOCENT_HEADER"}) d.addCallback(client.readBody) d.addCallback(checkResponse) return d
The CGI script is never called with the Proxy header passed through.
test_noProxyPassthrough
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
MIT
def test_duplicateHeaderCGI(self): """ If a CGI script emits two instances of the same header, both are sent in the response. """ cgiFilename = self.writeCGI(DUAL_HEADER_CGI) portnum = self.startServer(cgiFilename) url = "http://localhost:%d/cgi" % (portnum,) url = url.encode("ascii") agent = client.Agent(reactor) d = agent.request(b"GET", url) d.addCallback(discardBody) def checkResponse(response): self.assertEqual( response.headers.getRawHeaders('header'), ['spam', 'eggs']) d.addCallback(checkResponse) return d
If a CGI script emits two instances of the same header, both are sent in the response.
test_duplicateHeaderCGI
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
MIT
def test_malformedHeaderCGI(self): """ Check for the error message in the duplicated header """ cgiFilename = self.writeCGI(BROKEN_HEADER_CGI) portnum = self.startServer(cgiFilename) url = "http://localhost:%d/cgi" % (portnum,) url = url.encode("ascii") agent = client.Agent(reactor) d = agent.request(b"GET", url) d.addCallback(discardBody) loggedMessages = [] def addMessage(eventDict): loggedMessages.append(log.textFromEventDict(eventDict)) log.addObserver(addMessage) self.addCleanup(log.removeObserver, addMessage) def checkResponse(ignored): self.assertIn("ignoring malformed CGI header: " + repr(b'XYZ'), loggedMessages) d.addCallback(checkResponse) return d
Check for the error message in the duplicated header
test_malformedHeaderCGI
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
MIT
def spawnProcess(self, *args, **kwargs): """ Set the C{called} flag to C{True} if C{spawnProcess} is called. @param args: Positional arguments. @param kwargs: Keyword arguments. """ self.called = True
Set the C{called} flag to C{True} if C{spawnProcess} is called. @param args: Positional arguments. @param kwargs: Keyword arguments.
test_useReactorArgument.spawnProcess
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
MIT
def test_useReactorArgument(self): """ L{twcgi.FilteredScript.runProcess} uses the reactor passed as an argument to the constructor. """ class FakeReactor: """ A fake reactor recording whether spawnProcess is called. """ called = False def spawnProcess(self, *args, **kwargs): """ Set the C{called} flag to C{True} if C{spawnProcess} is called. @param args: Positional arguments. @param kwargs: Keyword arguments. """ self.called = True fakeReactor = FakeReactor() request = DummyRequest(['a', 'b']) request.client = address.IPv4Address('TCP', '127.0.0.1', 12345) resource = twcgi.FilteredScript("dummy-file", reactor=fakeReactor) _render(resource, request) self.assertTrue(fakeReactor.called)
L{twcgi.FilteredScript.runProcess} uses the reactor passed as an argument to the constructor.
test_useReactorArgument
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
MIT
def spawnProcess(self, process, filename, args, env, wdir): """ Store the C{env} L{dict} to an instance attribute. @param process: Ignored @param filename: Ignored @param args: Ignored @param env: The environment L{dict} which will be stored @param wdir: Ignored """ self.process_env = env
Store the C{env} L{dict} to an instance attribute. @param process: Ignored @param filename: Ignored @param args: Ignored @param env: The environment L{dict} which will be stored @param wdir: Ignored
test_pathInfo.spawnProcess
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
MIT
def test_pathInfo(self): """ L{twcgi.CGIScript.render} sets the process environment I{PATH_INFO} from the request path. """ class FakeReactor: """ A fake reactor recording the environment passed to spawnProcess. """ def spawnProcess(self, process, filename, args, env, wdir): """ Store the C{env} L{dict} to an instance attribute. @param process: Ignored @param filename: Ignored @param args: Ignored @param env: The environment L{dict} which will be stored @param wdir: Ignored """ self.process_env = env _reactor = FakeReactor() resource = twcgi.CGIScript(self.mktemp(), reactor=_reactor) request = DummyRequest(['a', 'b']) request.client = address.IPv4Address('TCP', '127.0.0.1', 12345) _render(resource, request) self.assertEqual(_reactor.process_env["PATH_INFO"], "/a/b")
L{twcgi.CGIScript.render} sets the process environment I{PATH_INFO} from the request path.
test_pathInfo
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
MIT
def test_render(self): """ L{twcgi.CGIDirectory.render} sets the HTTP response code to I{NOT FOUND}. """ resource = twcgi.CGIDirectory(self.mktemp()) request = DummyRequest(['']) d = _render(resource, request) def cbRendered(ignored): self.assertEqual(request.responseCode, NOT_FOUND) d.addCallback(cbRendered) return d
L{twcgi.CGIDirectory.render} sets the HTTP response code to I{NOT FOUND}.
test_render
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
MIT
def test_notFoundChild(self): """ L{twcgi.CGIDirectory.getChild} returns a resource which renders an response with the HTTP I{NOT FOUND} status code if the indicated child does not exist as an entry in the directory used to initialized the L{twcgi.CGIDirectory}. """ path = self.mktemp() os.makedirs(path) resource = twcgi.CGIDirectory(path) request = DummyRequest(['foo']) child = resource.getChild("foo", request) d = _render(child, request) def cbRendered(ignored): self.assertEqual(request.responseCode, NOT_FOUND) d.addCallback(cbRendered) return d
L{twcgi.CGIDirectory.getChild} returns a resource which renders an response with the HTTP I{NOT FOUND} status code if the indicated child does not exist as an entry in the directory used to initialized the L{twcgi.CGIDirectory}.
test_notFoundChild
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
MIT
def test_prematureEndOfHeaders(self): """ If the process communicating with L{CGIProcessProtocol} ends before finishing writing out headers, the response has I{INTERNAL SERVER ERROR} as its status code. """ request = DummyRequest(['']) protocol = twcgi.CGIProcessProtocol(request) protocol.processEnded(failure.Failure(error.ProcessTerminated())) self.assertEqual(request.responseCode, INTERNAL_SERVER_ERROR)
If the process communicating with L{CGIProcessProtocol} ends before finishing writing out headers, the response has I{INTERNAL SERVER ERROR} as its status code.
test_prematureEndOfHeaders
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
MIT
def discardBody(response): """ Discard the body of a HTTP response. @param response: The response. @return: The response. """ return client.readBody(response).addCallback(lambda _: response)
Discard the body of a HTTP response. @param response: The response. @return: The response.
discardBody
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_cgi.py
MIT
def _makeRequestProxyFactory(clsToWrap): """ Return a callable that proxies instances of C{clsToWrap} via L{_IDeprecatedHTTPChannelToRequestInterface}. @param clsToWrap: The class whose instances will be proxied. @type cls: L{_IDeprecatedHTTPChannelToRequestInterface} implementer. @return: A factory that returns L{_IDeprecatedHTTPChannelToRequestInterface} proxies. @rtype: L{callable} whose interface matches C{clsToWrap}'s constructor. """ def _makeRequestProxy(*args, **kwargs): instance = clsToWrap(*args, **kwargs) return _IDeprecatedHTTPChannelToRequestInterfaceProxy(instance) # For INonQueuedRequestFactory directlyProvides(_makeRequestProxy, providedBy(clsToWrap)) return _makeRequestProxy
Return a callable that proxies instances of C{clsToWrap} via L{_IDeprecatedHTTPChannelToRequestInterface}. @param clsToWrap: The class whose instances will be proxied. @type cls: L{_IDeprecatedHTTPChannelToRequestInterface} implementer. @return: A factory that returns L{_IDeprecatedHTTPChannelToRequestInterface} proxies. @rtype: L{callable} whose interface matches C{clsToWrap}'s constructor.
_makeRequestProxyFactory
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def parametrizeTimeoutMixin(protocol, reactor): """ Parametrizes the L{TimeoutMixin} so that it works with whatever reactor is being used by the test. @param protocol: A L{_GenericHTTPChannel} or something implementing a similar interface. @type protocol: L{_GenericHTTPChannel} @param reactor: An L{IReactorTime} implementation. @type reactor: L{IReactorTime} @return: The C{channel}, with its C{callLater} method patched. """ # This is a terrible violation of the abstraction later of # _genericHTTPChannelProtocol, but we need to do it because # policies.TimeoutMixin doesn't accept a reactor on the object. # See https://twistedmatrix.com/trac/ticket/8488 protocol._channel.callLater = reactor.callLater return protocol
Parametrizes the L{TimeoutMixin} so that it works with whatever reactor is being used by the test. @param protocol: A L{_GenericHTTPChannel} or something implementing a similar interface. @type protocol: L{_GenericHTTPChannel} @param reactor: An L{IReactorTime} implementation. @type reactor: L{IReactorTime} @return: The C{channel}, with its C{callLater} method patched.
parametrizeTimeoutMixin
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def assertResponseEquals(self, responses, expected): """ Assert that the C{responses} matches the C{expected} responses. @type responses: C{bytes} @param responses: The bytes sent in response to one or more requests. @type expected: C{list} of C{tuple} of C{bytes} @param expected: The expected values for the responses. Each tuple element of the list represents one response. Each byte string element of the tuple is a full header line without delimiter, except for the last element which gives the full response body. """ for response in expected: expectedHeaders, expectedContent = response[:-1], response[-1] # Intentionally avoid mutating the inputs here. expectedStatus = expectedHeaders[0] expectedHeaders = expectedHeaders[1:] headers, rest = responses.split(b'\r\n\r\n', 1) headers = headers.splitlines() status = headers.pop(0) self.assertEqual(expectedStatus, status) self.assertEqual(set(headers), set(expectedHeaders)) content = rest[:len(expectedContent)] responses = rest[len(expectedContent):] self.assertEqual(content, expectedContent)
Assert that the C{responses} matches the C{expected} responses. @type responses: C{bytes} @param responses: The bytes sent in response to one or more requests. @type expected: C{list} of C{tuple} of C{bytes} @param expected: The expected values for the responses. Each tuple element of the list represents one response. Each byte string element of the tuple is a full header line without delimiter, except for the last element which gives the full response body.
assertResponseEquals
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_buffer(self): """ Send requests over a channel and check responses match what is expected. """ b = StringTransport() a = http.HTTPChannel() a.requestFactory = DummyHTTPHandlerProxy a.makeConnection(b) # one byte at a time, to stress it. for byte in iterbytes(self.requests): a.dataReceived(byte) a.connectionLost(IOError("all one")) value = b.value() self.assertResponseEquals(value, self.expected_response)
Send requests over a channel and check responses match what is expected.
test_buffer
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_requestBodyTimeout(self): """ L{HTTPChannel} resets its timeout whenever data from a request body is delivered to it. """ clock = Clock() transport = StringTransport() protocol = http.HTTPChannel() protocol.timeOut = 100 protocol.callLater = clock.callLater protocol.makeConnection(transport) protocol.dataReceived(b'POST / HTTP/1.0\r\nContent-Length: 2\r\n\r\n') clock.advance(99) self.assertFalse(transport.disconnecting) protocol.dataReceived(b'x') clock.advance(99) self.assertFalse(transport.disconnecting) protocol.dataReceived(b'x') self.assertEqual(len(protocol.requests), 1)
L{HTTPChannel} resets its timeout whenever data from a request body is delivered to it.
test_requestBodyTimeout
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_requestBodyDefaultTimeout(self): """ L{HTTPChannel}'s default timeout is 60 seconds. """ clock = Clock() transport = StringTransport() factory = http.HTTPFactory() protocol = factory.buildProtocol(None) protocol = parametrizeTimeoutMixin(protocol, clock) protocol.makeConnection(transport) protocol.dataReceived(b'POST / HTTP/1.0\r\nContent-Length: 2\r\n\r\n') clock.advance(59) self.assertFalse(transport.disconnecting) clock.advance(1) self.assertTrue(transport.disconnecting)
L{HTTPChannel}'s default timeout is 60 seconds.
test_requestBodyDefaultTimeout
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_transportNotAbortedAfterConnectionLost(self): """ If a timed out transport ends up calling C{connectionLost}, it prevents the force-closure of the transport. """ clock = Clock() transport = StringTransport() factory = http.HTTPFactory() protocol = factory.buildProtocol(None) protocol = parametrizeTimeoutMixin(protocol, clock) protocol.makeConnection(transport) protocol.dataReceived(b'POST / HTTP/1.0\r\nContent-Length: 2\r\n\r\n') self.assertFalse(transport.disconnecting) self.assertFalse(transport.disconnected) # Force the initial timeout. clock.advance(60) self.assertTrue(transport.disconnecting) self.assertFalse(transport.disconnected) # Move forward nearly to the timeout, then fire connectionLost. clock.advance(14) protocol.connectionLost(None) # Check that the transport isn't forcibly closed. clock.advance(1) self.assertTrue(transport.disconnecting) self.assertFalse(transport.disconnected)
If a timed out transport ends up calling C{connectionLost}, it prevents the force-closure of the transport.
test_transportNotAbortedAfterConnectionLost
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_transportNotAbortedWithZeroAbortTimeout(self): """ If the L{HTTPChannel} has its c{abortTimeout} set to L{None}, it never aborts. """ clock = Clock() transport = StringTransport() factory = http.HTTPFactory() protocol = factory.buildProtocol(None) protocol._channel.abortTimeout = None protocol = parametrizeTimeoutMixin(protocol, clock) protocol.makeConnection(transport) protocol.dataReceived(b'POST / HTTP/1.0\r\nContent-Length: 2\r\n\r\n') self.assertFalse(transport.disconnecting) self.assertFalse(transport.disconnected) # Force the initial timeout. clock.advance(60) self.assertTrue(transport.disconnecting) self.assertFalse(transport.disconnected) # Move an absurdly long way just to prove the point. clock.advance(2**32) self.assertTrue(transport.disconnecting) self.assertFalse(transport.disconnected)
If the L{HTTPChannel} has its c{abortTimeout} set to L{None}, it never aborts.
test_transportNotAbortedWithZeroAbortTimeout
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_noPipeliningApi(self): """ Test that a L{http.Request} subclass with no queued kwarg works as expected. """ b = StringTransport() a = http.HTTPChannel() a.requestFactory = DummyHTTPHandlerProxy a.makeConnection(b) # one byte at a time, to stress it. for byte in iterbytes(self.requests): a.dataReceived(byte) a.connectionLost(IOError("all done")) value = b.value() self.assertResponseEquals(value, self.expected_response)
Test that a L{http.Request} subclass with no queued kwarg works as expected.
test_noPipeliningApi
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_noPipelining(self): """ Test that pipelined requests get buffered, not processed in parallel. """ b = StringTransport() a = http.HTTPChannel() a.requestFactory = DelayedHTTPHandlerProxy a.makeConnection(b) # one byte at a time, to stress it. for byte in iterbytes(self.requests): a.dataReceived(byte) value = b.value() # So far only one request should have been dispatched. self.assertEqual(value, b'') self.assertEqual(1, len(a.requests)) # Now, process each request one at a time. while a.requests: self.assertEqual(1, len(a.requests)) request = a.requests[0].original request.delayedProcess() value = b.value() self.assertResponseEquals(value, self.expected_response)
Test that pipelined requests get buffered, not processed in parallel.
test_noPipelining
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_pipeliningReadLimit(self): """ When pipelined requests are received, we will optimistically continue receiving data up to a specified limit, then pause the transport. @see: L{http.HTTPChannel._optimisticEagerReadSize} """ b = StringTransport() a = http.HTTPChannel() a.requestFactory = DelayedHTTPHandlerProxy a.makeConnection(b) underLimit = a._optimisticEagerReadSize // len(self.requests) for x in range(1, underLimit + 1): a.dataReceived(self.requests) self.assertEqual(b.producerState, 'producing', 'state was {state!r} after {x} iterations' .format(state=b.producerState, x=x)) a.dataReceived(self.requests) self.assertEquals(b.producerState, 'paused')
When pipelined requests are received, we will optimistically continue receiving data up to a specified limit, then pause the transport. @see: L{http.HTTPChannel._optimisticEagerReadSize}
test_pipeliningReadLimit
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_losingConnection(self): """ Calling L{http.Request.loseConnection} causes the transport to be disconnected. """ b = StringTransport() a = http.HTTPChannel() a.requestFactory = _makeRequestProxyFactory(self.ShutdownHTTPHandler) a.makeConnection(b) a.dataReceived(self.request) # The transport should have been shut down. self.assertTrue(b.disconnecting) # No response should have been written. value = b.value() self.assertEqual(value, b'')
Calling L{http.Request.loseConnection} causes the transport to be disconnected.
test_losingConnection
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_isSecure(self): """ Calling L{http.Request.isSecure} when the channel is backed with a secure transport will return L{True}. """ b = DummyChannel.SSL() a = http.HTTPChannel() a.makeConnection(b) req = http.Request(a) self.assertTrue(req.isSecure())
Calling L{http.Request.isSecure} when the channel is backed with a secure transport will return L{True}.
test_isSecure
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_notSecure(self): """ Calling L{http.Request.isSecure} when the channel is not backed with a secure transport will return L{False}. """ b = DummyChannel.TCP() a = http.HTTPChannel() a.makeConnection(b) req = http.Request(a) self.assertFalse(req.isSecure())
Calling L{http.Request.isSecure} when the channel is not backed with a secure transport will return L{False}.
test_notSecure
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_notSecureAfterFinish(self): """ After a request is finished, calling L{http.Request.isSecure} will always return L{False}. """ b = DummyChannel.SSL() a = http.HTTPChannel() a.makeConnection(b) req = http.Request(a) a.requests.append(req) req.setResponseCode(200) req.finish() self.assertFalse(req.isSecure())
After a request is finished, calling L{http.Request.isSecure} will always return L{False}.
test_notSecureAfterFinish
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def _negotiatedProtocolForTransportInstance(self, t): """ Run a request using the specific instance of a transport. Returns the negotiated protocol string. """ a = http._genericHTTPChannelProtocolFactory(b'') a.requestFactory = DummyHTTPHandlerProxy a.makeConnection(t) # one byte at a time, to stress it. for byte in iterbytes(self.requests): a.dataReceived(byte) a.connectionLost(IOError("all done")) return a._negotiatedProtocol
Run a request using the specific instance of a transport. Returns the negotiated protocol string.
_negotiatedProtocolForTransportInstance
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_protocolUnspecified(self): """ If the transport has no support for protocol negotiation (no negotiatedProtocol attribute), HTTP/1.1 is assumed. """ b = StringTransport() negotiatedProtocol = self._negotiatedProtocolForTransportInstance(b) self.assertEqual(negotiatedProtocol, b'http/1.1')
If the transport has no support for protocol negotiation (no negotiatedProtocol attribute), HTTP/1.1 is assumed.
test_protocolUnspecified
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_protocolNone(self): """ If the transport has no support for protocol negotiation (returns None for negotiatedProtocol), HTTP/1.1 is assumed. """ b = StringTransport() b.negotiatedProtocol = None negotiatedProtocol = self._negotiatedProtocolForTransportInstance(b) self.assertEqual(negotiatedProtocol, b'http/1.1')
If the transport has no support for protocol negotiation (returns None for negotiatedProtocol), HTTP/1.1 is assumed.
test_protocolNone
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_http11(self): """ If the transport reports that HTTP/1.1 is negotiated, that's what's negotiated. """ b = StringTransport() b.negotiatedProtocol = b'http/1.1' negotiatedProtocol = self._negotiatedProtocolForTransportInstance(b) self.assertEqual(negotiatedProtocol, b'http/1.1')
If the transport reports that HTTP/1.1 is negotiated, that's what's negotiated.
test_http11
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_http2_present(self): """ If the transport reports that HTTP/2 is negotiated and HTTP/2 is present, that's what's negotiated. """ b = StringTransport() b.negotiatedProtocol = b'h2' negotiatedProtocol = self._negotiatedProtocolForTransportInstance(b) self.assertEqual(negotiatedProtocol, b'h2')
If the transport reports that HTTP/2 is negotiated and HTTP/2 is present, that's what's negotiated.
test_http2_present
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_http2_absent(self): """ If the transport reports that HTTP/2 is negotiated and HTTP/2 is not present, an error is encountered. """ b = StringTransport() b.negotiatedProtocol = b'h2' self.assertRaises( ValueError, self._negotiatedProtocolForTransportInstance, b, )
If the transport reports that HTTP/2 is negotiated and HTTP/2 is not present, an error is encountered.
test_http2_absent
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_unknownProtocol(self): """ If the transport reports that a protocol other than HTTP/1.1 or HTTP/2 is negotiated, an error occurs. """ b = StringTransport() b.negotiatedProtocol = b'smtp' self.assertRaises( AssertionError, self._negotiatedProtocolForTransportInstance, b, )
If the transport reports that a protocol other than HTTP/1.1 or HTTP/2 is negotiated, an error occurs.
test_unknownProtocol
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_factory(self): """ The C{factory} attribute is taken from the inner channel. """ a = http._genericHTTPChannelProtocolFactory(b'') a._channel.factory = b"Foo" self.assertEqual(a.factory, b"Foo")
The C{factory} attribute is taken from the inner channel.
test_factory
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_GenericHTTPChannelPropagatesCallLater(self): """ If C{callLater} is patched onto the L{http._GenericHTTPChannelProtocol} then we need to propagate it through to the backing channel. """ clock = Clock() factory = http.HTTPFactory(reactor=clock) protocol = factory.buildProtocol(None) self.assertEqual(protocol.callLater, clock.callLater) self.assertEqual(protocol._channel.callLater, clock.callLater)
If C{callLater} is patched onto the L{http._GenericHTTPChannelProtocol} then we need to propagate it through to the backing channel.
test_GenericHTTPChannelPropagatesCallLater
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_genericHTTPChannelCallLaterUpgrade(self): """ If C{callLater} is patched onto the L{http._GenericHTTPChannelProtocol} then we need to propagate it across onto a new backing channel after upgrade. """ clock = Clock() factory = http.HTTPFactory(reactor=clock) protocol = factory.buildProtocol(None) self.assertEqual(protocol.callLater, clock.callLater) self.assertEqual(protocol._channel.callLater, clock.callLater) transport = StringTransport() transport.negotiatedProtocol = b'h2' protocol.requestFactory = DummyHTTPHandler protocol.makeConnection(transport) # Send a byte to make it think the handshake is done. protocol.dataReceived(b'P') self.assertEqual(protocol.callLater, clock.callLater) self.assertEqual(protocol._channel.callLater, clock.callLater)
If C{callLater} is patched onto the L{http._GenericHTTPChannelProtocol} then we need to propagate it across onto a new backing channel after upgrade.
test_genericHTTPChannelCallLaterUpgrade
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_unregistersProducer(self): """ The L{_GenericHTTPChannelProtocol} will unregister its proxy channel from the transport if upgrade is negotiated. """ transport = StringTransport() transport.negotiatedProtocol = b'h2' genericProtocol = http._genericHTTPChannelProtocolFactory(b'') genericProtocol.requestFactory = DummyHTTPHandlerProxy genericProtocol.makeConnection(transport) # We expect the transport has a underlying channel registered as # a producer. self.assertIs(transport.producer, genericProtocol._channel) # Force the upgrade. genericProtocol.dataReceived(b'P') # The transport should now have no producer. self.assertIs(transport.producer, None)
The L{_GenericHTTPChannelProtocol} will unregister its proxy channel from the transport if upgrade is negotiated.
test_unregistersProducer
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def _prequest(**headers): """ Make a request with the given request headers for the persistence tests. """ request = http.Request(DummyChannel(), False) for headerName, v in headers.items(): request.requestHeaders.setRawHeaders(networkString(headerName), v) return request
Make a request with the given request headers for the persistence tests.
_prequest
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_http09(self): """ After being used for an I{HTTP/0.9} request, the L{HTTPChannel} is not persistent. """ persist = self.channel.checkPersistence(self.request, b"HTTP/0.9") self.assertFalse(persist) self.assertEqual( [], list(self.request.responseHeaders.getAllRawHeaders()))
After being used for an I{HTTP/0.9} request, the L{HTTPChannel} is not persistent.
test_http09
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_http10(self): """ After being used for an I{HTTP/1.0} request, the L{HTTPChannel} is not persistent. """ persist = self.channel.checkPersistence(self.request, b"HTTP/1.0") self.assertFalse(persist) self.assertEqual( [], list(self.request.responseHeaders.getAllRawHeaders()))
After being used for an I{HTTP/1.0} request, the L{HTTPChannel} is not persistent.
test_http10
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_http11(self): """ After being used for an I{HTTP/1.1} request, the L{HTTPChannel} is persistent. """ persist = self.channel.checkPersistence(self.request, b"HTTP/1.1") self.assertTrue(persist) self.assertEqual( [], list(self.request.responseHeaders.getAllRawHeaders()))
After being used for an I{HTTP/1.1} request, the L{HTTPChannel} is persistent.
test_http11
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_http11Close(self): """ After being used for an I{HTTP/1.1} request with a I{Connection: Close} header, the L{HTTPChannel} is not persistent. """ request = _prequest(connection=[b"close"]) persist = self.channel.checkPersistence(request, b"HTTP/1.1") self.assertFalse(persist) self.assertEqual( [(b"Connection", [b"close"])], list(request.responseHeaders.getAllRawHeaders()))
After being used for an I{HTTP/1.1} request with a I{Connection: Close} header, the L{HTTPChannel} is not persistent.
test_http11Close
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def setUp(self): """ Create an L{_IdentityTransferDecoder} with callbacks hooked up so that calls to them can be inspected. """ self.data = [] self.finish = [] self.contentLength = 10 self.decoder = _IdentityTransferDecoder( self.contentLength, self.data.append, self.finish.append)
Create an L{_IdentityTransferDecoder} with callbacks hooked up so that calls to them can be inspected.
setUp
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_exactAmountReceived(self): """ If L{_IdentityTransferDecoder.dataReceived} is called with a byte string with length equal to the content length passed to L{_IdentityTransferDecoder}'s initializer, the data callback is invoked with that string and the finish callback is invoked with a zero-length string. """ self.decoder.dataReceived(b'x' * self.contentLength) self.assertEqual(self.data, [b'x' * self.contentLength]) self.assertEqual(self.finish, [b''])
If L{_IdentityTransferDecoder.dataReceived} is called with a byte string with length equal to the content length passed to L{_IdentityTransferDecoder}'s initializer, the data callback is invoked with that string and the finish callback is invoked with a zero-length string.
test_exactAmountReceived
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_shortStrings(self): """ If L{_IdentityTransferDecoder.dataReceived} is called multiple times with byte strings which, when concatenated, are as long as the content length provided, the data callback is invoked with each string and the finish callback is invoked only after the second call. """ self.decoder.dataReceived(b'x') self.assertEqual(self.data, [b'x']) self.assertEqual(self.finish, []) self.decoder.dataReceived(b'y' * (self.contentLength - 1)) self.assertEqual(self.data, [b'x', b'y' * (self.contentLength - 1)]) self.assertEqual(self.finish, [b''])
If L{_IdentityTransferDecoder.dataReceived} is called multiple times with byte strings which, when concatenated, are as long as the content length provided, the data callback is invoked with each string and the finish callback is invoked only after the second call.
test_shortStrings
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_longString(self): """ If L{_IdentityTransferDecoder.dataReceived} is called with a byte string with length greater than the provided content length, only the prefix of that string up to the content length is passed to the data callback and the remainder is passed to the finish callback. """ self.decoder.dataReceived(b'x' * self.contentLength + b'y') self.assertEqual(self.data, [b'x' * self.contentLength]) self.assertEqual(self.finish, [b'y'])
If L{_IdentityTransferDecoder.dataReceived} is called with a byte string with length greater than the provided content length, only the prefix of that string up to the content length is passed to the data callback and the remainder is passed to the finish callback.
test_longString
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_rejectDataAfterFinished(self): """ If data is passed to L{_IdentityTransferDecoder.dataReceived} after the finish callback has been invoked, C{RuntimeError} is raised. """ failures = [] def finish(bytes): try: decoder.dataReceived(b'foo') except: failures.append(Failure()) decoder = _IdentityTransferDecoder(5, self.data.append, finish) decoder.dataReceived(b'x' * 4) self.assertEqual(failures, []) decoder.dataReceived(b'y') failures[0].trap(RuntimeError) self.assertEqual( str(failures[0].value), "_IdentityTransferDecoder cannot decode data after finishing")
If data is passed to L{_IdentityTransferDecoder.dataReceived} after the finish callback has been invoked, C{RuntimeError} is raised.
test_rejectDataAfterFinished
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_unknownContentLength(self): """ If L{_IdentityTransferDecoder} is constructed with L{None} for the content length, it passes all data delivered to it through to the data callback. """ data = [] finish = [] decoder = _IdentityTransferDecoder(None, data.append, finish.append) decoder.dataReceived(b'x') self.assertEqual(data, [b'x']) decoder.dataReceived(b'y') self.assertEqual(data, [b'x', b'y']) self.assertEqual(finish, [])
If L{_IdentityTransferDecoder} is constructed with L{None} for the content length, it passes all data delivered to it through to the data callback.
test_unknownContentLength
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def _verifyCallbacksUnreferenced(self, decoder): """ Check the decoder's data and finish callbacks and make sure they are None in order to help avoid references cycles. """ self.assertIdentical(decoder.dataCallback, None) self.assertIdentical(decoder.finishCallback, None)
Check the decoder's data and finish callbacks and make sure they are None in order to help avoid references cycles.
_verifyCallbacksUnreferenced
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_earlyConnectionLose(self): """ L{_IdentityTransferDecoder.noMoreData} raises L{_DataLoss} if it is called and the content length is known but not enough bytes have been delivered. """ self.decoder.dataReceived(b'x' * (self.contentLength - 1)) self.assertRaises(_DataLoss, self.decoder.noMoreData) self._verifyCallbacksUnreferenced(self.decoder)
L{_IdentityTransferDecoder.noMoreData} raises L{_DataLoss} if it is called and the content length is known but not enough bytes have been delivered.
test_earlyConnectionLose
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_unknownContentLengthConnectionLose(self): """ L{_IdentityTransferDecoder.noMoreData} calls the finish callback and raises L{PotentialDataLoss} if it is called and the content length is unknown. """ body = [] finished = [] decoder = _IdentityTransferDecoder(None, body.append, finished.append) self.assertRaises(PotentialDataLoss, decoder.noMoreData) self.assertEqual(body, []) self.assertEqual(finished, [b'']) self._verifyCallbacksUnreferenced(decoder)
L{_IdentityTransferDecoder.noMoreData} calls the finish callback and raises L{PotentialDataLoss} if it is called and the content length is unknown.
test_unknownContentLengthConnectionLose
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_finishedConnectionLose(self): """ L{_IdentityTransferDecoder.noMoreData} does not raise any exception if it is called when the content length is known and that many bytes have been delivered. """ self.decoder.dataReceived(b'x' * self.contentLength) self.decoder.noMoreData() self._verifyCallbacksUnreferenced(self.decoder)
L{_IdentityTransferDecoder.noMoreData} does not raise any exception if it is called when the content length is known and that many bytes have been delivered.
test_finishedConnectionLose
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_decoding(self): """ L{_ChunkedTransferDecoder.dataReceived} decodes chunked-encoded data and passes the result to the specified callback. """ L = [] p = http._ChunkedTransferDecoder(L.append, None) p.dataReceived(b'3\r\nabc\r\n5\r\n12345\r\n') p.dataReceived(b'a\r\n0123456789\r\n') self.assertEqual(L, [b'abc', b'12345', b'0123456789'])
L{_ChunkedTransferDecoder.dataReceived} decodes chunked-encoded data and passes the result to the specified callback.
test_decoding
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_short(self): """ L{_ChunkedTransferDecoder.dataReceived} decodes chunks broken up and delivered in multiple calls. """ L = [] finished = [] p = http._ChunkedTransferDecoder(L.append, finished.append) for s in iterbytes(b'3\r\nabc\r\n5\r\n12345\r\n0\r\n\r\n'): p.dataReceived(s) self.assertEqual(L, [b'a', b'b', b'c', b'1', b'2', b'3', b'4', b'5']) self.assertEqual(finished, [b''])
L{_ChunkedTransferDecoder.dataReceived} decodes chunks broken up and delivered in multiple calls.
test_short
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_newlines(self): """ L{_ChunkedTransferDecoder.dataReceived} doesn't treat CR LF pairs embedded in chunk bodies specially. """ L = [] p = http._ChunkedTransferDecoder(L.append, None) p.dataReceived(b'2\r\n\r\n\r\n') self.assertEqual(L, [b'\r\n'])
L{_ChunkedTransferDecoder.dataReceived} doesn't treat CR LF pairs embedded in chunk bodies specially.
test_newlines
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_extensions(self): """ L{_ChunkedTransferDecoder.dataReceived} disregards chunk-extension fields. """ L = [] p = http._ChunkedTransferDecoder(L.append, None) p.dataReceived(b'3; x-foo=bar\r\nabc\r\n') self.assertEqual(L, [b'abc'])
L{_ChunkedTransferDecoder.dataReceived} disregards chunk-extension fields.
test_extensions
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_finish(self): """ L{_ChunkedTransferDecoder.dataReceived} interprets a zero-length chunk as the end of the chunked data stream and calls the completion callback. """ finished = [] p = http._ChunkedTransferDecoder(None, finished.append) p.dataReceived(b'0\r\n\r\n') self.assertEqual(finished, [b''])
L{_ChunkedTransferDecoder.dataReceived} interprets a zero-length chunk as the end of the chunked data stream and calls the completion callback.
test_finish
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_extra(self): """ L{_ChunkedTransferDecoder.dataReceived} passes any bytes which come after the terminating zero-length chunk to the completion callback. """ finished = [] p = http._ChunkedTransferDecoder(None, finished.append) p.dataReceived(b'0\r\n\r\nhello') self.assertEqual(finished, [b'hello'])
L{_ChunkedTransferDecoder.dataReceived} passes any bytes which come after the terminating zero-length chunk to the completion callback.
test_extra
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_afterFinished(self): """ L{_ChunkedTransferDecoder.dataReceived} raises C{RuntimeError} if it is called after it has seen the last chunk. """ p = http._ChunkedTransferDecoder(None, lambda bytes: None) p.dataReceived(b'0\r\n\r\n') self.assertRaises(RuntimeError, p.dataReceived, b'hello')
L{_ChunkedTransferDecoder.dataReceived} raises C{RuntimeError} if it is called after it has seen the last chunk.
test_afterFinished
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_earlyConnectionLose(self): """ L{_ChunkedTransferDecoder.noMoreData} raises L{_DataLoss} if it is called and the end of the last trailer has not yet been received. """ parser = http._ChunkedTransferDecoder(None, lambda bytes: None) parser.dataReceived(b'0\r\n\r') exc = self.assertRaises(_DataLoss, parser.noMoreData) self.assertEqual( str(exc), "Chunked decoder in 'TRAILER' state, still expecting more data " "to get to 'FINISHED' state.")
L{_ChunkedTransferDecoder.noMoreData} raises L{_DataLoss} if it is called and the end of the last trailer has not yet been received.
test_earlyConnectionLose
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_finishedConnectionLose(self): """ L{_ChunkedTransferDecoder.noMoreData} does not raise any exception if it is called after the terminal zero length chunk is received. """ parser = http._ChunkedTransferDecoder(None, lambda bytes: None) parser.dataReceived(b'0\r\n\r\n') parser.noMoreData()
L{_ChunkedTransferDecoder.noMoreData} does not raise any exception if it is called after the terminal zero length chunk is received.
test_finishedConnectionLose
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_reentrantFinishedNoMoreData(self): """ L{_ChunkedTransferDecoder.noMoreData} can be called from the finished callback without raising an exception. """ errors = [] successes = [] def finished(extra): try: parser.noMoreData() except: errors.append(Failure()) else: successes.append(True) parser = http._ChunkedTransferDecoder(None, finished) parser.dataReceived(b'0\r\n\r\n') self.assertEqual(errors, []) self.assertEqual(successes, [True])
L{_ChunkedTransferDecoder.noMoreData} can be called from the finished callback without raising an exception.
test_reentrantFinishedNoMoreData
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_chunkedResponses(self): """ Test that the L{HTTPChannel} correctly chunks responses when needed. """ trans = StringTransport() channel = http.HTTPChannel() channel.makeConnection(trans) req = http.Request(channel, False) req.setResponseCode(200) req.clientproto = b"HTTP/1.1" req.responseHeaders.setRawHeaders(b"test", [b"lemur"]) req.write(b'Hello') req.write(b'World!') self.assertResponseEquals( trans.value(), [(b"HTTP/1.1 200 OK", b"Test: lemur", b"Transfer-Encoding: chunked", b"5\r\nHello\r\n6\r\nWorld!\r\n")])
Test that the L{HTTPChannel} correctly chunks responses when needed.
test_chunkedResponses
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def runRequest(self, httpRequest, requestFactory=None, success=True, channel=None): """ Execute a web request based on plain text content. @param httpRequest: Content for the request which is processed. @type httpRequest: C{bytes} @param requestFactory: 2-argument callable returning a Request. @type requestFactory: C{callable} @param success: Value to compare against I{self.didRequest}. @type success: C{bool} @param channel: Channel instance over which the request is processed. @type channel: L{HTTPChannel} @return: Returns the channel used for processing the request. @rtype: L{HTTPChannel} """ if not channel: channel = http.HTTPChannel() if requestFactory: channel.requestFactory = _makeRequestProxyFactory(requestFactory) httpRequest = httpRequest.replace(b"\n", b"\r\n") transport = StringTransport() channel.makeConnection(transport) # one byte at a time, to stress it. for byte in iterbytes(httpRequest): if channel.transport.disconnecting: break channel.dataReceived(byte) channel.connectionLost(IOError("all done")) if success: self.assertTrue(self.didRequest) else: self.assertFalse(self.didRequest) return channel
Execute a web request based on plain text content. @param httpRequest: Content for the request which is processed. @type httpRequest: C{bytes} @param requestFactory: 2-argument callable returning a Request. @type requestFactory: C{callable} @param success: Value to compare against I{self.didRequest}. @type success: C{bool} @param channel: Channel instance over which the request is processed. @type channel: L{HTTPChannel} @return: Returns the channel used for processing the request. @rtype: L{HTTPChannel}
runRequest
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_invalidNonAsciiMethod(self): """ When client sends invalid HTTP method containing non-ascii characters HTTP 400 'Bad Request' status will be returned. """ processed = [] class MyRequest(http.Request): def process(self): processed.append(self) self.finish() badRequestLine = b"GE\xc2\xa9 / HTTP/1.1\r\n\r\n" channel = self.runRequest(badRequestLine, MyRequest, 0) self.assertEqual( channel.transport.value(), b"HTTP/1.1 400 Bad Request\r\n\r\n") self.assertTrue(channel.transport.disconnecting) self.assertEqual(processed, [])
When client sends invalid HTTP method containing non-ascii characters HTTP 400 'Bad Request' status will be returned.
test_invalidNonAsciiMethod
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_basicAuth(self): """ L{HTTPChannel} provides username and password information supplied in an I{Authorization} header to the L{Request} which makes it available via its C{getUser} and C{getPassword} methods. """ requests = [] class Request(http.Request): def process(self): self.credentials = (self.getUser(), self.getPassword()) requests.append(self) for u, p in [(b"foo", b"bar"), (b"hello", b"there:z")]: s = base64.encodestring(b":".join((u, p))).strip() f = b"GET / HTTP/1.0\nAuthorization: Basic " + s + b"\n\n" self.runRequest(f, Request, 0) req = requests.pop() self.assertEqual((u, p), req.credentials)
L{HTTPChannel} provides username and password information supplied in an I{Authorization} header to the L{Request} which makes it available via its C{getUser} and C{getPassword} methods.
test_basicAuth
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_headers(self): """ Headers received by L{HTTPChannel} in a request are made available to the L{Request}. """ processed = [] class MyRequest(http.Request): def process(self): processed.append(self) self.finish() requestLines = [ b"GET / HTTP/1.0", b"Foo: bar", b"baz: Quux", b"baz: quux", b"", b""] self.runRequest(b'\n'.join(requestLines), MyRequest, 0) [request] = processed self.assertEqual( request.requestHeaders.getRawHeaders(b'foo'), [b'bar']) self.assertEqual( request.requestHeaders.getRawHeaders(b'bAz'), [b'Quux', b'quux'])
Headers received by L{HTTPChannel} in a request are made available to the L{Request}.
test_headers
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_headersMultiline(self): """ Line folded headers are handled by L{HTTPChannel} by replacing each fold with a single space by the time they are made available to the L{Request}. Any leading whitespace in the folded lines of the header value is preserved. See RFC 7230 section 3.2.4. """ processed = [] class MyRequest(http.Request): def process(self): processed.append(self) self.finish() requestLines = [ b"GET / HTTP/1.0", b"nospace: ", b" nospace\t", b"space:space", b" space", b"spaces: spaces", b" spaces", b" spaces", b"tab: t", b"\ta", b"\tb", b"", b"", ] self.runRequest(b"\n".join(requestLines), MyRequest, 0) [request] = processed # All leading and trailing whitespace is stripped from the # header-value. self.assertEqual( request.requestHeaders.getRawHeaders(b"nospace"), [b"nospace"], ) self.assertEqual( request.requestHeaders.getRawHeaders(b"space"), [b"space space"], ) self.assertEqual( request.requestHeaders.getRawHeaders(b"spaces"), [b"spaces spaces spaces"], ) self.assertEqual( request.requestHeaders.getRawHeaders(b"tab"), [b"t \ta \tb"], )
Line folded headers are handled by L{HTTPChannel} by replacing each fold with a single space by the time they are made available to the L{Request}. Any leading whitespace in the folded lines of the header value is preserved. See RFC 7230 section 3.2.4.
test_headersMultiline
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_tooManyHeaders(self): """ L{HTTPChannel} enforces a limit of C{HTTPChannel.maxHeaders} on the number of headers received per request. """ processed = [] class MyRequest(http.Request): def process(self): processed.append(self) requestLines = [b"GET / HTTP/1.0"] for i in range(http.HTTPChannel.maxHeaders + 2): requestLines.append(networkString("%s: foo" % (i,))) requestLines.extend([b"", b""]) channel = self.runRequest(b"\n".join(requestLines), MyRequest, 0) self.assertEqual(processed, []) self.assertEqual( channel.transport.value(), b"HTTP/1.1 400 Bad Request\r\n\r\n")
L{HTTPChannel} enforces a limit of C{HTTPChannel.maxHeaders} on the number of headers received per request.
test_tooManyHeaders
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_invalidContentLengthHeader(self): """ If a Content-Length header with a non-integer value is received, a 400 (Bad Request) response is sent to the client and the connection is closed. """ processed = [] class MyRequest(http.Request): def process(self): processed.append(self) self.finish() requestLines = [b"GET / HTTP/1.0", b"Content-Length: x", b"", b""] channel = self.runRequest(b"\n".join(requestLines), MyRequest, 0) self.assertEqual( channel.transport.value(), b"HTTP/1.1 400 Bad Request\r\n\r\n") self.assertTrue(channel.transport.disconnecting) self.assertEqual(processed, [])
If a Content-Length header with a non-integer value is received, a 400 (Bad Request) response is sent to the client and the connection is closed.
test_invalidContentLengthHeader
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_invalidHeaderNoColon(self): """ If a header without colon is received a 400 (Bad Request) response is sent to the client and the connection is closed. """ processed = [] class MyRequest(http.Request): def process(self): processed.append(self) self.finish() requestLines = [b"GET / HTTP/1.0", b"HeaderName ", b"", b""] channel = self.runRequest(b"\n".join(requestLines), MyRequest, 0) self.assertEqual( channel.transport.value(), b"HTTP/1.1 400 Bad Request\r\n\r\n") self.assertTrue(channel.transport.disconnecting) self.assertEqual(processed, [])
If a header without colon is received a 400 (Bad Request) response is sent to the client and the connection is closed.
test_invalidHeaderNoColon
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_headerLimitPerRequest(self): """ L{HTTPChannel} enforces the limit of C{HTTPChannel.maxHeaders} per request so that headers received in an earlier request do not count towards the limit when processing a later request. """ processed = [] class MyRequest(http.Request): def process(self): processed.append(self) self.finish() self.patch(http.HTTPChannel, 'maxHeaders', 1) requestLines = [ b"GET / HTTP/1.1", b"Foo: bar", b"", b"", b"GET / HTTP/1.1", b"Bar: baz", b"", b""] channel = self.runRequest(b"\n".join(requestLines), MyRequest, 0) [first, second] = processed self.assertEqual(first.getHeader(b'foo'), b'bar') self.assertEqual(second.getHeader(b'bar'), b'baz') self.assertEqual( channel.transport.value(), b'HTTP/1.1 200 OK\r\n' b'Transfer-Encoding: chunked\r\n' b'\r\n' b'0\r\n' b'\r\n' b'HTTP/1.1 200 OK\r\n' b'Transfer-Encoding: chunked\r\n' b'\r\n' b'0\r\n' b'\r\n')
L{HTTPChannel} enforces the limit of C{HTTPChannel.maxHeaders} per request so that headers received in an earlier request do not count towards the limit when processing a later request.
test_headerLimitPerRequest
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_headersTooBigInitialCommand(self): """ Enforces a limit of C{HTTPChannel.totalHeadersSize} on the size of headers received per request starting from initial command line. """ processed = [] class MyRequest(http.Request): def process(self): processed.append(self) self.finish() channel = http.HTTPChannel() channel.totalHeadersSize = 10 httpRequest = b'GET /path/longer/than/10 HTTP/1.1\n' channel = self.runRequest( httpRequest=httpRequest, requestFactory=MyRequest, channel=channel, success=False ) self.assertEqual(processed, []) self.assertEqual( channel.transport.value(), b"HTTP/1.1 400 Bad Request\r\n\r\n")
Enforces a limit of C{HTTPChannel.totalHeadersSize} on the size of headers received per request starting from initial command line.
test_headersTooBigInitialCommand
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_headersTooBigOtherHeaders(self): """ Enforces a limit of C{HTTPChannel.totalHeadersSize} on the size of headers received per request counting first line and total headers. """ processed = [] class MyRequest(http.Request): def process(self): processed.append(self) self.finish() channel = http.HTTPChannel() channel.totalHeadersSize = 40 httpRequest = ( b'GET /less/than/40 HTTP/1.1\n' b'Some-Header: less-than-40\n' ) channel = self.runRequest( httpRequest=httpRequest, requestFactory=MyRequest, channel=channel, success=False ) self.assertEqual(processed, []) self.assertEqual( channel.transport.value(), b"HTTP/1.1 400 Bad Request\r\n\r\n")
Enforces a limit of C{HTTPChannel.totalHeadersSize} on the size of headers received per request counting first line and total headers.
test_headersTooBigOtherHeaders
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_headersTooBigPerRequest(self): """ Enforces total size of headers per individual request and counter is reset at the end of each request. """ class SimpleRequest(http.Request): def process(self): self.finish() channel = http.HTTPChannel() channel.totalHeadersSize = 60 channel.requestFactory = SimpleRequest httpRequest = ( b'GET / HTTP/1.1\n' b'Some-Header: total-less-than-60\n' b'\n' b'GET / HTTP/1.1\n' b'Some-Header: less-than-60\n' b'\n' ) channel = self.runRequest( httpRequest=httpRequest, channel=channel, success=False) self.assertEqual( channel.transport.value(), b'HTTP/1.1 200 OK\r\n' b'Transfer-Encoding: chunked\r\n' b'\r\n' b'0\r\n' b'\r\n' b'HTTP/1.1 200 OK\r\n' b'Transfer-Encoding: chunked\r\n' b'\r\n' b'0\r\n' b'\r\n' )
Enforces total size of headers per individual request and counter is reset at the end of each request.
test_headersTooBigPerRequest
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def testCookies(self): """ Test cookies parsing and reading. """ httpRequest = b'''\ GET / HTTP/1.0 Cookie: rabbit="eat carrot"; ninja=secret; spam="hey 1=1!" ''' cookies = {} testcase = self class MyRequest(http.Request): def process(self): for name in [b'rabbit', b'ninja', b'spam']: cookies[name] = self.getCookie(name) testcase.didRequest = True self.finish() self.runRequest(httpRequest, MyRequest) self.assertEqual( cookies, { b'rabbit': b'"eat carrot"', b'ninja': b'secret', b'spam': b'"hey 1=1!"'})
Test cookies parsing and reading.
testCookies
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_extraQuestionMark(self): """ While only a single '?' is allowed in an URL, several other servers allow several and pass all after the first through as part of the query arguments. Test that we emulate this behavior. """ httpRequest = b'GET /foo?bar=?&baz=quux HTTP/1.0\n\n' method = [] path = [] args = [] testcase = self class MyRequest(http.Request): def process(self): method.append(self.method) path.append(self.path) args.extend([self.args[b'bar'], self.args[b'baz']]) testcase.didRequest = True self.finish() self.runRequest(httpRequest, MyRequest) self.assertEqual(method, [b'GET']) self.assertEqual(path, [b'/foo']) self.assertEqual(args, [[b'?'], [b'quux']])
While only a single '?' is allowed in an URL, several other servers allow several and pass all after the first through as part of the query arguments. Test that we emulate this behavior.
test_extraQuestionMark
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_formPOSTRequest(self): """ The request body of a I{POST} request with a I{Content-Type} header of I{application/x-www-form-urlencoded} is parsed according to that content type and made available in the C{args} attribute of the request object. The original bytes of the request may still be read from the C{content} attribute. """ query = 'key=value&multiple=two+words&multiple=more%20words&empty=' httpRequest = networkString('''\ POST / HTTP/1.0 Content-Length: %d Content-Type: application/x-www-form-urlencoded %s''' % (len(query), query)) method = [] args = [] content = [] testcase = self class MyRequest(http.Request): def process(self): method.append(self.method) args.extend([ self.args[b'key'], self.args[b'empty'], self.args[b'multiple']]) content.append(self.content.read()) testcase.didRequest = True self.finish() self.runRequest(httpRequest, MyRequest) self.assertEqual(method, [b"POST"]) self.assertEqual( args, [[b"value"], [b""], [b"two words", b"more words"]]) # Reading from the content file-like must produce the entire request # body. self.assertEqual(content, [networkString(query)])
The request body of a I{POST} request with a I{Content-Type} header of I{application/x-www-form-urlencoded} is parsed according to that content type and made available in the C{args} attribute of the request object. The original bytes of the request may still be read from the C{content} attribute.
test_formPOSTRequest
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_missingContentDisposition(self): """ If the C{Content-Disposition} header is missing, the request is denied as a bad request. """ req = b'''\ POST / HTTP/1.0 Content-Type: multipart/form-data; boundary=AaB03x Content-Length: 103 --AaB03x Content-Type: text/plain Content-Transfer-Encoding: quoted-printable abasdfg --AaB03x-- ''' channel = self.runRequest(req, http.Request, success=False) self.assertEqual( channel.transport.value(), b"HTTP/1.1 400 Bad Request\r\n\r\n")
If the C{Content-Disposition} header is missing, the request is denied as a bad request.
test_missingContentDisposition
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_multipartProcessingFailure(self): """ When the multipart processing fails the client gets a 400 Bad Request. """ # The parsing failure is having a UTF-8 boundary -- the spec # says it must be ASCII. req = b'''\ POST / HTTP/1.0 Content-Type: multipart/form-data; boundary=\xe2\x98\x83 Content-Length: 103 --\xe2\x98\x83 Content-Type: text/plain Content-Length: 999999999999999999999999999999999999999999999999999999999999999 Content-Transfer-Encoding: quoted-printable abasdfg --\xe2\x98\x83-- ''' channel = self.runRequest(req, http.Request, success=False) self.assertEqual( channel.transport.value(), b"HTTP/1.1 400 Bad Request\r\n\r\n")
When the multipart processing fails the client gets a 400 Bad Request.
test_multipartProcessingFailure
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_multipartFormData(self): """ If the request has a Content-Type of C{multipart/form-data}, and the form data is parseable, the form arguments will be added to the request's args. """ processed = [] class MyRequest(http.Request): def process(self): processed.append(self) self.write(b"done") self.finish() req = b'''\ POST / HTTP/1.0 Content-Type: multipart/form-data; boundary=AaB03x Content-Length: 149 --AaB03x Content-Type: text/plain Content-Disposition: form-data; name="text" Content-Transfer-Encoding: quoted-printable abasdfg --AaB03x-- ''' channel = self.runRequest(req, MyRequest, success=False) self.assertEqual(channel.transport.value(), b"HTTP/1.0 200 OK\r\n\r\ndone") self.assertEqual(len(processed), 1) self.assertEqual(processed[0].args, {b"text": [b"abasdfg"]})
If the request has a Content-Type of C{multipart/form-data}, and the form data is parseable, the form arguments will be added to the request's args.
test_multipartFormData
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_multipartFileData(self): """ If the request has a Content-Type of C{multipart/form-data}, and the form data is parseable and contains files, the file portions will be added to the request's args. """ processed = [] class MyRequest(http.Request): def process(self): processed.append(self) self.write(b"done") self.finish() body = b"""-----------------------------738837029596785559389649595 Content-Disposition: form-data; name="uploadedfile"; filename="test" Content-Type: application/octet-stream abasdfg -----------------------------738837029596785559389649595-- """ req = '''\ POST / HTTP/1.0 Content-Type: multipart/form-data; boundary=---------------------------738837029596785559389649595 Content-Length: ''' + str(len(body.replace(b"\n", b"\r\n"))) + ''' ''' channel = self.runRequest(req.encode('ascii') + body, MyRequest, success=False) self.assertEqual(channel.transport.value(), b"HTTP/1.0 200 OK\r\n\r\ndone") self.assertEqual(len(processed), 1) self.assertEqual(processed[0].args, {b"uploadedfile": [b"abasdfg"]})
If the request has a Content-Type of C{multipart/form-data}, and the form data is parseable and contains files, the file portions will be added to the request's args.
test_multipartFileData
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT
def test_chunkedEncoding(self): """ If a request uses the I{chunked} transfer encoding, the request body is decoded accordingly before it is made available on the request. """ httpRequest = b'''\ GET / HTTP/1.0 Content-Type: text/plain Transfer-Encoding: chunked 6 Hello, 14 spam,eggs spam spam 0 ''' path = [] method = [] content = [] decoder = [] testcase = self class MyRequest(http.Request): def process(self): content.append(self.content.fileno()) content.append(self.content.read()) method.append(self.method) path.append(self.path) decoder.append(self.channel._transferDecoder) testcase.didRequest = True self.finish() self.runRequest(httpRequest, MyRequest) # The tempfile API used to create content returns an # instance of a different type depending on what platform # we're running on. The point here is to verify that the # request body is in a file that's on the filesystem. # Having a fileno method that returns an int is a somewhat # close approximation of this. -exarkun self.assertIsInstance(content[0], int) self.assertEqual(content[1], b'Hello, spam,eggs spam spam') self.assertEqual(method, [b'GET']) self.assertEqual(path, [b'/']) self.assertEqual(decoder, [None])
If a request uses the I{chunked} transfer encoding, the request body is decoded accordingly before it is made available on the request.
test_chunkedEncoding
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_http.py
MIT