def test_supported_api_version_invalid_rt_for_profile(self): cli = DummyCli() cli.cloud = Cloud('TestCloud', profile='2017-01-01-profile') test_profile = {'2017-01-01-profile': {ResourceType.MGMT_STORAGE: '2020-10-10'}} with mock.patch('azure.cli.core.profiles._shared.AZURE_API_PROFILES', test_profile): with self.assertRaises(APIVersionException): supported_api_version(cli, ResourceType.MGMT_COMPUTE, min_api='2020-01-01')
def test_case_insensitive_enum_choices(self): from enum import Enum class TestEnum(Enum): # pylint: disable=too-few-public-methods opt1 = "ALL_CAPS" opt2 = "camelCase" opt3 = "snake_case" def test_handler(): pass cli = DummyCli() cli.loader = mock.MagicMock() cli.loader.cli_ctx = cli command = AzCliCommand(cli.loader, 'test command', test_handler) command.add_argument('opt', '--opt', required=True, **enum_choice_list(TestEnum)) cmd_table = {'test command': command} cli.commands_loader.command_table = cmd_table parser = AzCliCommandParser(cli) parser.load_command_table(cli.commands_loader) args = parser.parse_args('test command --opt alL_cAps'.split()) self.assertEqual(args.opt, 'ALL_CAPS') args = parser.parse_args('test command --opt CAMELCASE'.split()) self.assertEqual(args.opt, 'camelCase') args = parser.parse_args('test command --opt sNake_CASE'.split()) self.assertEqual(args.opt, 'snake_case')
def test_get_api_version_semver(self): # Can get correct resource type API version if semver used cli = DummyCli() cli.cloud = Cloud('TestCloud', profile='2017-01-01-profile') test_profile = {'2017-01-01-profile': {ResourceType.MGMT_KEYVAULT: '7.0'}} with mock.patch('azure.cli.core.profiles._shared.AZURE_API_PROFILES', test_profile): self.assertEqual(get_api_version(cli, ResourceType.MGMT_KEYVAULT), '7.0')
def test_register_simple_commands(self): def test_handler1(): pass def test_handler2(): pass cli = DummyCli() cli.loader = mock.MagicMock() cli.loader.cli_ctx = cli command = AzCliCommand(cli.loader, 'command the-name', test_handler1) command2 = AzCliCommand(cli.loader, 'sub-command the-second-name', test_handler2) cmd_table = {'command the-name': command, 'sub-command the-second-name': command2} cli.commands_loader.command_table = cmd_table parser = AzCliCommandParser(cli) parser.load_command_table(cli.commands_loader) args = parser.parse_args('command the-name'.split()) self.assertIs(args.func, command) args = parser.parse_args('sub-command the-second-name'.split()) self.assertIs(args.func, command2) AzCliCommandParser.error = VerifyError(self,) parser.parse_args('sub-command'.split()) self.assertTrue(AzCliCommandParser.error.called)
def test_get_api_version(self): # Can get correct resource type API version cli = DummyCli() cli.cloud = Cloud('TestCloud', profile='2017-01-01-profile') test_profile = {'2017-01-01-profile': {ResourceType.MGMT_STORAGE: '2020-10-10'}} with mock.patch('azure.cli.core.profiles._shared.AZURE_API_PROFILES', test_profile): self.assertEqual(get_api_version(cli, ResourceType.MGMT_STORAGE), '2020-10-10')
def test_supported_api_version_min_max_constraint_semver(self): cli = DummyCli() cli.cloud = Cloud('TestCloud', profile='2017-01-01-profile') test_profile = {'2017-01-01-profile': {ResourceType.MGMT_KEYVAULT: '7.0'}} with mock.patch('azure.cli.core.profiles._shared.AZURE_API_PROFILES', test_profile): self.assertTrue( supported_api_version(cli, ResourceType.MGMT_KEYVAULT, min_api='6.0', max_api='8.0'))
def test_supported_api_version_min_max_constraint(self): cli = DummyCli() cli.cloud = Cloud('TestCloud', profile='2017-01-01-profile') test_profile = {'2017-01-01-profile': {ResourceType.MGMT_STORAGE: '2020-10-10'}} with mock.patch('azure.cli.core.profiles._shared.AZURE_API_PROFILES', test_profile): self.assertTrue( supported_api_version(cli, ResourceType.MGMT_STORAGE, min_api='2020-01-01', max_api='2021-01-01'))
def test_help_loads(self): from azure.cli.core.commands.arm import register_global_subscription_argument, register_ids_argument import knack.events as events parser_dict = {} cli = DummyCli() help_ctx = cli.help_cls(cli) try: cli.invoke(['-h']) except SystemExit: pass cmd_tbl = cli.invocation.commands_loader.command_table cli.invocation.parser.load_command_table(cli.invocation.commands_loader) for cmd in cmd_tbl: try: cmd_tbl[cmd].loader.command_name = cmd cmd_tbl[cmd].loader.load_arguments(cmd) except KeyError: pass cli.register_event(events.EVENT_INVOKER_POST_CMD_TBL_CREATE, register_global_subscription_argument) cli.register_event(events.EVENT_INVOKER_POST_CMD_TBL_CREATE, register_ids_argument) cli.raise_event(events.EVENT_INVOKER_CMD_TBL_LOADED, command_table=cmd_tbl) cli.invocation.parser.load_command_table(cli.invocation.commands_loader) _store_parsers(cli.invocation.parser, parser_dict) # TODO: do we want to update this as it doesn't actually load all help. # We do have a CLI linter which does indeed load all help. for name, parser in parser_dict.items(): try: help_file = GroupHelpFile(help_ctx, name, parser) if _is_group(parser) \ else CliCommandHelpFile(help_ctx, name, parser) help_file.load(parser) except Exception as ex: raise HelpAuthoringException('{}, {}'.format(name, ex))
def test_get_api_version_invalid_rt_2(self): # None is not a valid resource type cli = DummyCli() cli.cloud = Cloud('TestCloud', profile='2017-01-01-profile') test_profile = {'2017-01-01-profile': {ResourceType.MGMT_STORAGE: '2020-10-10'}} with mock.patch('azure.cli.core.profiles._shared.AZURE_API_PROFILES', test_profile): with self.assertRaises(APIVersionException): get_api_version(cli, None)
def test_get_api_version_invalid_active_profile(self): # The active profile is not in our profile dict cli = DummyCli() cli.cloud = Cloud('TestCloud', profile='not-a-real-profile') test_profile = {'2017-01-01-profile': {ResourceType.MGMT_STORAGE: '2020-10-10'}} with mock.patch('azure.cli.core.profiles._shared.AZURE_API_PROFILES', test_profile): with self.assertRaises(APIVersionException): get_api_version(cli, ResourceType.MGMT_STORAGE)
def test_client_request_id_is_refreshed_correctly(self): cli = DummyCli() cli.refresh_request_id() self.assertIn('x-ms-client-request-id', cli.data['headers']) old_id = cli.data['headers']['x-ms-client-request-id'] cli.refresh_request_id() self.assertIn('x-ms-client-request-id', cli.data['headers']) self.assertNotEquals(old_id, cli.data['headers']['x-ms-client-request-id'])
def test_when_alias_doc_is_missing(self, mock_get_active_cloud): from azure.cli.command_modules.vm._actions import load_images_from_aliases_doc p = mock.PropertyMock(side_effect=CloudEndpointNotSetException('')) mock_cloud = mock.MagicMock() type(mock_cloud.endpoints).vm_image_alias_doc = p mock_get_active_cloud.return_value = mock_cloud # assert cli_ctx = DummyCli() cli_ctx.cloud = mock_cloud with self.assertRaises(CLIError): load_images_from_aliases_doc(cli_ctx)
def test_parser_error_spellchecker(self): cli = DummyCli() main_loader = MainCommandsLoader(cli) cli.loader = main_loader cli.loader.load_command_table(None) parser = cli.parser_cls(cli) parser.load_command_table(cli.loader) logger_msgs = [] choice_lists = [] original_get_close_matches = difflib.get_close_matches def mock_log_error(_, msg): logger_msgs.append(msg) def mock_get_close_matches(*args, **kwargs): choice_lists.append(original_get_close_matches(*args, **kwargs)) # run multiple faulty commands and save error logs, as well as close matches with mock.patch('logging.Logger.error', mock_log_error), \ mock.patch('difflib.get_close_matches', mock_get_close_matches): faulty_cmd_args = [ 'test module1 --opt enum_1', 'test extension1 --opt enum_1', 'test foo_bar --opt enum_3', 'test module --opt enum_3', 'test extension --opt enum_3' ] for text in faulty_cmd_args: with self.assertRaises(SystemExit): parser.parse_args(text.split()) parser.parse_args('test module --opt enum_1'.split()) # assert the right type of error msg is logged for command vs argument parsing self.assertEqual(len(logger_msgs), 5) for msg in logger_msgs[:3]: self.assertIn("not in the", msg) self.assertIn("command group", msg) for msg in logger_msgs[3:]: self.assertIn("not a valid value for '--opt'.", msg) # assert the right choices are matched as "close". # If these don't hold, matching algorithm should be deemed flawed. for choices in choice_lists[:2]: self.assertEqual(len(choices), 1) self.assertEqual(len(choice_lists[2]), 0) for choices in choice_lists[3:]: self.assertEqual(len(choices), 2) for choice in ['enum_1', 'enum_2']: self.assertIn(choice, choices)
def mock_echo_args(command_name, parameters): from azure.cli.core.mock import DummyCli try: # TODO: continue work on this... argv = ' '.join((command_name, parameters)).split() cli = DummyCli() cli.invoke(argv) command_table = cli.invocation.commands_loader.command_table prefunc = command_table[command_name].handler command_table[command_name].handler = lambda args: args cli.invoke(argv) parsed_namespace = None # continue this too... return parsed_namespace finally: command_table[command_name].handler = prefunc
def test_register_command_from_extension(self): from azure.cli.core.commands import _load_command_loader cli = DummyCli() main_loader = MainCommandsLoader(cli) cli.loader = main_loader cmd_tbl = cli.loader.load_command_table(None) ext1 = cmd_tbl['hello noodle'] ext2 = cmd_tbl['hello world'] self.assertTrue(isinstance(ext1.command_source, ExtensionCommandSource)) self.assertFalse(ext1.command_source.overrides_command) self.assertTrue(isinstance(ext2.command_source, ExtensionCommandSource)) self.assertTrue(ext2.command_source.overrides_command)
def test_client_request_id_is_refreshed_after_execution(self): def _handler(args): return True class TestCommandsLoader(AzCommandsLoader): def load_command_table(self, args): super(TestCommandsLoader, self).load_command_table(args) self.command_table = {'test': AzCliCommand(self, 'test', _handler)} return self.command_table cli = DummyCli(commands_loader_cls=TestCommandsLoader) cli.invoke(['test']) self.assertIn('x-ms-client-request-id', cli.data['headers']) old_id = cli.data['headers']['x-ms-client-request-id'] cli.invoke(['test']) self.assertIn('x-ms-client-request-id', cli.data['headers']) self.assertNotEquals(old_id, cli.data['headers']['x-ms-client-request-id'])
def test_nargs_parameter(self): def test_handler(): pass cli = DummyCli() cli.loader = mock.MagicMock() cli.loader.cli_ctx = cli command = AzCliCommand(cli.loader, 'test command', test_handler) command.add_argument('req', '--req', required=True, nargs=2) cmd_table = {'test command': command} cli.commands_loader.command_table = cmd_table parser = AzCliCommandParser(cli) parser.load_command_table(cli.commands_loader) args = parser.parse_args('test command --req yep nope'.split()) self.assertIs(args.func, command) AzCliCommandParser.error = VerifyError(self) parser.parse_args('test command -req yep'.split()) self.assertTrue(AzCliCommandParser.error.called)
from azure.cli.core import AzCommandsLoader from azure.cli.core.commands import AzCliCommand from azure.cli.command_modules.vm.disk_encryption import (encrypt_vm, decrypt_vm, encrypt_vmss, decrypt_vmss) from azure.cli.core.profiles import get_sdk, ResourceType from azure.cli.core.mock import DummyCli NetworkProfile, StorageProfile, DataDisk, OSDisk, OperatingSystemTypes, InstanceViewStatus, \ VirtualMachineExtensionInstanceView, VirtualMachineExtension, ImageReference, DiskCreateOptionTypes, \ CachingTypes = get_sdk(DummyCli(), ResourceType.MGMT_COMPUTE, 'NetworkProfile', 'StorageProfile', 'DataDisk', 'OSDisk', 'OperatingSystemTypes', 'InstanceViewStatus', 'VirtualMachineExtensionInstanceView', 'VirtualMachineExtension', 'ImageReference', 'DiskCreateOptionTypes', 'CachingTypes', mod='models', operation_group='virtual_machines') # FIXME split into loading by RT def _get_test_cmd(): cli_ctx = DummyCli() loader = AzCommandsLoader(cli_ctx, resource_type=ResourceType.MGMT_COMPUTE) cmd = AzCliCommand(loader, 'test', None) cmd.command_kwargs = { 'resource_type': ResourceType.MGMT_COMPUTE, 'operation_group': 'virtual_machines' } cmd.cli_ctx = cli_ctx
def test_supported_api_profile_preview_constraint_in_profile(self): cli = DummyCli() cli.cloud = Cloud('TestCloud', profile='2000-01-01-profile-preview') self.assertFalse(supported_api_version(cli, PROFILE_TYPE, min_api='2000-01-01'))
def test_client_request_id_is_not_assigned_when_application_is_created(self): cli = DummyCli() self.assertNotIn('x-ms-client-request-id', cli.data['headers'])
def _get_log_analytics_workspace_id(resource_group, workspace_name): template = 'az monitor log-analytics workspace show --resource-group {} --workspace-name {}' workspace_details = execute( DummyCli(), template.format(resource_group, workspace_name)).get_output_in_json() return workspace_details["customerId"]
def test_cloud_is_registered(self): cli = DummyCli() self.assertTrue(cloud_is_registered(cli, AZURE_PUBLIC_CLOUD.name)) self.assertFalse(cloud_is_registered(cli, 'MyUnknownCloud'))
def test_endpoint_none(self): with self.assertRaises(CloudEndpointNotSetException): cli = DummyCli() cli.cloud = Cloud('AzureCloud') profile = Profile(cli_ctx=cli) profile.get_login_credentials()
def test_send_raw_requests(self, send_mock, get_raw_token_mock): if 'AZURE_HTTP_USER_AGENT' in os.environ: del os.environ[ 'AZURE_HTTP_USER_AGENT'] # Clear env var possibly added by DevOps return_val = mock.MagicMock() return_val.is_ok = True send_mock.return_value = return_val get_raw_token_mock.return_value = ("Bearer", "eyJ0eXAiOiJKV1", None), None, None cli_ctx = DummyCli() cli_ctx.data = {'command': 'rest', 'safe_params': ['method', 'uri']} test_arm_active_directory_resource_id = 'https://management.core.windows.net/' test_arm_endpoint = 'https://management.azure.com/' subscription_id = '00000001-0000-0000-0000-000000000000' arm_resource_id = '/subscriptions/{}/resourcegroups/02?api-version=2019-07-01'.format( subscription_id) full_arm_rest_url = test_arm_endpoint.rstrip('/') + arm_resource_id test_body = '{"b1": "v1"}' expected_header = { 'User-Agent': get_az_rest_user_agent(), 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Type': 'application/json', 'CommandName': 'rest', 'ParameterSetName': 'method uri', 'Content-Length': '12' } expected_header_with_auth = expected_header.copy() expected_header_with_auth['Authorization'] = 'Bearer eyJ0eXAiOiJKV1' # Test basic usage # Mock Put Blob https://docs.microsoft.com/en-us/rest/api/storageservices/put-blob # Authenticate with service SAS https://docs.microsoft.com/en-us/rest/api/storageservices/create-service-sas sas_token = ['sv=2019-02-02', '{"srt": "s"}', "{'ss': 'bf'}"] send_raw_request( cli_ctx, 'PUT', 'https://myaccount.blob.core.windows.net/mycontainer/myblob?timeout=30', uri_parameters=sas_token, body=test_body, generated_client_request_id_name=None) get_raw_token_mock.assert_not_called() request = send_mock.call_args[0][1] self.assertEqual(request.method, 'PUT') self.assertEqual( request.url, 'https://myaccount.blob.core.windows.net/mycontainer/myblob?timeout=30&sv=2019-02-02&srt=s&ss=bf' ) self.assertEqual(request.body, '{"b1": "v1"}') # Verify no Authorization header self.assertDictEqual(dict(request.headers), expected_header) self.assertEqual(send_mock.call_args[1]["verify"], not should_disable_connection_verify()) # Test Authorization header is skipped send_raw_request(cli_ctx, 'GET', full_arm_rest_url, body=test_body, skip_authorization_header=True, generated_client_request_id_name=None) get_raw_token_mock.assert_not_called() request = send_mock.call_args[0][1] self.assertDictEqual(dict(request.headers), expected_header) # Test Authorization header is already provided send_raw_request(cli_ctx, 'GET', full_arm_rest_url, body=test_body, headers={'Authorization=Basic ABCDE'}, generated_client_request_id_name=None) get_raw_token_mock.assert_not_called() request = send_mock.call_args[0][1] self.assertDictEqual(dict(request.headers), { **expected_header, 'Authorization': 'Basic ABCDE' }) # Test Authorization header is auto appended send_raw_request(cli_ctx, 'GET', full_arm_rest_url, body=test_body, generated_client_request_id_name=None) get_raw_token_mock.assert_called_with( mock.ANY, test_arm_active_directory_resource_id, subscription=subscription_id) request = send_mock.call_args[0][1] self.assertDictEqual(dict(request.headers), expected_header_with_auth) # Test ARM Subscriptions - List # https://docs.microsoft.com/en-us/rest/api/resources/subscriptions/list # /subscriptions?api-version=2020-01-01 send_raw_request(cli_ctx, 'GET', '/subscriptions?api-version=2020-01-01', body=test_body, generated_client_request_id_name=None) get_raw_token_mock.assert_called_with( mock.ANY, test_arm_active_directory_resource_id) request = send_mock.call_args[0][1] self.assertEqual( request.url, test_arm_endpoint.rstrip('/') + '/subscriptions?api-version=2020-01-01') self.assertDictEqual(dict(request.headers), expected_header_with_auth) # Test ARM Tenants - List # https://docs.microsoft.com/en-us/rest/api/resources/tenants/list # /tenants?api-version=2020-01-01 send_raw_request(cli_ctx, 'GET', '/tenants?api-version=2020-01-01', body=test_body, generated_client_request_id_name=None) get_raw_token_mock.assert_called_with( mock.ANY, test_arm_active_directory_resource_id) request = send_mock.call_args[0][1] self.assertEqual( request.url, test_arm_endpoint.rstrip('/') + '/tenants?api-version=2020-01-01') self.assertDictEqual(dict(request.headers), expected_header_with_auth) # Test ARM resource ID # /subscriptions/00000001-0000-0000-0000-000000000000/resourcegroups/02?api-version=2019-07-01 send_raw_request(cli_ctx, 'GET', arm_resource_id, body=test_body, generated_client_request_id_name=None) get_raw_token_mock.assert_called_with( mock.ANY, test_arm_active_directory_resource_id, subscription=subscription_id) request = send_mock.call_args[0][1] self.assertEqual(request.url, full_arm_rest_url) self.assertDictEqual(dict(request.headers), expected_header_with_auth) # Test full ARM URL # https://management.azure.com/subscriptions/00000001-0000-0000-0000-000000000000/resourcegroups/02?api-version=2019-07-01 send_raw_request(cli_ctx, 'GET', full_arm_rest_url) get_raw_token_mock.assert_called_with( mock.ANY, test_arm_active_directory_resource_id, subscription=subscription_id) request = send_mock.call_args[0][1] self.assertEqual(request.url, full_arm_rest_url) # Test full ARM URL with port # https://management.azure.com:443/subscriptions/00000001-0000-0000-0000-000000000000/resourcegroups/02?api-version=2019-07-01 test_arm_endpoint_with_port = 'https://management.azure.com:443/' full_arm_rest_url_with_port = test_arm_endpoint_with_port.rstrip( '/') + arm_resource_id send_raw_request(cli_ctx, 'GET', full_arm_rest_url_with_port) get_raw_token_mock.assert_called_with( mock.ANY, test_arm_active_directory_resource_id, subscription=subscription_id) request = send_mock.call_args[0][1] self.assertEqual( request.url, 'https://management.azure.com:443/subscriptions/00000001-0000-0000-0000-000000000000/resourcegroups/02?api-version=2019-07-01' ) # Test non-ARM APIs # Test AD Graph API https://graph.windows.net/ url = 'https://graph.windows.net/00000002-0000-0000-0000-000000000000/applications/00000003-0000-0000-0000-000000000000?api-version=1.6' send_raw_request(cli_ctx, 'PATCH', url, body=test_body, generated_client_request_id_name=None) get_raw_token_mock.assert_called_with(mock.ANY, 'https://graph.windows.net/') request = send_mock.call_args[0][1] self.assertEqual(request.method, 'PATCH') self.assertEqual(request.url, url) # Test MS Graph API https://graph.microsoft.com/beta/appRoleAssignments/01 url = 'https://graph.microsoft.com/beta/appRoleAssignments/01' send_raw_request(cli_ctx, 'PATCH', url, body=test_body, generated_client_request_id_name=None) get_raw_token_mock.assert_called_with(mock.ANY, 'https://graph.microsoft.com/') request = send_mock.call_args[0][1] self.assertEqual(request.method, 'PATCH') self.assertEqual(request.url, url) # Test custom case-insensitive User-Agent with mock.patch.dict('os.environ', {'AZURE_HTTP_USER_AGENT': "env-ua"}): send_raw_request(cli_ctx, 'GET', full_arm_rest_url, headers={'user-agent=ARG-UA'}) get_raw_token_mock.assert_called_with( mock.ANY, test_arm_active_directory_resource_id, subscription=subscription_id) request = send_mock.call_args[0][1] self.assertEqual(request.headers['User-Agent'], get_az_rest_user_agent() + ' env-ua ARG-UA')
def test_hub_monitor_events(self): for cg in LIVE_CONSUMER_GROUPS: self.cmd( "az iot hub consumer-group create --hub-name {} --resource-group {} --name {}" .format(LIVE_HUB, LIVE_RG, cg), checks=[self.check("name", cg)], ) from azext_iot.operations.hub import iot_device_send_message from azext_iot._factory import iot_hub_service_factory from azure.cli.core.mock import DummyCli cli_ctx = DummyCli() client = iot_hub_service_factory(cli_ctx) device_count = 10 device_ids = self.generate_device_names(device_count) # Test with invalid connection string self.cmd( "iot hub monitor-events -t 1 -y --login {}".format(LIVE_HUB_CS + "zzz"), expect_failure=True, ) # Create and Simulate Devices for i in range(device_count): self.cmd( "iot hub device-identity create -d {} -n {} -g {}".format( device_ids[i], LIVE_HUB, LIVE_RG), checks=[self.check("deviceId", device_ids[i])], ) enqueued_time = calculate_millisec_since_unix_epoch_utc() for i in range(device_count): execute_onthread( method=iot_device_send_message, args=[ client, device_ids[i], LIVE_HUB, '{\r\n"payload_data1":"payload_value1"\r\n}', "$.mid=12345;key0=value0;key1=1", 1, LIVE_RG, None, 0, ], max_runs=1, ) # Monitor events for all devices and include sys, anno, app self.command_execute_assert( "iot hub monitor-events -n {} -g {} --cg {} --et {} -t 10 -y -p sys anno app" .format(LIVE_HUB, LIVE_RG, LIVE_CONSUMER_GROUPS[0], enqueued_time), device_ids + [ "system", "annotations", "application", '"message_id": "12345"', '"key0": "value0"', '"key1": "1"', ], ) # Monitor events for a single device self.command_execute_assert( "iot hub monitor-events -n {} -g {} -d {} --cg {} --et {} -t 10 -y -p all" .format(LIVE_HUB, LIVE_RG, device_ids[0], LIVE_CONSUMER_GROUPS[1], enqueued_time), [ device_ids[0], "system", "annotations", "application", '"message_id": "12345"', '"key0": "value0"', '"key1": "1"', ], ) # Monitor events with device-id wildcards self.command_execute_assert( "iot hub monitor-events -n {} -g {} -d {} --et {} -t 10 -y -p sys anno app" .format(LIVE_HUB, LIVE_RG, PREFIX_DEVICE + "*", enqueued_time), device_ids, ) # Monitor events for specific devices using query language device_subset_include = device_ids[:device_count // 2] device_include_string = ", ".join( ["'" + deviceId + "'" for deviceId in device_subset_include]) query_string = "select * from devices where deviceId in [{}]".format( device_include_string) self.command_execute_assert( 'iot hub monitor-events -n {} -g {} --device-query "{}" --et {} -t 10 -y -p sys anno app' .format(LIVE_HUB, LIVE_RG, query_string, enqueued_time), device_subset_include, ) # Expect failure for excluded devices device_subset_exclude = device_ids[device_count // 2:] with pytest.raises(Exception): self.command_execute_assert( 'iot hub monitor-events -n {} -g {} --device-query "{}" --et {} -t 10 -y -p sys anno app' .format(LIVE_HUB, LIVE_RG, query_string, enqueued_time), device_subset_exclude, ) # Monitor events with --login parameter self.command_execute_assert( "iot hub monitor-events -t 10 -y -p all --cg {} --et {} --login {}" .format(LIVE_CONSUMER_GROUPS[2], enqueued_time, LIVE_HUB_CS), device_ids, ) enqueued_time = calculate_millisec_since_unix_epoch_utc() # Send messages that have JSON payload, but do not pass $.ct property execute_onthread( method=iot_device_send_message, args=[ client, device_ids[i], LIVE_HUB, '{\r\n"payload_data1":"payload_value1"\r\n}', "", 1, LIVE_RG, None, 1, ], max_runs=1, ) # Monitor messages for ugly JSON output self.command_execute_assert( "iot hub monitor-events -n {} -g {} --cg {} --et {} -t 10 -y". format(LIVE_HUB, LIVE_RG, LIVE_CONSUMER_GROUPS[0], enqueued_time), ["\\r\\n"], ) # Monitor messages and parse payload as JSON with the --ct parameter self.command_execute_assert( "iot hub monitor-events -n {} -g {} --cg {} --et {} -t 10 --ct application/json -y" .format(LIVE_HUB, LIVE_RG, LIVE_CONSUMER_GROUPS[1], enqueued_time), ['"payload_data1": "payload_value1"'], ) enqueued_time = calculate_millisec_since_unix_epoch_utc() # Send messages that have JSON payload and have $.ct property execute_onthread( method=iot_device_send_message, args=[ client, device_ids[i], LIVE_HUB, '{\r\n"payload_data1":"payload_value1"\r\n}', "$.ct=application/json", 1, LIVE_RG, ], max_runs=1, ) # Monitor messages for pretty JSON output self.command_execute_assert( "iot hub monitor-events -n {} -g {} --cg {} --et {} -t 10 -y". format(LIVE_HUB, LIVE_RG, LIVE_CONSUMER_GROUPS[0], enqueued_time), ['"payload_data1": "payload_value1"'], ) # Monitor messages with yaml output self.command_execute_assert( "iot hub monitor-events -n {} -g {} --cg {} --et {} -t 10 -y -o yaml" .format(LIVE_HUB, LIVE_RG, LIVE_CONSUMER_GROUPS[1], enqueued_time), ["payload_data1: payload_value1"], ) enqueued_time = calculate_millisec_since_unix_epoch_utc() # Send messages that have improperly formatted JSON payload and a $.ct property execute_onthread( method=iot_device_send_message, args=[ client, device_ids[i], LIVE_HUB, '{\r\n"payload_data1""payload_value1"\r\n}', "$.ct=application/json", 1, LIVE_RG, ], max_runs=1, ) # Monitor messages to ensure it returns improperly formatted JSON self.command_execute_assert( "iot hub monitor-events -n {} -g {} --cg {} --et {} -t 10 -y". format(LIVE_HUB, LIVE_RG, LIVE_CONSUMER_GROUPS[0], enqueued_time), ['{\\r\\n\\"payload_data1\\"\\"payload_value1\\"\\r\\n}'], ) for cg in LIVE_CONSUMER_GROUPS: self.cmd( "az iot hub consumer-group delete --hub-name {} --resource-group {} --name {}" .format(LIVE_HUB, LIVE_RG, cg), expect_failure=False, )
def setUp(self): from knack.help_files import helps self.test_cli = DummyCli() self.helps = helps self._tempdirName = tempfile.mkdtemp(prefix="help_test_temp_dir_")
def setUp(self): from azure.cli.core.profiles._shared import AZURE_API_PROFILES self.test_cli = DummyCli() self.all_profiles = AZURE_API_PROFILES self.all_profiles_str = " {} ".format(" , ".join(AZURE_API_PROFILES.keys()))
class TestHelpLoads(unittest.TestCase): def setUp(self): from knack.help_files import helps self.test_cli = DummyCli() self.helps = helps self._tempdirName = tempfile.mkdtemp(prefix="help_test_temp_dir_") def tearDown(self): # delete temporary directory to be used for temp files. shutil.rmtree(self._tempdirName) self.helps.clear() def set_help_py(self): self.helps['test'] = """ type: group short-summary: Foo Bar Group long-summary: Foo Bar Baz Group is a fun group """ self.helps['test alpha'] = """ type: command short-summary: Foo Bar Command long-summary: Foo Bar Baz Command is a fun command parameters: - name: --arg1 -a short-summary: A short summary populator-commands: - az foo bar - az bar baz - name: ARG4 # Note: positional's are discouraged in the CLI. short-summary: Positional parameter. Not required examples: - name: Alpha Example text: az test alpha --arg1 a --arg2 b --arg3 c supported-profiles: 2018-03-01-hybrid, latest - name: A simple example unsupported on latest text: az test alpha --arg1 a --arg2 b unsupported-profiles: 2017-03-09-profile """ def set_help_yaml(self): yaml_help = """ version: 1 content: - group: name: test summary: Group yaml summary description: Group yaml description. A.K.A long description links: - title: Azure Test Docs url: "https://docs.microsoft.com/azure/test" - url: "https://aka.ms/just-a-url" - command: name: test alpha summary: Command yaml summary description: Command yaml description. A.K.A long description links: - title: Azure Test Alpha Docs url: "https://docs.microsoft.com/azure/test/alpha" - url: "https://aka.ms/just-a-long-url" arguments: - name: --arg2 # we do not specify the short option in the name. summary: Arg 2's summary description: A true description of this parameter. value-sources: - string: "Number range: -5.0 to 5.0" - link: url: https://www.foo.com title: foo - link: command: az test show title: Show test details - name: ARG4 # Note: positional's are discouraged in the CLI. summary: Arg4's summary, yaml. Positional arg, not required examples: - summary: A simple example description: More detail on the simple example. command: az test alpha --arg1 apple --arg2 ball --arg3 cat supported-profiles: 2018-03-01-hybrid, latest - summary: Another example unsupported on latest description: More detail on the unsupported example. command: az test alpha --arg1 apple --arg2 ball unsupported-profiles: 2017-03-09-profile """ return self._create_new_temp_file(yaml_help, suffix="help.yaml") def set_help_json(self): json_help = """ { "version": 2, "content": [ { "group": { "name": "test", "short": "Group json summary", "long": "Group json description. A.K.A long description", "hyper-links": [ { "title": "Azure Json Test Docs", "url": "https://docs.microsoft.com/azure/test" }, { "url": "https://aka.ms/just-a-url" } ] } }, { "command": { "name": "test alpha", "short": "Command json summary", "long": "Command json description. A.K.A long description", "hyper-links": [ { "title": "Azure Json Test Alpha Docs", "url": "https://docs.microsoft.com/azure/test/alpha" }, { "url": "https://aka.ms/just-a-long-url" } ], "arguments": [ { "name": "--arg3", "short": "Arg 3's json summary", "long": "A truly true description of this parameter.", "sources": [ { "string": "Number range: 0 to 10" }, { "link": { "url": "https://www.foo-json.com", "title": "foo-json" } }, { "link": { "command": "az test show", "title": "Show test details. Json file" } } ] }, { "name": "ARG4", "summary": "Arg4's summary, json. Positional arg, not required" } ], "examples": [ { "summary": "A simple example from json", "description": "More detail on the simple example.", "command": "az test alpha --arg1 alpha --arg2 beta --arg3 chi", "supported-profiles": "2018-03-01-hybrid, latest" } ] } } ] } """ return self._create_new_temp_file(json_help, suffix="help.json") # Mock logic in core.MainCommandsLoader.load_command_table for retrieving installed modules. @mock.patch('pkgutil.iter_modules', side_effect=lambda x: [(None, MOCKED_COMMAND_LOADER_MOD, None)]) @mock.patch('azure.cli.core.commands._load_command_loader', side_effect=mock_load_command_loader) def test_basic(self, mocked_load, mocked_pkg_util): with self.assertRaises(SystemExit): self.test_cli.invoke(["test", "alpha", "-h"]) # Mock logic in core.MainCommandsLoader.load_command_table for retrieving installed modules. @mock.patch('pkgutil.iter_modules', side_effect=lambda x: [(None, MOCKED_COMMAND_LOADER_MOD, None)]) @mock.patch('azure.cli.core.commands._load_command_loader', side_effect=mock_load_command_loader) def test_load_from_help_py(self, mocked_load, mocked_pkg_util): self.set_help_py() create_invoker_and_load_cmds_and_args(self.test_cli) group_help_obj = next((help for help in get_all_help(self.test_cli) if help.command == "test"), None) command_help_obj = next((help for help in get_all_help(self.test_cli) if help.command == "test alpha"), None) # Test that group and command help are successfully displayed. with self.assertRaises(SystemExit): self.test_cli.invoke(["test", "-h"]) with self.assertRaises(SystemExit): self.test_cli.invoke(["test", "alpha", "-h"]) # Test group help self.assertIsNotNone(group_help_obj) self.assertEqual(group_help_obj.short_summary, "Foo Bar Group.") self.assertEqual(group_help_obj.long_summary, "Foo Bar Baz Group is a fun group.") # Test command help self.assertIsNotNone(command_help_obj) self.assertEqual(command_help_obj.short_summary, "Foo Bar Command.") self.assertEqual(command_help_obj.long_summary, "Foo Bar Baz Command is a fun command.") # test that parameters and help are loaded from command function docstring, argument registry help and help.py obj_param_dict = {param.name: param for param in command_help_obj.parameters} param_name_set = {"--arg1 -a", "--arg2 -b", "--arg3", "ARG4"} self.assertTrue(set(obj_param_dict.keys()).issuperset(param_name_set)) self.assertEqual(obj_param_dict["--arg3"].short_summary, "Arg3's docstring help text.") self.assertEqual(obj_param_dict["ARG4"].short_summary, "Positional parameter. Not required.") self.assertEqual(obj_param_dict["--arg1 -a"].short_summary, "A short summary.") self.assertEqual(obj_param_dict["--arg1 -a"].short_summary, "A short summary.") self.assertEqual(obj_param_dict["--arg1 -a"].value_sources[0]['link']['command'], "az foo bar") self.assertEqual(obj_param_dict["--arg1 -a"].value_sources[1]['link']['command'], "az bar baz") if self.test_cli.cloud.profile in ['2018-03-01-hybrid', 'latest']: self.assertEqual(command_help_obj.examples[0].short_summary, "Alpha Example") self.assertEqual(command_help_obj.examples[0].command, "az test alpha --arg1 a --arg2 b --arg3 c") self.assertEqual(command_help_obj.examples[0].supported_profiles, "2018-03-01-hybrid, latest") self.assertEqual(command_help_obj.examples[0].unsupported_profiles, None) self.assertEqual(command_help_obj.examples[1].supported_profiles, None) self.assertEqual(command_help_obj.examples[1].unsupported_profiles, "2017-03-09-profile") if self.test_cli.cloud.profile == '2019-03-01-hybrid': self.assertEqual(len(command_help_obj.examples), 1) self.assertEqual(command_help_obj.examples[0].short_summary, "A simple example unsupported on latest") self.assertEqual(command_help_obj.examples[0].command, "az test alpha --arg1 a --arg2 b") self.assertEqual(command_help_obj.examples[0].unsupported_profiles, '2017-03-09-profile') if self.test_cli.cloud.profile == '2017-03-09-profile': self.assertEqual(len(command_help_obj.examples), 0) @mock.patch('pkgutil.iter_modules', side_effect=lambda x: [(None, MOCKED_COMMAND_LOADER_MOD, None)]) @mock.patch('azure.cli.core.commands._load_command_loader', side_effect=mock_load_command_loader) def test_load_from_help_yaml(self, mocked_load, mocked_pkg_util): # setup help.py and help.yaml help. self.set_help_py() yaml_path = self.set_help_yaml() create_invoker_and_load_cmds_and_args(self.test_cli) # mock logic in core._help_loaders for retrieving yaml file from loader path. expected_arg = self.test_cli.invocation.commands_loader.cmd_to_loader_map['test alpha'][0].__class__ with mock.patch('inspect.getfile', side_effect=get_mocked_inspect_getfile(expected_arg, yaml_path)): group_help_obj = next((help for help in get_all_help(self.test_cli) if help.command == "test"), None) command_help_obj = next((help for help in get_all_help(self.test_cli) if help.command == "test alpha"), None) # pylint: disable=line-too-long # Test that group and command help are successfully displayed. with self.assertRaises(SystemExit): self.test_cli.invoke(["test", "-h"]) with self.assertRaises(SystemExit): self.test_cli.invoke(["test", "alpha", "-h"]) # Test group help self.assertIsNotNone(group_help_obj) self.assertEqual(group_help_obj.short_summary, "Group yaml summary.") self.assertEqual(group_help_obj.long_summary, "Group yaml description. A.K.A long description.") self.assertEqual(group_help_obj.links[0], {"title": "Azure Test Docs", "url": "https://docs.microsoft.com/azure/test"}) self.assertEqual(group_help_obj.links[1], {"url": "https://aka.ms/just-a-url"}) # Test command help self.assertIsNotNone(command_help_obj) self.assertEqual(command_help_obj.short_summary, "Command yaml summary.") self.assertEqual(command_help_obj.long_summary, "Command yaml description. A.K.A long description.") self.assertEqual(command_help_obj.links[0], {"title": "Azure Test Alpha Docs", "url": "https://docs.microsoft.com/azure/test/alpha"}) self.assertEqual(command_help_obj.links[1], {"url": "https://aka.ms/just-a-long-url"}) # test that parameters and help are loaded from command function docstring, argument registry help and help.yaml obj_param_dict = {param.name: param for param in command_help_obj.parameters} param_name_set = {"--arg1 -a", "--arg2 -b", "--arg3", "ARG4"} self.assertTrue(set(obj_param_dict.keys()).issuperset(param_name_set)) self.assertEqual(obj_param_dict["--arg1 -a"].short_summary, "A short summary.") self.assertEqual(obj_param_dict["--arg3"].short_summary, "Arg3's docstring help text.") self.assertEqual(obj_param_dict["ARG4"].short_summary, "Arg4's summary, yaml. Positional arg, not required.") self.assertEqual(obj_param_dict["--arg2 -b"].short_summary, "Arg 2's summary.") self.assertEqual(obj_param_dict["--arg2 -b"].long_summary, "A true description of this parameter.") self.assertEqual(obj_param_dict["--arg2 -b"].value_sources[0], {"string": "Number range: -5.0 to 5.0"}) self.assertEqual(obj_param_dict["--arg2 -b"].value_sources[1]['link'], {"url": "https://www.foo.com", "title": "foo"}) self.assertEqual(obj_param_dict["--arg2 -b"].value_sources[2]['link'], {"command": "az test show", "title": "Show test details"}) if self.test_cli.cloud.profile in ['2018-03-01-hybrid', 'latest']: self.assertEqual(command_help_obj.examples[0].short_summary, "A simple example") self.assertEqual(command_help_obj.examples[0].long_summary, "More detail on the simple example.") self.assertEqual(command_help_obj.examples[0].command, "az test alpha --arg1 apple --arg2 ball --arg3 cat") self.assertEqual(command_help_obj.examples[0].supported_profiles, "2018-03-01-hybrid, latest") self.assertEqual(command_help_obj.examples[0].unsupported_profiles, None) self.assertEqual(command_help_obj.examples[1].supported_profiles, None) self.assertEqual(command_help_obj.examples[1].unsupported_profiles, "2017-03-09-profile") if self.test_cli.cloud.profile == '2019-03-01-hybrid': self.assertEqual(len(command_help_obj.examples), 1) self.assertEqual(command_help_obj.examples[0].short_summary, "Another example unsupported on latest") self.assertEqual(command_help_obj.examples[0].command, "az test alpha --arg1 apple --arg2 ball") self.assertEqual(command_help_obj.examples[0].unsupported_profiles, '2017-03-09-profile') if self.test_cli.cloud.profile == '2017-03-09-profile': self.assertEqual(len(command_help_obj.examples), 0) @mock.patch('inspect.getmembers', side_effect=mock_inspect_getmembers) @mock.patch('pkgutil.iter_modules', side_effect=lambda x: [(None, MOCKED_COMMAND_LOADER_MOD, None)]) @mock.patch('azure.cli.core.commands._load_command_loader', side_effect=mock_load_command_loader) def test_load_from_help_json(self, mocked_load, mocked_pkg_util, mocked_getmembers): # setup help.py, help.yaml and help.json self.set_help_py() path = self.set_help_yaml() # either (yaml or json) path should work. As both files are in the same temp dir. self.set_help_json() create_invoker_and_load_cmds_and_args(self.test_cli) # mock logic in core._help_loaders for retrieving yaml file from loader path. expected_arg = self.test_cli.invocation.commands_loader.cmd_to_loader_map['test alpha'][0].__class__ with mock.patch('inspect.getfile', side_effect=get_mocked_inspect_getfile(expected_arg, path)): group_help_obj = next((help for help in get_all_help(self.test_cli) if help.command == "test"), None) command_help_obj = next((help for help in get_all_help(self.test_cli) if help.command == "test alpha"), None) # Test that group and command help are successfully displayed. with self.assertRaises(SystemExit): self.test_cli.invoke(["test", "-h"]) with self.assertRaises(SystemExit): self.test_cli.invoke(["test", "alpha", "-h"]) # Test group help self.assertIsNotNone(group_help_obj) self.assertEqual(group_help_obj.short_summary, "Group json summary.") self.assertEqual(group_help_obj.long_summary, "Group json description. A.K.A long description.") self.assertEqual(group_help_obj.links[0], {"title": "Azure Json Test Docs", "url": "https://docs.microsoft.com/azure/test"}) self.assertEqual(group_help_obj.links[1], {"url": "https://aka.ms/just-a-url"}) # Test command help self.assertIsNotNone(command_help_obj) self.assertEqual(command_help_obj.short_summary, "Command json summary.") self.assertEqual(command_help_obj.long_summary, "Command json description. A.K.A long description.") self.assertEqual(command_help_obj.links[0], {"title": "Azure Json Test Alpha Docs", "url": "https://docs.microsoft.com/azure/test/alpha"}) self.assertEqual(command_help_obj.links[1], {"url": "https://aka.ms/just-a-long-url"}) # test that parameters and help are loaded from command function docstring, argument registry help and help.yaml obj_param_dict = {param.name: param for param in command_help_obj.parameters} param_name_set = {"--arg1 -a", "--arg2 -b", "--arg3", "ARG4"} self.assertTrue(set(obj_param_dict.keys()).issuperset(param_name_set)) self.assertEqual(obj_param_dict["--arg3"].short_summary, "Arg 3's json summary.") self.assertEqual(obj_param_dict["--arg3"].long_summary, "A truly true description of this parameter.") self.assertEqual(obj_param_dict["--arg3"].value_sources[0], {"string": "Number range: 0 to 10"}) self.assertEqual(obj_param_dict["--arg3"].value_sources[1]['link'], {"url": "https://www.foo-json.com", "title": "foo-json"}) self.assertEqual(obj_param_dict["--arg3"].value_sources[2]['link'], {"command": "az test show", "title": "Show test details. Json file"}) if self.test_cli.cloud.profile in ['2018-03-01-hybrid', 'latest']: self.assertEqual(command_help_obj.examples[0].short_summary, "A simple example from json") self.assertEqual(command_help_obj.examples[0].long_summary, "More detail on the simple example.") self.assertEqual(command_help_obj.examples[0].command, "az test alpha --arg1 alpha --arg2 beta --arg3 chi") self.assertEqual(command_help_obj.examples[0].supported_profiles, "2018-03-01-hybrid, latest") if self.test_cli.cloud.profile == '2019-03-01-hybrid': # only supported example here self.assertEqual(len(command_help_obj.examples), 0) if self.test_cli.cloud.profile == '2017-03-09-profile': self.assertEqual(len(command_help_obj.examples), 0) # validate other parameters, which have help from help.py and help.yamls self.assertEqual(obj_param_dict["--arg1 -a"].short_summary, "A short summary.") self.assertEqual(obj_param_dict["--arg2 -b"].short_summary, "Arg 2's summary.") self.assertEqual(obj_param_dict["ARG4"].short_summary, "Arg4's summary, yaml. Positional arg, not required.") # arg2's help from help.yaml still preserved. self.assertEqual(obj_param_dict["--arg2 -b"].long_summary, "A true description of this parameter.") self.assertEqual(obj_param_dict["--arg2 -b"].value_sources[0], {"string": "Number range: -5.0 to 5.0"}) self.assertEqual(obj_param_dict["--arg2 -b"].value_sources[1]['link'], {"url": "https://www.foo.com", "title": "foo"}) self.assertEqual(obj_param_dict["--arg2 -b"].value_sources[2]['link'], {"command": "az test show", "title": "Show test details"}) # create a temporary file in the temp dir. Return the path of the file. def _create_new_temp_file(self, data, suffix=""): with tempfile.NamedTemporaryFile(mode='w', dir=self._tempdirName, delete=False, suffix=suffix) as f: f.write(data) return f.name
def test_help_loads(self): from azure.cli.core.commands.arm import register_global_subscription_argument, register_ids_argument import knack.events as events parser_dict = {} cli = DummyCli() help_ctx = cli.help_cls(cli) try: cli.invoke(['-h']) except SystemExit: pass cmd_tbl = cli.invocation.commands_loader.command_table cli.invocation.parser.load_command_table(cli.invocation.commands_loader) for cmd in cmd_tbl: try: cmd_tbl[cmd].loader.command_name = cmd cmd_tbl[cmd].loader.load_arguments(cmd) except KeyError: pass cli.register_event(events.EVENT_INVOKER_POST_CMD_TBL_CREATE, register_global_subscription_argument) cli.register_event(events.EVENT_INVOKER_POST_CMD_TBL_CREATE, register_ids_argument) cli.raise_event(events.EVENT_INVOKER_CMD_TBL_LOADED, command_table=cmd_tbl) cli.invocation.parser.load_command_table(cli.invocation.commands_loader) _store_parsers(cli.invocation.parser, parser_dict) # TODO: do we want to update this as it doesn't actually load all help. # We do have a CLI linter which does indeed load all help. for name, parser in parser_dict.items(): try: help_file = GroupHelpFile(help_ctx, name, parser) if _is_group(parser) \ else CliCommandHelpFile(help_ctx, name, parser) help_file.load(parser) except Exception as ex: raise HelpAuthoringException('{}, {}'.format(name, ex))
def test_uamqp_device_messaging(self): device_count = 1 device_ids = self.generate_device_names(device_count) self.cmd( "iot hub device-identity create -d {} -n {} -g {}".format( device_ids[0], LIVE_HUB, LIVE_RG), checks=[self.check("deviceId", device_ids[0])], ) test_body = str(uuid4()) test_props = "key0={};key1={}".format(str(uuid4()), str(uuid4())) test_cid = str(uuid4()) test_mid = str(uuid4()) test_ct = "text/plain" test_et = int((time() + 3600) * 1000) # milliseconds since epoch test_ce = "utf8" self.kwargs["c2d_json_send_data"] = json.dumps({"data": str(uuid4())}) # Send C2D message self.cmd( """iot device c2d-message send -d {} -n {} -g {} --data '{}' --cid {} --mid {} --ct {} --expiry {} --ce {} --props {}""".format( device_ids[0], LIVE_HUB, LIVE_RG, test_body, test_cid, test_mid, test_ct, test_et, test_ce, test_props, ), checks=self.is_empty(), ) result = self.cmd( "iot device c2d-message receive -d {} --hub-name {} -g {}".format( device_ids[0], LIVE_HUB, LIVE_RG)).get_output_in_json() assert result["data"] == test_body system_props = result["properties"]["system"] assert system_props["ContentEncoding"] == test_ce assert system_props["ContentType"] == test_ct assert system_props["iothub-correlationid"] == test_cid assert system_props["iothub-messageid"] == test_mid assert system_props["iothub-expiry"] assert system_props[ "iothub-to"] == "/devices/{}/messages/devicebound".format( device_ids[0]) # Ack is tested in message feedback tests assert system_props["iothub-ack"] == "none" app_props = result["properties"]["app"] assert app_props == validate_key_value_pairs(test_props) # Implicit etag assertion etag = result["etag"] self.cmd( "iot device c2d-message complete -d {} --hub-name {} -g {} --etag {}" .format(device_ids[0], LIVE_HUB, LIVE_RG, etag), checks=self.is_empty(), ) # Send C2D message via --login + application/json content ype test_ct = "application/json" test_mid = str(uuid4()) self.cmd( """iot device c2d-message send -d {} --login {} --data '{}' --cid {} --mid {} --ct {} --expiry {} --ce {} --ack positive --props {}""".format( device_ids[0], LIVE_HUB_CS, "{c2d_json_send_data}", test_cid, test_mid, test_ct, test_et, test_ce, test_props, ), checks=self.is_empty(), ) result = self.cmd( "iot device c2d-message receive -d {} --login {}".format( device_ids[0], LIVE_HUB_CS)).get_output_in_json() assert result["data"] == self.kwargs["c2d_json_send_data"] system_props = result["properties"]["system"] assert system_props["ContentEncoding"] == test_ce assert system_props["ContentType"] == test_ct assert system_props["iothub-correlationid"] == test_cid assert system_props["iothub-messageid"] == test_mid assert system_props["iothub-expiry"] assert system_props[ "iothub-to"] == "/devices/{}/messages/devicebound".format( device_ids[0]) assert system_props["iothub-ack"] == "positive" app_props = result["properties"]["app"] assert app_props == validate_key_value_pairs(test_props) etag = result["etag"] self.cmd( "iot device c2d-message reject -d {} --etag {} --login {}".format( device_ids[0], etag, LIVE_HUB_CS), checks=self.is_empty(), ) # Test waiting for ack from c2d send from azext_iot.operations.hub import iot_simulate_device from azext_iot._factory import iot_hub_service_factory from azure.cli.core.mock import DummyCli cli_ctx = DummyCli() client = iot_hub_service_factory(cli_ctx) token, thread = execute_onthread( method=iot_simulate_device, args=[ client, device_ids[0], LIVE_HUB, "complete", "Ping from c2d ack wait test", 2, 5, "http", ], max_runs=4, return_handle=True, ) self.cmd( "iot device c2d-message send -d {} --ack {} --login {} --wait -y". format(device_ids[0], "full", LIVE_HUB_CS)) token.set() thread.join() # Error - invalid wait when no ack requested self.cmd( "iot device c2d-message send -d {} --login {} --wait -y".format( device_ids[0], LIVE_HUB_CS), expect_failure=True, ) # Error - content-type is application/json but data is not. self.cmd( "iot device c2d-message send -d {} --login {} --ct application/json --data notjson" .format(device_ids[0], LIVE_HUB_CS), expect_failure=True, ) # Error - expiry is in the past. self.cmd( "iot device c2d-message send -d {} --login {} --expiry {}".format( device_ids[0], LIVE_HUB_CS, int(time() * 1000)), expect_failure=True, )
def test_supported_api_profile_min_max_constraint(self): cli = DummyCli() cli.cloud = Cloud('TestCloud', profile='2000-01-01-profile') self.assertTrue(supported_api_version(cli, PROFILE_TYPE, min_api='2000-01-01', max_api='2000-01-01'))
def __init__(self, *args, **kwargs): super(FeedbackTest, self).__init__(*args, **kwargs) from azure.cli.core.mock import DummyCli from azext_interactive.azclishell.app import AzInteractiveShell self.norm_update = fh.update_frequency self.shell_ctx = AzInteractiveShell(DummyCli(), None)
def test_supported_api_version_min_constraint_not_supported_mixed_type(self): cli = DummyCli() cli.cloud = Cloud('TestCloud', profile='2017-01-01-profile') test_profile = {'2017-01-01-profile': {ResourceType.MGMT_STORAGE: '2016-06-04'}} with mock.patch('azure.cli.core.profiles._shared.AZURE_API_PROFILES', test_profile): self.assertFalse(supported_api_version(cli, ResourceType.MGMT_STORAGE, min_api='8.0'))
def test_endpoint_none(self): with self.assertRaises(CloudEndpointNotSetException): cli = DummyCli() cli.cloud = Cloud('AzureCloud') profile = Profile(cli_ctx=cli) profile.get_login_credentials()
def test_remove_known_cloud(self): cli = DummyCli() with mock.patch('azure.cli.core.cloud.CLOUD_CONFIG_FILE', tempfile.mkstemp()[1]): with self.assertRaises(CannotUnregisterCloudException): remove_cloud(cli, AZURE_PUBLIC_CLOUD.name)
class TestHelpLoads(unittest.TestCase): def setUp(self): from knack.help_files import helps self.test_cli = DummyCli() self.helps = helps self._tempdirName = tempfile.mkdtemp(prefix="help_test_temp_dir_") def tearDown(self): # delete temporary directory to be used for temp files. shutil.rmtree(self._tempdirName) self.helps.clear() def set_help_py(self): self.helps['test'] = """ type: group short-summary: Foo Bar Group long-summary: Foo Bar Baz Group is a fun group """ self.helps['test alpha'] = """ type: command short-summary: Foo Bar Command long-summary: Foo Bar Baz Command is a fun command parameters: - name: --arg1 -a short-summary: A short summary populator-commands: - az foo bar - az bar baz - name: ARG4 # Note: positional's are discouraged in the CLI. short-summary: Positional parameter. Not required examples: - name: Alpha Example text: az test alpha --arg1 a --arg2 b --arg3 c supported-profiles: 2018-03-01-hybrid, latest - name: A simple example unsupported on latest text: az test alpha --arg1 a --arg2 b unsupported-profiles: 2017-03-09-profile """ def set_help_yaml(self): yaml_help = """ version: 1 content: - group: name: test summary: Group yaml summary description: Group yaml description. A.K.A long description links: - title: Azure Test Docs url: "https://docs.microsoft.com/en-us/azure/test" - url: "https://aka.ms/just-a-url" - command: name: test alpha summary: Command yaml summary description: Command yaml description. A.K.A long description links: - title: Azure Test Alpha Docs url: "https://docs.microsoft.com/en-us/azure/test/alpha" - url: "https://aka.ms/just-a-long-url" arguments: - name: --arg2 # we do not specify the short option in the name. summary: Arg 2's summary description: A true description of this parameter. value-sources: - string: "Number range: -5.0 to 5.0" - link: url: https://www.foo.com title: foo - link: command: az test show title: Show test details - name: ARG4 # Note: positional's are discouraged in the CLI. summary: Arg4's summary, yaml. Positional arg, not required examples: - summary: A simple example description: More detail on the simple example. command: az test alpha --arg1 apple --arg2 ball --arg3 cat supported-profiles: 2018-03-01-hybrid, latest - summary: Another example unsupported on latest description: More detail on the unsupported example. command: az test alpha --arg1 apple --arg2 ball unsupported-profiles: 2017-03-09-profile """ return self._create_new_temp_file(yaml_help, suffix="help.yaml") def set_help_json(self): json_help = """ { "version": 2, "content": [ { "group": { "name": "test", "short": "Group json summary", "long": "Group json description. A.K.A long description", "hyper-links": [ { "title": "Azure Json Test Docs", "url": "https://docs.microsoft.com/en-us/azure/test" }, { "url": "https://aka.ms/just-a-url" } ] } }, { "command": { "name": "test alpha", "short": "Command json summary", "long": "Command json description. A.K.A long description", "hyper-links": [ { "title": "Azure Json Test Alpha Docs", "url": "https://docs.microsoft.com/en-us/azure/test/alpha" }, { "url": "https://aka.ms/just-a-long-url" } ], "arguments": [ { "name": "--arg3", "short": "Arg 3's json summary", "long": "A truly true description of this parameter.", "sources": [ { "string": "Number range: 0 to 10" }, { "link": { "url": "https://www.foo-json.com", "title": "foo-json" } }, { "link": { "command": "az test show", "title": "Show test details. Json file" } } ] }, { "name": "ARG4", "summary": "Arg4's summary, json. Positional arg, not required" } ], "examples": [ { "summary": "A simple example from json", "description": "More detail on the simple example.", "command": "az test alpha --arg1 alpha --arg2 beta --arg3 chi", "supported-profiles": "2018-03-01-hybrid, latest" } ] } } ] } """ return self._create_new_temp_file(json_help, suffix="help.json") # Mock logic in core.MainCommandsLoader.load_command_table for retrieving installed modules. @mock.patch('pkgutil.iter_modules', side_effect=lambda x: [(None, MOCKED_COMMAND_LOADER_MOD, None)]) @mock.patch('azure.cli.core.commands._load_command_loader', side_effect=mock_load_command_loader) def test_basic(self, mocked_load, mocked_pkg_util): with self.assertRaises(SystemExit): self.test_cli.invoke(["test", "alpha", "-h"]) # Mock logic in core.MainCommandsLoader.load_command_table for retrieving installed modules. @mock.patch('pkgutil.iter_modules', side_effect=lambda x: [(None, MOCKED_COMMAND_LOADER_MOD, None)]) @mock.patch('azure.cli.core.commands._load_command_loader', side_effect=mock_load_command_loader) def test_load_from_help_py(self, mocked_load, mocked_pkg_util): self.set_help_py() create_invoker_and_load_cmds_and_args(self.test_cli) group_help_obj = next((help for help in get_all_help(self.test_cli) if help.command == "test"), None) command_help_obj = next((help for help in get_all_help(self.test_cli) if help.command == "test alpha"), None) # Test that group and command help are successfully displayed. with self.assertRaises(SystemExit): self.test_cli.invoke(["test", "-h"]) with self.assertRaises(SystemExit): self.test_cli.invoke(["test", "alpha", "-h"]) # Test group help self.assertIsNotNone(group_help_obj) self.assertEqual(group_help_obj.short_summary, "Foo Bar Group.") self.assertEqual(group_help_obj.long_summary, "Foo Bar Baz Group is a fun group.") # Test command help self.assertIsNotNone(command_help_obj) self.assertEqual(command_help_obj.short_summary, "Foo Bar Command.") self.assertEqual(command_help_obj.long_summary, "Foo Bar Baz Command is a fun command.") # test that parameters and help are loaded from command function docstring, argument registry help and help.py obj_param_dict = {param.name: param for param in command_help_obj.parameters} param_name_set = {"--arg1 -a", "--arg2 -b", "--arg3", "ARG4"} self.assertTrue(set(obj_param_dict.keys()).issuperset(param_name_set)) self.assertEqual(obj_param_dict["--arg3"].short_summary, "Arg3's docstring help text.") self.assertEqual(obj_param_dict["ARG4"].short_summary, "Positional parameter. Not required.") self.assertEqual(obj_param_dict["--arg1 -a"].short_summary, "A short summary.") self.assertEqual(obj_param_dict["--arg1 -a"].short_summary, "A short summary.") self.assertEqual(obj_param_dict["--arg1 -a"].value_sources[0]['link']['command'], "az foo bar") self.assertEqual(obj_param_dict["--arg1 -a"].value_sources[1]['link']['command'], "az bar baz") self.assertEqual(command_help_obj.examples[0].short_summary, "Alpha Example") self.assertEqual(command_help_obj.examples[0].command, "az test alpha --arg1 a --arg2 b --arg3 c") self.assertEqual(command_help_obj.examples[0].supported_profiles, "2018-03-01-hybrid, latest") self.assertEqual(command_help_obj.examples[0].unsupported_profiles, None) self.assertEqual(command_help_obj.examples[1].supported_profiles, None) self.assertEqual(command_help_obj.examples[1].unsupported_profiles, "2017-03-09-profile") @mock.patch('pkgutil.iter_modules', side_effect=lambda x: [(None, MOCKED_COMMAND_LOADER_MOD, None)]) @mock.patch('azure.cli.core.commands._load_command_loader', side_effect=mock_load_command_loader) def test_load_from_help_yaml(self, mocked_load, mocked_pkg_util): # setup help.py and help.yaml help. self.set_help_py() yaml_path = self.set_help_yaml() create_invoker_and_load_cmds_and_args(self.test_cli) # mock logic in core._help_loaders for retrieving yaml file from loader path. expected_arg = self.test_cli.invocation.commands_loader.cmd_to_loader_map['test alpha'][0].__class__ with mock.patch('inspect.getfile', side_effect=get_mocked_inspect_getfile(expected_arg, yaml_path)): group_help_obj = next((help for help in get_all_help(self.test_cli) if help.command == "test"), None) command_help_obj = next((help for help in get_all_help(self.test_cli) if help.command == "test alpha"), None) # pylint: disable=line-too-long # Test that group and command help are successfully displayed. with self.assertRaises(SystemExit): self.test_cli.invoke(["test", "-h"]) with self.assertRaises(SystemExit): self.test_cli.invoke(["test", "alpha", "-h"]) # Test group help self.assertIsNotNone(group_help_obj) self.assertEqual(group_help_obj.short_summary, "Group yaml summary.") self.assertEqual(group_help_obj.long_summary, "Group yaml description. A.K.A long description.") self.assertEqual(group_help_obj.links[0], {"title": "Azure Test Docs", "url": "https://docs.microsoft.com/en-us/azure/test"}) self.assertEqual(group_help_obj.links[1], {"url": "https://aka.ms/just-a-url"}) # Test command help self.assertIsNotNone(command_help_obj) self.assertEqual(command_help_obj.short_summary, "Command yaml summary.") self.assertEqual(command_help_obj.long_summary, "Command yaml description. A.K.A long description.") self.assertEqual(command_help_obj.links[0], {"title": "Azure Test Alpha Docs", "url": "https://docs.microsoft.com/en-us/azure/test/alpha"}) self.assertEqual(command_help_obj.links[1], {"url": "https://aka.ms/just-a-long-url"}) # test that parameters and help are loaded from command function docstring, argument registry help and help.yaml obj_param_dict = {param.name: param for param in command_help_obj.parameters} param_name_set = {"--arg1 -a", "--arg2 -b", "--arg3", "ARG4"} self.assertTrue(set(obj_param_dict.keys()).issuperset(param_name_set)) self.assertEqual(obj_param_dict["--arg1 -a"].short_summary, "A short summary.") self.assertEqual(obj_param_dict["--arg3"].short_summary, "Arg3's docstring help text.") self.assertEqual(obj_param_dict["ARG4"].short_summary, "Arg4's summary, yaml. Positional arg, not required.") self.assertEqual(obj_param_dict["--arg2 -b"].short_summary, "Arg 2's summary.") self.assertEqual(obj_param_dict["--arg2 -b"].long_summary, "A true description of this parameter.") self.assertEqual(obj_param_dict["--arg2 -b"].value_sources[0], {"string": "Number range: -5.0 to 5.0"}) self.assertEqual(obj_param_dict["--arg2 -b"].value_sources[1]['link'], {"url": "https://www.foo.com", "title": "foo"}) self.assertEqual(obj_param_dict["--arg2 -b"].value_sources[2]['link'], {"command": "az test show", "title": "Show test details"}) self.assertEqual(command_help_obj.examples[0].short_summary, "A simple example") self.assertEqual(command_help_obj.examples[0].long_summary, "More detail on the simple example.") self.assertEqual(command_help_obj.examples[0].command, "az test alpha --arg1 apple --arg2 ball --arg3 cat") self.assertEqual(command_help_obj.examples[0].supported_profiles, "2018-03-01-hybrid, latest") self.assertEqual(command_help_obj.examples[0].unsupported_profiles, None) self.assertEqual(command_help_obj.examples[1].supported_profiles, None) self.assertEqual(command_help_obj.examples[1].unsupported_profiles, "2017-03-09-profile") @mock.patch('inspect.getmembers', side_effect=mock_inspect_getmembers) @mock.patch('pkgutil.iter_modules', side_effect=lambda x: [(None, MOCKED_COMMAND_LOADER_MOD, None)]) @mock.patch('azure.cli.core.commands._load_command_loader', side_effect=mock_load_command_loader) def test_load_from_help_json(self, mocked_load, mocked_pkg_util, mocked_getmembers): # setup help.py, help.yaml and help.json self.set_help_py() path = self.set_help_yaml() # either (yaml or json) path should work. As both files are in the same temp dir. self.set_help_json() create_invoker_and_load_cmds_and_args(self.test_cli) # mock logic in core._help_loaders for retrieving yaml file from loader path. expected_arg = self.test_cli.invocation.commands_loader.cmd_to_loader_map['test alpha'][0].__class__ with mock.patch('inspect.getfile', side_effect=get_mocked_inspect_getfile(expected_arg, path)): group_help_obj = next((help for help in get_all_help(self.test_cli) if help.command == "test"), None) command_help_obj = next((help for help in get_all_help(self.test_cli) if help.command == "test alpha"), None) # Test that group and command help are successfully displayed. with self.assertRaises(SystemExit): self.test_cli.invoke(["test", "-h"]) with self.assertRaises(SystemExit): self.test_cli.invoke(["test", "alpha", "-h"]) # Test group help self.assertIsNotNone(group_help_obj) self.assertEqual(group_help_obj.short_summary, "Group json summary.") self.assertEqual(group_help_obj.long_summary, "Group json description. A.K.A long description.") self.assertEqual(group_help_obj.links[0], {"title": "Azure Json Test Docs", "url": "https://docs.microsoft.com/en-us/azure/test"}) self.assertEqual(group_help_obj.links[1], {"url": "https://aka.ms/just-a-url"}) # Test command help self.assertIsNotNone(command_help_obj) self.assertEqual(command_help_obj.short_summary, "Command json summary.") self.assertEqual(command_help_obj.long_summary, "Command json description. A.K.A long description.") self.assertEqual(command_help_obj.links[0], {"title": "Azure Json Test Alpha Docs", "url": "https://docs.microsoft.com/en-us/azure/test/alpha"}) self.assertEqual(command_help_obj.links[1], {"url": "https://aka.ms/just-a-long-url"}) # test that parameters and help are loaded from command function docstring, argument registry help and help.yaml obj_param_dict = {param.name: param for param in command_help_obj.parameters} param_name_set = {"--arg1 -a", "--arg2 -b", "--arg3", "ARG4"} self.assertTrue(set(obj_param_dict.keys()).issuperset(param_name_set)) self.assertEqual(obj_param_dict["--arg3"].short_summary, "Arg 3's json summary.") self.assertEqual(obj_param_dict["--arg3"].long_summary, "A truly true description of this parameter.") self.assertEqual(obj_param_dict["--arg3"].value_sources[0], {"string": "Number range: 0 to 10"}) self.assertEqual(obj_param_dict["--arg3"].value_sources[1]['link'], {"url": "https://www.foo-json.com", "title": "foo-json"}) self.assertEqual(obj_param_dict["--arg3"].value_sources[2]['link'], {"command": "az test show", "title": "Show test details. Json file"}) self.assertEqual(command_help_obj.examples[0].short_summary, "A simple example from json") self.assertEqual(command_help_obj.examples[0].long_summary, "More detail on the simple example.") self.assertEqual(command_help_obj.examples[0].command, "az test alpha --arg1 alpha --arg2 beta --arg3 chi") self.assertEqual(command_help_obj.examples[0].supported_profiles, "2018-03-01-hybrid, latest") # validate other parameters, which have help from help.py and help.yamls self.assertEqual(obj_param_dict["--arg1 -a"].short_summary, "A short summary.") self.assertEqual(obj_param_dict["--arg2 -b"].short_summary, "Arg 2's summary.") self.assertEqual(obj_param_dict["ARG4"].short_summary, "Arg4's summary, yaml. Positional arg, not required.") # arg2's help from help.yaml still preserved. self.assertEqual(obj_param_dict["--arg2 -b"].long_summary, "A true description of this parameter.") self.assertEqual(obj_param_dict["--arg2 -b"].value_sources[0], {"string": "Number range: -5.0 to 5.0"}) self.assertEqual(obj_param_dict["--arg2 -b"].value_sources[1]['link'], {"url": "https://www.foo.com", "title": "foo"}) self.assertEqual(obj_param_dict["--arg2 -b"].value_sources[2]['link'], {"command": "az test show", "title": "Show test details"}) # create a temporary file in the temp dir. Return the path of the file. def _create_new_temp_file(self, data, suffix=""): with tempfile.NamedTemporaryFile(mode='w', dir=self._tempdirName, delete=False, suffix=suffix) as f: f.write(data) return f.name
def _helper_get_clouds(_): """ Helper method for multiprocessing.Pool.map func that uses throwaway arg """ get_clouds(DummyCli())
def _get_resource_id(resource_group, sqlvm): resource_group_details = execute( DummyCli(), 'az group show -n {}'.format(resource_group)).get_output_in_json() resource_group_id = resource_group_details["id"] return f'{resource_group_id}/providers/Microsoft.Compute/VirtualMachines/{sqlvm}'
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- import unittest from azure.cli.core.profiles import ResourceType from azure.cli.core.mock import DummyCli from azure.cli.core import AzCommandsLoader from azure.cli.core.commands import AzCliCommand from azure.cli.command_modules.resource._color import Color, ColoredStringBuilder from azure.cli.command_modules.resource._formatters import format_json, format_what_if_operation_result cli_ctx = DummyCli() loader = AzCommandsLoader(cli_ctx, resource_type=ResourceType.MGMT_RESOURCE_RESOURCES) cmd = AzCliCommand(loader, "test", None, resource_type=ResourceType.MGMT_RESOURCE_RESOURCES) WhatIfOperationResult, WhatIfChange, WhatIfPropertyChange, ChangeType, PropertyChangeType = cmd.get_models( "WhatIfOperationResult", "WhatIfChange", "WhatIfPropertyChange", "ChangeType", "PropertyChangeType", )
def test_supported_api_version_no_constraints(self): # At least a min or max version must be specified cli = DummyCli() with self.assertRaises(ValueError): supported_api_version(cli, ResourceType.MGMT_STORAGE)
def _get_log_analytics_workspace_key(resource_group, workspace_name): template = 'az monitor log-analytics workspace get-shared-keys --resource-group {} --workspace-name {}' shared_keys = execute( DummyCli(), template.format(resource_group, workspace_name)).get_output_in_json() return shared_keys["primarySharedKey"]
def test_supported_api_version_invalid_profile_name(self): # Invalid name for the profile name cli = DummyCli() cli.cloud = Cloud('TestCloud', profile='not-a-real-profile') with self.assertRaises(ValueError): supported_api_version(cli, PROFILE_TYPE, min_api='2000-01-01')
def test_application_register_and_call_handlers(self): handler_called = [False] def handler(*args, **kwargs): kwargs['args'][0] = True def other_handler(*args, **kwargs): self.assertEqual(kwargs['args'], 'secret sauce') cli = DummyCli() cli.raise_event('was_handler_called', args=handler_called) self.assertFalse(handler_called[0], "Raising event with no handlers registered somehow failed...") cli.register_event('was_handler_called', handler) self.assertFalse(handler_called[0]) # Registered handler won't get called if event with different name # is raised... cli.raise_event('other_handler_called', args=handler_called) self.assertFalse(handler_called[0], 'Wrong handler called!') cli.raise_event('was_handler_called', args=handler_called) self.assertTrue(handler_called[0], "Handler didn't get called") cli.raise_event('other_handler_called', args='secret sauce')
def test_supported_api_profile_no_constraints(self): # At least a min or max version must be specified cli = DummyCli() with self.assertRaises(ValueError): supported_api_version(cli, PROFILE_TYPE)
def _restart_monitoring_service(resource_group, sqlvm): template = 'az vm run-command invoke --command-id {} --name {} -g {} --scripts \'Start-Sleep -Seconds 60\' \ \'Restart-Service HealthService\'' execute(DummyCli(), template.format('RunPowerShellScript', sqlvm, resource_group))
def test_get_default_latest_profile(self): with mock.patch('azure.cli.core.cloud.CLOUD_CONFIG_FILE', tempfile.mkstemp()[1]): cli = DummyCli() clouds = get_clouds(cli) for c in clouds: self.assertEqual(c.profile, 'latest')
def test_supported_api_profile_max_constraint_not_supported(self): cli = DummyCli() cli.cloud = Cloud('TestCloud', profile='2000-01-01-profile') self.assertFalse(supported_api_version(cli, PROFILE_TYPE, max_api='1999-12-30'))
def test_get_active_cloud_name_default(self): cli = DummyCli() expected = AZURE_PUBLIC_CLOUD.name actual = get_active_cloud_name(cli) self.assertEqual(expected, actual)
def test_supported_api_version_invalid_profile_name(self): # Invalid name for the profile name cli = DummyCli() cli.cloud = Cloud('TestCloud', profile='not-a-real-profile') with self.assertRaises(ValueError): supported_api_version(cli, PROFILE_TYPE, min_api='2000-01-01')
def test_get_known_clouds(self): cli = DummyCli() with mock.patch('azure.cli.core.cloud.CLOUD_CONFIG_FILE', tempfile.mkstemp()[1]): # Check that we can get all the known clouds without any exceptions for kc in KNOWN_CLOUDS: get_cloud(cli, kc.name)
def test_supported_api_profile_max_constraint_not_supported(self): cli = DummyCli() cli.cloud = Cloud('TestCloud', profile='2000-01-01-profile') self.assertFalse( supported_api_version(cli, PROFILE_TYPE, max_api='1999-12-30'))
def test_reset_credentials_certificate_append_option( self, graph_client_mock): patch_invoked = [ False ] # to be used in a nested function below, array type is needed to get scoping work test_object_id = 'app_object_id' test_cert = _try_x509_pem('\n'.join([ '-----BEGIN CERTIFICATE-----', 'MIICoTCCAYkCAgPoMA0GCSqGSIb3DQEBBQUAMBQxEjAQBgNVBAMMCUNMSS1Mb2dp', 'bjAiGA8yMDE3MTExMzIxMjQyMloYDzIwMTgxMTEzMjEyNDI0WjAUMRIwEAYDVQQD', 'DAlDTEktTG9naW4wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCtyRA6', 'mbUtByQBODMlp3r5fGpnYCfRhAzp2U29KRVTOQK1ntMIo3FWR19ceqK6T0UM+BFb', 'XGn28hGhgz5Y1lrbqyKrAcF10/3y42wmiMyPWjmXJ+WOEKjckKKzPMm2KBsn/ePV', 'qsr5UwlnHh2rGFR0PF1qjC0IU/SI0UQN0KJKpVp0OB8+lRlIAcsLUTveTXbdFDlp', 'k5AA8w3TTo7pT5sKNZr3+qv1o4ogDfDEx0bCYtlm4L1HvGer4pbX7q35ucZY9BWq', 'VjHQ/MjiuAyxZoyY5xVoULMWJupRyMT3wP1Hb+oJ9/tTBZbpNTv1ed9OswCc2W1l', 'MQzLwE10Ev0LJkhlAgMBAAEwDQYJKoZIhvcNAQEFBQADggEBAF+RP+7uzmf4u4+l', 'xjS+lXd3O0tqTNOVe8RR+GXl1s2Un6UhwmP3SKs2RNcXkb9+6Q4Zvg7GODK7Z8th', 't/enpTcvLmPmq2ow1hFGWJk/lONZtVKU2mikTY/ICnQrbhf3WYr1cuf98CRqoG71', 'ldrjgSsM1Ut7Gee1Tpc2eamRtHTm07AUQhqGnS5wVp6s1HUd43nvu/lVx+j2hjEB', 'y63BSuD3aSUweVne4roBNcBJjLU1wvYl+3cLgnZ9///3y/C4pKebsKHljkejRaer', 'nvbPfW9hy7BqMem7t0Qk2D84VzaK+6x9EnnsXy+90nfvTLUSqpU1MjpdWhuWyxDL', 'p4oYS5Q=', '-----END CERTIFICATE-----' ])) key_id_of_existing_cert = 'existing cert' name = 'http://mysp' def test_patch(id, param): patch_invoked[0] = True self.assertEqual(id, test_object_id) self.assertEqual(2, len(param.key_credentials)) self.assertTrue(len(param.key_credentials[1].value) > 0) self.assertEqual(param.key_credentials[1].type, 'AsymmetricX509Cert') self.assertEqual(param.key_credentials[1].usage, 'Verify') self.assertEqual(param.key_credentials[0].key_id, key_id_of_existing_cert) faked_graph_client = mock.MagicMock() sp_object = mock.MagicMock() sp_object.app_id = 'app_id' app_object = mock.MagicMock() app_object.object_id = test_object_id key_cred = mock.MagicMock() key_cred.key_id = key_id_of_existing_cert cmd = mock.MagicMock() cmd.cli_ctx = DummyCli() graph_client_mock.return_value = faked_graph_client faked_graph_client.service_principals.list.return_value = [sp_object] faked_graph_client.applications.list.return_value = [app_object] faked_graph_client.applications.get.side_effect = [app_object] faked_graph_client.applications.patch = test_patch faked_graph_client.applications.list_key_credentials.return_value = [ key_cred ] # action reset_service_principal_credential(cmd, name, cert=test_cert, append=True) # assert self.assertTrue(patch_invoked[0])
def test_supported_api_profile_preview_constraint_in_profile(self): cli = DummyCli() cli.cloud = Cloud('TestCloud', profile='2000-01-01-profile-preview') self.assertFalse( supported_api_version(cli, PROFILE_TYPE, min_api='2000-01-01'))
def test_supported_api_profile_latest(self): cli = DummyCli() cli.cloud = Cloud('TestCloud', profile='latest') self.assertTrue( supported_api_version(cli, PROFILE_TYPE, min_api='2000-01-01'))
def setUp(self): from knack.help_files import helps self.test_cli = DummyCli() self.helps = helps self._tempdirName = tempfile.mkdtemp(prefix="help_test_temp_dir_")
def test_supported_api_profile_latest(self): cli = DummyCli() cli.cloud = Cloud('TestCloud', profile='latest') self.assertTrue(supported_api_version(cli, PROFILE_TYPE, min_api='2000-01-01'))