-
Notifications
You must be signed in to change notification settings - Fork 4k
/
test_argprocess.py
550 lines (480 loc) · 22.4 KB
/
test_argprocess.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
# Copyright 2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file 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 json
from awscli.testutils import unittest
from awscli.testutils import BaseCLIDriverTest
from awscli.testutils import temporary_file
import mock
from awscli.clidriver import CLIArgument
from awscli.help import OperationHelpCommand
from awscli.argprocess import detect_shape_structure
from awscli.argprocess import unpack_cli_arg
from awscli.argprocess import ParamShorthand
from awscli.argprocess import ParamError
from awscli.argprocess import ParamUnknownKeyError
from awscli.argprocess import uri_param
from awscli.arguments import CustomArgument
MAPHELP = """--attributes key_name=string,key_name2=string
Where valid key names are:
Policy"""
# These tests use real service types so that we can
# verify the real shapes of services.
class BaseArgProcessTest(BaseCLIDriverTest):
def get_param_object(self, dotted_name):
service_name, operation_name, param_name = dotted_name.split('.')
service = self.session.get_service(service_name)
operation = service.get_operation(operation_name)
for p in operation.params:
if p.name == param_name:
return p
else:
raise ValueError("Unknown param: %s" % param_name)
class TestURIParams(BaseArgProcessTest):
def test_uri_param(self):
p = self.get_param_object('ec2.DescribeInstances.Filters')
with temporary_file('r+') as f:
json_argument = json.dumps([{"Name": "instance-id", "Values": ["i-1234"]}])
f.write(json_argument)
f.flush()
result = uri_param(p, 'file://%s' % f.name)
self.assertEqual(result, json_argument)
def test_uri_param_no_paramfile_false(self):
p = self.get_param_object('ec2.DescribeInstances.Filters')
p.no_paramfile = False
with temporary_file('r+') as f:
json_argument = json.dumps([{"Name": "instance-id", "Values": ["i-1234"]}])
f.write(json_argument)
f.flush()
result = uri_param(p, 'file://%s' % f.name)
self.assertEqual(result, json_argument)
def test_uri_param_no_paramfile_true(self):
p = self.get_param_object('ec2.DescribeInstances.Filters')
p.no_paramfile = True
with temporary_file('r+') as f:
json_argument = json.dumps([{"Name": "instance-id", "Values": ["i-1234"]}])
f.write(json_argument)
f.flush()
result = uri_param(p, 'file://%s' % f.name)
self.assertEqual(result, None)
class TestArgShapeDetection(BaseArgProcessTest):
def assert_shape_type(self, spec, expected_type):
p = self.get_param_object(spec)
actual_structure = detect_shape_structure(p)
self.assertEqual(actual_structure, expected_type)
def assert_custom_shape_type(self, schema, expected_type):
argument = CustomArgument('test', schema=schema)
argument.create_argument_object()
actual_structure = detect_shape_structure(argument.argument_object)
self.assertEqual(actual_structure, expected_type)
def test_detect_scalar(self):
self.assert_shape_type('iam.AddRoleToInstanceProfile.RoleName',
'scalar')
def test_detect_list_of_strings(self):
self.assert_shape_type('sns.AddPermission.AWSAccountId', 'list-scalar')
def test_detect_structure_of_scalars(self):
self.assert_shape_type(
'elasticbeanstalk.CreateConfigurationTemplate.SourceConfiguration',
'structure(scalars)')
def test_list_structure_scalars(self):
self.assert_shape_type(
'elb.RegisterInstancesWithLoadBalancer.Instances',
'list-structure(scalar)')
def test_list_structure_scalars_2(self):
self.assert_shape_type(
'elb.CreateLoadBalancer.Listeners',
'list-structure(scalars)')
def test_list_structure_of_list_and_strings(self):
self.assert_shape_type(
'ec2.DescribeInstances.Filters', 'list-structure(list-scalar, scalar)')
def test_map_scalar(self):
self.assert_shape_type(
'sqs.SetQueueAttributes.Attributes', 'map-scalar')
def test_struct_list_scalar(self):
self.assert_custom_shape_type({
"type": "object",
"properties": {
"Consistent": {
"type": "boolean",
},
"Args": {
"type": "array",
"items": {
"type": "string"
}
}
}
}, 'structure(list-scalar, scalar)')
class TestParamShorthand(BaseArgProcessTest):
def setUp(self):
super(TestParamShorthand, self).setUp()
self.simplify = ParamShorthand()
def test_simplify_structure_scalars(self):
p = self.get_param_object(
'elasticbeanstalk.CreateConfigurationTemplate.SourceConfiguration')
value = 'ApplicationName=foo,TemplateName=bar'
json_value = '{"ApplicationName": "foo", "TemplateName": "bar"}'
returned = self.simplify(p, value)
json_version = unpack_cli_arg(p, json_value)
self.assertEqual(returned, json_version)
def test_parse_boolean_shorthand(self):
bool_param = mock.Mock()
bool_param.type = 'boolean'
self.assertTrue(unpack_cli_arg(bool_param, True))
self.assertTrue(unpack_cli_arg(bool_param, 'True'))
self.assertTrue(unpack_cli_arg(bool_param, 'true'))
self.assertFalse(unpack_cli_arg(bool_param, False))
self.assertFalse(unpack_cli_arg(bool_param, 'False'))
self.assertFalse(unpack_cli_arg(bool_param, 'false'))
def test_simplify_map_scalar(self):
p = self.get_param_object('sqs.SetQueueAttributes.Attributes')
returned = self.simplify(p, 'VisibilityTimeout=15')
json_version = unpack_cli_arg(p, '{"VisibilityTimeout": "15"}')
self.assertEqual(returned, {'VisibilityTimeout': '15'})
self.assertEqual(returned, json_version)
def test_list_structure_scalars(self):
p = self.get_param_object(
'elb.RegisterInstancesWithLoadBalancer.Instances')
# Because this is a list type param, we'll use nargs
# with argparse which means the value will be presented
# to us as a list.
returned = self.simplify(p, ['instance-1', 'instance-2'])
self.assertEqual(returned, [{'InstanceId': 'instance-1'},
{'InstanceId': 'instance-2'}])
def test_list_structure_list_scalar(self):
p = self.get_param_object('ec2.DescribeInstances.Filters')
expected = [{"Name": "instance-id", "Values": ["i-1", "i-2"]},
{"Name": "architecture", "Values": ["i386"]}]
returned = self.simplify(
p, ["Name=instance-id,Values=i-1,i-2",
"Name=architecture,Values=i386"])
self.assertEqual(returned, expected)
# With spaces around the comma.
returned2 = self.simplify(
p, ["Name=instance-id, Values=i-1,i-2",
"Name=architecture, Values=i386"])
self.assertEqual(returned2, expected)
# Strip off leading/trailing spaces.
returned3 = self.simplify(
p, ["Name = instance-id, Values = i-1,i-2",
"Name = architecture, Values = i386"])
self.assertEqual(returned3, expected)
def test_list_structure_list_scalar_2(self):
p = self.get_param_object('emr.ModifyInstanceGroups.InstanceGroups')
expected = [
{"InstanceGroupId": "foo",
"InstanceCount": 4},
{"InstanceGroupId": "bar",
"InstanceCount": 1}
]
simplified = self.simplify(p, [
"InstanceGroupId=foo,InstanceCount=4",
"InstanceGroupId=bar,InstanceCount=1"
])
self.assertEqual(simplified, expected)
def test_list_structure_list_scalar_3(self):
arg = CustomArgument('foo', schema={
'type': 'array',
'items': {
'type': 'object',
'properties': {
'Name': {
'type': 'string'
},
'Args': {
'type': 'array',
'items': {
'type': 'string'
}
}
}
}
})
arg.create_argument_object()
p = arg.argument_object
expected = [
{"Name": "foo",
"Args": ["a", "k1=v1", "b"]},
{"Name": "bar",
"Args": ["baz"]},
{"Name": "single_kv",
"Args": ["key=value"]},
{"Name": "single_v",
"Args": ["value"]}
]
simplified = self.simplify(p, [
"Name=foo,Args=[a,k1=v1,b]",
"Name=bar,Args=baz",
"Name=single_kv,Args=[key=value]",
"Name=single_v,Args=[value]"
])
self.assertEqual(simplified, expected)
def test_list_structure_list_multiple_scalar(self):
p = self.get_param_object('elastictranscoder.CreateJob.Playlists')
returned = self.simplify(
p, ['Name=foo,Format=hslv3,OutputKeys=iphone1,iphone2'])
self.assertEqual(returned, [{'OutputKeys': ['iphone1', 'iphone2'],
'Name': 'foo', 'Format': 'hslv3'}])
def test_list_structure_scalars_2(self):
p = self.get_param_object('elb.CreateLoadBalancer.Listeners')
expected = [
{"Protocol": "protocol1",
"LoadBalancerPort": 1,
"InstanceProtocol": "instance_protocol1",
"InstancePort": 2,
"SSLCertificateId": "ssl_certificate_id1"},
{"Protocol": "protocol2",
"LoadBalancerPort": 3,
"InstanceProtocol": "instance_protocol2",
"InstancePort": 4,
"SSLCertificateId": "ssl_certificate_id2"},
]
returned = unpack_cli_arg(
p, ['{"Protocol": "protocol1", "LoadBalancerPort": 1, '
'"InstanceProtocol": "instance_protocol1", '
'"InstancePort": 2, "SSLCertificateId": '
'"ssl_certificate_id1"}',
'{"Protocol": "protocol2", "LoadBalancerPort": 3, '
'"InstanceProtocol": "instance_protocol2", '
'"InstancePort": 4, "SSLCertificateId": '
'"ssl_certificate_id2"}',
])
self.maxDiff = None
self.assertEqual(returned, expected)
simplified = self.simplify(p, [
'Protocol=protocol1,LoadBalancerPort=1,'
'InstanceProtocol=instance_protocol1,'
'InstancePort=2,SSLCertificateId=ssl_certificate_id1',
'Protocol=protocol2,LoadBalancerPort=3,'
'InstanceProtocol=instance_protocol2,'
'InstancePort=4,SSLCertificateId=ssl_certificate_id2'
])
self.assertEqual(simplified, expected)
def test_struct_list_scalars(self):
schema = {
"type": "object",
"properties": {
"Consistent": {
"type": "boolean",
},
"Args": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
argument = CustomArgument('test', schema=schema)
argument.create_argument_object()
p = argument.argument_object
returned = self.simplify(p, 'Consistent=true,Args=foo1,foo2')
self.assertEqual(returned, {'Consistent': True,
'Args': ['foo1', 'foo2']})
def test_keyval_with_long_values(self):
p = self.get_param_object(
'dynamodb.UpdateTable.ProvisionedThroughput')
value = 'WriteCapacityUnits=10,ReadCapacityUnits=10'
returned = self.simplify(p, value)
self.assertEqual(returned, {'WriteCapacityUnits': 10,
'ReadCapacityUnits': 10})
def test_error_messages_for_structure_scalar(self):
p = self.get_param_object(
'elasticbeanstalk.CreateConfigurationTemplate.SourceConfiguration')
value = 'ApplicationName:foo,TemplateName=bar'
error_msg = "Error parsing parameter '--source-configuration'.*should be"
with self.assertRaisesRegexp(ParamError, error_msg):
self.simplify(p, value)
def test_mispelled_param_name(self):
p = self.get_param_object(
'elasticbeanstalk.CreateConfigurationTemplate.SourceConfiguration')
error_msg = 'valid choices.*ApplicationName'
with self.assertRaisesRegexp(ParamUnknownKeyError, error_msg):
# Typo in 'ApplicationName'
self.simplify(p, 'ApplicationNames=foo, TemplateName=bar')
def test_improper_separator(self):
# If the user uses ':' instead of '=', we should give a good
# error message.
p = self.get_param_object(
'elasticbeanstalk.CreateConfigurationTemplate.SourceConfiguration')
value = 'ApplicationName:foo,TemplateName:bar'
error_msg = "Error parsing parameter '--source-configuration'.*should be"
with self.assertRaisesRegexp(ParamError, error_msg):
self.simplify(p, value)
def test_improper_separator_for_filters_param(self):
p = self.get_param_object('ec2.DescribeInstances.Filters')
error_msg = "Error parsing parameter '--filters'.*should be"
with self.assertRaisesRegexp(ParamError, error_msg):
self.simplify(p, ["Name:tag:Name,Values:foo"])
def test_unknown_key_for_filters_param(self):
p = self.get_param_object('ec2.DescribeInstances.Filters')
with self.assertRaisesRegexp(ParamUnknownKeyError,
'valid choices.*Name'):
self.simplify(p, ["Names=instance-id,Values=foo,bar"])
def test_csv_syntax_escaped(self):
p = self.get_param_object('cloudformation.CreateStack.Parameters')
returned = self.simplify(
p, ["ParameterKey=key,ParameterValue=foo\,bar"])
expected = [{"ParameterKey": "key",
"ParameterValue": "foo,bar"}]
self.assertEqual(returned, expected)
def test_csv_syntax_double_quoted(self):
p = self.get_param_object('cloudformation.CreateStack.Parameters')
returned = self.simplify(
p, ['ParameterKey=key,ParameterValue="foo,bar"'])
expected = [{"ParameterKey": "key",
"ParameterValue": "foo,bar"}]
self.assertEqual(returned, expected)
def test_csv_syntax_single_quoted(self):
p = self.get_param_object('cloudformation.CreateStack.Parameters')
returned = self.simplify(
p, ["ParameterKey=key,ParameterValue='foo,bar'"])
expected = [{"ParameterKey": "key",
"ParameterValue": "foo,bar"}]
self.assertEqual(returned, expected)
def test_csv_syntax_errors(self):
p = self.get_param_object('cloudformation.CreateStack.Parameters')
error_msg = "Error parsing parameter '--parameters'.*should be"
with self.assertRaisesRegexp(ParamError, error_msg):
self.simplify(p, ['ParameterKey=key,ParameterValue="foo,bar'])
with self.assertRaisesRegexp(ParamError, error_msg):
self.simplify(p, ['ParameterKey=key,ParameterValue=foo,bar"'])
with self.assertRaisesRegexp(ParamError, error_msg):
self.simplify(p, ['ParameterKey=key,ParameterValue=""foo,bar"'])
with self.assertRaisesRegexp(ParamError, error_msg):
self.simplify(p, ['ParameterKey=key,ParameterValue="foo,bar\''])
class TestDocGen(BaseArgProcessTest):
# These aren't very extensive doc tests, as we want to stay somewhat
# flexible and allow the docs to slightly change without breaking these
# tests.
def setUp(self):
super(TestDocGen, self).setUp()
self.simplify = ParamShorthand()
def test_gen_map_type_docs(self):
p = self.get_param_object('sqs.SetQueueAttributes.Attributes')
argument = CLIArgument(p.cli_name, p, p.operation)
help_command = OperationHelpCommand(
self.session, p.operation, None, {p.cli_name: argument},
name='set-queue-attributes', event_class='sqs')
help_command.param_shorthand.add_example_fn(p.cli_name, help_command)
self.assertTrue(p.example_fn)
doc_string = p.example_fn(p)
self.assertIn(MAPHELP, doc_string)
def test_gen_list_scalar_docs(self):
p = self.get_param_object(
'elb.RegisterInstancesWithLoadBalancer.Instances')
argument = CLIArgument(p.cli_name, p, p.operation)
help_command = OperationHelpCommand(
self.session, p.operation, None,
{p.cli_name: argument},
name='register-instances-with-load-balancer',
event_class='elb')
help_command.param_shorthand.add_example_fn(p.cli_name, help_command)
self.assertTrue(p.example_fn)
doc_string = p.example_fn(p)
self.assertEqual(doc_string,
'--instances InstanceId1 InstanceId2 InstanceId3')
def test_gen_list_structure_of_scalars_docs(self):
p = self.get_param_object('elb.CreateLoadBalancer.Listeners')
argument = CLIArgument(p.cli_name, p, p.operation)
help_command = OperationHelpCommand(
self.session, p.operation, None, {p.cli_name: argument},
name='create-load-balancer', event_class='elb')
help_command.param_shorthand.add_example_fn(p.cli_name, help_command)
self.assertTrue(p.example_fn)
doc_string = p.example_fn(p)
self.assertIn('Key value pairs, with multiple values separated by a space.', doc_string)
self.assertIn('Protocol=string', doc_string)
self.assertIn('LoadBalancerPort=integer', doc_string)
self.assertIn('InstanceProtocol=string', doc_string)
self.assertIn('InstancePort=integer', doc_string)
self.assertIn('SSLCertificateId=string', doc_string)
def test_gen_list_structure_multiple_scalar_docs(self):
p = self.get_param_object('elastictranscoder.CreateJob.Playlists')
argument = CLIArgument(p.cli_name, p, p.operation)
help_command = OperationHelpCommand(
self.session, p.operation, None, {p.cli_name: argument},
name='create-job', event_class='elastictranscoder')
help_command.param_shorthand.add_example_fn(p.cli_name, help_command)
doc_string = p.example_fn(p)
s = ('Key value pairs, where values are separated by commas, '
'and multiple pairs are separated by spaces.\n'
'--playlists Name=string1,Format=string1,OutputKeys=string1,string2 '
'Name=string1,Format=string1,OutputKeys=string1,string2')
self.assertEqual(doc_string, s)
def test_gen_list_structure_list_scalar_scalar_docs(self):
# Verify that we have *two* top level list items displayed,
# so we make it clear that multiple values are separated by spaces.
p = self.get_param_object('ec2.DescribeInstances.Filters')
argument = CLIArgument(p.cli_name, p, p.operation)
help_command = OperationHelpCommand(
self.session, p.operation, None, {p.cli_name: argument},
name='describe-instances', event_class='ec2')
help_command.param_shorthand.add_example_fn(p.cli_name, help_command)
doc_string = p.example_fn(p)
self.assertIn('multiple pairs are separated by spaces', doc_string)
self.assertIn('Name=string1,Values=string1,string2 '
'Name=string1,Values=string1,string2', doc_string)
def test_gen_structure_list_scalar_docs(self):
schema = {
"type": "object",
"properties": {
"Consistent": {
"type": "boolean",
},
"Args": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
argument = CustomArgument('test', schema=schema)
argument.create_argument_object()
p = argument.argument_object
help_command = OperationHelpCommand(
self.session, p.operation, None, {p.cli_name: argument},
name='foo', event_class='bar')
help_command.param_shorthand.add_example_fn(p.cli_name, help_command)
doc_string = p.example_fn(p)
self.assertIn('Key value pairs', doc_string)
self.assertIn('Consistent=boolean1,Args=string1,string2', doc_string)
class TestUnpackJSONParams(BaseArgProcessTest):
def setUp(self):
super(TestUnpackJSONParams, self).setUp()
self.simplify = ParamShorthand()
def test_json_with_spaces(self):
p = self.get_param_object('ec2.RunInstances.BlockDeviceMappings')
# If a user specifies the json with spaces, it will show up as
# a multi element list. For example:
# --block-device-mappings [{ "DeviceName":"/dev/sdf",
# "VirtualName":"ephemeral0"}, {"DeviceName":"/dev/sdg",
# "VirtualName":"ephemeral1" }]
#
# Will show up as:
block_device_mapping = [
'[{', 'DeviceName:/dev/sdf,', 'VirtualName:ephemeral0},',
'{DeviceName:/dev/sdg,', 'VirtualName:ephemeral1', '}]']
# The shell has removed the double quotes so this is invalid
# JSON, but we should still raise a better exception.
with self.assertRaises(ParamError) as e:
unpack_cli_arg(p, block_device_mapping)
# Parameter name should be in error message.
self.assertIn('--block-device-mappings', str(e.exception))
# The actual JSON itself should be in the error message.
# Becaues this is a list, only the first element in the JSON
# will show. This will at least let customers know what
# we tried to parse.
self.assertIn('[{', str(e.exception))
if __name__ == '__main__':
unittest.main()