Beispiel #1
0
def _load_options(path, conf):
    full_path = conf.find_file(path)
    if not full_path:
        raise cfg.ConfigFilesNotFoundError([path])

    with open(full_path) as fd:
        return json.load(fd)
def load_app(conf, args=None):
    global APPCONFIGS

    # Build the WSGI app
    cfg_file = None
    cfg_path = conf.api_paste_config
    if not os.path.isabs(cfg_path):
        cfg_file = conf.find_file(cfg_path)
    elif os.path.exists(cfg_path):
        cfg_file = cfg_path

    if not cfg_file:
        raise cfg.ConfigFilesNotFoundError([conf.api_paste_config])

    config = dict([(key, value) for key, value in args.iteritems()
                   if key in conf and value is not None])
    for key, value in config.iteritems():
        if key == 'config_file':
            conf.config_file = value
        if key == 'pipeline_cfg_file':
            conf.pipeline_cfg_file = value

    configkey = str(uuid.uuid4())
    APPCONFIGS[configkey] = conf

    LOG.info("Full WSGI config used: %s", cfg_file)
    LOG.debug("Note: Ceilometer API is deprecated; use APIs from Aodh"
              " (alarms), Gnocchi (metrics) and/or Panko (events).")
    return deploy.loadapp("config:" + cfg_file,
                          global_conf={'configkey': configkey})
Beispiel #3
0
def load_app(conf,
             appname=None,
             indexer=None,
             storage=None,
             not_implemented_middleware=True):
    global APPCONFIGS

    # NOTE(sileht): We load config, storage and indexer,
    # so all
    if not storage:
        storage = gnocchi_storage.get_driver(conf)
    if not indexer:
        indexer = gnocchi_indexer.get_driver(conf)
        indexer.connect()

    # Build the WSGI app
    cfg_path = conf.api.paste_config
    if not os.path.isabs(cfg_path):
        cfg_path = conf.find_file(cfg_path)

    if cfg_path is None or not os.path.exists(cfg_path):
        raise cfg.ConfigFilesNotFoundError([conf.api.paste_config])

    config = dict(conf=conf,
                  indexer=indexer,
                  storage=storage,
                  not_implemented_middleware=not_implemented_middleware)
    configkey = str(uuid.uuid4())
    APPCONFIGS[configkey] = config

    LOG.info("WSGI config used: %s" % cfg_path)
    return deploy.loadapp("config:" + cfg_path,
                          name=appname,
                          global_conf={'configkey': configkey})
Beispiel #4
0
def load_paste_app(app_name):
    """Builds and returns a WSGI app from a paste config file.

    :param app_name: Name of the application to load
    :raises ConfigFilesNotFoundError when config file cannot be located
    :raises RuntimeError when application cannot be loaded from config file
    """

    config_path = cfg.CONF.find_file(cfg.CONF.api_paste_config)
    if not config_path:
        raise cfg.ConfigFilesNotFoundError(
            config_files=[cfg.CONF.api_paste_config])
    config_path = os.path.abspath(config_path)
    LOG.info(_LI("Config paste file: %s"), config_path)

    try:
        app = deploy.loadapp("config:%s" % config_path, name=app_name)
    except (LookupError, ImportError):
        msg = (_("Unable to load %(app_name)s from "
                 "configuration file %(config_path)s.") % {
                     'app_name': app_name,
                     'config_path': config_path
                 })
        LOG.exception(msg)
        raise RuntimeError(msg)
    return app
Beispiel #5
0
def _load_rules(path):
    full_path = _CONF.find_file(path)
    if not full_path:
        raise cfg.ConfigFilesNotFoundError([path])

    with open(full_path) as fd:
        return json.load(fd)
Beispiel #6
0
def find_paste_config():
    config_path = cfg.CONF.find_file(cfg.CONF.api_paste_config)

    if not config_path:
        raise cfg.ConfigFilesNotFoundError(
            config_files=[cfg.CONF.api_paste_config])
    config_path = os.path.abspath(config_path)
    LOG.info(_("Config paste file: %s"), config_path)
    return config_path
Beispiel #7
0
def _load_json_file(path):
    full_path = _CONF.find_file(path)
    if not full_path:
        raise cfg.ConfigFilesNotFoundError([path or '<Empty>'])

    with open(full_path) as fd:
        document = json.load(fd)

    return document
Beispiel #8
0
def load_app():
    cfg_file = None
    cfg_path = cfg.CONF.api_paste_config
    if not os.path.isabs(cfg_path):
        cfg_file = CONF.find_file(cfg_path)
    elif os.path.exists(cfg_path):
        cfg_file = cfg_path

    if not cfg_file:
        raise cfg.ConfigFilesNotFoundError([cfg.CONF.api_paste_config])
    LOG.info("Full WSGI config used: %s" % cfg_file)
    return deploy.loadapp("config:" + cfg_file)
Beispiel #9
0
def load_app():
    # Build the WSGI app
    cfg_file = None
    cfg_path = cfg.CONF.api_paste_config
    if not os.path.isabs(cfg_path):
        cfg_file = CONF.find_file(cfg_path)
    elif os.path.exists(cfg_path):
        cfg_file = cfg_path

    if not cfg_file:
        raise cfg.ConfigFilesNotFoundError([cfg.CONF.api_paste_config])
    return deploy.loadapp("config:" + cfg_file)
Beispiel #10
0
def load_app(conf):
    # Build the WSGI app
    cfg_file = None
    cfg_path = conf.api.paste_config
    if not os.path.isabs(cfg_path):
        cfg_file = conf.find_file(cfg_path)
    elif os.path.exists(cfg_path):
        cfg_file = cfg_path

    if not cfg_file:
        raise cfg.ConfigFilesNotFoundError([conf.api.paste_config])
    LOG.info(_LI('Full WSGI config used: %s') % cfg_file)
    return deploy.loadapp("config:" + cfg_file)
Beispiel #11
0
def load_app(conf):
    cfg_file = None
    cfg_path = conf.api_paste_config
    if not os.path.isabs(cfg_path):
        cfg_file = conf.find_file(cfg_path)
    elif os.path.exists(cfg_path):
        cfg_file = cfg_path

    if not cfg_file:
        raise cfg.ConfigFilesNotFoundError([conf.api_paste_config])
    LOG.info(_LI('Full WSGI config used: %s') % cfg_file)
    return deploy.loadapp('config:%s' % cfg_file,
                          global_conf={'nabu_config': conf})
Beispiel #12
0
def load_app():
    cfg_file = None
    cfg_path = cfg.CONF.api_paste_config
    if not os.path.isabs(cfg_path):
        cfg_file = CONF.find_file(cfg_path)
    elif os.path.exists(cfg_path):
        cfg_file = cfg_path

    if not cfg_file:
        raise cfg.ConfigFilesNotFoundError([cfg.CONF.api_paste_config])
    LOG.info("Full WSGI config used: %s", cfg_file)
    appname = "cloudkitty+{}".format(cfg.CONF.auth_strategy)
    LOG.info("Cloudkitty api with '%s' auth type will be loaded.",
             cfg.CONF.auth_strategy)
    return deploy.loadapp("config:" + cfg_file, name=appname)
Beispiel #13
0
    def test_main_sudo_failed(self, register_cli_opt, log_setup,
                              register_log_opts, config_opts_call):
        script_name = 'manila-manage'
        sys.argv = [script_name, 'fake_category', 'fake_action']
        config_opts_call.side_effect = cfg.ConfigFilesNotFoundError(
            mock.sentinel._namespace)

        exit = self.assertRaises(SystemExit, manila_manage.main)

        self.assertTrue(register_cli_opt.called)
        register_log_opts.assert_called_once_with(CONF)
        config_opts_call.assert_called_once_with(
            sys.argv[1:], project='manila', version=version.version_string())
        self.assertFalse(log_setup.called)
        self.assertEqual(exit.code, 2)
Beispiel #14
0
    def test_main_sudo_failed(self, register_cli_opt, log_setup,
                              config_opts_call):
        script_name = '<project_name>-manage'
        sys.argv = [script_name, 'fake_category', 'fake_action']
        config_opts_call.side_effect = cfg.ConfigFilesNotFoundError(
            mock.sentinel._namespace)

        with mock.patch('sys.stdout', new=six.StringIO()):
            exit = self.assertRaises(SystemExit, <project_name>_manage.main)

            self.assertTrue(register_cli_opt.called)
            config_opts_call.assert_called_once_with(
                sys.argv[1:], project='<project_name>',
                version=version.version_string())
            self.assertFalse(log_setup.called)
            self.assertEqual(2, exit.code)
Beispiel #15
0
    def _get_policy_path(self):
        """Locate the policy json data file.

        :param policy_file: Custom policy file to locate.

        :returns: The policy path

        :raises: ConfigFilesNotFoundError if the file couldn't
                 be located.
        """
        policy_file = CONF.find_file(self.policy_file)

        if policy_file:
            return policy_file

        raise cfg.ConfigFilesNotFoundError((self.policy_file, ))
Beispiel #16
0
def getUri(conf):
    # TODO(), it needs to get real path of api-paste.ini
    # the path is setted by the data_files under [files] in setup.config
    # configPath = "/etc/myproject/api-paste.ini"

    # find the absolute path of api-paste.ini
    cfgFile = None
    apiPastePath = conf.api.paste_config
    if not os.path.isabs(apiPastePath):
        cfgFile = conf.find_file(apiPastePath)
    elif os.path.exists(apiPastePath):
        cfgFile = apiPastePath
    if not cfgFile:
        raise cfg.ConfigFilesNotFoundError([conf.api.paste_config])
    LOG.info("The wsgi config file path is: %s" % (cfgFile))
    result = "config:" + cfgFile
    return result
Beispiel #17
0
    def _get_policy_path(self, project_id, file_name=None):
        """Locate the policy json data file/path.

        :param path: It's value can be a full path or related path. When
                     full path specified, this function just returns the full
                     path. When related path specified, this function will
                     search configuration directories to find one that exists.

        :returns: The policy path

        :raises: ConfigFilesNotFoundError if the file/path couldn't
                 be located.
        """

        policy_path = CONF.find_file("policy.json")

        # Edited by Yang Luo.
        if project_id != "" and project_id != None and policy_path != None:
            file_path = os.path.dirname(policy_path)
            if file_name == None:
                file_name = os.path.basename(policy_path)
            custom_policy_path = file_path + "/custom_policy/" + project_id + "/" + file_name
            if os.path.exists(custom_policy_path):
                LOG.info("Custom policy path [%s] exists" % custom_policy_path)
                policy_path = custom_policy_path
            else:
                LOG.info("Custom policy path [%s] doesn't exist" %
                         custom_policy_path)
        else:
            file_path = os.path.dirname(policy_path)
            if file_name == None:
                file_name = os.path.basename(policy_path)
            builtin_policy_path = file_path + "/" + file_name
            if os.path.exists(builtin_policy_path):
                LOG.info("Built-in policy path [%s] exists" %
                         builtin_policy_path)
                policy_path = builtin_policy_path
            else:
                LOG.info("Built-in policy path [%s] doesn't exist" %
                         builtin_policy_path)

        if policy_path:
            return policy_path

        raise cfg.ConfigFilesNotFoundError((path, ))
Beispiel #18
0
def load_app():
    cfg_file = None
    cfg_path = CONF.api.api_paste_config
    paste_pipeline = CONF.api.paste_pipeline
    if not os.path.isabs(cfg_path):
        cfg_file = CONF.find_file(cfg_path)
    elif os.path.exists(cfg_path):
        cfg_file = cfg_path

    if not cfg_file:
        raise cfg.ConfigFilesNotFoundError([cfg.CONF.api.api_paste_config])
    LOG.info(
        "Loading craton-api with pipeline %(pipeline)s and WSGI config:"
        "%(conf)s", {
            'conf': cfg_file,
            'pipeline': paste_pipeline
        })
    return deploy.loadapp("config:%s" % cfg_file, name=paste_pipeline)
Beispiel #19
0
def load_app(conf, appname='panko+keystone'):
    global APPCONFIGS

    # Build the WSGI app
    cfg_path = conf.api_paste_config
    if not os.path.isabs(cfg_path):
        cfg_path = conf.find_file(cfg_path)

    if cfg_path is None or not os.path.exists(cfg_path):
        raise cfg.ConfigFilesNotFoundError([conf.api_paste_config])

    config = dict(conf=conf)
    configkey = str(uuid.uuid4())
    APPCONFIGS[configkey] = config

    LOG.info("Full WSGI config used: %s" % cfg_path)
    return deploy.loadapp("config:" + cfg_path,
                          name=appname,
                          global_conf={'configkey': configkey})
    def _get_policy_path(self, path):
        """Locate the policy json data file/path.

        :param path: It's value can be a full path or related path. When
                     full path specified, this function just returns the full
                     path. When related path specified, this function will
                     search configuration directories to find one that exists.

        :returns: The policy path

        :raises: ConfigFilesNotFoundError if the file/path couldn't
                 be located.
        """
        policy_path = CONF.find_file(path)

        if policy_path:
            return policy_path

        raise cfg.ConfigFilesNotFoundError((path,))
Beispiel #21
0
def load_app(conf):
    global APPCONFIGS

    # Build the WSGI app
    cfg_file = None
    cfg_path = conf.api_paste_config
    if not os.path.isabs(cfg_path):
        cfg_file = conf.find_file(cfg_path)
    elif os.path.exists(cfg_path):
        cfg_file = cfg_path

    if not cfg_file:
        raise cfg.ConfigFilesNotFoundError([conf.api_paste_config])

    configkey = str(uuid.uuid4())
    APPCONFIGS[configkey] = conf

    LOG.info("Full WSGI config used: %s" % cfg_file)
    return deploy.loadapp("config:" + cfg_file,
                          global_conf={'configkey': configkey})
Beispiel #22
0
def load_app(conf):
    global APPCONFIGS

    # Build the WSGI app
    cfg_path = conf.api.paste_config
    if not os.path.isabs(cfg_path):
        cfg_path = conf.find_file(cfg_path)

    if cfg_path is None or not os.path.exists(cfg_path):
        raise cfg.ConfigFilesNotFoundError([conf.api.paste_config])

    config = dict(conf=conf)
    configkey = uuidutils.generate_uuid()
    APPCONFIGS[configkey] = config

    LOG.info('Full WSGI config used: %s', cfg_path)

    appname = "vitrage+" + conf.api.auth_mode
    return deploy.loadapp("config:" + cfg_path, name=appname,
                          global_conf={'configkey': configkey})
Beispiel #23
0
def load_app(conf):
    global APPCONFIGS

    # Build the WSGI app
    cfg_path = conf.api.paste_config
    if not os.path.isabs(cfg_path):
        cfg_path = conf.find_file(cfg_path)

    if cfg_path is None or not os.path.exists(cfg_path):
        raise cfg.ConfigFilesNotFoundError([conf.api.paste_config])

    config = dict(conf=conf)
    configkey = str(uuid.uuid4())
    APPCONFIGS[configkey] = config

    LOG.info("WSGI config used: %s", cfg_path)
    return deploy.loadapp("config:" + cfg_path,
                          name="aodh+" + (
                              conf.api.auth_mode
                              if conf.api.auth_mode else "noauth"
                          ),
                          global_conf={'configkey': configkey})
Beispiel #24
0
def load_app(conf):
    global APPCONFIGS

    # Build the WSGI app
    cfg_file = None
    cfg_path = conf.api_paste_config
    if not os.path.isabs(cfg_path):
        cfg_file = conf.find_file(cfg_path)
    elif os.path.exists(cfg_path):
        cfg_file = cfg_path

    if not cfg_file:
        raise cfg.ConfigFilesNotFoundError([conf.api_paste_config])

    configkey = str(uuid.uuid4())
    APPCONFIGS[configkey] = conf

    LOG.info("Full WSGI config used: %s", cfg_file)
    LOG.warning("Note: Ceilometer API is deprecated; use APIs from "
                "Aodh (alarms), Gnocchi (metrics) and/or Panko (events).")
    return deploy.loadapp("config:" + cfg_file,
                          global_conf={'configkey': configkey})
Beispiel #25
0
class CliUtilsTestCase(test.TestCase):
    def setUp(self):
        super(CliUtilsTestCase, self).setUp()
        self.categories = {
            "deployment": deployment.DeploymentCommands,
            "info": info.InfoCommands,
            "show": show.ShowCommands,
            "task": task.TaskCommands,
            "use": use.UseCommands,
            "verify": verify.VerifyCommands
        }

    def tearDown(self):
        self._unregister_opts()
        super(CliUtilsTestCase, self).tearDown()

    def test_make_header(self):
        h1 = cliutils.make_header("msg", size="4", symbol="=")
        self.assertEqual(h1, "====\n msg\n====\n")

    def test_pretty_float_formatter_rounding(self):
        test_table_rows = {"test_header": 6.56565}
        self.__dict__.update(**test_table_rows)

        formatter = cliutils.pretty_float_formatter("test_header", 3)
        return_value = formatter(self)

        self.assertEqual(return_value, 6.566)

    def test_pretty_float_formatter_nonrounding(self):
        test_table_rows = {"test_header": 6.56565}
        self.__dict__.update(**test_table_rows)

        formatter = cliutils.pretty_float_formatter("test_header")
        return_value = formatter(self)

        self.assertEqual(return_value, 6.56565)

    def test_pretty_float_formatter_none_value(self):
        test_table_rows = {"test_header": None}
        self.__dict__.update(**test_table_rows)

        formatter = cliutils.pretty_float_formatter("test_header")
        return_value = formatter(self)

        self.assertEqual(return_value, "n/a")

    def test__methods_of_with_class(self):
        class fake_class(object):
            def public(self):
                pass

            def _private(self):
                pass

        result = cliutils._methods_of(fake_class)
        self.assertEqual(1, len(result))
        self.assertEqual("public", result[0][0])

    def test__methods_of_with_object(self):
        class fake_class(object):
            def public(self):
                pass

            def _private(self):
                pass

        mock_obj = fake_class()
        result = cliutils._methods_of(mock_obj)
        self.assertEqual(1, len(result))
        self.assertEqual("public", result[0][0])

    def test__methods_of_empty_result(self):
        class fake_class(object):
            def _private(self):
                pass

            def _private2(self):
                pass

        mock_obj = fake_class()
        result = cliutils._methods_of(mock_obj)
        self.assertEqual(result, [])

    def _unregister_opts(self):
        CONF.reset()
        category_opt = cfg.SubCommandOpt("category",
                                         title="Command categories",
                                         help="Available categories")
        CONF.unregister_opt(category_opt)

    @mock.patch("rally.cmd.cliutils.CONF",
                config_file=None,
                side_effect=cfg.ConfigFilesNotFoundError("config_file"))
    def test_run_fails(self, mock_cmd_cliutils_conf):
        ret = cliutils.run(["rally", "show", "flavors"], self.categories)
        self.assertEqual(ret, 2)

    def test_run_version(self):
        ret = cliutils.run(["rally", "version"], self.categories)
        self.assertEqual(ret, 0)

    def test_run_bash_completion(self):
        ret = cliutils.run(["rally", "bash-completion"], self.categories)
        self.assertEqual(ret, 0)

    def test_run_bash_completion_with_query_category(self):
        ret = cliutils.run(["rally", "bash-completion", "info"],
                           self.categories)
        self.assertEqual(ret, 0)

    def test_run_show(self):
        ret = cliutils.run(["rally", "show", "keypairs"], self.categories)
        self.assertEqual(ret, 1)

    @mock.patch("rally.db.task_get",
                side_effect=exceptions.TaskNotFound(FAKE_TASK_UUID))
    def test_run_task_not_found(self, mock_task_get):
        ret = cliutils.run(["rally", "task", "status",
                            "%s" % FAKE_TASK_UUID], self.categories)
        self.assertTrue(mock_task_get.called)
        self.assertEqual(ret, 1)

    @mock.patch("rally.common.cliutils.validate_args",
                side_effect=cliutils.MissingArgs("missing"))
    def test_run_show_fails(self, mock_validate_args):
        ret = cliutils.run(["rally", "show", "keypairs"], self.categories)
        self.assertTrue(mock_validate_args.called)
        self.assertEqual(ret, 1)

    def test_run_failed_to_open_file(self):
        class FailuresCommands(object):
            def failed_to_open_file(self):
                raise IOError("No such file")

        ret = cliutils.run(["rally", "failure", "failed_to_open_file"],
                           {"failure": FailuresCommands})
        self.assertEqual(1, ret)
Beispiel #26
0
 def __init__(self, cell_state_cls=None):
     cells_config = CONF.cells.cells_config
     self.cells_config_path = CONF.find_file(cells_config)
     if not self.cells_config_path:
         raise cfg.ConfigFilesNotFoundError(config_files=[cells_config])
     super(CellStateManagerFile, self).__init__(cell_state_cls)
Beispiel #27
0
class CliUtilsTestCase(test.TestCase):
    def setUp(self):
        super(CliUtilsTestCase, self).setUp()
        self.categories = {
            "deployment": deployment.DeploymentCommands,
            "show": show.ShowCommands,
            "task": task.TaskCommands,
            "verify": verify.VerifyCommands
        }

    def tearDown(self):
        self._unregister_opts()
        super(CliUtilsTestCase, self).tearDown()

    @mock.patch("rally.cli.cliutils.os.path")
    def test_find_config_files(self, mock_os_path):

        mock_os_path.expanduser.return_value = "expanduser"
        mock_os_path.abspath.return_value = "abspath"
        mock_os_path.isfile.return_value = True

        result = cliutils.find_config_files(["path1", "path2"])
        mock_os_path.expanduser.assert_called_once_with("path1")
        mock_os_path.abspath.assert_called_once_with(
            mock_os_path.expanduser.return_value)
        mock_os_path.isfile.assert_called_once_with(
            mock_os_path.abspath.return_value + "/rally.conf")
        self.assertEqual([mock_os_path.abspath.return_value + "/rally.conf"],
                         result)

        mock_os_path.isfile.return_value = False

        result = cliutils.find_config_files(["path1", "path2"])
        self.assertIsNone(result)

    def test_make_header(self):
        h1 = cliutils.make_header("msg", size=4, symbol="=")
        self.assertEqual(h1, "====\n msg\n====\n")

    def test_make_table_header(self):
        actual = cliutils.make_table_header("Response Times (sec)", 40)
        expected = "\n".join((
            "+--------------------------------------+",
            "|         Response Times (sec)         |",
        ))
        self.assertEqual(expected, actual)

        actual = cliutils.make_table_header("Response Times (sec)", 39)
        expected = "\n".join((
            "+-------------------------------------+",
            "|        Response Times (sec)         |",
        ))
        self.assertEqual(expected, actual)

        self.assertRaises(ValueError, cliutils.make_table_header,
                          "Response Times (sec)", len("Response Times (sec)"))

    def test_pretty_float_formatter_rounding(self):
        test_table_rows = {"test_header": 6.56565}
        self.__dict__.update(**test_table_rows)

        formatter = cliutils.pretty_float_formatter("test_header", 3)
        return_value = formatter(self)

        self.assertEqual(return_value, 6.566)

    def test_pretty_float_formatter_nonrounding(self):
        test_table_rows = {"test_header": 6.56565}
        self.__dict__.update(**test_table_rows)

        formatter = cliutils.pretty_float_formatter("test_header")
        return_value = formatter(self)

        self.assertEqual(return_value, 6.56565)

    def test_pretty_float_formatter_none_value(self):
        test_table_rows = {"test_header": None}
        self.__dict__.update(**test_table_rows)

        formatter = cliutils.pretty_float_formatter("test_header")
        return_value = formatter(self)

        self.assertEqual(return_value, "n/a")

    def test_process_keyestone_exc(self):
        @cliutils.process_keystone_exc
        def a(a):
            if a == 1:
                raise keystone_exc.Unauthorized()

            if a == 2:
                raise keystone_exc.AuthorizationFailure()

            if a == 3:
                raise keystone_exc.ConnectionRefused()

            return a

        self.assertEqual(1, a(1))
        self.assertEqual(1, a(2))
        self.assertEqual(1, a(3))
        self.assertEqual(4, a(4))

    def test__methods_of_with_class(self):
        class fake_class(object):
            def public(self):
                pass

            def _private(self):
                pass

        result = cliutils._methods_of(fake_class)
        self.assertEqual(1, len(result))
        self.assertEqual("public", result[0][0])

    def test__methods_of_with_object(self):
        class fake_class(object):
            def public(self):
                pass

            def _private(self):
                pass

        mock_obj = fake_class()
        result = cliutils._methods_of(mock_obj)
        self.assertEqual(1, len(result))
        self.assertEqual("public", result[0][0])

    def test__methods_of_empty_result(self):
        class fake_class(object):
            def _private(self):
                pass

            def _private2(self):
                pass

        mock_obj = fake_class()
        result = cliutils._methods_of(mock_obj)
        self.assertEqual(result, [])

    def _unregister_opts(self):
        CONF.reset()
        category_opt = cfg.SubCommandOpt("category",
                                         title="Command categories",
                                         help="Available categories")
        CONF.unregister_opt(category_opt)

    @mock.patch("rally.cli.cliutils.CONF",
                config_file=None,
                side_effect=cfg.ConfigFilesNotFoundError("config_file"))
    def test_run_fails(self, mock_cliutils_conf):
        ret = cliutils.run(["rally", "show", "flavors"], self.categories)
        self.assertEqual(ret, 2)

    def test_run_version(self):
        ret = cliutils.run(["rally", "version"], self.categories)
        self.assertEqual(ret, 0)

    def test_run_bash_completion(self):
        ret = cliutils.run(["rally", "bash-completion"], self.categories)
        self.assertEqual(ret, 0)

    def test_run_show(self):
        ret = cliutils.run(["rally", "show", "keypairs"], self.categories)
        self.assertEqual(ret, 1)

    @mock.patch("rally.common.db.task_get",
                side_effect=exceptions.TaskNotFound(uuid=FAKE_TASK_UUID))
    def test_run_task_not_found(self, mock_task_get):
        ret = cliutils.run(["rally", "task", "status",
                            "%s" % FAKE_TASK_UUID], self.categories)
        self.assertTrue(mock_task_get.called)
        self.assertEqual(ret, 1)

    @mock.patch("rally.cli.cliutils.validate_args",
                side_effect=cliutils.MissingArgs("missing"))
    def test_run_show_fails(self, mock_validate_args):
        ret = cliutils.run(["rally", "show", "keypairs"], self.categories)
        self.assertTrue(mock_validate_args.called)
        self.assertEqual(ret, 1)

    def test_run_failed_to_open_file(self):
        class FailuresCommands(object):
            def failed_to_open_file(self):
                raise IOError("No such file")

        ret = cliutils.run(["rally", "failure", "failed_to_open_file"],
                           {"failure": FailuresCommands})
        self.assertEqual(1, ret)

    def test_run_sqlalchmey_operational_failure(self):
        class SQLAlchemyCommands(object):
            def operational_failure(self):
                raise sqlalchemy.exc.OperationalError("Can't open DB file")

        ret = cliutils.run(["rally", "failure", "operational_failure"],
                           {"failure": SQLAlchemyCommands})
        self.assertEqual(1, ret)

    def test_print_list(self):
        class TestObj(object):
            x = 1
            y = 2
            z = 3.142857142857143
            aOrB = 3  # mixed case field

        out = moves.StringIO()
        cliutils.print_list([TestObj()], ["x", "y"],
                            print_header=True,
                            print_border=True,
                            sortby_index=None,
                            out=out)
        self.assertEqual(
            "+---+---+\n"
            "| x | y |\n"
            "+---+---+\n"
            "| 1 | 2 |\n"
            "+---+---+",
            out.getvalue().strip())

        out = moves.StringIO()
        formatter = cliutils.pretty_float_formatter("z", 5)
        cliutils.print_list([TestObj()], ["z"],
                            print_header=True,
                            print_border=True,
                            sortby_index=None,
                            formatters={"z": formatter},
                            out=out)
        self.assertEqual(
            "+---------+\n"
            "| z       |\n"
            "+---------+\n"
            "| 3.14286 |\n"
            "+---------+",
            out.getvalue().strip())

        out = moves.StringIO()
        cliutils.print_list([TestObj()], ["x"],
                            print_header=True,
                            print_border=True,
                            out=out)
        self.assertEqual("+---+\n"
                         "| x |\n"
                         "+---+\n"
                         "| 1 |\n"
                         "+---+",
                         out.getvalue().strip())

        out = moves.StringIO()
        cliutils.print_list([TestObj()], ["x", "y"],
                            print_header=True,
                            print_border=True,
                            out=out)
        self.assertEqual(
            "+---+---+\n"
            "| x | y |\n"
            "+---+---+\n"
            "| 1 | 2 |\n"
            "+---+---+",
            out.getvalue().strip())

        out = moves.StringIO()
        cliutils.print_list([TestObj()], ["x"],
                            print_header=False,
                            print_border=False,
                            out=out)
        self.assertEqual("1", out.getvalue().strip())

        out = moves.StringIO()
        cliutils.print_list([TestObj()], ["x", "y"],
                            print_header=False,
                            print_border=False,
                            out=out)
        self.assertEqual("1 2", out.getvalue().strip())

        out = moves.StringIO()
        cliutils.print_list([TestObj()], ["x"],
                            print_header=True,
                            print_border=False,
                            out=out)
        self.assertEqual("x \n1", out.getvalue().strip())

        out = moves.StringIO()
        cliutils.print_list([TestObj()], ["x", "y"],
                            print_header=True,
                            print_border=False,
                            out=out)
        self.assertEqual("x y \n1 2", out.getvalue().strip())

        out = moves.StringIO()
        cliutils.print_list([TestObj()], ["x"],
                            print_header=False,
                            print_border=True,
                            out=out)
        self.assertEqual("+--+\n" "|1 |\n" "+--+", out.getvalue().strip())

        out = moves.StringIO()
        cliutils.print_list([TestObj()], ["x", "y"],
                            print_header=False,
                            print_border=True,
                            out=out)
        self.assertEqual("+--+--+\n"
                         "|1 |2 |\n"
                         "+--+--+",
                         out.getvalue().strip())

        out = moves.StringIO()
        cliutils.print_list([TestObj()], ["aOrB"],
                            mixed_case_fields=["aOrB"],
                            print_header=True,
                            print_border=True,
                            out=out)
        self.assertEqual(
            "+------+\n"
            "| aOrB |\n"
            "+------+\n"
            "| 3    |\n"
            "+------+",
            out.getvalue().strip())

        out = moves.StringIO()
        cliutils.print_list([TestObj()], ["aOrB"],
                            mixed_case_fields=["aOrB"],
                            print_header=False,
                            print_border=True,
                            out=out)
        self.assertEqual("+--+\n" "|3 |\n" "+--+", out.getvalue().strip())

        out = moves.StringIO()
        cliutils.print_list([TestObj()], ["aOrB"],
                            mixed_case_fields=["aOrB"],
                            print_header=True,
                            print_border=False,
                            out=out)
        self.assertEqual("aOrB \n" "3", out.getvalue().strip())

        out = moves.StringIO()
        cliutils.print_list([TestObj()], ["aOrB"],
                            mixed_case_fields=["aOrB"],
                            print_header=False,
                            print_border=False,
                            out=out)
        self.assertEqual("3", out.getvalue().strip())

        out = moves.StringIO()
        self.assertRaisesRegexp(ValueError,
                                "Field labels list.*has different number "
                                "of elements than fields list",
                                cliutils.print_list, [TestObj()], ["x"],
                                field_labels=["x", "y"],
                                sortby_index=None,
                                out=out)