コード例 #1
0
ファイル: __main__.py プロジェクト: lodexinc/azure-cli
def main(style=None):
    os.environ[ENV_ADDITIONAL_USER_AGENT] = 'AZURECLISHELL/' + __version__

    azure_folder = cli_config_dir()
    if not os.path.exists(azure_folder):
        os.makedirs(azure_folder)

    ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
    CONFIG.load(os.path.join(azure_folder, 'az.json'))
    SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)

    config = SHELL_CONFIGURATION
    shell_config_dir = azclishell.configuration.get_config_dir

    if style:
        given_style = style
        config.set_style(given_style)
    else:
        given_style = config.get_style()

    style_obj = style_factory(given_style)

    if config.BOOLEAN_STATES[config.config.get('DEFAULT', 'firsttime')]:
        print("When in doubt, ask for 'help'")
        config.firsttime()

    shell_app = Shell(completer=AZCOMPLETER,
                      lexer=AzLexer,
                      history=FileHistory(
                          os.path.join(shell_config_dir(),
                                       config.get_history())),
                      app=APPLICATION,
                      styles=style_obj)
    shell_app.run()
コード例 #2
0
def main():
    """ the main function """

    azure_folder = cli_config_dir()
    if not os.path.exists(azure_folder):
        os.makedirs(azure_folder)

    ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
    CONFIG.load(os.path.join(azure_folder, 'az.json'))
    SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)

    config = CONFIGURATION

    if config.BOOLEAN_STATES[config.config.get('DEFAULT', 'firsttime')]:
        APPLICATION.execute(["configure"])
        print("When in doubt, ask for 'help'")
        config.firsttime()

    shell_app = Shell(
        completer=AZCOMPLETER,
        lexer=AzLexer,
        history=FileHistory(os.path.join(CONFIGURATION.get_config_dir(), config.get_history())),
        app=APPLICATION,
        # cli_config=os.path.join(azure_folder, 'config')
    )
    shell_app.run()
コード例 #3
0
    def __init__(self, *args, **kwargs):
        super(QueryInjection, self).__init__(*args, **kwargs)
        from azclishell.app import Shell

        self.stream = six.StringIO()
        self.shell = Shell(output_custom=self.stream)
        self.shell.cli_execute = self._mock_execute
        self.shell.last = MockValues()
コード例 #4
0
def main(style=None):
    if APPLICATION.session["az_interactive_active"]:
        logger.warning("You're in the interactive shell already.\n")
        return

    os.environ[ENV_ADDITIONAL_USER_AGENT] = 'AZURECLISHELL/' + __version__

    azure_folder = cli_config_dir()
    if not os.path.exists(azure_folder):
        os.makedirs(azure_folder)

    ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
    CONFIG.load(os.path.join(azure_folder, 'az.json'))
    SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)

    config = azclishell.configuration.CONFIGURATION
    shell_config_dir = azclishell.configuration.get_config_dir

    try:
        commands = GatherCommands()
        az_completer = AzCompleter(commands)
    except IOError:  # if there is no cache
        az_completer = None

    if style:
        given_style = style
        config.set_style(given_style)
    else:
        given_style = config.get_style()

    style_obj = style_factory(given_style)

    if config.BOOLEAN_STATES[config.config.get('DEFAULT', 'firsttime')]:
        config.firsttime()

    ask_feedback = False
    if not config.has_feedback() and frequent_user:
        print(
            "\n\nAny comments or concerns? You can use the \'feedback\' command!"
            + " We would greatly appreciate it.\n")
        ask_feedback = True

    shell_app = Shell(completer=az_completer,
                      lexer=AzLexer,
                      history=FileHistory(
                          os.path.join(shell_config_dir(),
                                       config.get_history())),
                      app=APPLICATION,
                      styles=style_obj,
                      user_feedback=ask_feedback)
    shell_app.app.session["az_interactive_active"] = True
    shell_app.run()
    shell_app.app.session["az_interactive_active"] = False
コード例 #5
0
ファイル: __main__.py プロジェクト: LukaszStem/azure-cli
def main(style=None):
    if APPLICATION.session["az_interactive_active"]:
        logger.warning("You're in the interactive shell already.\n")
        return

    os.environ[ENV_ADDITIONAL_USER_AGENT] = 'AZURECLISHELL/' + __version__

    azure_folder = cli_config_dir()
    if not os.path.exists(azure_folder):
        os.makedirs(azure_folder)

    ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
    CONFIG.load(os.path.join(azure_folder, 'az.json'))
    SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)

    config = azclishell.configuration.CONFIGURATION
    shell_config_dir = azclishell.configuration.get_config_dir

    try:
        commands = GatherCommands()
        az_completer = AzCompleter(commands)
    except IOError:  # if there is no cache
        az_completer = None

    if style:
        given_style = style
        config.set_style(given_style)
    else:
        given_style = config.get_style()

    style_obj = style_factory(given_style)

    if config.BOOLEAN_STATES[config.config.get('DEFAULT', 'firsttime')]:
        config.firsttime()

    ask_feedback = False
    if not config.has_feedback() and frequent_user:
        print("\n\nAny comments or concerns? You can use the \'feedback\' command!" +
              " We would greatly appreciate it.\n")
        ask_feedback = True

    shell_app = Shell(
        completer=az_completer,
        lexer=AzLexer,
        history=FileHistory(
            os.path.join(shell_config_dir(), config.get_history())),
        app=APPLICATION,
        styles=style_obj,
        user_feedback=ask_feedback
    )
    shell_app.app.session["az_interactive_active"] = True
    shell_app.run()
    shell_app.app.session["az_interactive_active"] = False
コード例 #6
0
    def __init__(self, *args, **kwargs):
        super(QueryInjection, self).__init__(*args, **kwargs)
        from azclishell.app import Shell

        self.stream = six.StringIO()
        self.shell = Shell(output_custom=self.stream)
        self.shell.cli_execute = self._mock_execute
        self.shell.last = MockValues()
コード例 #7
0
ファイル: __main__.py プロジェクト: akshaysngupta/azure-cli
def main(style=None):
    os.environ[ENV_ADDITIONAL_USER_AGENT] = 'AZURECLISHELL/' + __version__

    azure_folder = cli_config_dir()
    if not os.path.exists(azure_folder):
        os.makedirs(azure_folder)

    ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
    CONFIG.load(os.path.join(azure_folder, 'az.json'))
    SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)

    config = SHELL_CONFIGURATION
    shell_config_dir = azclishell.configuration.get_config_dir

    if style:
        given_style = style
        config.set_style(given_style)
    else:
        given_style = config.get_style()

    style_obj = style_factory(given_style)

    if config.BOOLEAN_STATES[config.config.get('DEFAULT', 'firsttime')]:
        print("When in doubt, ask for 'help'")
        config.firsttime()

    ask_feedback = False
    if not config.has_feedback() and frequent_user:
        print("\n\nAny comments or concerns? You can use the \'feedback\' command!" +
              " We would greatly appreciate it.\n")
        ask_feedback = True

    shell_app = Shell(
        completer=AZCOMPLETER,
        lexer=AzLexer,
        history=FileHistory(
            os.path.join(shell_config_dir(), config.get_history())),
        app=APPLICATION,
        styles=style_obj,
        user_feedback=ask_feedback
    )
    shell_app.run()
コード例 #8
0
def main(style=None):
    os.environ[ENV_ADDITIONAL_USER_AGENT] = 'AZURECLISHELL/' + __version__

    azure_folder = cli_config_dir()
    if not os.path.exists(azure_folder):
        os.makedirs(azure_folder)

    ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
    CONFIG.load(os.path.join(azure_folder, 'az.json'))
    SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)

    config = SHELL_CONFIGURATION
    shell_config_dir = azclishell.configuration.get_config_dir

    if style:
        given_style = style
        config.set_style(given_style)
    else:
        given_style = config.get_style()

    style_obj = style_factory(given_style)

    if config.BOOLEAN_STATES[config.config.get('DEFAULT', 'firsttime')]:
        print("When in doubt, ask for 'help'")
        config.firsttime()

    ask_feedback = False
    if not config.has_feedback() and frequent_user:
        print(
            "\n\nAny comments or concerns? You can use the \'feedback\' command!"
            + " We would greatly appreciate it.\n")
        ask_feedback = True

    shell_app = Shell(completer=AZCOMPLETER,
                      lexer=AzLexer,
                      history=FileHistory(
                          os.path.join(shell_config_dir(),
                                       config.get_history())),
                      app=APPLICATION,
                      styles=style_obj,
                      user_feedback=ask_feedback)
    shell_app.run()
コード例 #9
0
ファイル: __main__.py プロジェクト: sasukeh/azure-cli-shell
def main(args):
    os.environ[ENV_ADDITIONAL_USER_AGENT] = 'AZURECLISHELL/' + __version__

    parser = argparse.ArgumentParser(prog='az-shell')
    parser.add_argument('--style',
                        dest='style',
                        help='the colors of the shell',
                        choices=get_options())
    args = parser.parse_args(args)

    azure_folder = cli_config_dir()
    if not os.path.exists(azure_folder):
        os.makedirs(azure_folder)

    ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
    CONFIG.load(os.path.join(azure_folder, 'az.json'))
    SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)

    config = SHELL_CONFIGURATION
    shell_config_dir = azclishell.configuration.get_config_dir

    if args.style:
        given_style = args.style
        config.set_style(given_style)
    else:
        given_style = config.get_style()

    style = style_factory(given_style)

    if config.BOOLEAN_STATES[config.config.get('DEFAULT', 'firsttime')]:
        print("When in doubt, ask for 'help'")
        config.firsttime()

    shell_app = Shell(completer=AZCOMPLETER,
                      lexer=AzLexer,
                      history=FileHistory(
                          os.path.join(shell_config_dir(),
                                       config.get_history())),
                      app=APPLICATION,
                      styles=style)
    shell_app.run()
コード例 #10
0
    def __init__(self, *args, **kwargs):
        super(ShellScenarioTest, self).__init__(*args, **kwargs)

        self.out_stream = six.StringIO()
        self.shell = Shell(history=None, output_custom=self.out_stream)
        self.shell.completer = TestCompleter()
コード例 #11
0
class ShellScenarioTest(unittest.TestCase):
    """ tests whether dump commands works """
    def __init__(self, *args, **kwargs):
        super(ShellScenarioTest, self).__init__(*args, **kwargs)

        self.out_stream = six.StringIO()
        self.shell = Shell(history=None, output_custom=self.out_stream)
        self.shell.completer = TestCompleter()

    def test_generate_help_text(self):
        """ tests building the help text """
        self.shell.completer = None
        description, example = self.shell.generate_help_text('')
        self.assertEqual(description, '')
        self.assertEqual(example, '')

        self.shell.completer = TestCompleter()
        description, example = self.shell.generate_help_text('friendship --calls')
        self.assertEqual(description, '--calls:\n' + 'call the friends')
        self.assertEqual(example, space_examples('use with care', 25, 1))

    def test_handle_examples(self):
        """ tests handling of example repl """
        temp_function = self.shell.example_repl
        self.shell.example_repl = mock_pass
        text = 'guess :: h'
        c_flag = False

        self.shell.handle_example(text, c_flag)
        self.assertEqual(self.out_stream.getvalue(), 'An Integer should follow the colon\n')
        self.out_stream.truncate(0)
        self.out_stream.seek(0)

        text = 'guess :: 2.8'
        c_flag = False
        self.shell.handle_example(text, c_flag)
        self.assertEqual(self.out_stream.getvalue(), 'An Integer should follow the colon\n')
        self.out_stream.truncate(0)
        self.out_stream.seek(0)

        text = 'guess :: -3'
        c_flag = False
        self.shell.handle_example(text, c_flag)
        self.assertEqual(self.out_stream.getvalue(), 'Invalid example number\n')
        self.out_stream.truncate(0)
        self.out_stream.seek(0)

        text = 'guess :: 3'
        c_flag = False
        self.shell.handle_example(text, c_flag)
        self.assertEqual(self.out_stream.getvalue(), 'Invalid example number\n')
        self.out_stream.truncate(0)
        self.out_stream.seek(0)

        text = 'guess :: 1'
        c_flag = False
        self.shell.handle_example(text, c_flag)

        self.shell.example_repl = temp_function
コード例 #12
0
    def __init__(self, *args, **kwargs):
        super(ShellScenarioTest, self).__init__(*args, **kwargs)

        self.out_stream = six.StringIO()
        self.shell = Shell(history=None, output_custom=self.out_stream)
        self.shell.completer = TestCompleter()
コード例 #13
0
class QueryInjection(unittest.TestCase):
    """ tests using the query gesture for the interactive mode """
    def __init__(self, *args, **kwargs):
        super(QueryInjection, self).__init__(*args, **kwargs)
        from azclishell.app import Shell, validate_contains_query

        self.stream = six.StringIO()
        self.shell = Shell(output_custom=self.stream)
        self.shell.cli_execute = self._mock_execute
        self.shell.last = MockValues()
        self.validation_func = validate_contains_query

    def _mock_execute(self, cmd):
        self.stream.write(cmd)
        self.stream.write('\n')

    def test_null(self):
        """ tests empty case """
        args = []
        self.shell.last.result = {}
        flag = self.shell.handle_jmespath_query(args, False)
        self.assertTrue(flag)
        self.assertEqual('\n', self.stream.getvalue())

    def test_just_query(self):
        """ tests flushing just the query """
        args = ['?x']
        self.shell.last.result = {'x': 'result'}
        flag = self.shell.handle_jmespath_query(args, False)
        self.assertTrue(flag)
        self.assertEqual('"result"\n', self.stream.getvalue())

    def test_string_replacement(self):
        """ tests that the query replaces the values in the command """
        args = 'vm show -g "?group" -n "?name"'
        args = parse_quotes(args)
        args_no_quotes = []
        for arg in args:
            args_no_quotes.append(arg.strip("/'").strip('/"'))
        self.shell.last.result = {
            'group': 'mygroup',
            'name': 'myname'
        }
        flag = self.shell.handle_jmespath_query(args, False)
        self.assertTrue(flag)
        self.assertEqual(u"vm show -g mygroup -n myname\n", self.stream.getvalue())

    def test_list_replacement(self):
        """ tests that the query replaces the values in the command """
        args = 'vm show -g "?[].group" -n "?[].name"'
        args = parse_quotes(args)
        args_no_quotes = []
        for arg in args:
            args_no_quotes.append(arg.strip("/'").strip('/"'))
        self.shell.last.result = [
            {
                'group': 'mygroup',
                'name': 'myname'
            },
            {
                'group': 'mygroup2',
                'name': 'myname2'
            },
            {
                'group': 'mygroup3',
                'name': 'myname3'
            }
        ]
        flag = self.shell.handle_jmespath_query(args, False)
        self.assertTrue(flag)
        results = self.stream.getvalue().strip().split('\n')
        self.assertTrue(len(results) == 3)
        self.assertEqual(results[0], 'vm show -g mygroup -n myname')
        self.assertEqual(results[1], 'vm show -g mygroup2 -n myname2')
        self.assertEqual(results[2], 'vm show -g mygroup3 -n myname3')

    def test_quotes(self):
        """ tests that it parses correctly with quotes in the command """
        self.shell.last.result = {'x': 'result'}
        # pylint: disable=protected-access
        b_flag, c_flag, out, cmd = self.shell._special_cases(
            "this is 'url?what' negative", "this is 'url?what' negative", False)
        self.assertFalse(b_flag)
        self.assertFalse(c_flag)
        self.assertFalse(out)
        self.assertEqual(cmd, "this is 'url?what' negative")

    def test_errors(self):
        """ tests invalid query """
        args = 'vm show -g "?[].group" -n "?[].name"'
        args = parse_quotes(args)
        args_no_quotes = []
        for arg in args:
            args_no_quotes.append(arg.strip("/'").strip('/"'))
        self.shell.last.result = [
            {
                'group': 'mygroup',
                'name': 'myname'
            },
            {
                'group': 'mygroup3',
            }
        ]
        flag = self.shell.handle_jmespath_query(args, False)
        results = self.stream.getvalue().split('\n')
        self.assertTrue(flag)
        self.assertEqual(results[0], 'vm show -g mygroup -n myname')
        self.assertEqual(len(results), 2)

    def test_singleton(self):
        """ tests a singleton example """
        args = 'vm show -g "?group" -n "?name"'
        args = parse_quotes(args)
        args_no_quotes = []
        for arg in args:
            args_no_quotes.append(arg.strip("/'").strip('/"'))
        self.shell.last.result = {
            'group': 'mygroup',
            'name': 'myname'
        }

        flag = self.shell.handle_jmespath_query(args, False)
        self.assertTrue(flag)
        results = self.stream.getvalue().split('\n')
        self.assertEqual(results[0], u'vm show -g mygroup -n myname')

    def test_spaces(self):
        """ tests quotes with spaces """
        args = 'vm show -g "?[?group == \'mygroup\'].name"'
        args = parse_quotes(args)
        args_no_quotes = []
        for arg in args:
            args_no_quotes.append(arg.strip("/'").strip('/"'))
        self.shell.last.result = [
            {
                'group': 'mygroup',
                'name': 'fred'
            },
            {
                'group': 'mygroup3',
                'name': 'myname3'
            }
        ]

        self.shell.handle_jmespath_query(args_no_quotes, False)
        results = self.stream.getvalue().split('\n')
        self.assertEqual(results[0], u'vm show -g fred')

    def test_spaces_with_equal(self):
        """ tests quotes with spaces """
        args = 'vm show -g="?[?group == \'myg roup\'].name"'
        args = parse_quotes(args)
        args_no_quotes = []
        for arg in args:
            args_no_quotes.append(arg.strip("/'").strip('/"'))
        self.shell.last.result = [
            {
                'group': 'myg roup',
                'name': 'fred'
            },
            {
                'group': 'mygroup3',
                'name': 'myname3'
            }
        ]

        self.shell.handle_jmespath_query(args_no_quotes, False)
        results = self.stream.getvalue().split('\n')
        self.assertEqual(results[0], u'vm show -g=fred')

    def test_validation(self):
        """ tests line validation that the command is an injection """
        args = 'foo bar --foo=?bar'
        self.assertTrue(self.validation_func(args.split(), '?'))

        args = 'foo bar --is fun -g ?bar '
        self.assertTrue(self.validation_func(args.split(), '?'))

        args = 'foo bar --is fun -g bar '
        self.assertFalse(self.validation_func(args.split(), '?'))

        args = 'foo bar --isfun=bar '
        self.assertFalse(self.validation_func(args.split(), '?'))

        args = 'foo bar --is ?[?group == \'word\'].name '
        self.assertTrue(self.validation_func(parse_quotes(args), '?'))

        args = 'foo bar --query [?group == \'word\'].name '
        self.assertFalse(self.validation_func(parse_quotes(args), '?'))

        args = 'foo bar --query=[?group == \'w or =?d\'].name '
        self.assertFalse(self.validation_func(parse_quotes(args), '?'))
コード例 #14
0
class QueryInjection(unittest.TestCase):
    """ tests using the query gesture for the interactive mode """
    def __init__(self, *args, **kwargs):
        super(QueryInjection, self).__init__(*args, **kwargs)
        from azclishell.app import Shell

        self.stream = six.StringIO()
        self.shell = Shell(output_custom=self.stream)
        self.shell.cli_execute = self._mock_execute
        self.shell.last = MockValues()

    def _mock_execute(self, cmd):
        self.stream.write(cmd)
        self.stream.write(os.linesep)

    def test_print_last_command(self):
        # tests getting last command result
        args = ['??']
        self.shell.last.result = {'x': 'result'}
        flag = self.shell.handle_jmespath_query(args)
        self.assertTrue(flag)
        self.assertEqual(json.loads(self.stream.getvalue()), {'x': 'result'})

    def test_print_just_query(self):
        # tests flushing just the query
        args = ['??x']
        self.shell.last.result = {'x': 'result'}
        flag = self.shell.handle_jmespath_query(args)
        self.assertTrue(flag)
        self.assertEqual(json.loads(self.stream.getvalue()), 'result')

    def test_print_list_replacement(self):
        # tests that the query replaces the values in the command
        args = '??[].group'
        args = parse_quotes(args)
        self.shell.last.result = [{
            'group': 'mygroup',
            'name': 'myname'
        }, {
            'group': 'mygroup2',
            'name': 'myname2'
        }, {
            'group': 'mygroup3',
            'name': 'myname3'
        }]
        flag = self.shell.handle_jmespath_query(args)
        self.assertTrue(flag)
        self.assertEqual(json.loads(self.stream.getvalue()),
                         ['mygroup', 'mygroup2', 'mygroup3'])

    def test_usage_error(self):
        # tests case when multiple args but first arg starts with query
        args = '??[].group foo bar'
        args = parse_quotes(args)
        self.shell.last.result = {'group': 'mygroup', 'name': 'myname'}
        flag = self.shell.handle_jmespath_query(args)
        self.assertTrue(flag)
        self.assertEqual(
            self.stream.getvalue().strip(), "Usage Error: " + os.linesep +
            "1. Use ?? stand-alone to display previous result with optional filtering "
            "(Ex: ??[jmespath query])" + os.linesep + "OR:" + os.linesep +
            "2. Use ?? to query the previous result for argument values "
            "(Ex: group show --name ??[jmespath query])")

    def test_string_replacement(self):
        # tests that the query replaces the values in the command
        args = 'vm show -g "??group" -n "??name"'
        args = parse_quotes(args)
        self.shell.last.result = {'group': 'mygroup', 'name': 'myname'}
        flag = self.shell.handle_jmespath_query(args)
        self.assertTrue(flag)
        results = self.stream.getvalue().split(os.linesep)
        self.assertEqual(results[0],
                         '"vm" "show" "-g" "mygroup" "-n" "myname"')

    def test_list_replacement(self):
        # tests that the query replaces the values in the command
        args = 'foo update --set blah=??[].group'
        args = parse_quotes(args)
        self.shell.last.result = [{
            'group': 'mygroup',
            'name': 'myname'
        }, {
            'group': 'mygroup2',
            'name': 'myname2'
        }, {
            'group': 'mygroup3',
            'name': 'myname3'
        }]
        flag = self.shell.handle_jmespath_query(args)
        self.assertTrue(flag)
        results = self.stream.getvalue().strip().split(os.linesep)
        self.assertTrue(len(results) == 1)
        self.assertEqual(
            results[0],
            '"foo" "update" "--set" "blah=[\'mygroup\', \'mygroup2\', \'mygroup3\']"'
        )

    def test_quotes(self):
        # tests that it parses correctly with quotes in the command
        self.shell.last.result = {'x': 'result'}
        # pylint: disable=protected-access
        b_flag, c_flag, out, cmd = self.shell._special_cases(
            "this is 'url?what' negative", False)
        self.assertFalse(b_flag)
        self.assertFalse(c_flag)
        self.assertFalse(out)
        self.assertEqual(cmd, "this is 'url?what' negative")

    def test_errors(self):
        # tests invalid query
        args = 'vm show -g "??[0].group" -n "??[1].name"'
        args = parse_quotes(args)
        self.shell.last.result = [{
            'group': 'mygroup',
            'name': 'myname'
        }, {
            'group': 'mygroup3',
        }]
        flag = self.shell.handle_jmespath_query(args)
        self.assertTrue(flag)
        results = self.stream.getvalue().split(os.linesep)
        self.assertEqual(results[0], '"vm" "show" "-g" "mygroup" "-n" "None"')

    def test_query_result_spaces(self):
        # tests a singleton example
        args = 'vm show -g "??group" -n "??name"'
        args = parse_quotes(args)
        self.shell.last.result = {'group': 'mygroup', 'name': 'my name'}
        flag = self.shell.handle_jmespath_query(args)
        self.assertTrue(flag)
        results = self.stream.getvalue().split(os.linesep)
        self.assertEqual(results[0],
                         '"vm" "show" "-g" "mygroup" "-n" "my name"')

    def test_spaces(self):
        # tests quotes with spaces
        args = 'foo update --set "bar=??[?group == \'mygroup\'].name"'
        args = parse_quotes(args)
        self.shell.last.result = [{
            'group': 'mygroup',
            'name': 'fred'
        }, {
            'group': 'mygroup3',
            'name': 'myname3'
        }]

        self.shell.handle_jmespath_query(args)
        results = self.stream.getvalue().split(os.linesep)
        self.assertEqual(results[0], '"foo" "update" "--set" "bar=[\'fred\']"')

    def test_spaces_with_equal(self):
        # tests quotes with spaces
        args = 'foo doo -bar="??[?group == \'myg roup\'].name"'
        args = parse_quotes(args)
        self.shell.last.result = [{
            'group': 'myg roup',
            'name': 'fred'
        }, {
            'group': 'mygroup3',
            'name': 'myname3'
        }]

        self.shell.handle_jmespath_query(args)
        results = self.stream.getvalue().split(os.linesep)
        self.assertEqual(results[0], '"foo" "doo" "-bar=[\'fred\']"')
コード例 #15
0
class ShellScenarioTest(unittest.TestCase):
    """ tests whether dump commands works """
    def __init__(self, *args, **kwargs):
        super(ShellScenarioTest, self).__init__(*args, **kwargs)

        self.out_stream = six.StringIO()
        self.shell = Shell(history=None, output_custom=self.out_stream)
        self.shell.completer = TestCompleter()

    def test_generate_help_text(self):
        """ tests building the help text """
        self.shell.completer = None
        description, example = self.shell.generate_help_text('')
        self.assertEqual(description, '')
        self.assertEqual(example, '')

        self.shell.completer = TestCompleter()
        description, example = self.shell.generate_help_text(
            'friendship --calls')
        self.assertEqual(description, '--calls:\n' + 'call the friends')
        self.assertEqual(example, space_examples('use with care', 25, 1))

    def test_handle_examples(self):
        """ tests handling of example repl """
        temp_function = self.shell.example_repl
        self.shell.example_repl = mock_pass
        text = 'guess :: h'
        c_flag = False

        self.shell.handle_example(text, c_flag)
        self.assertEqual(self.out_stream.getvalue(),
                         'An Integer should follow the colon\n')
        self.out_stream.truncate(0)
        self.out_stream.seek(0)

        text = 'guess :: 2.8'
        c_flag = False
        self.shell.handle_example(text, c_flag)
        self.assertEqual(self.out_stream.getvalue(),
                         'An Integer should follow the colon\n')
        self.out_stream.truncate(0)
        self.out_stream.seek(0)

        text = 'guess :: -3'
        c_flag = False
        self.shell.handle_example(text, c_flag)
        self.assertEqual(self.out_stream.getvalue(),
                         'Invalid example number\n')
        self.out_stream.truncate(0)
        self.out_stream.seek(0)

        text = 'guess :: 3'
        c_flag = False
        self.shell.handle_example(text, c_flag)
        self.assertEqual(self.out_stream.getvalue(),
                         'Invalid example number\n')
        self.out_stream.truncate(0)
        self.out_stream.seek(0)

        text = 'guess :: 1'
        c_flag = False
        self.shell.handle_example(text, c_flag)

        self.shell.example_repl = temp_function
コード例 #16
0
class QueryInjection(unittest.TestCase):
    """ tests using the query gesture for the interactive mode """
    def __init__(self, *args, **kwargs):
        super(QueryInjection, self).__init__(*args, **kwargs)
        from azclishell.app import Shell

        self.stream = six.StringIO()
        self.shell = Shell(output_custom=self.stream)
        self.shell.cli_execute = self._mock_execute
        self.shell.last = MockValues()

    def _mock_execute(self, cmd):
        self.stream.write(cmd)
        self.stream.write(os.linesep)

    def test_print_last_command(self):
        # tests getting last command result
        args = ['??']
        self.shell.last.result = {'x': 'result'}
        flag = self.shell.handle_jmespath_query(args)
        self.assertTrue(flag)
        self.assertEqual(json.loads(self.stream.getvalue()), {'x': 'result'})

    def test_print_just_query(self):
        # tests flushing just the query
        args = ['??x']
        self.shell.last.result = {'x': 'result'}
        flag = self.shell.handle_jmespath_query(args)
        self.assertTrue(flag)
        self.assertEqual(json.loads(self.stream.getvalue()), 'result')

    def test_print_list_replacement(self):
        # tests that the query replaces the values in the command
        args = '??[].group'
        args = parse_quotes(args)
        self.shell.last.result = [
            {
                'group': 'mygroup',
                'name': 'myname'
            },
            {
                'group': 'mygroup2',
                'name': 'myname2'
            },
            {
                'group': 'mygroup3',
                'name': 'myname3'
            }
        ]
        flag = self.shell.handle_jmespath_query(args)
        self.assertTrue(flag)
        self.assertEqual(json.loads(self.stream.getvalue()), ['mygroup', 'mygroup2', 'mygroup3'])

    def test_usage_error(self):
        # tests case when multiple args but first arg starts with query
        args = '??[].group foo bar'
        args = parse_quotes(args)
        self.shell.last.result = {
            'group': 'mygroup',
            'name': 'myname'
        }
        flag = self.shell.handle_jmespath_query(args)
        self.assertTrue(flag)
        self.assertEqual(self.stream.getvalue().strip(),
                         "Usage Error: " + os.linesep +
                         "1. Use ?? stand-alone to display previous result with optional filtering "
                         "(Ex: ??[jmespath query])" +
                         os.linesep + "OR:" + os.linesep +
                         "2. Use ?? to query the previous result for argument values "
                         "(Ex: group show --name ??[jmespath query])")

    def test_string_replacement(self):
        # tests that the query replaces the values in the command
        args = 'vm show -g "??group" -n "??name"'
        args = parse_quotes(args)
        self.shell.last.result = {
            'group': 'mygroup',
            'name': 'myname'
        }
        flag = self.shell.handle_jmespath_query(args)
        self.assertTrue(flag)
        results = self.stream.getvalue().split(os.linesep)
        self.assertEqual(results[0], '"vm" "show" "-g" "mygroup" "-n" "myname"')

    def test_list_replacement(self):
        # tests that the query replaces the values in the command
        args = 'foo update --set blah=??[].group'
        args = parse_quotes(args)
        self.shell.last.result = [
            {
                'group': 'mygroup',
                'name': 'myname'
            },
            {
                'group': 'mygroup2',
                'name': 'myname2'
            },
            {
                'group': 'mygroup3',
                'name': 'myname3'
            }
        ]
        flag = self.shell.handle_jmespath_query(args)
        self.assertTrue(flag)
        results = self.stream.getvalue().strip().split(os.linesep)
        self.assertTrue(len(results) == 1)
        self.assertEqual(results[0], '"foo" "update" "--set" "blah=[\'mygroup\', \'mygroup2\', \'mygroup3\']"')

    def test_quotes(self):
        # tests that it parses correctly with quotes in the command
        self.shell.last.result = {'x': 'result'}
        # pylint: disable=protected-access
        b_flag, c_flag, out, cmd = self.shell._special_cases(
            "this is 'url?what' negative", False)
        self.assertFalse(b_flag)
        self.assertFalse(c_flag)
        self.assertFalse(out)
        self.assertEqual(cmd, "this is 'url?what' negative")

    def test_errors(self):
        # tests invalid query
        args = 'vm show -g "??[0].group" -n "??[1].name"'
        args = parse_quotes(args)
        self.shell.last.result = [
            {
                'group': 'mygroup',
                'name': 'myname'
            },
            {
                'group': 'mygroup3',
            }
        ]
        flag = self.shell.handle_jmespath_query(args)
        self.assertTrue(flag)
        results = self.stream.getvalue().split(os.linesep)
        self.assertEqual(results[0], '"vm" "show" "-g" "mygroup" "-n" "None"')

    def test_query_result_spaces(self):
        # tests a singleton example
        args = 'vm show -g "??group" -n "??name"'
        args = parse_quotes(args)
        self.shell.last.result = {
            'group': 'mygroup',
            'name': 'my name'
        }
        flag = self.shell.handle_jmespath_query(args)
        self.assertTrue(flag)
        results = self.stream.getvalue().split(os.linesep)
        self.assertEqual(results[0], '"vm" "show" "-g" "mygroup" "-n" "my name"')

    def test_spaces(self):
        # tests quotes with spaces
        args = 'foo update --set "bar=??[?group == \'mygroup\'].name"'
        args = parse_quotes(args)
        self.shell.last.result = [
            {
                'group': 'mygroup',
                'name': 'fred'
            },
            {
                'group': 'mygroup3',
                'name': 'myname3'
            }
        ]

        self.shell.handle_jmespath_query(args)
        results = self.stream.getvalue().split(os.linesep)
        self.assertEqual(results[0], '"foo" "update" "--set" "bar=[\'fred\']"')

    def test_spaces_with_equal(self):
        # tests quotes with spaces
        args = 'foo doo -bar="??[?group == \'myg roup\'].name"'
        args = parse_quotes(args)
        self.shell.last.result = [
            {
                'group': 'myg roup',
                'name': 'fred'
            },
            {
                'group': 'mygroup3',
                'name': 'myname3'
            }
        ]

        self.shell.handle_jmespath_query(args)
        results = self.stream.getvalue().split(os.linesep)
        self.assertEqual(results[0], '"foo" "doo" "-bar=[\'fred\']"')
コード例 #17
0
class QueryInjection(unittest.TestCase):
    """ tests using the query gesture for the interactive mode """
    def __init__(self, *args, **kwargs):
        super(QueryInjection, self).__init__(*args, **kwargs)
        from azclishell.app import Shell, validate_contains_query

        self.stream = six.StringIO()
        self.shell = Shell(output_custom=self.stream)
        self.shell.cli_execute = self._mock_execute
        self.shell.last = MockValues()
        self.validation_func = validate_contains_query

    def _mock_execute(self, cmd):
        self.stream.write(cmd)
        self.stream.write('\n')

    def test_null(self):
        # tests empty case
        args = []
        self.shell.last.result = {}
        flag = self.shell.handle_jmespath_query(args, False)
        self.assertTrue(flag)
        self.assertEqual('\n', self.stream.getvalue())

    def test_just_query(self):
        # tests flushing just the query
        args = ['?x']
        self.shell.last.result = {'x': 'result'}
        flag = self.shell.handle_jmespath_query(args, False)
        self.assertTrue(flag)
        self.assertEqual('"result"\n', self.stream.getvalue())

    def test_string_replacement(self):
        # tests that the query replaces the values in the command
        args = 'vm show -g "?group" -n "?name"'
        args = parse_quotes(args)
        args_no_quotes = []
        for arg in args:
            args_no_quotes.append(arg.strip("/'").strip('/"'))
        self.shell.last.result = {
            'group': 'mygroup',
            'name': 'myname'
        }
        flag = self.shell.handle_jmespath_query(args, False)
        self.assertTrue(flag)
        self.assertEqual(u"vm show -g mygroup -n myname\n", self.stream.getvalue())

    def test_list_replacement(self):
        # tests that the query replaces the values in the command
        args = 'vm show -g "?[].group" -n "?[].name"'
        args = parse_quotes(args)
        args_no_quotes = []
        for arg in args:
            args_no_quotes.append(arg.strip("/'").strip('/"'))
        self.shell.last.result = [
            {
                'group': 'mygroup',
                'name': 'myname'
            },
            {
                'group': 'mygroup2',
                'name': 'myname2'
            },
            {
                'group': 'mygroup3',
                'name': 'myname3'
            }
        ]
        flag = self.shell.handle_jmespath_query(args, False)
        self.assertTrue(flag)
        results = self.stream.getvalue().strip().split('\n')
        self.assertTrue(len(results) == 3)
        self.assertEqual(results[0], 'vm show -g mygroup -n myname')
        self.assertEqual(results[1], 'vm show -g mygroup2 -n myname2')
        self.assertEqual(results[2], 'vm show -g mygroup3 -n myname3')

    def test_quotes(self):
        # tests that it parses correctly with quotes in the command
        self.shell.last.result = {'x': 'result'}
        # pylint: disable=protected-access
        b_flag, c_flag, out, cmd = self.shell._special_cases(
            "this is 'url?what' negative", "this is 'url?what' negative", False)
        self.assertFalse(b_flag)
        self.assertFalse(c_flag)
        self.assertFalse(out)
        self.assertEqual(cmd, "this is 'url?what' negative")

    def test_errors(self):
        # tests invalid query
        args = 'vm show -g "?[].group" -n "?[].name"'
        args = parse_quotes(args)
        args_no_quotes = []
        for arg in args:
            args_no_quotes.append(arg.strip("/'").strip('/"'))
        self.shell.last.result = [
            {
                'group': 'mygroup',
                'name': 'myname'
            },
            {
                'group': 'mygroup3',
            }
        ]
        flag = self.shell.handle_jmespath_query(args, False)
        results = self.stream.getvalue().split('\n')
        self.assertTrue(flag)
        self.assertEqual(results[0], 'vm show -g mygroup -n myname')
        self.assertEqual(len(results), 2)

    def test_singleton(self):
        # tests a singleton example
        args = 'vm show -g "?group" -n "?name"'
        args = parse_quotes(args)
        args_no_quotes = []
        for arg in args:
            args_no_quotes.append(arg.strip("/'").strip('/"'))
        self.shell.last.result = {
            'group': 'mygroup',
            'name': 'myname'
        }

        flag = self.shell.handle_jmespath_query(args, False)
        self.assertTrue(flag)
        results = self.stream.getvalue().split('\n')
        self.assertEqual(results[0], u'vm show -g mygroup -n myname')

    def test_spaces(self):
        # tests quotes with spaces
        args = 'vm show -g "?[?group == \'mygroup\'].name"'
        args = parse_quotes(args)
        args_no_quotes = []
        for arg in args:
            args_no_quotes.append(arg.strip("/'").strip('/"'))
        self.shell.last.result = [
            {
                'group': 'mygroup',
                'name': 'fred'
            },
            {
                'group': 'mygroup3',
                'name': 'myname3'
            }
        ]

        self.shell.handle_jmespath_query(args_no_quotes, False)
        results = self.stream.getvalue().split('\n')
        self.assertEqual(results[0], u'vm show -g fred')

    def test_spaces_with_equal(self):
        # tests quotes with spaces
        args = 'vm show -g="?[?group == \'myg roup\'].name"'
        args = parse_quotes(args)
        args_no_quotes = []
        for arg in args:
            args_no_quotes.append(arg.strip("/'").strip('/"'))
        self.shell.last.result = [
            {
                'group': 'myg roup',
                'name': 'fred'
            },
            {
                'group': 'mygroup3',
                'name': 'myname3'
            }
        ]

        self.shell.handle_jmespath_query(args_no_quotes, False)
        results = self.stream.getvalue().split('\n')
        self.assertEqual(results[0], u'vm show -g=fred')

    def test_validation(self):
        # tests line validation that the command is an injection
        args = 'foo bar --foo=?bar'
        self.assertTrue(self.validation_func(args.split(), '?'))

        args = 'foo bar --is fun -g ?bar '
        self.assertTrue(self.validation_func(args.split(), '?'))

        args = 'foo bar --is fun -g bar '
        self.assertFalse(self.validation_func(args.split(), '?'))

        args = 'foo bar --isfun=bar '
        self.assertFalse(self.validation_func(args.split(), '?'))

        args = 'foo bar --is ?[?group == \'word\'].name '
        self.assertTrue(self.validation_func(parse_quotes(args), '?'))

        args = 'foo bar --query [?group == \'word\'].name '
        self.assertFalse(self.validation_func(parse_quotes(args), '?'))

        args = 'foo bar --query=[?group == \'w or =?d\'].name '
        self.assertFalse(self.validation_func(parse_quotes(args), '?'))