def test_rpc_errors(self): api = create_api() req = webob.Request.blank('/rpc') req.method = 'POST' req.content_type = 'application/json' # Body is not a list, it should fail req.body = jsonutils.dumps({}) res = req.get_response(api) self.assertEqual(res.status_int, 400) # cmd is not dict, it should fail. req.body = jsonutils.dumps([None]) res = req.get_response(api) self.assertEqual(res.status_int, 400) # No command key, it should fail. req.body = jsonutils.dumps([{}]) res = req.get_response(api) self.assertEqual(res.status_int, 400) # kwargs not dict, it should fail. req.body = jsonutils.dumps([{"command": "test", "kwargs": 200}]) res = req.get_response(api) self.assertEqual(res.status_int, 400) # Command does not exist, it should fail. req.body = jsonutils.dumps([{"command": "test"}]) res = req.get_response(api) self.assertEqual(res.status_int, 404)
def test_rpc_errors(self): api = create_api() req = webob.Request.blank('/rpc') req.method = 'POST' req.content_type = 'application/json' # Body is not a list, it should fail req.body = jsonutils.dumps({}) res = req.get_response(api) self.assertEqual(res.status_int, 400) # cmd is not dict, it should fail. req.body = jsonutils.dumps([None]) res = req.get_response(api) self.assertEqual(res.status_int, 400) # No command key, it should fail. req.body = jsonutils.dumps([{}]) res = req.get_response(api) self.assertEqual(res.status_int, 400) # kwargs not dict, it should fail. req.body = jsonutils.dumps([{"command": "test", "kwargs": 200}]) res = req.get_response(api) self.assertEqual(res.status_int, 400) # Command does not exist, it should fail. req.body = jsonutils.dumps([{"command": "test"}]) res = req.get_response(api) self.assertEqual(res.status_int, 404)
def __call__(self, target, creds): """ Check http: rules by calling to a remote server. This example implementation simply verifies that the response is exactly 'True'. """ url = ('http:' + self.match) % target data = {'target': jsonutils.dumps(target), 'credentials': jsonutils.dumps(creds)} post_data = urllib.urlencode(data) f = urllib2.urlopen(url, post_data) return f.read() == "True"
def __call__(self, target, creds): """ Check http: rules by calling to a remote server. This example implementation simply verifies that the response is exactly 'True'. """ url = ('http:' + self.match) % target data = { 'target': jsonutils.dumps(target), 'credentials': jsonutils.dumps(creds) } post_data = urllib.urlencode(data) f = urllib2.urlopen(url, post_data) return f.read() == "True"
def index(self, req): """Respond to a request for all OpenStack API versions.""" def build_version_object(version, path, status): return { 'id': 'v%s' % version, 'status': status, 'links': [ { 'rel': 'self', 'href': '%s/%s/' % (req.host_url, path), }, ], } version_objs = [] if CONF.enable_v2_api: version_objs.extend([ build_version_object(2.2, 'v2', 'CURRENT'), build_version_object(2.1, 'v2', 'SUPPORTED'), build_version_object(2.0, 'v2', 'SUPPORTED'), ]) if CONF.enable_v1_api: version_objs.extend([ build_version_object(1.1, 'v1', 'CURRENT'), build_version_object(1.0, 'v1', 'SUPPORTED'), ]) response = webob.Response(request=req, status=httplib.MULTIPLE_CHOICES, content_type='application/json') response.body = jsonutils.dumps(dict(versions=version_objs)) return response
def format(self, record): message = {'message': record.getMessage(), 'asctime': self.formatTime(record, self.datefmt), 'name': record.name, 'msg': record.msg, 'args': record.args, 'levelname': record.levelname, 'levelno': record.levelno, 'pathname': record.pathname, 'filename': record.filename, 'module': record.module, 'lineno': record.lineno, 'funcname': record.funcName, 'created': record.created, 'msecs': record.msecs, 'relative_created': record.relativeCreated, 'thread': record.thread, 'thread_name': record.threadName, 'process_name': record.processName, 'process': record.process, 'traceback': None} if hasattr(record, 'extra'): message['extra'] = record.extra if record.exc_info: message['traceback'] = self.formatException(record.exc_info) return jsonutils.dumps(message)
def test_rpc_exception_propagation(self): api = create_api() req = webob.Request.blank('/rpc') req.method = 'POST' req.content_type = 'application/json' req.body = jsonutils.dumps([{"command": "raise_value_error"}]) res = req.get_response(api) self.assertEqual(res.status_int, 200) returned = jsonutils.loads(res.body)[0] self.assertEqual(returned['_error']['cls'], 'exceptions.ValueError') req.body = jsonutils.dumps([{"command": "raise_weird_error"}]) res = req.get_response(api) self.assertEqual(res.status_int, 200) returned = jsonutils.loads(res.body)[0] self.assertEqual(returned['_error']['cls'], 'sps.common.exception.RPCError')
def test_rpc_exception_propagation(self): api = create_api() req = webob.Request.blank('/rpc') req.method = 'POST' req.content_type = 'application/json' req.body = jsonutils.dumps([{"command": "raise_value_error"}]) res = req.get_response(api) self.assertEqual(res.status_int, 200) returned = jsonutils.loads(res.body)[0] self.assertEqual(returned['_error']['cls'], 'exceptions.ValueError') req.body = jsonutils.dumps([{"command": "raise_weird_error"}]) res = req.get_response(api) self.assertEqual(res.status_int, 200) returned = jsonutils.loads(res.body)[0] self.assertEqual(returned['_error']['cls'], 'sps.common.exception.RPCError')
def test_request(self): api = create_api() req = webob.Request.blank('/rpc') req.method = 'POST' req.body = jsonutils.dumps([{ "command": "get_demos", "kwargs": { "keyword": 1 } }]) res = req.get_response(api) returned = jsonutils.loads(res.body) self.assertIsInstance(returned, list) self.assertEqual(returned[0], 1)
def __str__(self): """Dumps a string representation of the rules.""" # Start by building the canonical strings for the rules out_rules = {} for key, value in self.items(): # Use empty string for singleton TrueCheck instances if isinstance(value, TrueCheck): out_rules[key] = '' else: out_rules[key] = str(value) # Dump a pretty-printed JSON representation return jsonutils.dumps(out_rules, indent=4)
def __str__(self): """Dumps a string representation of the rules.""" # Start by building the canonical strings for the rules out_rules = {} for key, value in self.items(): # Use empty string for singleton TrueCheck instances if isinstance(value, TrueCheck): out_rules[key] = '' else: out_rules[key] = str(value) # Dump a pretty-printed JSON representation return jsonutils.dumps(out_rules, indent=4)
def test_request(self): api = create_api() req = webob.Request.blank('/rpc') req.method = 'POST' req.body = jsonutils.dumps([ { "command": "get_demos", "kwargs": {"keyword": 1} } ]) res = req.get_response(api) returned = jsonutils.loads(res.body) self.assertIsInstance(returned, list) self.assertEqual(returned[0], 1)
def test_request_exc(self): api = create_api() req = webob.Request.blank('/rpc') req.method = 'POST' req.body = jsonutils.dumps([ { "command": "get_all_demos", "kwargs": {"keyword": 1} } ]) # Sending non-accepted keyword # to get_all_demos method res = req.get_response(api) returned = jsonutils.loads(res.body) self.assertIn("_error", returned[0])
def test_request_exc(self): api = create_api() req = webob.Request.blank('/rpc') req.method = 'POST' req.body = jsonutils.dumps([{ "command": "get_all_demos", "kwargs": { "keyword": 1 } }]) # Sending non-accepted keyword # to get_all_demos method res = req.get_response(api) returned = jsonutils.loads(res.body) self.assertIn("_error", returned[0])
def fake_do_request(cls, url, method, headers=None, body=None): if (not url.rstrip('/').endswith('v2.0/tokens') or url.count("2.0") != 1): self.fail("Invalid v2.0 token path (%s)" % url) creds = jsonutils.loads(body)['auth'] username = creds['passwordCredentials']['username'] password = creds['passwordCredentials']['password'] tenant = creds['tenantName'] resp = webob.Response() if (username != 'user1' or password != 'pass' or tenant != 'tenant-ok'): resp.status = 401 else: resp.status = 200 body = mock_token.token return FakeResponse(resp), jsonutils.dumps(body)
def fake_do_request(cls, url, method, headers=None, body=None): if (not url.rstrip('/').endswith('v2.0/tokens') or url.count("2.0") != 1): self.fail("Invalid v2.0 token path (%s)" % url) creds = jsonutils.loads(body)['auth'] username = creds['passwordCredentials']['username'] password = creds['passwordCredentials']['password'] tenant = creds['tenantName'] resp = webob.Response() if (username != 'user1' or password != 'pass' or tenant != 'tenant-ok'): resp.status = 401 else: resp.status = 200 body = mock_token.token return FakeResponse(resp), jsonutils.dumps(body)
def _v2_auth(self, token_url): creds = self.creds creds = { "auth": { "tenantName": creds['tenant'], "passwordCredentials": { "username": creds['username'], "password": creds['password'] } } } headers = {} headers['Content-Type'] = 'application/json' req_body = jsonutils.dumps(creds) resp, resp_body = self._do_request( token_url, 'POST', headers=headers, body=req_body) if resp.status == 200: resp_auth = jsonutils.loads(resp_body)['access'] creds_region = self.creds.get('region') if self.configure_via_auth: endpoint = get_endpoint(resp_auth['serviceCatalog'], endpoint_region=creds_region) self.management_url = endpoint self.auth_token = resp_auth['token']['id'] elif resp.status == 305: raise exception.RedirectException(resp['location']) elif resp.status == 400: raise exception.AuthBadRequest(url=token_url) elif resp.status == 401: raise exception.NotAuthenticated() elif resp.status == 404: raise exception.AuthUrlNotFound(url=token_url) else: raise Exception(_('Unexpected response: %s') % resp.status)
def process_bind_param(self, value, dialect): if value is not None: value = jsonutils.dumps(value) return value
def to_json(self, data): return jsonutils.dumps(data, default=self._sanitizer)
def process_bind_param(self, value, dialect): if value is not None: value = jsonutils.dumps(value) return value
def to_json(self, data): return jsonutils.dumps(data, default=self._sanitizer)
def set_policy_rules(self, rules): fap = open(CONF.policy_file, 'w') fap.write(jsonutils.dumps(rules)) fap.close()