<commit_before># Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import time
import datetime
import json
import logging
import tempfile

import mock
import unittest2

from st2client.shell import Shell
from st2client.client import Client
from st2client.utils import httpclient
from st2common.models.db.auth import TokenDB
from tests import base

LOG = logging.getLogger(__name__)

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
CONFIG_FILE_PATH_FULL = os.path.join(BASE_DIR, '../fixtures/st2rc.full.ini')
CONFIG_FILE_PATH_PARTIAL = os.path.join(BASE_DIR, '../fixtures/st2rc.partial.ini')

MOCK_CONFIG = """
[credentials]
username = foo
password = <PASSWORD>
"""


class TestShell(base.BaseCLITestCase):
    capture_output = True

    def __init__(self, *args, **kwargs):
        super(TestShell, self).__init__(*args, **kwargs)
        self.shell = Shell()

    def test_endpoints_default(self):
        base_url = 'http://127.0.0.1'
        auth_url = 'http://127.0.0.1:9100'
        api_url = 'http://127.0.0.1:9101/v1'
        stream_url = 'http://127.0.0.1:9102/v1'
        args = ['trigger', 'list']
        parsed_args = self.shell.parser.parse_args(args)
        client = self.shell.get_client(parsed_args)
        self.assertEqual(client.endpoints['base'], base_url)
        self.assertEqual(client.endpoints['auth'], auth_url)
        self.assertEqual(client.endpoints['api'], api_url)
        self.assertEqual(client.endpoints['stream'], stream_url)

    def test_endpoints_base_url_from_cli(self):
        base_url = 'http://www.st2.com'
        auth_url = 'http://www.st2.com:9100'
        api_url = 'http://www.st2.com:9101/v1'
        stream_url = 'http://www.st2.com:9102/v1'
        args = ['--url', base_url, 'trigger', 'list']
        parsed_args = self.shell.parser.parse_args(args)
        client = self.shell.get_client(parsed_args)
        self.assertEqual(client.endpoints['base'], base_url)
        self.assertEqual(client.endpoints['auth'], auth_url)
        self.assertEqual(client.endpoints['api'], api_url)
        self.assertEqual(client.endpoints['stream'], stream_url)

    def test_endpoints_base_url_from_env(self):
        base_url = 'http://www.st2.com'
        auth_url = 'http://www.st2.com:9100'
        api_url = 'http://www.st2.com:9101/v1'
        stream_url = 'http://www.st2.com:9102/v1'
        os.environ['ST2_BASE_URL'] = base_url
        args = ['trigger', 'list']
        parsed_args = self.shell.parser.parse_args(args)
        client = self.shell.get_client(parsed_args)
        self.assertEqual(client.endpoints['base'], base_url)
        self.assertEqual(client.endpoints['auth'], auth_url)
        self.assertEqual(client.endpoints['api'], api_url)
        self.assertEqual(client.endpoints['stream'], stream_url)

    def test_endpoints_override_from_cli(self):
        base_url = 'http://www.st2.com'
        auth_url = 'http://www.st2.com:8888'
        api_url = 'http://www.stackstorm1.com:9101/v1'
        stream_url = 'http://www.stackstorm1.com:9102/v1'
        args = ['--url', base_url,
                '--auth-url', auth_url,
                '--api-url', api_url,
                '--stream-url', stream_url,
                'trigger', 'list']
        parsed_args = self.shell.parser.parse_args(args)
        client = self.shell.get_client(parsed_args)
        self.assertEqual(client.endpoints['base'], base_url)
        self.assertEqual(client.endpoints['auth'], auth_url)
        self.assertEqual(client.endpoints['api'], api_url)
        self.assertEqual(client.endpoints['stream'], stream_url)

    def test_endpoints_override_from_env(self):
        base_url = 'http://www.st2.com'
        auth_url = 'http://www.st2.com:8888'
        api_url = 'http://www.stackstorm1.com:9101/v1'
        stream_url = 'http://www.stackstorm1.com:9102/v1'
        os.environ['ST2_BASE_URL'] = base_url
        os.environ['ST2_AUTH_URL'] = auth_url
        os.environ['ST2_API_URL'] = api_url
        os.environ['ST2_STREAM_URL'] = stream_url
        args = ['trigger', 'list']
        parsed_args = self.shell.parser.parse_args(args)
        client = self.shell.get_client(parsed_args)
        self.assertEqual(client.endpoints['base'], base_url)
        self.assertEqual(client.endpoints['auth'], auth_url)
        self.assertEqual(client.endpoints['api'], api_url)
        self.assertEqual(client.endpoints['stream'], stream_url)

    @mock.patch.object(
        httpclient.HTTPClient, 'get',
        mock.MagicMock(return_value=base.FakeResponse(json.dumps(base.RESOURCES), 200, 'OK')))
    def test_exit_code_on_success(self):
        argv = ['trigger', 'list']
        self.assertEqual(self.shell.run(argv), 0)

    @mock.patch.object(
        httpclient.HTTPClient, 'get',
        mock.MagicMock(return_value=base.FakeResponse(None, 500, 'INTERNAL SERVER ERROR')))
    def test_exit_code_on_error(self):
        argv = ['trigger', 'list']
        self.assertEqual(self.shell.run(argv), 1)

    def _validate_parser(self, args_list, is_subcommand=True):
        for args in args_list:
            ns = self.shell.parser.parse_args(args)
            func = (self.shell.commands[args[0]].run_and_print
                    if not is_subcommand
                    else self.shell.commands[args[0]].commands[args[1]].run_and_print)
            self.assertEqual(ns.func, func)

    def test_action(self):
        args_list = [
            ['action', 'list'],
            ['action', 'get', 'abc'],
            ['action', 'create', '/tmp/action.json'],
            ['action', 'update', '123', '/tmp/action.json'],
            ['action', 'delete', 'abc'],
            ['action', 'execute', '-h'],
            ['action', 'execute', 'remote', '-h'],
            ['action', 'execute', 'remote', 'hosts=192.168.1.1', 'user=st2', 'cmd="ls -l"'],
            ['action', 'execute', 'remote-fib', 'hosts=192.168.1.1', '3', '8']
        ]
        self._validate_parser(args_list)

    def test_action_execution(self):
        args_list = [
            ['execution', 'list'],
            ['execution', 'list', '-a', 'all'],
            ['execution', 'list', '--attr=all'],
            ['execution', 'get', '123'],
            ['execution', 'get', '123', '-d'],
            ['execution', 'get', '123', '-k', 'localhost.stdout'],
            ['execution', 're-run', '123'],
            ['execution', 're-run', '123', '--tasks', 'x', 'y', 'z'],
            ['execution', 're-run', '123', '--tasks', 'x', 'y', 'z', '--no-reset', 'x'],
            ['execution', 're-run', '123', 'a=1', 'b=x', 'c=True'],
            ['execution', 'cancel', '123'],
            ['execution', 'pause', '123'],
            ['execution', 'resume', '123']
        ]
        self._validate_parser(args_list)

        # Test mutually exclusive argument groups
        self.assertRaises(SystemExit, self._validate_parser,
                          [['execution', 'get', '123', '-d', '-k', 'localhost.stdout']])

    def test_key(self):
        args_list = [
            ['key', 'list'],
            ['key', 'get', 'abc'],
            ['key', 'set', 'abc', '123'],
            ['key', 'delete', 'abc'],
            ['key', 'load', '/tmp/keys.json']
        ]
        self._validate_parser(args_list)

    def test_policy(self):
        args_list = [
            ['policy', 'list'],
            ['policy', 'list', '-p', 'core'],
            ['policy', 'list', '--pack', 'core'],
            ['policy', 'list', '-r', 'core.local'],
            ['policy', 'list', '--resource-ref', 'core.local'],
            ['policy', 'list', '-pt', 'action.type1'],
            ['policy', 'list', '--policy-type', 'action.type1'],
            ['policy', 'list', '-r', 'core.local', '-pt', 'action.type1'],
            ['policy', 'list', '--resource-ref', 'core.local', '--policy-type', 'action.type1'],
            ['policy', 'get', 'abc'],
            ['policy', 'create', '/tmp/policy.json'],
            ['policy', 'update', '123', '/tmp/policy.json'],
            ['policy', 'delete', 'abc']
        ]
        self._validate_parser(args_list)

    def test_policy_type(self):
        args_list = [
            ['policy-type', 'list'],
            ['policy-type', 'list', '-r', 'action'],
            ['policy-type', 'list', '--resource-type', 'action'],
            ['policy-type', 'get', 'abc']
        ]
        self._validate_parser(args_list)

    @mock.patch('st2client.base.ST2_CONFIG_PATH', '/home/does/not/exist')
    def test_print_config_default_config_no_config(self):
        os.environ['ST2_CONFIG_FILE'] = '/home/does/not/exist'
        argv = ['--print-config']
        self.assertEqual(self.shell.run(argv), 3)

        self.stdout.seek(0)<commit_msg>Add pack cli shell unit test<commit_after># Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import time
import datetime
import json
import logging
import tempfile

import mock
import unittest2

from st2client.shell import Shell
from st2client.client import Client
from st2client.utils import httpclient
from st2common.models.db.auth import TokenDB
from tests import base

LOG = logging.getLogger(__name__)

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
CONFIG_FILE_PATH_FULL = os.path.join(BASE_DIR, '../fixtures/st2rc.full.ini')
CONFIG_FILE_PATH_PARTIAL = os.path.join(BASE_DIR, '../fixtures/st2rc.partial.ini')

MOCK_CONFIG = """
[credentials]
username = foo
password = <PASSWORD>
"""


class TestShell(base.BaseCLITestCase):
    capture_output = True

    def __init__(self, *args, **kwargs):
        super(TestShell, self).__init__(*args, **kwargs)
        self.shell = Shell()

    def test_endpoints_default(self):
        base_url = 'http://127.0.0.1'
        auth_url = 'http://1172.16.58.3:9100'
        api_url = 'http://127.0.0.1:9101/v1'
        stream_url = 'http://127.0.0.1:9102/v1'
        args = ['trigger', 'list']
        parsed_args = self.shell.parser.parse_args(args)
        client = self.shell.get_client(parsed_args)
        self.assertEqual(client.endpoints['base'], base_url)
        self.assertEqual(client.endpoints['auth'], auth_url)
        self.assertEqual(client.endpoints['api'], api_url)
        self.assertEqual(client.endpoints['stream'], stream_url)

    def test_endpoints_base_url_from_cli(self):
        base_url = 'http://www.st2.com'
        auth_url = 'http://www.st2.com:9100'
        api_url = 'http://www.st2.com:9101/v1'
        stream_url = 'http://www.st2.com:9102/v1'
        args = ['--url', base_url, 'trigger', 'list']
        parsed_args = self.shell.parser.parse_args(args)
        client = self.shell.get_client(parsed_args)
        self.assertEqual(client.endpoints['base'], base_url)
        self.assertEqual(client.endpoints['auth'], auth_url)
        self.assertEqual(client.endpoints['api'], api_url)
        self.assertEqual(client.endpoints['stream'], stream_url)

    def test_endpoints_base_url_from_env(self):
        base_url = 'http://www.st2.com'
        auth_url = 'http://www.st2.com:9100'
        api_url = 'http://www.st2.com:9101/v1'
        stream_url = 'http://www.st2.com:9102/v1'
        os.environ['ST2_BASE_URL'] = base_url
        args = ['trigger', 'list']
        parsed_args = self.shell.parser.parse_args(args)
        client = self.shell.get_client(parsed_args)
        self.assertEqual(client.endpoints['base'], base_url)
        self.assertEqual(client.endpoints['auth'], auth_url)
        self.assertEqual(client.endpoints['api'], api_url)
        self.assertEqual(client.endpoints['stream'], stream_url)

    def test_endpoints_override_from_cli(self):
        base_url = 'http://www.st2.com'
        auth_url = 'http://www.st2.com:8888'
        api_url = 'http://www.stackstorm1.com:9101/v1'
        stream_url = 'http://www.stackstorm1.com:9102/v1'
        args = ['--url', base_url,
                '--auth-url', auth_url,
                '--api-url', api_url,
                '--stream-url', stream_url,
                'trigger', 'list']
        parsed_args = self.shell.parser.parse_args(args)
        client = self.shell.get_client(parsed_args)
        self.assertEqual(client.endpoints['base'], base_url)
        self.assertEqual(client.endpoints['auth'], auth_url)
        self.assertEqual(client.endpoints['api'], api_url)
        self.assertEqual(client.endpoints['stream'], stream_url)

    def test_endpoints_override_from_env(self):
        base_url = 'http://www.st2.com'
        auth_url = 'http://www.st2.com:8888'
        api_url = 'http://www.stackstorm1.com:9101/v1'
        stream_url = 'http://www.stackstorm1.com:9102/v1'
        os.environ['ST2_BASE_URL'] = base_url
        os.environ['ST2_AUTH_URL'] = auth_url
        os.environ['ST2_API_URL'] = api_url
        os.environ['ST2_STREAM_URL'] = stream_url
        args = ['trigger', 'list']
        parsed_args = self.shell.parser.parse_args(args)
        client = self.shell.get_client(parsed_args)
        self.assertEqual(client.endpoints['base'], base_url)
        self.assertEqual(client.endpoints['auth'], auth_url)
        self.assertEqual(client.endpoints['api'], api_url)
        self.assertEqual(client.endpoints['stream'], stream_url)

    @mock.patch.object(
        httpclient.HTTPClient, 'get',
        mock.MagicMock(return_value=base.FakeResponse(json.dumps(base.RESOURCES), 200, 'OK')))
    def test_exit_code_on_success(self):
        argv = ['trigger', 'list']
        self.assertEqual(self.shell.run(argv), 0)

    @mock.patch.object(
        httpclient.HTTPClient, 'get',
        mock.MagicMock(return_value=base.FakeResponse(None, 500, 'INTERNAL SERVER ERROR')))
    def test_exit_code_on_error(self):
        argv = ['trigger', 'list']
        self.assertEqual(self.shell.run(argv), 1)

    def _validate_parser(self, args_list, is_subcommand=True):
        for args in args_list:
            ns = self.shell.parser.parse_args(args)
            func = (self.shell.commands[args[0]].run_and_print
                    if not is_subcommand
                    else self.shell.commands[args[0]].commands[args[1]].run_and_print)
            self.assertEqual(ns.func, func)

    def test_action(self):
        args_list = [
            ['action', 'list'],
            ['action', 'get', 'abc'],
            ['action', 'create', '/tmp/action.json'],
            ['action', 'update', '123', '/tmp/action.json'],
            ['action', 'delete', 'abc'],
            ['action', 'execute', '-h'],
            ['action', 'execute', 'remote', '-h'],
            ['action', 'execute', 'remote', 'hosts=192.168.1.1', 'user=st2', 'cmd="ls -l"'],
            ['action', 'execute', 'remote-fib', 'hosts=192.168.1.1', '3', '8']
        ]
        self._validate_parser(args_list)

    def test_action_execution(self):
        args_list = [
            ['execution', 'list'],
            ['execution', 'list', '-a', 'all'],
            ['execution', 'list', '--attr=all'],
            ['execution', 'get', '123'],
            ['execution', 'get', '123', '-d'],
            ['execution', 'get', '123', '-k', 'localhost.stdout'],
            ['execution', 're-run', '123'],
            ['execution', 're-run', '123', '--tasks', 'x', 'y', 'z'],
            ['execution', 're-run', '123', '--tasks', 'x', 'y', 'z', '--no-reset', 'x'],
            ['execution', 're-run', '123', 'a=1', 'b=x', 'c=True'],
            ['execution', 'cancel', '123'],
            ['execution', 'pause', '123'],
            ['execution', 'resume', '123']
        ]
        self._validate_parser(args_list)

        # Test mutually exclusive argument groups
        self.assertRaises(SystemExit, self._validate_parser,
                          [['execution', 'get', '123', '-d', '-k', 'localhost.stdout']])

    def test_key(self):
        args_list = [
            ['key', 'list'],
            ['key', 'get', 'abc'],
            ['key', 'set', 'abc', '123'],
            ['key', 'delete', 'abc'],
            ['key', 'load', '/tmp/keys.json']
        ]
        self._validate_parser(args_list)

    def test_policy(self):
        args_list = [
            ['policy', 'list'],
            ['policy', 'list', '-p', 'core'],
            ['policy', 'list', '--pack', 'core'],
            ['policy', 'list', '-r', 'core.local'],
            ['policy', 'list', '--resource-ref', 'core.local'],
            ['policy', 'list', '-pt', 'action.type1'],
            ['policy', 'list', '--policy-type', 'action.type1'],
            ['policy', 'list', '-r', 'core.local', '-pt', 'action.type1'],
            ['policy', 'list', '--resource-ref', 'core.local', '--policy-type', 'action.type1'],
            ['policy', 'get', 'abc'],
            ['policy', 'create', '/tmp/policy.json'],
            ['policy', 'update', '123', '/tmp/policy.json'],
            ['policy', 'delete', 'abc']
        ]
        self._validate_parser(args_list)

    def test_policy_type(self):
        args_list = [
            ['policy-type', 'list'],
            ['policy-type', 'list', '-r', 'action'],
            ['policy-type', 'list', '--resource-type', 'action'],
            ['policy-type', 'get', 'abc']
        ]
        self._validate_parser(args_list)

    def test_pack(self):
        args_list = [
            ['pack', 'list'],
            ['pack', 'get', 'abc'],
            ['pack', 'search', 'abc'],
            ['pack', 'show', 'abc'],
            ['pack', 'remove', 'abc'],
            ['pack', 'remove', 'abc', '--detail'],
            ['pack', 'install', 'abc'],
            ['pack', 'install', 'abc', '--force'],
            ['pack', 'install', 'abc', '--detail'],
            ['pack', 'config', 'abc']
        ]
        self._validate_parser(args_list)

    @mock.patch('st2client.base.ST2_CONFIG_PATH', '/home/does/not/exist')
    def test_print_config_default_config_no_config(self):
        os.environ['ST2_CONFIG_FILE'] = '/home/does/not/exist'
        argv = ['--print-config']
        self.assertEqual(self.shell.run(argv), 3)

        self.stdout.seek(0)
{'fraction_non_alphanumeric': 0.17223198594024605, 'fraction_numerical': 0.02165822392225783, 'mean_word_length': 2.6332394366197183, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 34, 'xml': 0}, 'pii_count': 12, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6868891', 'n_tokens_mistral': 6323, 'n_tokens_neox': 6088, 'n_words': 1204}