def test_renderIProtocol(self): """ If the protocol returned by C{lookupProtocol} isn't a C{WebSocketsProtocol}, L{WebSocketsResource} wraps it automatically with L{WebSocketsProtocolWrapper}. """ def lookupProtocol(names, otherRequest): return AccumulatingProtocol(), None self.resource = WebSocketsResource(lookupProtocol) request = DummyRequest("/") request.requestHeaders = Headers() transport = StringTransportWithDisconnection() transport.protocol = Protocol() request.transport = transport request.headers.update({ "upgrade": "Websocket", "connection": "Upgrade", "sec-websocket-key": "secure", "sec-websocket-version": "13"}) result = self.resource.render(request) self.assertEqual(NOT_DONE_YET, result) self.assertIsInstance(transport.protocol, WebSocketsProtocolWrapper) self.assertIsInstance(transport.protocol.wrappedProtocol, AccumulatingProtocol)
def test_renderSecureRequest(self): """ When the rendered request is over HTTPS, L{WebSocketsResource} wraps the protocol of the C{TLSMemoryBIOProtocol} instance. """ request = DummyRequest("/") request.requestHeaders = Headers() transport = StringTransportWithDisconnection() secureProtocol = TLSMemoryBIOProtocol(Factory(), Protocol()) transport.protocol = secureProtocol request.transport = transport request.headers.update({ "upgrade": "Websocket", "connection": "Upgrade", "sec-websocket-key": "secure", "sec-websocket-version": "13"}) result = self.resource.render(request) self.assertEqual(NOT_DONE_YET, result) self.assertEqual( {"connection": "Upgrade", "upgrade": "WebSocket", "sec-websocket-accept": "oYBv54i42V5dw6KnZqOFroecUTc="}, request.outgoingHeaders) self.assertEqual([""], request.written) self.assertEqual(101, request.responseCode) self.assertIdentical(None, request.transport) self.assertIsInstance( transport.protocol.wrappedProtocol, WebSocketsProtocol) self.assertIsInstance( transport.protocol.wrappedProtocol._receiver, SavingEchoReceiver)
def test_receipt_processing(self): """it should be able to process an incoming XML receipt via HTTP""" publisher = TestPublisher() resource = transport.OperaReceiptResource(publisher) request = DummyRequest('/api/v1/sms/opera/receipt.xml') request.content = StringIO(""" <?xml version="1.0"?> <!DOCTYPE receipts> <receipts> <receipt> <msgid>26567958</msgid> <reference>001efc31</reference> <msisdn>+27123456789</msisdn> <status>D</status> <timestamp>20080831T15:59:24</timestamp> <billed>NO</billed> </receipt> </receipts> """.strip()) resource.render_POST(request) self.assertEquals(publisher.queue.pop(), (Message(**{ 'transport_name': 'Opera', 'transport_msg_id': '001efc31', 'transport_status': 'D', # OK / delivered, opera specific 'transport_delivered_at': datetime(2008, 8, 31, 15, 59, 24), }), { 'routing_key': 'sms.receipt.opera' }) )
def test_renderWithHost(self): """ L{NameVirtualHost.render} returns the result of rendering the resource which is the value in the instance's C{host} dictionary corresponding to the key indicated by the value of the I{Host} header in the request. """ virtualHostResource = NameVirtualHost() virtualHostResource.addHost('example.org', Data("winner", "")) request = DummyRequest(['']) request.headers['host'] = 'example.org' d = _render(virtualHostResource, request) def cbRendered(ignored, request): self.assertEqual(''.join(request.written), "winner") d.addCallback(cbRendered, request) # The port portion of the Host header should not be considered. requestWithPort = DummyRequest(['']) requestWithPort.headers['host'] = 'example.org:8000' dWithPort = _render(virtualHostResource, requestWithPort) def cbRendered(ignored, requestWithPort): self.assertEqual(''.join(requestWithPort.written), "winner") dWithPort.addCallback(cbRendered, requestWithPort) return gatherResults([d, dWithPort])
def test_getChild(self): """ L{NameVirtualHost.getChild} returns correct I{Resource} based off the header and modifies I{Request} to ensure proper prepath and postpath are set. """ virtualHostResource = NameVirtualHost() leafResource = Data(b"leaf data", "") leafResource.isLeaf = True normResource = Data(b"norm data", "") virtualHostResource.addHost(b'leaf.example.org', leafResource) virtualHostResource.addHost(b'norm.example.org', normResource) request = DummyRequest([]) request.requestHeaders.addRawHeader(b'host', b'norm.example.org') request.prepath = [b''] self.assertIsInstance(virtualHostResource.getChild(b'', request), NoResource) self.assertEqual(request.prepath, [b'']) self.assertEqual(request.postpath, []) request = DummyRequest([]) request.requestHeaders.addRawHeader(b'host', b'leaf.example.org') request.prepath = [b''] self.assertIsInstance(virtualHostResource.getChild(b'', request), Data) self.assertEqual(request.prepath, []) self.assertEqual(request.postpath, [b''])
def __init__(self, postpath, params, session=None): self.content = StringIO() self.content.write(urllib.urlencode(params)) self.content.seek(0, 0) self.requestHeaders = Headers() DummyRequest.__init__(self, postpath, session)
def mk_request(self, user=None, password=None): request = DummyRequest(['']) if user is not None: request.headers["authorization"] = ( "Basic %s" % base64.b64encode("%s:%s" % (user, password)) ) return request
def test_render(self): """ When rendering a request, L{WebSocketsResource} uses the C{Sec-WebSocket-Key} header to generate a C{Sec-WebSocket-Accept} value. It creates a L{WebSocketsProtocol} instance connected to the protocol provided by the user factory. """ request = DummyRequest("/") request.requestHeaders = Headers() transport = StringTransportWithDisconnection() transport.protocol = Protocol() request.transport = transport request.headers.update({ "upgrade": "Websocket", "connection": "Upgrade", "sec-websocket-key": "secure", "sec-websocket-version": "13"}) result = self.resource.render(request) self.assertEqual(NOT_DONE_YET, result) self.assertEqual( {"connection": "Upgrade", "upgrade": "WebSocket", "sec-websocket-accept": "oYBv54i42V5dw6KnZqOFroecUTc="}, request.outgoingHeaders) self.assertEqual([""], request.written) self.assertEqual(101, request.responseCode) self.assertIdentical(None, request.transport) self.assertIsInstance(transport.protocol._receiver, SavingEchoReceiver)
def test_renderProtocol(self): """ If protocols are specified via the C{Sec-WebSocket-Protocol} header, L{WebSocketsResource} passes them to its C{lookupProtocol} argument, which can decide which protocol to return, and which is accepted. """ def lookupProtocol(names, otherRequest): self.assertEqual(["foo", "bar"], names) self.assertIdentical(request, otherRequest) return self.echoProtocol, "bar" self.resource = WebSocketsResource(lookupProtocol) request = DummyRequest("/") request.requestHeaders = Headers( {"sec-websocket-protocol": ["foo", "bar"]}) transport = StringTransportWithDisconnection() transport.protocol = Protocol() request.transport = transport request.headers.update({ "upgrade": "Websocket", "connection": "Upgrade", "sec-websocket-key": "secure", "sec-websocket-version": "13"}) result = self.resource.render(request) self.assertEqual(NOT_DONE_YET, result) self.assertEqual( {"connection": "Upgrade", "upgrade": "WebSocket", "sec-websocket-protocol": "bar", "sec-websocket-accept": "oYBv54i42V5dw6KnZqOFroecUTc="}, request.outgoingHeaders) self.assertEqual([""], request.written) self.assertEqual(101, request.responseCode)
def create_request(params={}, path='/', method='POST'): """ Creates a dummy Vas2Nets request for testing our resources with """ request = DummyRequest(path) request.method = method request.args = params return request
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)
def __init__(self, method, url, args=None): DummyRequest.__init__(self, url.split('/')) self.method = method # set args args = args or {} for k, v in args.items(): self.addArg(k, v)
def __init__(self, postpath, params): DummyRequest.__init__(self, postpath, None) self.content = StringIO() self.content.write(json.dumps(params)) self.content.seek(0, 0) self.requestHeaders = Headers() self.method = 'POST' self.requestHeaders.addRawHeader('content-type', 'application/json')
def request_generator(url, method='GET', content=True, headers=True): request = DummyRequest(url) request.method = method if content: request.content = StringIO() if headers: request.requestHeaders = Headers() return request
def makeRequest(self, method='GET', clientAddress=None): """ Create a L{DummyRequest} (change me to create a L{twisted.web.http.Request} instead). """ request = DummyRequest('/') request.method = method request.client = clientAddress return request
def test_song_id_does_not_exist(self): raise SkipTest("Twisted using deferToThread seems to break the test db connection that django establishes. However, with the real django db connection this works fine...") r = web.Song(1) request = DummyRequest([""]) d = request.notifyFinish() d.addCallback(self._assert_song_does_not_exist, request) result = r.render_GET(request) self.assertEqual(result, server.NOT_DONE_YET) return d
def __init__(self, method, url, args=None, headers=None): DummyRequest.__init__(self, url.split('/')) self.uri = url self.method = method self.headers.update(headers or {}) # set args args = args or {} for k, v in args.items(): self.addArg(k, v)
def test_handles_defaults_correctly(): u2m = {} u2m["/doesn/t/exist"] = root.__default__ u2m["/sub/doesn/t/exist"] = root.sub.__default__ for path, method in u2m.items(): request = DummyRequest([]) request.path = path action = site.routeRequest(request) assert getattr(action, "func", None) == method, "Expecting %s but got %s for URL %s" % (method, action, path)
def test_hook_bad_ip(self): """ An error is raised when request is comming from an untrusted IP. """ request = DummyRequest([]) request.client = IPv4Address('TCP', '111.0.0.0', 2345) result = hook(request, 'hook_name') self.assertEqual(403, request.code) self.assertTrue(result.startswith('Error:001: '))
def test_noSuchMethodNoId(self): request = DummyRequest(['']) request.content = StringIO('{"method": "aaaa"}') d = _render(self.srv, request) def rendered(_): self.assertEquals(request.written, []) d.addCallback(rendered) return d
def __init__(self, method, url, args=None, headers=None, body=None): DummyRequest.__init__(self, url.split('/')) if body is not None: self.content = _FakeContent(body) self.method = method self.headers.update(headers or {}) args = args or {} for k, v in args.items(): self.addArg(k, v)
def test_notificationV2(self): request = DummyRequest(['']) request.content = StringIO('{"method": "sql", "jsonrpc": "2.0"}') d = _render(self.srv, request) def rendered(_): self.assertEquals(request.written, []) d.addCallback(rendered) return d
def test_renderHEAD(self): """ The rendering behavior of L{UnauthorizedResource} for a I{HEAD} request is like its handling of a I{GET} request, but no response body is written. """ request = DummyRequest(['']) request.method = 'HEAD' self._unauthorizedRenderTest(request) self.assertEqual('', ''.join(request.written))
def test_sqlOkV1(self): request = DummyRequest(['']) request.content = StringIO('{"method": "sql", "id": 1}') d = _render(self.srv, request) def rendered(_): expected = '{"error": null, "id": 1, "result": [' self.assertTrue(request.written[0].startswith(expected)) d.addCallback(rendered) return d
def test_invalidIdCaseSensitive(self): request = DummyRequest(['']) request.content = StringIO('{"method": "echo", "ID": "ABCD", ' + '"params": ["AB"]}') d = _render(self.srv, request) def rendered(_): self.assertEquals(request.written, []) d.addCallback(rendered) return d
def test_everything(): postPath = ["first argument", "second argument"] request = DummyRequest(postPath) request.addArg("foo", "hello") request.addArg("bar", "world") eCon = ExtendedController() actuals = eCon.everything(request) assert actuals['u_first'] == postPath[0] assert actuals['u_second'] == postPath[1] assert actuals['a_foo'] == "hello" assert actuals['a_bar'] == "world"
def test_idStrV1(self): request = DummyRequest(['']) request.content = StringIO('{"method": "echo", "id": "abcd", ' + '"params": ["ab"]}') d = _render(self.srv, request) def rendered(_): expected = '{"error": null, "id": "abcd", "result": "ab"}' self.assertEquals(request.written[0], expected) d.addCallback(rendered) return d
def test_sqlOkV2(self): request = DummyRequest(['']) request.content = StringIO('{"jsonrpc": "2.0", "method": "sql", ' '"id": 1}') d = _render(self.srv, request) def rendered(_): expected = '{"jsonrpc": "2.0", "id": 1, "result": [' self.assertTrue(request.written[0].startswith(expected)) d.addCallback(rendered) return d
def test_keywordsOkV2(self): request = DummyRequest(['']) request.content = StringIO('{"method": "echo", "id": 1, "params": ' + '{"data": "arg"}, "jsonrpc": "2.0"}') d = _render(self.srv, request) def rendered(_): expected = '{"jsonrpc": "2.0", "id": 1, "result": "arg"}' self.assertEquals(request.written[0], expected) d.addCallback(rendered) return d
def test_wrongParams(self): request = DummyRequest(['']) request.content = BytesIO(b'{"method": "sql", "id": 1, "params": ["aa", "bb"]}') d = _render(self.srv, request) def rendered(_): expected = '{"id": 1, "error": {"message": "jsonrpc_sql() takes 1 positional argument ' + \ 'but 3 were given", "code": -32602}, "result": null}' self.assert_json(request.written[0], expected) d.addCallback(rendered) return d
def test_batchNotificationOnly(self): json = '[{"method": "echo", "params": {"data": "arg"}}, ' + \ '{"method": "echo", "params": {"data": "arg"}}]' request = DummyRequest(['']) request.content = StringIO(json) d = _render(self.srv, request) def rendered(_): self.assertEquals(request.written, []) d.addCallback(rendered) return d
def test_emptyRequest(self): request = DummyRequest(['']) request.content = BytesIO(b'') d = _render(self.srv, request) def rendered(_): expected = '{"jsonrpc": "2.0", "id": null, "error": ' + \ '{"message": "Parse error", "code": -32700}}' self.assert_json(request.written[0], expected) d.addCallback(rendered) return d
def test_returnNone(self): request = DummyRequest(['']) request.content = StringIO('{"method": "returnNone", "id": 1}') d = _render(self.srv, request) def rendered(_): expected = '{"error": null, "id": 1, "result": null}' self.assertEquals(request.written[0], expected) d.addCallback(rendered) return d
def test_batchSingle(self): json = '[{"method": "echo", "id": 1, "params": ["arg"]}]' request = DummyRequest(['']) request.content = StringIO(json) d = _render(self.srv, request) def rendered(_): expected = '[{"error": null, "id": 1, "result": "arg"}]' self.assertEquals(request.written[0], expected) d.addCallback(rendered) return d
def test_malformed(self): request = DummyRequest(['']) request.content = StringIO('{"method": "sql", "id') d = _render(self.srv, request) def rendered(_): expected = '{"jsonrpc": "2.0", "id": null, "error": ' + \ '{"message": "Parse error", "code": -32700}}' self.assertEquals(request.written[0], expected) d.addCallback(rendered) return d
def test_contentType(self): request = DummyRequest(['']) request.content = StringIO('{"method": "echo", "id": 1, ' + '"params": ["ab"]}') d = _render(self.srv, request) def rendered(_): self.assertEquals(request.outgoingHeaders['content-type'], 'application/json') d.addCallback(rendered) return d
def test_contentLength(self): request = DummyRequest(['']) request.content = StringIO('{"method": "echo", "id": 1, ' + '"params": ["ab"]}') d = _render(self.srv, request) def rendered(_): self.assertEquals(str(len(request.written[0])), request.outgoingHeaders['content-length']) d.addCallback(rendered) return d
def test_caseSensitiveParamsV2(self): request = DummyRequest(['']) request.content = StringIO('{"method": "echo", "id": "ABCD", ' + '"params": ["AB"], "jsonrpc": "2.0"}') d = _render(self.srv, request) def rendered(_): expected = '{"jsonrpc": "2.0", "id": "ABCD", "result": "AB"}' self.assertEquals(request.written[0], expected) d.addCallback(rendered) return d
def test_invalidParamsCaseSensitive(self): request = DummyRequest(['']) request.content = BytesIO(b'{"method": "echo", "id": "ABCD", "PARAMS": ["AB"]}') d = _render(self.srv, request) def rendered(_): expected = '{"id": "ABCD", "error": {"message": "jsonrpc_echo() missing 1 required positional argument:' + \ ' \'data\'", "code": -32602}, "result": null}' self.assert_json(request.written[0], expected) d.addCallback(rendered) return d
def setUp(self): self.request = DummyRequest(['']) self.request.method = 'POST' self.request.content = NativeStringIO( payloadTemplate % ('async', xmlrpclib.dumps(()))) result = self.result = defer.Deferred() class AsyncResource(XMLRPC): def xmlrpc_async(self): return result self.resource = AsyncResource()
def test_caseSensitiveMethodV1(self): request = DummyRequest(['']) request.content = BytesIO(b'{"method": "ECHO", "id": "ABCD", "params": ["AB"]}') d = _render(self.srv, request) def rendered(_): expected = '{"result": null, "id": "ABCD", "error": {' + \ '"message": "Method ECHO not found", "code": -32601}}' self.assert_json(request.written[0], expected) d.addCallback(rendered) return d
def test_idStrV2(self): request = DummyRequest(['']) request.content = BytesIO(b'{"method": "echo", "id": "abcd", "params": ["ab"], "jsonrpc": "2.0"}') d = _render(self.srv, request) def rendered(_): expected = '{"jsonrpc": "2.0", "id": "abcd", ' + \ '"result": "ab"}' self.assert_json(request.written[0], expected) d.addCallback(rendered) return d
def test_renderQuotesDigest(self): """ The digest value must be correctly quoted. It is a byte string in python3, so we must make sure the proper conversion is done """ resource = UnauthorizedResource([ digest.DigestCredentialFactory(b'md5', b'example\\"foo')]) request = DummyRequest([b'']) request.render(resource) auth_header = request.responseHeaders.getRawHeaders(b'www-authenticate')[0] self.assertIn(b'realm="example\\\\\\"foo"', auth_header) self.assertIn(b'hm="md5', auth_header)
def test_invalidMethodCaseSensitive(self): request = DummyRequest(['']) request.content = BytesIO(b'{"METHOD": "echo", "id": "ABCD", "params": ["AB"]}') d = _render(self.srv, request) def rendered(_): expected = '{"result": null, "id": "ABCD", "error": ' + \ '{"message": "Invalid method type", "code": -32600}}' self.assert_json(request.written[0], expected) d.addCallback(rendered) return d
def test_noSuchMethodV2(self): request = DummyRequest(['']) request.content = BytesIO(b'{"method": "aaaa", "id": 1, "jsonrpc": "2.0"}') d = _render(self.srv, request) def rendered(_): expected = '{"jsonrpc": "2.0", "id": 1, "error": ' + \ '{"message": "Method aaaa not found", ' + \ '"code": -32601}}' self.assert_json(request.written[0], expected) d.addCallback(rendered) return d
def test_unknown_button(self): status = self._create_status({'adapter': {'button': {'foo': {}}}}) # Setup request_unknown = DummyRequest(['unknown']) request_malformed = DummyRequest(['foo', 'bar']) resource = monitor.web_resources.Button(status) # Ensure these fail. self.assertRaises(monitor.web_resources.UnknownComponent, self._render, resource, request_unknown) self.assertRaises(AssertionError, self._render, resource, request_malformed)
def __init__(self, method, url, project='test', data=None, args=None, headers=None): DummyRequest.__init__(self, url.split('/')) if data is not None: self.content = StringIO(data) if project is not None: self.project = project self.method = method self.headers.update(headers or {}) # set args args = args or {} for k, v in args.items(): self.addArg(k, v)
def test_batchNotificationAndSingle(self): json = '[{"method": "echo", "id": 1, "params": ["arg"]}, ' + \ '{"method": "echo", "params": ["arg"]}]' request = DummyRequest(['']) request.content = BytesIO(json.encode()) d = _render(self.srv, request) def rendered(_): expected = '[{"error": null, "id": 1, "result": "arg"}]' self.assert_json(request.written[0], expected) d.addCallback(rendered) return d
def test_renderQuotesRealm(self): """ The realm value included in the I{WWW-Authenticate} header set in the response when L{UnauthorizedResounrce} is rendered has quotes and backslashes escaped. """ resource = UnauthorizedResource( [BasicCredentialFactory('example\\"foo')]) request = DummyRequest(['']) request.render(resource) self.assertEqual( request.responseHeaders.getRawHeaders('www-authenticate'), ['basic realm="example\\\\\\"foo"'])
def test_get_blobs_enabled(self): blobs_resource = BlobsResource("filesystem", '/tmp') streaming_resource = StreamingResource("filesystem", '/tmp') resource = PublicResource( blobs_resource=blobs_resource, streaming_resource=streaming_resource, sync_pool=_pool) request = DummyRequest(['blobs']) child = getChildForRequest(resource, request) self.assertIsInstance(child, BlobsResource) request = DummyRequest(['stream']) child = getChildForRequest(resource, request) self.assertIsInstance(child, StreamingResource)
def test_noSuchMethodV1(self): request = DummyRequest(['']) request.content = StringIO('{"method": "aaaa", "id": 1}') d = _render(self.srv, request) def rendered(_): expected = '{"result": null, "id": 1, "error": ' + \ '{"message": "Method aaaa not found", ' + \ '"code": -32601}}' self.assertEquals(request.written[0], expected) d.addCallback(rendered) return d
def test_invalidParamsCaseSensitive(self): request = DummyRequest(['']) request.content = StringIO('{"method": "echo", "id": "ABCD", ' + '"PARAMS": ["AB"]}') d = _render(self.srv, request) def rendered(_): expected = '{"result": null, "id": "ABCD", "error": ' + \ '{"message": "jsonrpc_echo() takes exactly 2 ' + \ 'arguments (1 given)", "code": -32602}}' self.assertEquals(request.written[0], expected) d.addCallback(rendered) return d
def test_save_document(self): formatter = IncomingFormatter() doc_id, scheme = uuid4().hex, EncryptionSchemes.PUBKEY content = 'Incoming content' request = DummyRequest([self.user_uuid, doc_id]) request.content = BytesIO(content) self.resource.render_PUT(request) open_database = self.backend_factory.open_database open_database.assert_called_once_with(self.user_uuid) self.couchdb.put_doc.assert_called_once() doc = self.couchdb.put_doc.call_args[0][0] self.assertEquals(doc_id, doc.doc_id) self.assertEquals(formatter.format(content, scheme), doc.content)
def test_renderWithUnknownHostNoDefault(self): """ L{NameVirtualHost.render} returns a response with a status of I{NOT FOUND} if the instance's C{default} is C{None} and there is no host matching the value of the I{Host} header in the request. """ virtualHostResource = NameVirtualHost() request = DummyRequest(['']) request.headers['host'] = 'example.com' d = _render(virtualHostResource, request) def cbRendered(ignored): self.assertEqual(request.responseCode, NOT_FOUND) d.addCallback(cbRendered) return d
def test_wrongParams(self): request = DummyRequest(['']) request.content = StringIO('{"method": "sql", "id": 1, ' + '"params": ["aa", "bb"]}') d = _render(self.srv, request) def rendered(_): expected = '{"result": null, "id": 1, "error": {"message": ' + \ '"jsonrpc_sql() takes exactly 1 argument (3 given)"' + \ ', "code": -32602}}' self.assertEquals(request.written[0], expected) d.addCallback(rendered) return d
def test_render_get_a_rendered_template(self): request = DummyRequest(['']) request.prepath = ['test'] self.assertEqual( self.root.render_GET(request), '<!DOCTYPE html>\n' '<html lang="en">\n' '<head>\n' ' <title></title>\n' '</head>\n' '<body>\n' ' \n' '</body>\n' '</html>')