desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'No directory operation. Local source name given. S3
full key given.'
| def test_s3_keep_dest_name(self):
| src = 'fileformat_test.py'
dest = 's3://kyknapp/golfVid/file.py'
parameters = {'dir_op': False}
files = self.file_format.format(src, dest, parameters)
ref_files = {'src': {'path': os.path.abspath(src), 'type': 'local'}, 'dest': {'path': 'kyknapp/golfVid/file.py', 'type': 's3'}, 'dir_op': False, 'use... |
'Ensures that the table for the service was created properly.
Also ensures the original s3 service is renamed to ``s3api``.'
| def test_s3(self):
| s3_service = Mock()
s3_service.name = 's3'
self.services = {'s3': s3_service}
add_s3(self.services, True)
orig_service = self.services.pop('s3api')
self.assertEqual(orig_service, s3_service)
for service in self.services.keys():
self.assertIn(service, ['s3'])
|
'Creates a link in a digest chain for testing.'
| @staticmethod
def create_link(key, next_key, next_bucket, position, action, logs, bucket):
| digest_logs = []
if (len(logs) > position):
digest_logs = logs[position]
end_date = parse_date(extract_digest_key_date(key))
if (action == 'gap'):
digest = MockDigestProvider.create_digest(key=key, bucket=bucket, fingerprint=str(position), start_date=end_date, logs=digest_logs)
else:... |
'Tests that deploy method is invoked when command is run'
| @patch('awscli.customizations.cloudformation.deploy.yaml_parse')
def test_command_invoked(self, mock_yaml_parse):
| fake_parameter_overrides = []
fake_parameters = 'some return value'
template_str = 'some template'
with tempfile.NamedTemporaryFile() as handle:
file_path = handle.name
open_mock = mock.mock_open()
with patch('awscli.customizations.cloudformation.deploy.open', open_mock(... |
'Tests that we call the deploy command'
| def test_deploy_success(self):
| stack_name = 'stack_name'
changeset_id = 'some changeset'
parameters = ['a', 'b']
template = 'cloudformation template'
capabilities = ['foo', 'bar']
execute_changeset = True
changeset_type = 'CREATE'
self.deployer.create_and_wait_for_changeset.return_value = ChangeSetResult(changes... |
'Tests that we can parse parameter arguments provided in proper format
Expected format: ["Key=Value", "Key=Value"]
:return:'
| def test_parse_parameter_arg_success(self):
| data = ['Key1=Value1', 'Key2=[1,2,3]', 'Key3={"a":"val", "b": 2}']
output = {'Key1': 'Value1', 'Key2': '[1,2,3]', 'Key3': '{"a":"val", "b": 2}'}
result = self.deploy_command.parse_parameter_arg(data)
self.assertEqual(result, output)
result = self.deploy_command.parse_parameter_arg([])
... |
'Tests that we can merge parameters specified in CloudFormation template
with override values specified as commandline arguments'
| def test_merge_parameters_success(self):
| template = {'Parameters': {'Key1': {'Type': 'String'}, 'Key2': {'Type': 'String'}, 'Key3': 'Something', 'Key4': {'Type': 'Number'}, 'KeyWithDefaultValue': {'Type': 'String', 'Default': 'something'}, 'KeyWithDefaultValueButOverridden': {'Type': 'String', 'Default': 'something'}}}
overrides = {'Key1': 'Value1', '... |
'Tests that we can merge parameters specified in CloudFormation template
with override values specified as commandline arguments'
| def test_merge_parameters_success_nothing_to_override(self):
| template = {'Parameters': {'Key1': {'Type': 'String'}, 'Key2': {'Type': 'String'}, 'Key3': 'Something', 'Key4': {'Type': 'Number'}}}
overrides = {'Key5': 'Value5'}
expected_result = [{'ParameterKey': 'Key1', 'UsePreviousValue': True}, {'ParameterKey': 'Key2', 'UsePreviousValue': True}, {'ParameterKey': 'Key... |
'Checks if we properly export from the Resource classc
:return:'
| @patch('awscli.customizations.cloudformation.artifact_exporter.upload_local_artifacts')
def test_resource_with_s3_url_dict(self, upload_local_artifacts_mock):
| self.assertTrue(issubclass(ResourceWithS3UrlDict, Resource))
class MockResource(ResourceWithS3UrlDict, ):
PROPERTY_NAME = 'foo'
BUCKET_NAME_PROPERTY = 'b'
OBJECT_KEY_PROPERTY = 'o'
VERSION_PROPERTY = 'v'
resource = MockResource(self.s3_uploader_mock)
resource_id = 'id'
... |
'When the output of the aws command is being piped,
the `encoding` attribute of `sys.stdout` is `None`.'
| def test_encoding_with_encoding_none(self):
| out = MockPipedStdout()
utils.uni_print(u'SomeChars\u2713\u2714OtherChars', out)
self.assertEqual(out.getvalue(), 'SomeChars??OtherChars')
|
'Should create clients without additional parameters by default.'
| def test_create_clients_simple(self):
| self.register._create_clients(self._build_args(), argparse.Namespace())
self.mock_session.create_client.assert_has_calls([mock.call('iam'), mock.call('opsworks')])
|
'Should pass region names to OpsWorks, but not to IAM clients.'
| def test_create_clients_with_region(self):
| self.register._create_clients(self._build_args(), argparse.Namespace(region='mars-east-1'))
self.mock_session.create_client.assert_has_calls([mock.call('iam'), mock.call('opsworks', region_name='mars-east-1')])
|
'Should pass endpoints to OpsWorks, but not to IAM clients.'
| def test_create_clients_with_opsworks_endpoint_url(self):
| self.register._create_clients(self._build_args(), argparse.Namespace(endpoint_url='http://xxx/'))
self.mock_session.create_client.assert_has_calls([mock.call('iam'), mock.call('opsworks', endpoint_url='http://xxx/')])
|
'Should pass verify-ssl to OpsWorks, but not to IAM clients.'
| def test_create_clients_with_verify_ssl(self):
| self.register._create_clients(self._build_args(), argparse.Namespace(verify_ssl=False))
self.mock_session.create_client.assert_has_calls([mock.call('iam'), mock.call('opsworks', verify=False)])
self.register._create_clients(self._build_args(), argparse.Namespace(verify_ssl='/path/to/ca'))
self.mock_sess... |
'Should only accept valid hostnames.'
| @mock.patch.object(opsworks, 'platform')
def test_prevalidate_arguments_invalid_hostnames(self, mock_platform):
| mock_platform.system.return_value = 'Linux'
self.register.prevalidate_arguments(self._build_args(infrastructure_class='on-premises', hostname=None, local=True))
self.register.prevalidate_arguments(self._build_args(infrastructure_class='on-premises', hostname='good-hostname', local=True))
self.register.p... |
'Shouldn\'t allow local and remote mode at the same time.'
| @mock.patch.object(opsworks, 'platform')
def test_prevalidate_arguments_local_vs_remote(self, mock_platform):
| mock_platform.system.return_value = 'Linux'
with self.assertRaises(ValueError):
self.register.prevalidate_arguments(self._build_args(infrastructure_class='on-premises', hostname=None, target=None, local=False))
with self.assertRaises(ValueError):
self.register.prevalidate_arguments(self._bui... |
'Shouldn\'t allow local and remote mode at the same time.'
| @mock.patch.object(opsworks, 'platform')
def test_prevalidate_arguments_local_linux_only(self, mock_platform):
| mock_platform.system.return_value = 'Linux'
self.register.prevalidate_arguments(self._build_args(infrastructure_class='on-premises', target=None, local=True))
with self.assertRaises(ValueError):
mock_platform.system.return_value = 'Windows'
self.register.prevalidate_arguments(self._build_arg... |
'Should not allow --override-ssh and other SSH options.'
| def test_prevalidate_arguments_ssh_override(self):
| self.register.prevalidate_arguments(self._build_args(ssh='telnet', infrastructure_class='ec2', target='i-12345678'))
self.register.prevalidate_arguments(self._build_args(username='root', private_key='id_rsa', infrastructure_class='ec2', target='1.2.3.4'))
with self.assertRaises(ValueError):
self.reg... |
'Basic IAM side-effects.
Should create a group with a user, and an access key.'
| def test_create_iam_entities_simple(self):
| with mock.patch.object(self.register, 'iam', create=True) as mock_iam:
self.register._stack = dict(StackId='STACKID', Name='STACKNAME', Arn='ARN')
self.register._name_for_iam = 'HOSTNAME'
self.register.create_iam_entities(self._build_args())
mock_iam.create_group.assert_any_call(Path... |
'Should reuse an existing group.'
| def test_create_iam_entities_group_exists(self):
| with mock.patch.object(self.register, 'iam', create=True) as mock_iam:
self.register._stack = dict(StackId='STACKID', Name='STACKNAME', Arn='ARN')
self.register._name_for_iam = 'HOSTNAME'
mock_iam.create_group.side_effect = ClientError({'Error': {'Code': 'EntityAlreadyExists', 'Message': ''}... |
'Should use an alternate username if the preferred one is taken.'
| def test_create_iam_entities_user_exists(self):
| with mock.patch.object(self.register, 'iam', create=True) as mock_iam:
self.register._stack = dict(StackId='STACKID', Name='STACKNAME', Arn='ARN')
self.register._name_for_iam = 'HOSTNAME'
mock_iam.create_user = mock.Mock(side_effect=[ClientError({'Error': {'Code': 'EntityAlreadyExists', 'Mes... |
'Should shorten IAM entity names to a valid size.'
| def test_create_iam_entities_long_names(self):
| long_hostname = 'hostname1.very-long-domain-name.within.company.tld'
shortened_username = 'OpsWorks-long-stack-...ork-as-well-hostname1.v...company.tld'
with mock.patch.object(self.register, 'iam', create=True) as mock_iam:
self.register._stack = dict(StackId='STACKID', Name='long stack names ... |
'Should not create IAM entities when using instance profiles.'
| def test_create_no_iam_entities(self):
| with mock.patch.object(self.register, 'iam', create=True) as mock_iam:
self.register.create_iam_entities(self._build_args(use_instance_profile=True))
self.assertFalse(mock_iam.create_group.called)
self.assertFalse(mock_iam.create_user.called)
self.assertFalse(mock_iam.add_user_to_gro... |
'Should detect duplicate host names in the stack early.'
| def test_validate_unique_hostname(self):
| self.register._stack = {'StackId': 'STACKID'}
with mock.patch.object(self.register, 'opsworks', create=True) as mock_opsworks:
mock_opsworks.describe_instances.return_value = {'Instances': [dict(Hostname='duplicated-hostname')]}
self.register.validate_arguments(mock.Mock(hostname='good-hostname'... |
'Should use plink on Windows correctly.'
| @mock.patch.object(opsworks, 'tempfile')
@mock.patch.object(opsworks, 'platform')
@mock.patch.object(opsworks, 'subprocess')
@mock.patch.object(opsworks, 'os')
def test_ssh_windows(self, mock_os, mock_subprocess, mock_platform, mock_tempfile):
| mock_platform.system.return_value = 'Windows'
self.register._use_address = 'ip'
mock_file = mock.Mock()
mock_tempfile.NamedTemporaryFile.return_value = mock_file
mock_file.name = 'tmpfilename'
self.register.ssh(self._build_args(), 'script')
mock_subprocess.check_call.assert_called_with('plin... |
'Should use ssh on non-windows correctly.'
| @mock.patch.object(opsworks, 'platform')
@mock.patch.object(opsworks, 'subprocess')
def test_ssh_nix(self, mock_subprocess, mock_platform):
| mock_platform.system.return_value = 'Linux'
self.register._use_address = 'ip'
self.register.ssh(self._build_args(), 'script')
mock_subprocess.check_call.assert_called_with(['ssh', '-tt', 'ip', '/bin/sh -c script'])
self.register.ssh(self._build_args(username='foo'), 'script')
mock_subproce... |
'Should setup a remote machine from a non-Windows host correctly.'
| @mock.patch.object(opsworks, 'platform')
@mock.patch.object(opsworks, 'subprocess')
def test_setup_target_machine_remote_nix(self, mock_subprocess, mock_platform):
| mock_platform.system.return_value = 'Linux'
args = self._build_args(infrastructure_class='ec2', hostname='HOSTNAME', local=False)
self.register._stack = {'StackId': 'STACKID'}
self.register._prov_params = {'AgentInstallerUrl': 'URL', 'Parameters': {'assets_download_bucket': 'xxx'}}
self.register.acc... |
'Should setup a remote machine from a Windows host correctly.'
| @mock.patch.object(opsworks, 'platform')
@mock.patch.object(opsworks, 'subprocess')
def test_setup_target_machine_remote_windows(self, mock_subprocess, mock_platform):
| mock_platform.system.return_value = 'Windows'
args = self._build_args(infrastructure_class='ec2', hostname='HOSTNAME', local=False)
self.register._stack = {'StackId': 'STACKID'}
self.register._prov_params = {'AgentInstallerUrl': 'URL', 'Parameters': {'assets_download_bucket': 'xxx'}}
self.register.a... |
'Should setup the local machine correctly.'
| @mock.patch.object(opsworks, 'subprocess')
def test_setup_target_machine_local(self, mock_subprocess):
| args = self._build_args(infrastructure_class='ec2', local=True)
self.register._stack = {'StackId': 'STACKID'}
self.register._prov_params = {'AgentInstallerUrl': 'URL', 'Parameters': {'assets_download_bucket': 'xxx'}}
self.register.access_key = {'AccessKeyId': 'AKIAXXX', 'SecretAccessKey': 'foobarbaz'}
... |
'Should produce a simple preconfiguration file.'
| def test_pre_config_document_simple(self):
| self.register._stack = {'StackId': 'Foo'}
self.register._prov_params = {'Parameters': {'foo': 'Bar', 'bar': 'Baz'}}
self.register.access_key = None
self.register._use_hostname = None
pre_config = self.register._pre_config_document(mock.Mock(private_ip=None, public_ip=None))
self.assertEqual(pre_... |
'Should produce a complex preconfiguration file.'
| def test_pre_config_document_full(self):
| self.register._stack = {'StackId': 'Foo'}
self.register._prov_params = {'Parameters': {'foo': 'Bar', 'bar': 'Baz'}}
self.register.access_key = {'AccessKeyId': 'Bar', 'SecretAccessKey': 'Baz'}
self.register._use_hostname = 'HOSTNAME'
pre_config = self.register._pre_config_document(mock.Mock(private_i... |
'Flow test w/ all the expected side-effects for a remote instance.'
| @mock.patch.object(opsworks, 'subprocess')
def test_run_main_remote(self, mock_subprocess):
| args = self._build_args(stack_id='STACKID', target='i-12345678', local=False)
parsed_globals = argparse.Namespace()
mock_ec2 = mock.Mock()
mock_iam = mock.Mock()
mock_opsworks = mock.Mock()
self.mock_session.create_client.side_effect = (lambda name, **_: dict(ec2=mock_ec2, iam=mock_iam, opsworks... |
'Flow test w/ all the expected side-effects for a local instance.'
| @mock.patch.object(opsworks, 'urlopen')
@mock.patch.object(opsworks, 'subprocess')
@mock.patch.object(opsworks, 'socket')
@mock.patch.object(opsworks, 'platform')
def test_run_main_local(self, mock_platform, mock_socket, mock_subprocess, mock_urlopen):
| args = self._build_args(stack_id='STACKID', target=None, local=True)
parsed_globals = argparse.Namespace()
mock_ec2 = mock.Mock()
mock_iam = mock.Mock()
mock_opsworks = mock.Mock()
mock_platform.system.return_value = 'Linux'
self.mock_session.create_client.side_effect = (lambda name, **_: di... |
'Shouldn\'t allow overriding IP addresses for EC2.'
| def test_prevalidate_arguments_no_ips_for_ec2(self):
| with self.assertRaises(ValueError):
self.register.prevalidate_arguments(self._build_args(target='target', private_ip='private-ip'))
with self.assertRaises(ValueError):
self.register.prevalidate_arguments(self._build_args(target='target', public_ip='public-ip'))
|
'Should ensure that the local instance is in the correct region.'
| @mock.patch.object(opsworks, 'urlopen')
def test_validate_same_region(self, mock_urlopen):
| self.register._stack = {'Region': 'mars-east-1'}
mock_urlopen.return_value.read.return_value = '{"region": "mars-east-1"}'
self.register.validate_arguments(self._build_args(hostname=None, local=True))
with self.assertRaises(ValueError):
mock_urlopen.return_value.read.return_value = '{"region"... |
'Check that register can handle bytes returned by urlopen.read'
| @mock.patch.object(opsworks, 'urlopen')
def test_validate_same_region_bytes(self, mock_urlopen):
| self.register._stack = {'Region': 'mars-east-1'}
mock_urlopen.return_value.read.return_value = '{"region": "mars-east-1"}'
try:
self.register.validate_arguments(self._build_args(hostname=None, local=True))
except Exception as e:
self.fail(('Register should work with bytes ... |
'Should retrieve an EC2 stack and the matching instance.'
| def test_retrieve_stack_ec2(self):
| with mock.patch.object(self.register, 'opsworks', create=True) as mock_opsworks:
mock_ec2 = mock.Mock()
self.mock_session.create_client.return_value = mock_ec2
mock_opsworks.describe_stacks.return_value = {'Stacks': [{'StackId': 'STACKID', 'Region': 'mars-east-1'}]}
mock_ec2.describe... |
'Should retrieve an VPC stack and the matching instance.'
| def test_retrieve_stack_vpc(self):
| with mock.patch.object(self.register, 'opsworks', create=True) as mock_opsworks:
mock_ec2 = mock.Mock()
self.mock_session.create_client.return_value = mock_ec2
mock_opsworks.describe_stacks.return_value = {'Stacks': [{'StackId': 'STACKID', 'Region': 'mars-east-1', 'VpcId': 'vpc-123456'}]}
... |
'Should find an EC2 instance by instance ID.'
| def test_retrieve_stack_ec2_instance_id(self):
| with mock.patch.object(self.register, 'opsworks', create=True) as mock_opsworks:
mock_ec2 = mock.Mock()
self.mock_session.create_client.return_value = mock_ec2
mock_opsworks.describe_stacks.return_value = {'Stacks': [{'StackId': 'STACKID', 'Region': 'mars-east-1'}]}
mock_ec2.describe... |
'Should find an EC2 instance by IP address.'
| def test_retrieve_stack_target_ip_address(self):
| with mock.patch.object(self.register, 'opsworks', create=True) as mock_opsworks:
mock_ec2 = mock.Mock()
self.mock_session.create_client.return_value = mock_ec2
mock_opsworks.describe_stacks.return_value = {'Stacks': [{'StackId': 'STACKID', 'Region': 'mars-east-1'}]}
mock_ec2.describe... |
'Should find an EC2 instance by name.'
| def test_retrieve_stack_target_name(self):
| with mock.patch.object(self.register, 'opsworks', create=True) as mock_opsworks:
mock_ec2 = mock.Mock()
self.mock_session.create_client.return_value = mock_ec2
mock_opsworks.describe_stacks.return_value = {'Stacks': [{'StackId': 'STACKID', 'Region': 'mars-east-1'}]}
mock_ec2.describe... |
'Should complain if it cannot find matching instances.'
| def test_retrieve_stack_target_none(self):
| with mock.patch.object(self.register, 'opsworks', create=True) as mock_opsworks:
mock_ec2 = mock.Mock()
self.mock_session.create_client.return_value = mock_ec2
mock_opsworks.describe_stacks.return_value = {'Stacks': [{'StackId': 'STACKID', 'Region': 'mars-east-1'}]}
mock_ec2.describe... |
'Should complain if it finds too many matching instances.'
| def test_retrieve_stack_target_too_many(self):
| with mock.patch.object(self.register, 'opsworks', create=True) as mock_opsworks:
mock_ec2 = mock.Mock()
self.mock_session.create_client.return_value = mock_ec2
mock_opsworks.describe_stacks.return_value = {'Stacks': [{'StackId': 'STACKID', 'Region': 'mars-east-1'}]}
mock_ec2.describe... |
'Should determine names and address for a basic EC2 instance.'
| def test_determine_details_simple(self):
| self.register._ec2_instance = {'PublicIpAddress': '192.0.2.42'}
self.register._use_address = None
self.register.determine_details(self._build_args(target='i-12345678'))
self.assertEqual(self.register._use_address, '192.0.2.42')
self.assertEqual(self.register._use_hostname, None)
self.assertEqual... |
'Should determine names and address with a hostname override.'
| def test_determine_details_with_hostname(self):
| self.register._ec2_instance = {'PublicIpAddress': '192.0.2.42'}
self.register._use_address = None
self.register.determine_details(self._build_args(infrastructure_class='ec2', hostname='prettyhostname'))
self.assertEqual(self.register._use_address, '192.0.2.42')
self.assertEqual(self.register._use_ho... |
'Should determine names and address for a EC2 instance without a
public IP address.'
| def test_determine_details_private_ip_only(self):
| self.register._ec2_instance = {'PrivateIpAddress': '192.0.2.42'}
self.register._use_address = None
self.register.determine_details(self._build_args(target='i-12345678'))
self.assertEqual(self.register._use_address, '192.0.2.42')
self.assertEqual(self.register._use_hostname, None)
self.assertEqua... |
'Should determine names and address for the local EC2 instance.'
| @mock.patch.object(opsworks, 'socket')
def test_determine_details_local_simple(self, mock_socket):
| mock_socket.gethostname.return_value = 'HOSTNAME'
self.register._use_address = None
self.register.determine_details(self._build_args(hostname=None, local=True))
self.assertEqual(self.register._use_address, None)
self.assertEqual(self.register._use_hostname, None)
self.assertEqual(self.register._... |
'Should determine names and address for the local EC2 instance with
a hostname override.'
| def test_determine_details_local_with_hostname(self):
| self.register._use_address = None
self.register.determine_details(self._build_args(hostname='prettyhostname', local=True))
self.assertEqual(self.register._use_address, None)
self.assertEqual(self.register._use_hostname, 'prettyhostname')
self.assertEqual(self.register._name_for_iam, 'prettyhostname'... |
'Should use a given address.'
| def test_determine_details_given_address(self):
| self.register._use_address = '192.0.2.42'
self.register.determine_details(self._build_args(target='192.0.2.42'))
self.assertEqual(self.register._use_address, '192.0.2.42')
self.assertEqual(self.register._use_hostname, None)
self.assertEqual(self.register._name_for_iam, '192.0.2.42')
|
'Flow test w/ all the expected side-effects for a remote instance.'
| @mock.patch.object(opsworks, 'subprocess')
def test_run_main(self, mock_subprocess):
| args = self._build_args(stack_id='STACKID', target='HOSTNAME', local=False, ssh=None, hostname=None, private_ip=None, public_ip=None)
parsed_globals = argparse.Namespace()
mock_ec2 = mock.Mock()
mock_iam = mock.Mock()
mock_opsworks = mock.Mock()
self.mock_session.create_client.side_effect = (lam... |
'Shouldn\'t allow using an instance profile on-premises.'
| def test_prevalidate_arguments_no_instance_profile(self):
| with self.assertRaises(ValueError):
self.register.prevalidate_arguments(self._build_args(target='target', use_instance_profile=True))
|
'Should determine names and address for a basic instance.'
| def test_determine_details_simple(self):
| self.register._use_address = None
self.register.determine_details(self._build_args(infrastructure_class='on-premises', target='HOSTNAME', hostname=None, local=False))
self.assertEqual(self.register._use_address, 'HOSTNAME')
self.assertEqual(self.register._use_hostname, None)
self.assertEqual(self.re... |
'Should determine names and address with a hostname override.'
| def test_determine_details_with_hostname(self):
| self.register._use_address = None
self.register.determine_details(self._build_args(infrastructure_class='on-premises', target='HOSTNAME', hostname='prettyhostname', local=False))
self.assertEqual(self.register._use_address, 'HOSTNAME')
self.assertEqual(self.register._use_hostname, 'prettyhostname')
... |
'Should determine names and address for the local instance.'
| @mock.patch.object(opsworks, 'socket')
def test_determine_details_local_simple(self, mock_socket):
| mock_socket.gethostname.return_value = 'HOSTNAME'
self.register._use_address = None
self.register.determine_details(self._build_args(infrastructure_class='on-premises', hostname=None, local=True))
self.assertEqual(self.register._use_address, None)
self.assertEqual(self.register._use_hostname, None)
... |
'Should determine names and address for the local instance with a
hostname override.'
| def test_determine_details_local_with_hostname(self):
| self.register._use_address = None
self.register.determine_details(self._build_args(infrastructure_class='on-premises', hostname='prettyhostname', local=True))
self.assertEqual(self.register._use_address, None)
self.assertEqual(self.register._use_hostname, 'prettyhostname')
self.assertEqual(self.regi... |
'Should sanitize strings for IAM.'
| def test_clean_for_iam(self):
| self.assertEqual(opsworks.clean_for_iam('foobar'), 'foobar')
self.assertEqual(opsworks.clean_for_iam('foo bar 123'), 'foo-bar-123')
self.assertEqual(opsworks.clean_for_iam('baz&@%#^*$bar'), 'baz-@-bar')
|
'Should shorten strings by introducing ellipses.'
| def test_shorten_name(self):
| self.assertEqual(opsworks.shorten_name('1234', 5), '1234')
self.assertEqual(opsworks.shorten_name('12345', 5), '12345')
self.assertEqual(opsworks.shorten_name('123456789', 5), '1...9')
self.assertEqual(opsworks.shorten_name('123456789', 6), '12...9')
self.assertEqual(opsworks.shorten_name('123456789... |
'Create a topic source file from a list of tags and topic name'
| def create_topic_src_file(self, topic_name, tags):
| content = '\n'.join(tags)
topic_name = (topic_name + '.rst')
topic_filepath = self.file_creator.create_file(topic_name, content)
return topic_filepath
|
'Asserts the scanned tags by checking the saved JSON index'
| def assert_json_index(self, file_paths, reference_tag_dict):
| json_index = self.file_creator.create_file('index.json', '')
self.topic_tag_db = TopicTagDB(index_file=json_index)
self.topic_tag_db.scan(file_paths)
self.topic_tag_db.save_to_json_index()
with open(json_index, 'r') as f:
saved_index = json.loads(f.read())
self.assertEqual(saved_inde... |
'Override docutils default table formatter to not include a border
and to use Bootstrap CSS
See: http://sourceforge.net/p/docutils/code/HEAD/tree/trunk/docutils/docutils/writers/html4css1/__init__.py#l1550'
| def visit_table(self, node, name=''):
| self.context.append(self.compact_p)
self.compact_p = True
classes = ' '.join(['table', 'table-bordered', self.settings.table_style]).strip()
self.body.append(self.starttag(node, 'table', CLASS=classes))
|
'This needs overridin\' too'
| def depart_table(self, node):
| self.compact_p = self.context.pop()
self.body.append('</table>\n')
|
':type cli_name: string
:param cli_name: The complete cli argument name,
e.g. "--foo-bar". It should include the leading
hyphens if that\'s how a user would specify the name.
:type message: string
:param message: The error message to display to the user.'
| def __init__(self, cli_name, message):
| full_message = ("Error parsing parameter '%s': %s" % (cli_name, message))
super(ParamError, self).__init__(full_message)
self.cli_name = cli_name
self.message = message
|
'Determines whether a given operation for a service needs to use the
deprecated shorthand parsing case for lists of structures that only have
a single member.'
| def _uses_old_list_case(self, service_name, operation_name, argument_name):
| cases = {'firehose': {'put-record-batch': ['records']}, 'workspaces': {'reboot-workspaces': ['reboot-workspace-requests'], 'rebuild-workspaces': ['rebuild-workspace-requests'], 'terminate-workspaces': ['terminate-workspace-requests']}, 'elb': {'remove-tags': ['tags'], 'describe-instance-health': ['instances'], 'der... |
'Attempt to parse shorthand syntax for values.
This is intended to be hooked up as an event handler (hence the
**kwargs). Given ``param`` object and its string ``value``,
figure out if we can parse it. If we can parse it, we return
the parsed value (typically some sort of python dict).
:type cli_argument: :class:`aws... | def __call__(self, cli_argument, value, event_name, **kwargs):
| if (not self._should_parse_as_shorthand(cli_argument, value)):
return
else:
(service_name, operation_name) = find_service_and_method_in_event_name(event_name)
return self._parse_as_shorthand(cli_argument, value, service_name, operation_name)
|
'Checks if a CLI argument supports shorthand syntax.'
| def supports_shorthand(self, argument_model):
| if (argument_model is not None):
return _is_complex_shape(argument_model)
return False
|
'Generate documentation for a CLI argument.
:type cli_argument: awscli.arguments.BaseCLIArgument
:param cli_argument: The CLI argument which to generate
documentation for.
:return: Returns either a string or ``None``. If a string
is returned, it is the generated shorthand example.
If a value of ``None`` is returned th... | def generate_shorthand_example(self, cli_argument, service_name, operation_name):
| docstring = self._handle_special_cases(cli_argument, service_name, operation_name)
if (docstring is self._DONT_DOC):
return None
elif docstring:
return docstring
stack = []
try:
if (cli_argument.argument_model.type_name == 'list'):
argument_model = cli_argument.ar... |
'The default register iterates through all of the
available document events and looks for a corresponding
handler method defined in the object. If it\'s there, that
handler method will be registered for the all events of
that type for the specified ``event_class``.'
| def register(self, session, event_class):
| self._map_handlers(session, event_class, session.register)
|
'The default unregister iterates through all of the
available document events and looks for a corresponding
handler method defined in the object. If it\'s there, that
handler method will be unregistered for the all events of
that type for the specified ``event_class``.'
| def unregister(self):
| self._map_handlers(self.help_command.session, self.help_command.event_class, self.help_command.session.unregister)
|
'Documents top-level parameter enums'
| def _document_enums(self, argument, doc):
| if hasattr(argument, 'argument_model'):
model = argument.argument_model
if isinstance(model, StringShape):
if model.enum:
doc.style.new_paragraph()
doc.write('Possible values:')
doc.style.start_ul()
for enum in model.enum... |
':param index_file: The path to a specific JSON index to load.
If nothing is specified it will default to the default JSON
index at ``JSON_INDEX``.
:param topic_dir: The path to the directory where to retrieve
the topic source files. Note that if you store your index
in this directory, you must supply the full path to ... | def __init__(self, tag_dictionary=None, index_file=JSON_INDEX, topic_dir=TOPIC_DIR):
| self._tag_dictionary = tag_dictionary
if (self._tag_dictionary is None):
self._tag_dictionary = {}
self._index_file = index_file
self._topic_dir = topic_dir
|
'Loads a JSON file into the tag dictionary.'
| def load_json_index(self):
| with open(self.index_file, 'r') as f:
self._tag_dictionary = json.load(f)
|
'Writes the loaded data back out to the JSON index.'
| def save_to_json_index(self):
| with open(self.index_file, 'w') as f:
f.write(json.dumps(self._tag_dictionary, indent=4, sort_keys=True))
|
'Retrieves all of the topic names of the loaded JSON index'
| def get_all_topic_names(self):
| return list(self._tag_dictionary)
|
'Retrieves the file paths of all the topics in directory'
| def get_all_topic_src_files(self):
| topic_full_paths = []
topic_names = os.listdir(self.topic_dir)
for topic_name in topic_names:
if (not topic_name.startswith('.')):
topic_full_path = os.path.join(self.topic_dir, topic_name)
if (topic_full_path != self.index_file):
topic_full_paths.append(topic... |
'Scan in the tags of a list of topics into memory.
Note that if there are existing values in an entry in the database
of tags, they will not be overwritten. Any new values will be
appended to original values.
:param topic_files: A list of paths to topics to scan into memory.'
| def scan(self, topic_files):
| for topic_file in topic_files:
with open(topic_file, 'r') as f:
topic_name = self._find_topic_name(topic_file)
self._add_topic_name_to_dict(topic_name)
topic_content = f.read()
self._add_tag_and_values_from_content(topic_name, topic_content)
|
'Groups topics by a specific tag and/or tag value.
:param tag: The name of the tag to query for.
:param values: A list of tag values to only include in query.
If no value is provided, all possible tag values will be returned
:rtype: dictionary
:returns: A dictionary whose keys are all possible tag values and the
keys\'... | def query(self, tag, values=None):
| query_dict = {}
for topic_name in self._tag_dictionary.keys():
if (self._tag_dictionary[topic_name].get(tag, None) is not None):
tag_values = self._tag_dictionary[topic_name][tag]
for tag_value in tag_values:
if ((values is None) or (tag_value in values)):
... |
'Get a value of a tag for a topic
:param topic_name: The name of the topic
:param tag: The name of the tag to retrieve
:param default_value: The value to return if the topic and/or tag
does not exist.'
| def get_tag_value(self, topic_name, tag, default_value=None):
| if (topic_name in self._tag_dictionary):
return self._tag_dictionary[topic_name].get(tag, default_value)
return default_value
|
'Get the value of a tag for a topic (i.e. not wrapped in a list)
:param topic_name: The name of the topic
:param tag: The name of the tag to retrieve
:raises VauleError: Raised if there is not exactly one value
in the list value.'
| def get_tag_single_value(self, topic_name, tag):
| value = self.get_tag_value(topic_name, tag)
if (value is not None):
if (len(value) != 1):
raise ValueError(('Tag %s for topic %s has value %. Expected a single element in list.' % (tag, topic_name, value)))
value = value[0]
return value
|
'Add this object to the argument_table.
The ``argument_table`` represents the argument for the operation.
This is called by the ``ServiceOperation`` object to create the
arguments associated with the operation.
:type argument_table: dict
:param argument_table: The argument table. The key is the argument
name, and the ... | def add_to_arg_table(self, argument_table):
| argument_table[self.name] = self
|
'Add this object to the parser instance.
This method is called by the associated ``ArgumentParser``
instance. This method should make the relevant calls
to ``add_argument`` to add itself to the argparser.
:type parser: ``argparse.ArgumentParser``.
:param parser: The argument parser associated with the operation.'
| def add_to_parser(self, parser):
| pass
|
'Add this object to the parameters dict.
This method is responsible for taking the value specified
on the command line, and deciding how that corresponds to
parameters used by the service/operation.
:type parameters: dict
:param parameters: The parameters dictionary that will be
given to ``botocore``. This should matc... | def add_to_params(self, parameters, value):
| pass
|
'List valid choices for argument value.
If this value is not None then this should return a list of valid
values for the argument.'
| @property
def choices(self):
| return None
|
'Get the group name associated with the argument.
An argument can be part of a group. This property will
return the name of that group.
This base class has no default behavior for groups, code
that consumes argument objects can use them for whatever
purposes they like (documentation, mutually exclusive group
validatio... | @property
def group_name(self):
| return None
|
'See the ``BaseCLIArgument.add_to_parser`` docs for more information.'
| def add_to_parser(self, parser):
| cli_name = self.cli_name
kwargs = {}
if (self._dest is not None):
kwargs['dest'] = self._dest
if (self._action is not None):
kwargs['action'] = self._action
if (self._default is not None):
kwargs['default'] = self._default
if self._choices:
kwargs['choices'] = sel... |
':type name: str
:param name: The name of the argument in "cli" form
(e.g. ``min-instances``).
:type argument_model: ``botocore.model.Shape``
:param argument_model: The shape object that models the argument.
:type argument_model: ``botocore.model.OperationModel``
:param argument_model: The object that models the assoc... | def __init__(self, name, argument_model, operation_model, event_emitter, is_required=False, serialized_name=None):
| self._name = name
if (serialized_name is None):
serialized_name = name
self._serialized_name = serialized_name
self.argument_model = argument_model
self._required = is_required
self._operation_model = operation_model
self._event_emitter = event_emitter
self._documentation = argum... |
'See the ``BaseCLIArgument.add_to_parser`` docs for more information.'
| def add_to_parser(self, parser):
| cli_name = self.cli_name
parser.add_argument(cli_name, help=self.documentation, type=self.cli_type, required=self.required)
|
'Interface for loading and interacting with alias file
:param alias_filename: The name of the file to load aliases from.
This file must be an INI file.'
| def __init__(self, alias_filename=os.path.expanduser(os.path.join('~', '.aws', 'cli', 'alias'))):
| self._filename = alias_filename
self._aliases = None
|
'Injects alias commands for a command table
:type session: botocore.session.Session
:param session: The botocore session
:type alias_loader: awscli.alias.AliasLoader
:param alias_loader: The alias loader to use'
| def __init__(self, session, alias_loader):
| self._session = session
self._alias_loader = alias_loader
|
'Base class for alias command
:type alias_name: string
:param alias_name: The name of the alias
:type alias_value: string
:param alias_value: The parsed value of the alias. This can be
retrieved from `AliasLoader.get_aliases()[alias_name]`'
| def __init__(self, alias_name, alias_value):
| self._alias_name = alias_name
self._alias_value = alias_value
|
'Command for a `toplevel` subcommand alias
:type alias_name: string
:param alias_name: The name of the alias
:type alias_value: string
:param alias_value: The parsed value of the alias. This can be
retrieved from `AliasLoader.get_aliases()[alias_name]`
:type session: botocore.session.Session
:param session: The botocor... | def __init__(self, alias_name, alias_value, session, command_table, parser, shadow_proxy_command=None):
| super(ServiceAliasCommand, self).__init__(alias_name, alias_value)
self._session = session
self._command_table = command_table
self._parser = parser
self._shadow_proxy_command = shadow_proxy_command
|
'Command for external aliases
Executes command external of CLI as opposed to being a proxy
to another command.
:type alias_name: string
:param alias_name: The name of the alias
:type alias_value: string
:param alias_value: The parsed value of the alias. This can be
retrieved from `AliasLoader.get_aliases()[alias_name]`... | def __init__(self, alias_name, alias_value, invoker=subprocess.call):
| self._alias_name = alias_name
self._alias_value = alias_value
self._invoker = invoker
|
'Parse shorthand syntax.
For example::
parser = ShorthandParser()
parser.parse(\'a=b\') # {\'a\': \'b\'}
parser.parse(\'a=b,c\') # {\'a\': [\'b\', \'c\']}
:tpye value: str
:param value: Any value that needs to be parsed.
:return: Parsed value, which will be a dictionary.'
| def parse(self, value):
| self._input_value = value
self._index = 0
return self._parameter()
|
'Creates a file in a tmpdir
``filename`` should be a relative path, e.g. "foo/bar/baz.txt"
It will be translated into a full path in a tmp dir.
If the ``mtime`` argument is provided, then the file\'s
mtime will be set to the provided value (must be an epoch time).
Otherwise the mtime is left untouched.
``mode`` is the ... | def create_file(self, filename, contents, mtime=None, mode='w'):
| full_path = os.path.join(self.rootdir, filename)
if (not os.path.isdir(os.path.dirname(full_path))):
os.makedirs(os.path.dirname(full_path))
with open(full_path, mode) as f:
f.write(contents)
current_time = os.path.getmtime(full_path)
os.utime(full_path, (current_time, (current_time ... |
'Append contents to a file
``filename`` should be a relative path, e.g. "foo/bar/baz.txt"
It will be translated into a full path in a tmp dir.
Returns the full path to the file.'
| def append_file(self, filename, contents):
| full_path = os.path.join(self.rootdir, filename)
if (not os.path.isdir(os.path.dirname(full_path))):
os.makedirs(os.path.dirname(full_path))
with open(full_path, 'a') as f:
f.write(contents)
return full_path
|
'Translate relative path to full path in temp dir.
f.full_path(\'foo/bar.txt\') -> /tmp/asdfasd/foo/bar.txt'
| def full_path(self, filename):
| return os.path.join(self.rootdir, filename)
|
'Each implementation of HelpRenderer must implement this
render method.'
| def render(self, contents):
| converted_content = self._convert_doc_content(contents)
self._send_output_to_pager(converted_content)
|
'Return the ``event_class`` for this object.
The ``event_class`` is used by the documentation pipeline
when generating documentation events. For the event below::
doc-title.<event_class>.<name>
The document pipeline would use this property to determine
the ``event_class`` value.'
| @property
def event_class(self):
| pass
|
'Return the name of the wrapped object.
This would be called by the document pipeline to determine
the ``name`` to be inserted into the event, as shown above.'
| @property
def name(self):
| pass
|
'These are the commands that may follow after the help command'
| @property
def subcommand_table(self):
| return self._subcommand_table
|
'This is list of items that are related to the help command'
| @property
def related_items(self):
| return self._related_items
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.