本文整理汇总了Python中st2client.shell.Shell类的典型用法代码示例。如果您正苦于以下问题:Python Shell类的具体用法?Python Shell怎么用?Python Shell使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Shell类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_failed_to_get_locale_encoding_warning_is_printed
def test_failed_to_get_locale_encoding_warning_is_printed(self, mock_logger):
shell = Shell()
shell.run(argv=['trigger', 'list'])
call_args = mock_logger.warn.call_args[0][0]
self.assertTrue('Locale unknown with encoding unknown which is not UTF-8 is used.' in
call_args)
示例2: test_get_cached_auth_token_no_token_cache_file
def test_get_cached_auth_token_no_token_cache_file(self):
client = Client()
shell = Shell()
username = 'testu'
password = 'testp'
result = shell._get_cached_auth_token(client=client, username=username,
password=password)
self.assertEqual(result, None)
示例3: test_automatic_auth_skipped_on_auth_command
def test_automatic_auth_skipped_on_auth_command(self):
self._write_mock_config()
shell = Shell()
shell._get_auth_token = mock.Mock()
argv = ['auth', 'testu', '-p', 'testp']
args = shell.parser.parse_args(args=argv)
shell.get_client(args=args)
self.assertEqual(shell._get_auth_token.call_count, 0)
示例4: test_automatic_auth_skipped_if_token_provided_as_env_variable
def test_automatic_auth_skipped_if_token_provided_as_env_variable(self):
self._write_mock_config()
shell = Shell()
shell._get_auth_token = mock.Mock()
os.environ['ST2_AUTH_TOKEN'] = 'fooo'
argv = ['action', 'list']
args = shell.parser.parse_args(args=argv)
shell.get_client(args=args)
self.assertEqual(shell._get_auth_token.call_count, 0)
示例5: test_get_version_package_metadata_file_exists_stable_version
def test_get_version_package_metadata_file_exists_stable_version(self):
# stable version, package metadata file exists on disk - no git revision should be included
package_metadata_path = self._write_mock_package_metadata_file()
st2client.shell.PACKAGE_METADATA_FILE_PATH = package_metadata_path
shell = Shell()
shell.run(argv=['--version'])
self.version_output.seek(0)
stderr = self.version_output.read()
self.assertTrue('v2.8.0, on Python' in stderr)
示例6: test_get_cached_auth_token_corrupted_token_cache_file
def test_get_cached_auth_token_corrupted_token_cache_file(self):
client = Client()
shell = Shell()
username = 'testu'
password = 'testp'
cached_token_path = shell._get_cached_token_path_for_user(username=username)
with open(cached_token_path, 'w') as fp:
fp.write('CORRRRRUPTED!')
expected_msg = 'File (.+) with cached token is corrupted or invalid'
self.assertRaisesRegexp(ValueError, expected_msg, shell._get_cached_auth_token,
client=client, username=username, password=password)
示例7: test_get_cached_auth_token_invalid_permissions
def test_get_cached_auth_token_invalid_permissions(self):
shell = Shell()
client = Client()
username = 'testu'
password = 'testp'
cached_token_path = shell._get_cached_token_path_for_user(username=username)
data = {
'token': 'yayvalid',
'expire_timestamp': (int(time.time()) + 20)
}
with open(cached_token_path, 'w') as fp:
fp.write(json.dumps(data))
# 1. Current user doesn't have read access to the config directory
os.chmod(self._mock_config_directory_path, 0000)
shell.LOG = mock.Mock()
result = shell._get_cached_auth_token(client=client, username=username,
password=password)
self.assertEqual(result, None)
self.assertEqual(shell.LOG.warn.call_count, 1)
log_message = shell.LOG.warn.call_args[0][0]
expected_msg = ('Unable to retrieve cached token from .*? read access to the parent '
'directory')
self.assertRegexpMatches(log_message, expected_msg)
# 2. Read access on the directory, but not on the cached token file
os.chmod(self._mock_config_directory_path, 0777) # nosec
os.chmod(cached_token_path, 0000)
shell.LOG = mock.Mock()
result = shell._get_cached_auth_token(client=client, username=username,
password=password)
self.assertEqual(result, None)
self.assertEqual(shell.LOG.warn.call_count, 1)
log_message = shell.LOG.warn.call_args[0][0]
expected_msg = ('Unable to retrieve cached token from .*? read access to this file')
self.assertRegexpMatches(log_message, expected_msg)
# 3. Other users also have read access to the file
os.chmod(self._mock_config_directory_path, 0777) # nosec
os.chmod(cached_token_path, 0444)
shell.LOG = mock.Mock()
result = shell._get_cached_auth_token(client=client, username=username,
password=password)
self.assertEqual(result, 'yayvalid')
self.assertEqual(shell.LOG.warn.call_count, 1)
log_message = shell.LOG.warn.call_args[0][0]
expected_msg = ('Permissions .*? for cached token file .*? are to permissive')
self.assertRegexpMatches(log_message, expected_msg)
示例8: test_help_command_line_arg_works_for_supported_commands
def test_help_command_line_arg_works_for_supported_commands(self):
shell = Shell()
for command in self.COMMANDS:
# First test longhang notation
argv = command + ['--help']
try:
result = shell.run(argv)
except SystemExit as e:
self.assertEqual(e.code, 0)
else:
self.assertEqual(result, 0)
stdout = self.stdout.getvalue()
self.assertTrue('usage:' in stdout)
self.assertTrue(' '.join(command) in stdout)
# self.assertTrue('positional arguments:' in stdout)
self.assertTrue('optional arguments:' in stdout)
# Reset stdout and stderr after each iteration
self._reset_output_streams()
# Then shorthand notation
argv = command + ['-h']
try:
result = shell.run(argv)
except SystemExit as e:
self.assertEqual(e.code, 0)
else:
self.assertEqual(result, 0)
stdout = self.stdout.getvalue()
self.assertTrue('usage:' in stdout)
self.assertTrue(' '.join(command) in stdout)
# self.assertTrue('positional arguments:' in stdout)
self.assertTrue('optional arguments:' in stdout)
# Verify that the actual help usage string was triggered and not the invalid
# "too few arguments" which would indicate command doesn't actually correctly handle
# --help flag
self.assertTrue('too few arguments' not in stdout)
self._reset_output_streams()
示例9: test_get_cached_auth_token_valid_token_in_cache_file
def test_get_cached_auth_token_valid_token_in_cache_file(self):
client = Client()
shell = Shell()
username = 'testu'
password = 'testp'
cached_token_path = shell._get_cached_token_path_for_user(username=username)
data = {
'token': 'yayvalid',
'expire_timestamp': (int(time.time()) + 20)
}
with open(cached_token_path, 'w') as fp:
fp.write(json.dumps(data))
result = shell._get_cached_auth_token(client=client, username=username,
password=password)
self.assertEqual(result, 'yayvalid')
示例10: test_cache_auth_token_success
def test_cache_auth_token_success(self):
client = Client()
shell = Shell()
username = 'testu'
password = 'testp'
expiry = datetime.datetime.utcnow() + datetime.timedelta(seconds=30)
result = shell._get_cached_auth_token(client=client, username=username,
password=password)
self.assertEqual(result, None)
token_db = TokenDB(user=username, token='fyeah', expiry=expiry)
shell._cache_auth_token(token_obj=token_db)
result = shell._get_cached_auth_token(client=client, username=username,
password=password)
self.assertEqual(result, 'fyeah')
示例11: test_cache_auth_token_invalid_permissions
def test_cache_auth_token_invalid_permissions(self):
shell = Shell()
username = 'testu'
cached_token_path = shell._get_cached_token_path_for_user(username=username)
expiry = datetime.datetime.utcnow() + datetime.timedelta(seconds=30)
token_db = TokenDB(user=username, token='fyeah', expiry=expiry)
cached_token_path = shell._get_cached_token_path_for_user(username=username)
data = {
'token': 'yayvalid',
'expire_timestamp': (int(time.time()) + 20)
}
with open(cached_token_path, 'w') as fp:
fp.write(json.dumps(data))
# 1. Current user has no write access to the parent directory
os.chmod(self._mock_config_directory_path, 0000)
shell.LOG = mock.Mock()
shell._cache_auth_token(token_obj=token_db)
self.assertEqual(shell.LOG.warn.call_count, 1)
log_message = shell.LOG.warn.call_args[0][0]
expected_msg = ('Unable to write token to .*? doesn\'t have write access to the parent '
'directory')
self.assertRegexpMatches(log_message, expected_msg)
# 2. Current user has no write access to the cached token file
os.chmod(self._mock_config_directory_path, 0777) # nosec
os.chmod(cached_token_path, 0000)
shell.LOG = mock.Mock()
shell._cache_auth_token(token_obj=token_db)
self.assertEqual(shell.LOG.warn.call_count, 1)
log_message = shell.LOG.warn.call_args[0][0]
expected_msg = ('Unable to write token to .*? doesn\'t have write access to this file')
self.assertRegexpMatches(log_message, expected_msg)
示例12: test_dont_warn_multiple_times
def test_dont_warn_multiple_times(self):
mock_temp_dir_path = tempfile.mkdtemp()
mock_config_dir_path = os.path.join(mock_temp_dir_path, 'testconfig')
mock_config_path = os.path.join(mock_config_dir_path, 'config')
# Make the temporary config directory
os.makedirs(mock_config_dir_path)
old_perms = os.stat(mock_config_dir_path).st_mode
new_perms = old_perms | 0o7
os.chmod(mock_config_dir_path, new_perms)
# Make the temporary config file
shutil.copyfile(CONFIG_FILE_PATH_FULL, mock_config_path)
os.chmod(mock_config_path, 0o777) # nosec
shell = Shell()
shell.LOG = mock.Mock()
# Test without token.
shell.run(['--config-file', mock_config_path, 'action', 'list'])
self.assertEqual(shell.LOG.warn.call_count, 2)
self.assertEqual(
shell.LOG.warn.call_args_list[0][0][0][:63],
'The StackStorm configuration directory permissions are insecure')
self.assertEqual(
shell.LOG.warn.call_args_list[1][0][0][:58],
'The StackStorm configuration file permissions are insecure')
self.assertEqual(shell.LOG.info.call_count, 2)
self.assertEqual(
shell.LOG.info.call_args_list[0][0][0], "The SGID bit is not "
"set on the StackStorm configuration directory.")
self.assertEqual(
shell.LOG.info.call_args_list[1][0][0], 'Skipping parsing CLI config')
示例13: test_automatic_auth_skipped_if_token_provided_as_cli_argument
def test_automatic_auth_skipped_if_token_provided_as_cli_argument(self):
self._write_mock_config()
shell = Shell()
shell._get_auth_token = mock.Mock()
argv = ['action', 'list', '--token=bar']
args = shell.parser.parse_args(args=argv)
shell.get_client(args=args)
self.assertEqual(shell._get_auth_token.call_count, 0)
argv = ['action', 'list', '-t', 'bar']
args = shell.parser.parse_args(args=argv)
shell.get_client(args=args)
self.assertEqual(shell._get_auth_token.call_count, 0)
示例14: ActionExecutionTailCommandTestCase
class ActionExecutionTailCommandTestCase(BaseCLITestCase):
capture_output = True
def __init__(self, *args, **kwargs):
super(ActionExecutionTailCommandTestCase, self).__init__(*args, **kwargs)
self.shell = Shell()
@mock.patch.object(
httpclient.HTTPClient, 'get',
mock.MagicMock(return_value=base.FakeResponse(json.dumps(MOCK_LIVEACTION_1_SUCCEEDED),
200, 'OK')))
def test_tail_simple_execution_already_finished_succeeded(self):
argv = ['execution', 'tail', 'idfoo1']
self.assertEqual(self.shell.run(argv), 0)
stdout = self.stdout.getvalue()
stderr = self.stderr.getvalue()
self.assertTrue('Execution idfoo1 has completed (status=succeeded)' in stdout)
self.assertEqual(stderr, '')
@mock.patch.object(
httpclient.HTTPClient, 'get',
mock.MagicMock(return_value=base.FakeResponse(json.dumps(MOCK_LIVEACTION_2_FAILED),
200, 'OK')))
def test_tail_simple_execution_already_finished_failed(self):
argv = ['execution', 'tail', 'idfoo2']
self.assertEqual(self.shell.run(argv), 0)
stdout = self.stdout.getvalue()
stderr = self.stderr.getvalue()
self.assertTrue('Execution idfoo2 has completed (status=failed)' in stdout)
self.assertEqual(stderr, '')
@mock.patch.object(
httpclient.HTTPClient, 'get',
mock.MagicMock(return_value=base.FakeResponse(json.dumps(MOCK_LIVEACTION_1_RUNNING),
200, 'OK')))
@mock.patch('st2client.client.StreamManager', autospec=True)
def test_tail_simple_execution_running_no_data_produced(self, mock_stream_manager):
argv = ['execution', 'tail', 'idfoo1']
MOCK_EVENTS = [
MOCK_LIVEACTION_1_SUCCEEDED
]
mock_cls = mock.Mock()
mock_cls.listen = mock.Mock()
mock_listen_generator = mock.Mock()
mock_listen_generator.return_value = MOCK_EVENTS
mock_cls.listen.side_effect = mock_listen_generator
mock_stream_manager.return_value = mock_cls
self.assertEqual(self.shell.run(argv), 0)
self.assertEqual(mock_listen_generator.call_count, 1)
stdout = self.stdout.getvalue()
stderr = self.stderr.getvalue()
expected_result = """
Execution idfoo1 has completed (status=succeeded).
"""
self.assertEqual(stdout, expected_result)
self.assertEqual(stderr, '')
@mock.patch.object(
httpclient.HTTPClient, 'get',
mock.MagicMock(return_value=base.FakeResponse(json.dumps(MOCK_LIVEACTION_3_RUNNING),
200, 'OK')))
@mock.patch('st2client.client.StreamManager', autospec=True)
def test_tail_simple_execution_running_with_data(self, mock_stream_manager):
argv = ['execution', 'tail', 'idfoo3']
MOCK_EVENTS = [
MOCK_LIVEACTION_3_RUNNING,
MOCK_OUTPUT_1,
MOCK_OUTPUT_2,
MOCK_LIVEACTION_3_SUCCEDED
]
mock_cls = mock.Mock()
mock_cls.listen = mock.Mock()
mock_listen_generator = mock.Mock()
mock_listen_generator.return_value = MOCK_EVENTS
mock_cls.listen.side_effect = mock_listen_generator
mock_stream_manager.return_value = mock_cls
self.assertEqual(self.shell.run(argv), 0)
self.assertEqual(mock_listen_generator.call_count, 1)
stdout = self.stdout.getvalue()
stderr = self.stderr.getvalue()
expected_result = """
Execution idfoo3 has started.
line 1
line 2
Execution idfoo3 has completed (status=succeeded).
""".lstrip()
#.........这里部分代码省略.........
示例15: ShellTestCase
class ShellTestCase(base.BaseCLITestCase):
capture_output = True
def __init__(self, *args, **kwargs):
super(ShellTestCase, self).__init__(*args, **kwargs)
self.shell = Shell()
def setUp(self):
super(ShellTestCase, self).setUp()
if six.PY3:
# In python --version outputs to stdout and in 2.x to stderr
self.version_output = self.stdout
else:
self.version_output = self.stderr
def test_commands_usage_and_help_strings(self):
# No command, should print out user friendly usage / help string
self.assertEqual(self.shell.run([]), 2)
self.stderr.seek(0)
stderr = self.stderr.read()
self.assertTrue('Usage: ' in stderr)
self.assertTrue('For example:' in stderr)
self.assertTrue('CLI for StackStorm' in stderr)
self.assertTrue('positional arguments:' in stderr)
self.stdout.truncate()
self.stderr.truncate()
# --help should result in the same output
try:
self.assertEqual(self.shell.run(['--help']), 0)
except SystemExit as e:
self.assertEqual(e.code, 0)
self.stdout.seek(0)
stdout = self.stdout.read()
self.assertTrue('Usage: ' in stdout)
self.assertTrue('For example:' in stdout)
self.assertTrue('CLI for StackStorm' in stdout)
self.assertTrue('positional arguments:' in stdout)
self.stdout.truncate()
self.stderr.truncate()
# Sub command with no args
try:
self.assertEqual(self.shell.run(['action']), 2)
except SystemExit as e:
self.assertEqual(e.code, 2)
self.stderr.seek(0)
stderr = self.stderr.read()
self.assertTrue('usage' in stderr)
if six.PY2:
self.assertTrue('{list,get,create,update' in stderr)
self.assertTrue('error: too few arguments' in stderr)
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)
#.........这里部分代码省略.........