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
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
import sys
import unittest
from knack.commands import CLICommandsLoader, CommandGroup
from knack.arguments import CLIArgumentType, CLICommandArgument, ArgumentsContext
from tests.util import MockContext
def _dictContainsSubset(expected, actual):
"""Checks whether actual is a superset of expected.
Helper for deprecated assertDictContainsSubset"""
missing = False
mismatched = False
for key, value in expected.items():
if key not in actual:
missing = True
elif value != actual[key]:
mismatched = True
return False if missing or mismatched else True
class TestCommandRegistration(unittest.TestCase):
def setUp(self):
self.mock_ctx = MockContext()
@staticmethod
def sample_command_handler(group_name, resource_name, opt_param=None, expand=None):
"""
The operation to get a virtual machine.
:param group_name: The name of the group.
:type group_name: str
:param resource_name: The name of the resource.
:type resource_name: str
:param opt_param: Used to verify reflection correctly
identifies optional params.
:type opt_param: object
:param expand: The expand expression to apply on the operation.
:type expand: str
:param dict custom_headers: headers that will be added to the request
:param boolean raw: returns the direct response alongside the
deserialized response
"""
pass
@staticmethod
def sample_command_handler2(group_name, resource_name, opt_param=None, expand=None, custom_headers=None,
raw=False, **operation_config):
pass
def _set_command_name(self, command):
self.mock_ctx.invocation.data['command_string'] = command
return command
def test_register_cli_argument(self):
cl = CLICommandsLoader(self.mock_ctx)
command_name = self._set_command_name('test register sample-command')
with CommandGroup(cl, 'test register', '{}#{{}}'.format(__name__)) as g:
g.command('sample-command', '{}.{}'.format(TestCommandRegistration.__name__,
TestCommandRegistration.sample_command_handler.__name__))
with ArgumentsContext(cl, command_name) as ac:
ac.argument('resource_name', CLIArgumentType(
options_list=('--wonky-name', '-n'), metavar='RNAME', help='Completely WONKY name...',
required=False
))
cl.load_arguments(command_name)
self.assertEqual(len(cl.command_table), 1, 'We expect exactly one command in the command table')
command_metadata = cl.command_table[command_name]
self.assertEqual(len(command_metadata.arguments), 4, 'We expected exactly 4 arguments')
some_expected_arguments = {
'group_name': CLIArgumentType(dest='group_name', required=True),
'resource_name': CLIArgumentType(dest='resource_name', required=False),
}
for probe in some_expected_arguments:
existing = next(arg for arg in command_metadata.arguments if arg == probe)
contains_subset = _dictContainsSubset(some_expected_arguments[existing].settings,
command_metadata.arguments[existing].options)
self.assertTrue(contains_subset)
self.assertEqual(command_metadata.arguments['resource_name'].options_list, ('--wonky-name', '-n'))
def test_register_command_custom_excluded_params(self):
command_name = self._set_command_name('test sample-command')
ep = ['self', 'raw', 'custom_headers', 'operation_config', 'content_version', 'kwargs', 'client']
cl = CLICommandsLoader(self.mock_ctx, excluded_command_handler_args=ep)
with CommandGroup(cl, 'test', '{}#{{}}'.format(__name__)) as g:
g.command('sample-command', '{}.{}'.format(TestCommandRegistration.__name__,
TestCommandRegistration.sample_command_handler2.__name__))
self.assertEqual(len(cl.command_table), 1, 'We expect exactly one command in the command table')
cl.load_arguments(command_name)
command_metadata = cl.command_table[command_name]
self.assertEqual(len(command_metadata.arguments), 4, 'We expected exactly 4 arguments')
self.assertIn(command_name, cl.command_table)
def test_register_command(self):
cl = CLICommandsLoader(self.mock_ctx)
command_name = self._set_command_name('test register sample-command')
with CommandGroup(cl, 'test register', '{}#{{}}'.format(__name__)) as g:
g.command('sample-command', '{}.{}'.format(TestCommandRegistration.__name__,
TestCommandRegistration.sample_command_handler.__name__))
self.assertEqual(len(cl.command_table), 1, 'We expect exactly one command in the command table')
cl.load_arguments(command_name)
command_metadata = cl.command_table[command_name]
self.assertEqual(len(command_metadata.arguments), 4, 'We expected exactly 4 arguments')
some_expected_arguments = {
'group_name': CLIArgumentType(dest='group_name',
required=True,
help='The name of the group.'),
'resource_name': CLIArgumentType(dest='resource_name',
required=True,
help='The name of the resource.'),
'opt_param': CLIArgumentType(required=False,
help='Used to verify reflection correctly identifies optional params.'),
'expand': CLIArgumentType(required=False,
help='The expand expression to apply on the operation.')
}
for probe in some_expected_arguments:
existing = next(arg for arg in command_metadata.arguments if arg == probe)
contains_subset = _dictContainsSubset(some_expected_arguments[existing].settings,
command_metadata.arguments[existing].options)
self.assertTrue(contains_subset)
self.assertEqual(command_metadata.arguments['resource_name'].options_list, ['--resource-name'])
def test_register_command_group_with_no_group_name(self):
cl = CLICommandsLoader(self.mock_ctx)
command_name = self._set_command_name('sample-command')
with CommandGroup(cl, None, '{}#{{}}'.format(__name__)) as g:
g.command('sample-command', '{}.{}'.format(TestCommandRegistration.__name__,
TestCommandRegistration.sample_command_handler.__name__))
self.assertEqual(len(cl.command_table), 1, 'We expect exactly one command in the command table')
self.assertIn(command_name, cl.command_table)
def test_register_command_confirmation_bool(self):
cl = CLICommandsLoader(self.mock_ctx)
command_name = self._set_command_name('test sample-command')
with CommandGroup(cl, 'test', '{}#{{}}'.format(__name__)) as g:
g.command('sample-command', '{}.{}'.format(TestCommandRegistration.__name__,
TestCommandRegistration.sample_command_handler.__name__),
confirmation=True)
self.assertEqual(len(cl.command_table), 1, 'We expect exactly one command in the command table')
cl.load_arguments(command_name)
command_metadata = cl.command_table[command_name]
self.assertIn('yes', command_metadata.arguments)
self.assertEqual(command_metadata.arguments['yes'].type.settings['action'], 'store_true')
self.assertIs(command_metadata.confirmation, True)
def test_register_command_confirmation_callable(self):
cl = CLICommandsLoader(self.mock_ctx)
def confirm_callable(_):
pass
command_name = self._set_command_name('test sample-command')
with CommandGroup(cl, 'test', '{}#{{}}'.format(__name__)) as g:
g.command('sample-command', '{}.{}'.format(TestCommandRegistration.__name__,
TestCommandRegistration.sample_command_handler.__name__),
confirmation=confirm_callable)
self.assertEqual(len(cl.command_table), 1, 'We expect exactly one command in the command table')
cl.load_arguments(command_name)
command_metadata = cl.command_table[command_name]
self.assertIn('yes', command_metadata.arguments)
self.assertEqual(command_metadata.arguments['yes'].type.settings['action'], 'store_true')
self.assertIs(command_metadata.confirmation, confirm_callable)
def test_register_cli_argument_with_overrides(self):
cl = CLICommandsLoader(self.mock_ctx)
base_type = CLIArgumentType(options_list=['--foo', '-f'], metavar='FOO', help='help1')
derived_type = CLIArgumentType(base_type=base_type, help='help2')
with CommandGroup(cl, 'test', '{}#{{}}'.format(__name__)) as g:
g.command('sample-get', '{}.{}'.format(TestCommandRegistration.__name__,
TestCommandRegistration.sample_command_handler.__name__))
g.command('command sample-get-1', '{}.{}'.format(TestCommandRegistration.__name__,
TestCommandRegistration.sample_command_handler.__name__))
g.command('command sample-get-2', '{}.{}'.format(TestCommandRegistration.__name__,
TestCommandRegistration.sample_command_handler.__name__))
self.assertEqual(len(cl.command_table), 3, 'We expect exactly three commands in the command table')
def test_with_command(command, target_value):
self._set_command_name(command)
with ArgumentsContext(cl, 'test') as c:
c.argument('resource_name', base_type)
with ArgumentsContext(cl, 'test command') as c:
c.argument('resource_name', derived_type)
with ArgumentsContext(cl, 'test command sample-get-2') as c:
c.argument('resource_name', derived_type, help='help3')
cl.load_arguments(command)
command1 = cl.command_table[command].arguments['resource_name']
self.assertEqual(command1.options['help'], target_value)
test_with_command('test sample-get', 'help1')
test_with_command('test command sample-get-1', 'help2')
test_with_command('test command sample-get-2', 'help3')
def test_register_extra_cli_argument(self):
cl = CLICommandsLoader(self.mock_ctx)
command_name = self._set_command_name('test register sample-command')
with CommandGroup(cl, 'test register', '{}#{{}}'.format(__name__)) as g:
g.command('sample-command', '{}.{}'.format(TestCommandRegistration.__name__,
TestCommandRegistration.sample_command_handler.__name__))
with ArgumentsContext(cl, command_name) as ac:
ac.extra('added_param', options_list=('--added-param',),
metavar='ADDED', help='Just added this right now!', required=True)
cl.load_arguments(command_name)
self.assertEqual(len(cl.command_table), 1, 'We expect exactly one command in the command table')
command_metadata = cl.command_table[command_name]
self.assertEqual(len(command_metadata.arguments), 5, 'We expected exactly 5 arguments')
some_expected_arguments = {
'added_param': CLIArgumentType(dest='added_param', required=True)
}
for probe in some_expected_arguments:
existing = next(arg for arg in command_metadata.arguments if arg == probe)
contains_subset = _dictContainsSubset(some_expected_arguments[existing].settings,
command_metadata.arguments[existing].options)
self.assertTrue(contains_subset)
def test_register_ignore_cli_argument(self):
cl = CLICommandsLoader(self.mock_ctx)
command_name = self._set_command_name('test register sample-command')
self.mock_ctx.invocation.data['command_string'] = command_name
with CommandGroup(cl, 'test register', '{}#{{}}'.format(__name__)) as g:
g.command('sample-command', '{}.{}'.format(TestCommandRegistration.__name__,
TestCommandRegistration.sample_command_handler.__name__))
with ArgumentsContext(cl, 'test register') as ac:
ac.argument('resource_name', options_list=['--this'])
with ArgumentsContext(cl, 'test register sample-command') as ac:
ac.ignore('resource_name')
ac.argument('opt_param', options_list=['--this'])
cl.load_arguments(command_name)
self.assertNotEqual(cl.command_table[command_name].arguments['resource_name'].options_list,
cl.command_table[command_name].arguments['opt_param'].options_list,
"Name conflict in options list")
def test_command_build_argument_help_text(self):
def sample_sdk_method_with_weird_docstring(param_a, param_b, param_c): # pylint: disable=unused-argument
"""
An operation with nothing good.
:param dict param_a:
:param param_b: The name
of
nothing.
:param param_c: The name
of
nothing2.
"""
pass
cl = CLICommandsLoader(self.mock_ctx)
command_name = self._set_command_name('test command foo')
setattr(sys.modules[__name__], sample_sdk_method_with_weird_docstring.__name__,
sample_sdk_method_with_weird_docstring)
with CommandGroup(cl, 'test command', '{}#{{}}'.format(__name__)) as g:
g.command('foo', sample_sdk_method_with_weird_docstring.__name__)
cl.load_arguments(command_name)
command_metadata = cl.command_table[command_name]
self.assertEqual(len(command_metadata.arguments), 3, 'We expected exactly 3 arguments')
some_expected_arguments = {
'param_a': CLIArgumentType(dest='param_a', required=True, help=''),
'param_b': CLIArgumentType(dest='param_b', required=True, help='The name of nothing.'),
'param_c': CLIArgumentType(dest='param_c', required=True, help='The name of nothing2.')
}
for probe in some_expected_arguments:
existing = next(arg for arg in command_metadata.arguments if arg == probe)
contains_subset = _dictContainsSubset(some_expected_arguments[existing].settings,
command_metadata.arguments[existing].options)
self.assertTrue(contains_subset)
def test_override_existing_option_string(self):
arg = CLIArgumentType(options_list=('--funky', '-f'))
updated_options_list = ('--something-else', '-s')
arg.update(options_list=updated_options_list, validator=lambda: (), completer=lambda: ())
self.assertEqual(arg.settings['options_list'], updated_options_list)
self.assertIsNotNone(arg.settings['validator'])
self.assertIsNotNone(arg.settings['completer'])
def test_dont_override_existing_option_string(self):
existing_options_list = ('--something-else', '-s')
arg = CLIArgumentType(options_list=existing_options_list)
arg.update()
self.assertEqual(arg.settings['options_list'], existing_options_list)
def test_override_remove_validator(self):
existing_options_list = ('--something-else', '-s')
arg = CLIArgumentType(options_list=existing_options_list,
validator=lambda *args, **kwargs: ())
arg.update(validator=None)
self.assertIsNone(arg.settings['validator'])
def test_override_using_register_cli_argument(self):
def sample_sdk_method(param_a): # pylint: disable=unused-argument
pass
def test_validator_completer():
pass
cl = CLICommandsLoader(self.mock_ctx)
command_name = self._set_command_name('override_using_register_cli_argument foo')
setattr(sys.modules[__name__], sample_sdk_method.__name__, sample_sdk_method)
with CommandGroup(cl, 'override_using_register_cli_argument', '{}#{{}}'.format(__name__)) as g:
g.command('foo', sample_sdk_method.__name__)
with ArgumentsContext(cl, 'override_using_register_cli_argument') as ac:
ac.argument('param_a',
options_list=('--overridden', '-r'),
validator=test_validator_completer,
completer=test_validator_completer,
required=False)
cl.load_arguments(command_name)
command_metadata = cl.command_table[command_name]
self.assertEqual(len(command_metadata.arguments), 1, 'We expected exactly 1 arguments')
actual_arg = command_metadata.arguments['param_a']
self.assertEqual(actual_arg.options_list, ('--overridden', '-r'))
self.assertEqual(actual_arg.validator, test_validator_completer)
self.assertEqual(actual_arg.completer, test_validator_completer)
self.assertFalse(actual_arg.options['required'])
def test_override_argtype_with_argtype(self):
existing_options_list = ('--default', '-d')
arg = CLIArgumentType(options_list=existing_options_list, validator=None, completer='base',
help='base', required=True)
overriding_argtype = CLIArgumentType(options_list=('--overridden',), validator='overridden',
completer=None, overrides=arg, help='overridden',
required=CLIArgumentType.REMOVE)
self.assertEqual(overriding_argtype.settings['validator'], 'overridden')
self.assertIsNone(overriding_argtype.settings['completer'])
self.assertEqual(overriding_argtype.settings['options_list'], ('--overridden',))
self.assertEqual(overriding_argtype.settings['help'], 'overridden')
self.assertEqual(overriding_argtype.settings['required'], CLIArgumentType.REMOVE)
cmd_arg = CLICommandArgument(dest='whatever', argtype=overriding_argtype,
help=CLIArgumentType.REMOVE)
self.assertNotIn('required', cmd_arg.options)
self.assertNotIn('help', cmd_arg.options)
def test_cli_ctx_type_error(self):
with self.assertRaises(TypeError):
CLICommandsLoader(cli_ctx=object())
if __name__ == '__main__':
unittest.main()
|