diff --git a/src/portal/HISTORY.rst b/src/portal/HISTORY.rst index 1c139576ba0..27f152061e8 100644 --- a/src/portal/HISTORY.rst +++ b/src/portal/HISTORY.rst @@ -1,8 +1,8 @@ -.. :changelog: - -Release History -=============== - -0.1.0 -++++++ -* Initial release. +.. :changelog: + +Release History +=============== + +0.1.0 +++++++ +* Initial release. diff --git a/src/portal/README.md b/src/portal/README.md index 8e8c168f4f2..8b94239e86f 100644 --- a/src/portal/README.md +++ b/src/portal/README.md @@ -1,80 +1,5 @@ -Microsoft Azure CLI 'portal' Extension -========================================== - -This package is for the 'portal' extension. i.e. 'az portal' -More info on what is [Azure portal](https://docs.microsoft.com/en-us/azure/azure-portal/azure-portal-overview). - -### How to use ### -Install this extension using the below CLI command -``` -az extension add --name portal -``` - -### Included Features ### -Manage Azure portal dashboards: [more info](https://docs.microsoft.com/en-us/azure/azure-portal/azure-portal-dashboards-create-programmatically#fetch-the-json-representation-of-the-dashboard) - - -#### Import a portal dashboard #### -You should have a dashboard json template ready before using this operation, the file can be downloaded from Azure portal website. -More info can be found [here](https://docs.microsoft.com/en-us/azure/azure-portal/azure-portal-dashboards-create-programmatically#fetch-the-json-representation-of-the-dashboard) -Example: -``` -az portal dashboard import \ ---name dashboardName \ ---resource-group groupName \ ---input-path "/path/to/dashboard/template/file/directory" -``` -An example dashboard JSON template may look like: -[dashboard.json](https://github.com/Azure/azure-cli-extensions/blob/master/src/portal/azext_portal/tests/latest/dashboard.json) - -#### Create a portal dashboard #### -Example: -``` -az portal dashboard create \ ---location "eastus" \ ---name dashboardName \ ---resource-group groupName \ ---input-path "/path/to/properties/file/directory" ---tags aKey=aValue anotherKey=anotherValue -``` -An example propeties JSON file may look like: -[properties.json](https://github.com/Azure/azure-cli-extensions/blob/master/src/portal/azext_portal/tests/latest/properties.json) - -#### List all portal dashboards #### -Example: -List all dashboards in a resourceGroup -``` -az portal dashboard list \ ---resource-group groupName -``` -List all dashboards in a subscription -``` -az portal dashboard list -``` - -#### Show a portal dashboard details #### -Example: -``` -az portal dashboard show \ ---name dashboardName \ ---resource-group groupName -``` - -#### Update an existing dashboard #### -Example: -``` -az portal dashboard update \ ---name dashboardName \ ---resource-group groupName \ ---input-path "/src/json/properties.json" -``` - -#### Delete a dashboard #### -Example: -``` -az portal dashboard delete \ ---name dashboardName \ ---resource-group groupName \ -``` - -If you have issues, please give feedback by opening an issue at https://github.com/Azure/azure-cli-extensions/issues. \ No newline at end of file +Microsoft Azure CLI 'portal' Extension +========================================== + +This package is for the 'portal' extension. +i.e. 'az portal' diff --git a/src/portal/azext_portal/__init__.py b/src/portal/azext_portal/__init__.py index aa06a723e75..ba2052776e8 100644 --- a/src/portal/azext_portal/__init__.py +++ b/src/portal/azext_portal/__init__.py @@ -1,31 +1,46 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -from azure.cli.core import AzCommandsLoader -from .generated._help import helps # pylint: disable=unused-import - - -class PortalCommandsLoader(AzCommandsLoader): - - def __init__(self, cli_ctx=None): - from azure.cli.core.commands import CliCommandType - from .generated._client_factory import cf_portal - portal_custom = CliCommandType( - operations_tmpl='azext_portal.custom#{}', - client_factory=cf_portal) - super(PortalCommandsLoader, self).__init__(cli_ctx=cli_ctx, - custom_command_type=portal_custom) - - def load_command_table(self, args): - from .generated.commands import load_command_table - load_command_table(self, args) - return self.command_table - - def load_arguments(self, command): - from .generated._params import load_arguments - load_arguments(self, command) - - -COMMAND_LOADER_CLS = PortalCommandsLoader +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +from azure.cli.core import AzCommandsLoader +from azext_portal.generated._help import helps # pylint: disable=unused-import + + +class PortalCommandsLoader(AzCommandsLoader): + + def __init__(self, cli_ctx=None): + from azure.cli.core.commands import CliCommandType + from azext_portal.generated._client_factory import cf_portal + portal_custom = CliCommandType( + operations_tmpl='azext_portal.custom#{}', + client_factory=cf_portal) + super(PortalCommandsLoader, self).__init__(cli_ctx=cli_ctx, + custom_command_type=portal_custom) + + def load_command_table(self, args): + from azext_portal.generated.commands import load_command_table + load_command_table(self, args) + try: + from azext_portal.manual.commands import load_command_table as load_command_table_manual + load_command_table_manual(self, args) + except ImportError: + pass + return self.command_table + + def load_arguments(self, command): + from azext_portal.generated._params import load_arguments + load_arguments(self, command) + try: + from azext_portal.manual._params import load_arguments as load_arguments_manual + load_arguments_manual(self, command) + except ImportError: + pass + + +COMMAND_LOADER_CLS = PortalCommandsLoader diff --git a/src/portal/azext_portal/action.py b/src/portal/azext_portal/action.py index d66d3c5d0d7..a846b2766c4 100644 --- a/src/portal/azext_portal/action.py +++ b/src/portal/azext_portal/action.py @@ -1,12 +1,17 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- -# pylint: disable=wildcard-import -# pylint: disable=unused-wildcard-import - -from .generated.action import * # noqa: F403 -try: - from .manual.action import * # noqa: F403 -except ImportError: - pass +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wildcard-import +# pylint: disable=unused-wildcard-import + +from .generated.action import * # noqa: F403 +try: + from .manual.action import * # noqa: F403 +except ImportError: + pass diff --git a/src/portal/azext_portal/azext_metadata.json b/src/portal/azext_portal/azext_metadata.json index 13025150393..7b56fb1e11a 100644 --- a/src/portal/azext_portal/azext_metadata.json +++ b/src/portal/azext_portal/azext_metadata.json @@ -1,4 +1,4 @@ -{ - "azext.isExperimental": true, - "azext.minCliCoreVersion": "2.3.1" +{ + "azext.isExperimental": true, + "azext.minCliCoreVersion": "2.3.1" } \ No newline at end of file diff --git a/src/portal/azext_portal/custom.py b/src/portal/azext_portal/custom.py index d1fd3543ed0..7f31674ce96 100644 --- a/src/portal/azext_portal/custom.py +++ b/src/portal/azext_portal/custom.py @@ -1,12 +1,17 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- -# pylint: disable=wildcard-import -# pylint: disable=unused-wildcard-import - -from .generated.custom import * # noqa: F403 -try: - from .manual.custom import * # noqa: F403 -except ImportError: - pass +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wildcard-import +# pylint: disable=unused-wildcard-import + +from .generated.custom import * # noqa: F403 +try: + from .manual.custom import * # noqa: F403 +except ImportError: + pass diff --git a/src/portal/azext_portal/generated/__init__.py b/src/portal/azext_portal/generated/__init__.py new file mode 100644 index 00000000000..ee0c4f36bd0 --- /dev/null +++ b/src/portal/azext_portal/generated/__init__.py @@ -0,0 +1,12 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +__path__ = __import__('pkgutil').extend_path(__path__, __name__) diff --git a/src/portal/azext_portal/generated/_client_factory.py b/src/portal/azext_portal/generated/_client_factory.py index da39dd7f9fb..4372ad2af9a 100644 --- a/src/portal/azext_portal/generated/_client_factory.py +++ b/src/portal/azext_portal/generated/_client_factory.py @@ -1,14 +1,19 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - - -def cf_portal(cli_ctx, *_): - from azure.cli.core.commands.client_factory import get_mgmt_service_client - from ..vendored_sdks.portal import Portal - return get_mgmt_service_client(cli_ctx, Portal) - - -def cf_dashboard(cli_ctx, *_): - return cf_portal(cli_ctx).dashboard +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + + +def cf_portal(cli_ctx, *_): + from azure.cli.core.commands.client_factory import get_mgmt_service_client + from ..vendored_sdks.portal import Portal + return get_mgmt_service_client(cli_ctx, Portal) + + +def cf_dashboard(cli_ctx, *_): + return cf_portal(cli_ctx).dashboard diff --git a/src/portal/azext_portal/generated/_help.py b/src/portal/azext_portal/generated/_help.py index e702c567cbc..c1ffc94f5e6 100644 --- a/src/portal/azext_portal/generated/_help.py +++ b/src/portal/azext_portal/generated/_help.py @@ -1,75 +1,68 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- -# pylint: disable=line-too-long -# pylint: disable=too-many-lines - -from knack.help_files import helps - - -helps['portal dashboard'] = """ - type: group - short-summary: Manage portal dashboards -""" - -helps['portal dashboard list'] = """ - type: command - short-summary: Lists the dashboards within a subscription or resource group. - examples: - - name: List all dashboards in a resourceGroup - text: |- - az portal dashboard list --resource-group "testRG" - - name: List all dashboards in a subscription - text: |- - az portal dashboard list -""" - -helps['portal dashboard show'] = """ - type: command - short-summary: Gets details for a single dashboard. - examples: - - name: Get a Dashboard - text: |- - az portal dashboard show --name "testDashboard" --resource-group "testRG" -""" - -helps['portal dashboard create'] = """ - type: command - short-summary: Creates or updates a dashboard. - examples: - - name: Create or update a Dashboard - text: |- - az portal dashboard create --location "eastus" --name "testDashboard" \\ - --resource-group "testRG" --input-path "/src/json/properties.json" \\ - --tags aKey=aValue anotherKey=anotherValue -""" - -helps['portal dashboard update'] = """ - type: command - short-summary: Updates an existing dashboard. - examples: - - name: Update a Dashboard - text: |- - az portal dashboard update --name "testDashboard" --resource-group "testRG" \\ - --input-path "/src/json/properties.json" -""" - -helps['portal dashboard delete'] = """ - type: command - short-summary: Deletes a dashboard. - examples: - - name: Delete a Dashboard - text: |- - az portal dashboard delete --name "testDashboard" --resource-group "testRG" -""" - -helps['portal dashboard import'] = """ - type: command - short-summary: Imports a dashboard from a JSON file. - examples: - - name: Import a Dashboard - text: |- - az portal dashboard import --name "testDashboard" --resource-group "testRG" \\ - --input-path "/src/json/dashboard.json" -""" +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=too-many-lines + +from knack.help_files import helps + + +helps['portal dashboard'] = """ + type: group + short-summary: portal dashboard +""" + +helps['portal dashboard list'] = """ + type: command + short-summary: Gets all the dashboards within a subscription. + examples: + - name: List all custom resource providers on the resourceGroup + text: |- + az portal dashboard list --resource-group "testRG" +""" + +helps['portal dashboard show'] = """ + type: command + short-summary: Gets the Dashboard. + examples: + - name: Get a Dashboard + text: |- + az portal dashboard show --name "testDashboard" --resource-group "testRG" +""" + +helps['portal dashboard create'] = """ + type: command + short-summary: Creates or updates a Dashboard. + examples: + - name: Create or update a Dashboard + text: |- + az portal dashboard create --location "eastus" --lenses "{\\"aLens\\":{\\"order\\":1,\\"parts\\":{\\"aPa\ +rt\\":{\\"position\\":{\\"colSpan\\":3,\\"rowSpan\\":4,\\"x\\":1,\\"y\\":2}},\\"bPart\\":{\\"position\\":{\\"colSpan\\"\ +:6,\\"rowSpan\\":6,\\"x\\":5,\\"y\\":5}}}},\\"bLens\\":{\\"order\\":2,\\"parts\\":{}}}" --metadata "{\\"metadata\\":{\\\ +"ColSpan\\":2,\\"RowSpan\\":1,\\"X\\":4,\\"Y\\":3}}" --tags aKey="aValue" anotherKey="anotherValue" --name "testDashboa\ +rd" --resource-group "testRG" +""" + +helps['portal dashboard update'] = """ + type: command + short-summary: Updates an existing Dashboard. + examples: + - name: Update a Dashboard + text: |- + az portal dashboard update --tags aKey="bValue" anotherKey="anotherValue2" --name "testDashboard" --reso\ +urce-group "testRG" +""" + +helps['portal dashboard delete'] = """ + type: command + short-summary: Deletes the Dashboard. + examples: + - name: Delete a Dashboard + text: |- + az portal dashboard delete --name "testDashboard" --resource-group "testRG" +""" diff --git a/src/portal/azext_portal/generated/_params.py b/src/portal/azext_portal/generated/_params.py index e036901b70c..2e45cd565cb 100644 --- a/src/portal/azext_portal/generated/_params.py +++ b/src/portal/azext_portal/generated/_params.py @@ -1,61 +1,53 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- -# pylint: disable=line-too-long -# pylint: disable=too-many-lines -# pylint: disable=too-many-statements - -from argcomplete.completers import FilesCompleter -from azure.cli.core.commands.parameters import ( - tags_type, - resource_group_name_type, - get_location_type, - file_type -) -from azure.cli.core.commands.validators import get_default_location_from_resource_group - - -def load_arguments(self, _): - - with self.argument_context('portal dashboard list') as c: - c.argument('resource_group_name', resource_group_name_type, - help='The name of the resource group.') - - with self.argument_context('portal dashboard show') as c: - c.argument('resource_group_name', resource_group_name_type) - c.argument('name', options_list=[ - '--name', '-n'], help='The name of the dashboard.') - - with self.argument_context('portal dashboard create') as c: - c.argument('resource_group_name', resource_group_name_type, - help='The name of the resource group.') - c.argument('name', options_list=[ - '--name', '-n'], help='The name of the dashboard.') - c.argument('location', arg_type=get_location_type(self.cli_ctx), - validator=get_default_location_from_resource_group) - c.argument('tags', tags_type) - c.argument('input_path', type=file_type, - help='The path to the dashboard properties JSON file.', completer=FilesCompleter()) - - with self.argument_context('portal dashboard update') as c: - c.argument('resource_group_name', resource_group_name_type, - help='The name of the resource group.') - c.argument('name', options_list=[ - '--name', '-n'], help='The name of the dashboard.') - c.argument('input_path', type=file_type, - help='The path to the dashboard properties JSON file.', completer=FilesCompleter()) - - with self.argument_context('portal dashboard delete') as c: - c.argument('resource_group_name', resource_group_name_type, - help='The name of the resource group.') - c.argument('name', options_list=[ - '--name', '-n'], help='The name of the dashboard.') - - with self.argument_context('portal dashboard import') as c: - c.argument('resource_group_name', resource_group_name_type, - help='The name of the resource group.') - c.argument('name', options_list=[ - '--name', '-n'], help='The name of the dashboard.') - c.argument('input_path', type=file_type, - help='The path to the dashboard json file.', completer=FilesCompleter()) +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=too-many-lines +# pylint: disable=too-many-statements + +from knack.arguments import CLIArgumentType +from azure.cli.core.commands.parameters import ( + tags_type, + resource_group_name_type, + get_location_type +) +from azure.cli.core.commands.validators import get_default_location_from_resource_group + + +def load_arguments(self, _): + + with self.argument_context('portal dashboard list') as c: + c.argument('resource_group_name', resource_group_name_type) + + with self.argument_context('portal dashboard show') as c: + c.argument('resource_group_name', resource_group_name_type) + c.argument('name', help='The name of the dashboard.') + + with self.argument_context('portal dashboard create') as c: + c.argument('resource_group_name', resource_group_name_type) + c.argument('name', help='The name of the dashboard.') + c.argument('location', arg_type=get_location_type(self.cli_ctx), + validator=get_default_location_from_resource_group) + c.argument('tags', tags_type) + c.argument('lenses', arg_type=CLIArgumentType(options_list=['--lenses'], help='The dashboard lenses. Expected v' + 'alue: json-string/@json-file.')) + c.argument('metadata', arg_type=CLIArgumentType(options_list=['--metadata'], help='The dashboard metadata. Expe' + 'cted value: json-string/@json-file.')) + + with self.argument_context('portal dashboard update') as c: + c.argument('resource_group_name', resource_group_name_type) + c.argument('name', help='The name of the dashboard.') + c.argument('tags', tags_type) + c.argument('lenses', arg_type=CLIArgumentType(options_list=['--lenses'], help='The dashboard lenses. Expected v' + 'alue: json-string/@json-file.')) + c.argument('metadata', arg_type=CLIArgumentType(options_list=['--metadata'], help='The dashboard metadata. Expe' + 'cted value: json-string/@json-file.')) + + with self.argument_context('portal dashboard delete') as c: + c.argument('resource_group_name', resource_group_name_type) + c.argument('name', help='The name of the dashboard.') diff --git a/src/portal/azext_portal/generated/_validators.py b/src/portal/azext_portal/generated/_validators.py new file mode 100644 index 00000000000..7536d0531ea --- /dev/null +++ b/src/portal/azext_portal/generated/_validators.py @@ -0,0 +1,23 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + + +def example_name_or_id_validator(cmd, namespace): + from azure.cli.core.commands.client_factory import get_subscription_id + from msrestazure.tools import is_valid_resource_id, resource_id + if namespace.storage_account: + if not is_valid_resource_id(namespace.RESOURCE): + namespace.storage_account = resource_id( + subscription=get_subscription_id(cmd.cli_ctx), + resource_group=namespace.resource_group_name, + namespace='Microsoft.Storage', + type='storageAccounts', + name=namespace.storage_account + ) diff --git a/src/portal/azext_portal/generated/action.py b/src/portal/azext_portal/generated/action.py index d7d2d91da6b..01ed94902ce 100644 --- a/src/portal/azext_portal/generated/action.py +++ b/src/portal/azext_portal/generated/action.py @@ -1,26 +1,14 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- -# pylint: disable=protected-access - -import argparse -from knack.util import CLIError - - -class AddMetadata(argparse.Action): - def __call__(self, parser, namespace, values, option_string=None): - action = self.get_action(values, option_string) - namespace.properties_metadata = action - - def get_action(self, values, option_string): # pylint: disable=no-self-use - try: - properties = dict(x.split('=', 1) for x in values) - except ValueError: - raise CLIError( - 'usage error: {} [KEY=VALUE ...]'.format(option_string)) - d = {} - for k in properties: - v = properties[k] - d[k] = v - return d +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=protected-access + +import argparse +from knack.util import CLIError +from collections import defaultdict diff --git a/src/portal/azext_portal/generated/commands.py b/src/portal/azext_portal/generated/commands.py index b111eaf4dfc..a3eed84843c 100644 --- a/src/portal/azext_portal/generated/commands.py +++ b/src/portal/azext_portal/generated/commands.py @@ -1,25 +1,26 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -from azure.cli.core.commands import CliCommandType - - -def load_command_table(self, _): - - with self.command_group('stream-analytics', is_experimental=True): - pass - - from azext_portal.generated._client_factory import cf_dashboard - portal_dashboard = CliCommandType( - operations_tmpl='azext_portal.vendored_sdks.portal.operations._dashboard_operations#DashboardOperations.{}', - client_factory=cf_dashboard) - with self.command_group('portal dashboard', portal_dashboard, client_factory=cf_dashboard) as g: - g.custom_command('list', 'portal_dashboard_list') - g.custom_show_command('show', 'portal_dashboard_show') - g.custom_command('create', 'portal_dashboard_create') - g.custom_command('update', 'portal_dashboard_update') - g.custom_command('delete', 'portal_dashboard_delete', - confirmation=True) - g.custom_command('import', 'portal_dashboard_import') +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +from azure.cli.core.commands import CliCommandType + + +def load_command_table(self, _): + + from azext_portal.generated._client_factory import cf_dashboard + portal_dashboard = CliCommandType( + operations_tmpl='azext_portal.vendored_sdks.portal.operations._dashboard_operations#DashboardOperations.{}', + client_factory=cf_dashboard) + with self.command_group('portal dashboard', portal_dashboard, client_factory=cf_dashboard, + is_experimental=True) as g: + g.custom_command('list', 'portal_dashboard_list') + g.custom_show_command('show', 'portal_dashboard_show') + g.custom_command('create', 'portal_dashboard_create') + g.custom_command('update', 'portal_dashboard_update') + g.custom_command('delete', 'portal_dashboard_delete') diff --git a/src/portal/azext_portal/generated/custom.py b/src/portal/azext_portal/generated/custom.py index 1d4557ac4ab..38d1ae826fb 100644 --- a/src/portal/azext_portal/generated/custom.py +++ b/src/portal/azext_portal/generated/custom.py @@ -1,100 +1,69 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- -# pylint: disable=line-too-long -# pylint: disable=too-many-lines - -import json -from knack.util import CLIError - - -def portal_dashboard_list(cmd, client, - resource_group_name=None): - if resource_group_name: - return client.list_by_resource_group(resource_group_name=resource_group_name) - return client.list_by_subscription() - - -def portal_dashboard_show(cmd, client, - resource_group_name, - name): - return client.get(resource_group_name=resource_group_name, dashboard_name=name) - - -def portal_dashboard_create(cmd, client, - resource_group_name, - name, - input_path, - location=None, - tags=None): - properties_lenses, properties_metadata = parse_properties_json(input_path) - return client.create_or_update(resource_group_name=resource_group_name, dashboard_name=name, location=location, tags=tags, lenses=properties_lenses, metadata=properties_metadata) - - -def portal_dashboard_update(cmd, client, - resource_group_name, - name, - input_path): - properties_lenses, properties_metadata = parse_properties_json(input_path) - return client.update(resource_group_name=resource_group_name, dashboard_name=name, lenses=properties_lenses, metadata=properties_metadata) - - -def portal_dashboard_delete(cmd, client, - resource_group_name, - name): - return client.delete(resource_group_name=resource_group_name, dashboard_name=name) - - -def portal_dashboard_import(cmd, client, - resource_group_name, - input_path, - name=None): - dashboard = parse_dashboard_json(input_path) - return client.dashboard_import(resource_group_name=resource_group_name, dashboard_name=dashboard.get('name', name), dashboard=dashboard) - - -def parse_properties_json(input_path): - try: - with open(input_path) as json_file: - try: - properties = json.load(json_file) - except json.decoder.JSONDecodeError as ex: - raise CLIError( - 'JSON decode error for {}: {}'.format(json_file, str(ex))) - if 'lenses' not in properties: - raise CLIError(str(json_file) + - " does not contain the property 'lenses'") - properties_lenses = properties['lenses'] - if 'metadata' not in properties: - raise CLIError(str(json_file) + - " does not contain the property 'metadata'") - properties_metadata = properties['metadata'] - return properties_lenses, properties_metadata - except FileNotFoundError as ex: - raise CLIError('File not Found: {}'.format(str(ex))) - - -def parse_dashboard_json(input_path): - try: - with open(input_path) as json_file: - try: - dashboard = json.load(json_file) - except json.decoder.JSONDecodeError as ex: - raise CLIError( - 'There was an error decoding the JSON file {}: {}'.format(json_file, str(ex))) - if 'location' not in dashboard: - raise CLIError(str(json_file) + - " does not contain the property 'location'") - if 'properties' not in dashboard: - raise CLIError(str(json_file) + - " does not contain the property 'properties'") - if 'lenses' not in dashboard['properties']: - raise CLIError( - str(json_file) + " does not contain the property 'lenses' in 'properties'") - if 'metadata' not in dashboard['properties']: - raise CLIError( - str(json_file) + " does not contain the property 'metadata' in 'properties'") - return dashboard - except FileNotFoundError as ex: - raise CLIError('File not Found: {}'.format(str(ex))) +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=too-many-lines + +import json + + +def portal_dashboard_list(cmd, client, + resource_group_name=None): + if resource_group_name is not None: + return client.list_by_resource_group(resource_group_name=resource_group_name) + return client.list_by_subscription() + + +def portal_dashboard_show(cmd, client, + resource_group_name, + name): + return client.get(resource_group_name=resource_group_name, + dashboard_name=name) + + +def portal_dashboard_create(cmd, client, + resource_group_name, + name, + location, + tags=None, + lenses=None, + metadata=None): + if isinstance(lenses, str): + lenses = json.loads(lenses) + if isinstance(metadata, str): + metadata = json.loads(metadata) + return client.create_or_update(resource_group_name=resource_group_name, + dashboard_name=name, + location=location, + tags=tags, + lenses=lenses, + metadata=metadata) + + +def portal_dashboard_update(cmd, client, + resource_group_name, + name, + tags=None, + lenses=None, + metadata=None): + if isinstance(lenses, str): + lenses = json.loads(lenses) + if isinstance(metadata, str): + metadata = json.loads(metadata) + return client.update(resource_group_name=resource_group_name, + dashboard_name=name, + tags=tags, + lenses=lenses, + metadata=metadata) + + +def portal_dashboard_delete(cmd, client, + resource_group_name, + name): + return client.delete(resource_group_name=resource_group_name, + dashboard_name=name) diff --git a/src/portal/azext_portal/manual/__init__.py b/src/portal/azext_portal/manual/__init__.py new file mode 100644 index 00000000000..ee0c4f36bd0 --- /dev/null +++ b/src/portal/azext_portal/manual/__init__.py @@ -0,0 +1,12 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +__path__ = __import__('pkgutil').extend_path(__path__, __name__) diff --git a/src/portal/azext_portal/tests/__init__.py b/src/portal/azext_portal/tests/__init__.py new file mode 100644 index 00000000000..fe1bd438b46 --- /dev/null +++ b/src/portal/azext_portal/tests/__init__.py @@ -0,0 +1,49 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- +import inspect +import os + + +__path__ = __import__('pkgutil').extend_path(__path__, __name__) + + +def try_manual(func): + def import_manual_function(origin_func): + from importlib import import_module + decorated_path = inspect.getfile(origin_func) + module_path = __path__[0] + if not decorated_path.startswith(module_path): + raise Exception("Decorator can only be used in submodules!") + manual_path = os.path.join( + decorated_path[module_path.rfind(os.path.sep) + 1:]) + manual_file_path, manual_file_name = os.path.split(manual_path) + module_name, _ = os.path.splitext(manual_file_name) + manual_module = "..manual." + \ + ".".join(manual_file_path.split(os.path.sep) + [module_name, ]) + return getattr(import_module(manual_module, package=__name__), origin_func.__name__) + + def get_func_to_call(): + func_to_call = func + try: + func_to_call = import_manual_function(func) + except (ImportError, AttributeError): + pass + return func_to_call + + def wrapper(*args, **kwargs): + func_to_call = get_func_to_call() + print("running {}()...".format(func.__name__)) + return func_to_call(*args, **kwargs) + + if inspect.isclass(func): + return get_func_to_call() + else: + return wrapper diff --git a/src/portal/azext_portal/tests/latest/__init__.py b/src/portal/azext_portal/tests/latest/__init__.py index 34913fb394d..ee0c4f36bd0 100644 --- a/src/portal/azext_portal/tests/latest/__init__.py +++ b/src/portal/azext_portal/tests/latest/__init__.py @@ -1,4 +1,12 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +__path__ = __import__('pkgutil').extend_path(__path__, __name__) diff --git a/src/portal/azext_portal/tests/latest/dashboard.json b/src/portal/azext_portal/tests/latest/dashboard.json deleted file mode 100644 index 94524e39309..00000000000 --- a/src/portal/azext_portal/tests/latest/dashboard.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "properties": { - "lenses": { - "0": { - "order": 0, - "parts": { - "0": { - "position": { - "x": 0, - "y": 0, - "colSpan": 6, - "rowSpan": 4 - }, - "metadata": { - "inputs": [ - { - "name": "resourceType", - "value": "Microsoft.Resources/subscriptions/resourcegroups", - "isOptional": true - }, - { - "name": "filter", - "isOptional": true - }, - { - "name": "scope", - "isOptional": true - }, - { - "name": "kind", - "isOptional": true - } - ], - "type": "Extension/HubsExtension/PartType/BrowseResourceGroupPinnedPart" - } - } - } - } - }, - "metadata": { - "model": { - "timeRange": { - "value": { - "relative": { - "duration": 24, - "timeUnit": 1 - } - }, - "type": "MsPortalFx.Composition.Configuration.ValueTypes.TimeRange" - } - } - } - }, - "name": "7c0464ec-b1cd-4a98-a4a5-1ebe2d980260", - "type": "Microsoft.Portal/dashboards", - "location": "eastus", - "tags": { - "hidden-title": "test dashboard" - }, - "apiVersion": "2019-01-01-preview" -} \ No newline at end of file diff --git a/src/portal/azext_portal/tests/latest/preparers.py b/src/portal/azext_portal/tests/latest/preparers.py index 1388cfd22cc..3d6672de64f 100644 --- a/src/portal/azext_portal/tests/latest/preparers.py +++ b/src/portal/azext_portal/tests/latest/preparers.py @@ -1,111 +1,116 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -import os -from datetime import datetime -from azure.cli.testsdk.preparers import NoTrafficRecordingPreparer -from azure_devtools.scenario_tests import SingleValueReplacer -from azure.cli.testsdk.exceptions import CliTestError -from azure.cli.testsdk.reverse_dependency import get_dummy_cli - - -KEY_RESOURCE_GROUP = 'rg' -KEY_VIRTUAL_NETWORK = 'vnet' -KEY_VNET_SUBNET = 'subnet' - - -class VirtualNetworkPreparer(NoTrafficRecordingPreparer, SingleValueReplacer): - def __init__(self, name_prefix='clitest.vn', - parameter_name='virtual_network', - resource_group_name=None, - resource_group_key=KEY_RESOURCE_GROUP, - dev_setting_name='AZURE_CLI_TEST_DEV_VIRTUAL_NETWORK_NAME', - random_name_length=24, key=KEY_VIRTUAL_NETWORK): - if ' ' in name_prefix: - raise CliTestError( - 'Error: Space character in name prefix \'%s\'' % name_prefix) - super(VirtualNetworkPreparer, self).__init__( - name_prefix, random_name_length) - self.cli_ctx = get_dummy_cli() - self.parameter_name = parameter_name - self.key = key - self.resource_group_name = resource_group_name - self.resource_group_key = resource_group_key - self.dev_setting_name = os.environ.get(dev_setting_name, None) - - def create_resource(self, name, **kwargs): - if self.dev_setting_name: - return {self.parameter_name: self.dev_setting_name, } - - if not self.resource_group_name: - self.resource_group_name = self.test_class_instance.kwargs.get( - self.resource_group_key) - if not self.resource_group_name: - raise CliTestError("Error: No resource group configured!") - - tags = {'product': 'azurecli', 'cause': 'automation', - 'date': datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')} - if 'ENV_JOB_NAME' in os.environ: - tags['job'] = os.environ['ENV_JOB_NAME'] - tags = ' '.join(['{}={}'.format(key, value) - for key, value in tags.items()]) - template = 'az network vnet create --resource-group {} --name {} --tag ' + tags - self.live_only_execute(self.cli_ctx, template.format( - self.resource_group_name, name)) - - self.test_class_instance.kwargs[self.key] = name - return {self.parameter_name: name} - - def remove_resource(self, name, **kwargs): - # delete vnet if test is being recorded and if the vnet is not a dev rg - if not self.dev_setting_name: - self.live_only_execute( - self.cli_ctx, 'az network vnet delete --name {} --resource-group {}'.format(name, self.resource_group_name)) - - -class VnetSubnetPreparer(NoTrafficRecordingPreparer, SingleValueReplacer): - def __init__(self, name_prefix='clitest.vn', - parameter_name='subnet', - resource_group_name=None, - resource_group_key=KEY_RESOURCE_GROUP, - vnet_name=None, - vnet_key=KEY_VIRTUAL_NETWORK, - address_prefixes="11.0.0.0/24", - dev_setting_name='AZURE_CLI_TEST_DEV_VNET_SUBNET_NAME', - random_name_length=24, key=KEY_VNET_SUBNET): - if ' ' in name_prefix: - raise CliTestError( - 'Error: Space character in name prefix \'%s\'' % name_prefix) - super(VnetSubnetPreparer, self).__init__( - name_prefix, random_name_length) - self.cli_ctx = get_dummy_cli() - self.parameter_name = parameter_name - self.key = key - self.resource_group_name = resource_group_name - self.resource_group_key = resource_group_key - self.vnet_name = vnet_name - self.vnet_key = vnet_key - self.address_prefixes = address_prefixes - self.dev_setting_name = os.environ.get(dev_setting_name, None) - - def create_resource(self, name, **kwargs): - if self.dev_setting_name: - return {self.parameter_name: self.dev_setting_name, } - - if not self.resource_group_name: - self.resource_group_name = self.test_class_instance.kwargs.get( - self.resource_group_key) - if not self.resource_group_name: - raise CliTestError("Error: No resource group configured!") - if not self.vnet_name: - self.vnet_name = self.test_class_instance.kwargs.get(self.vnet_key) - if not self.vnet_name: - raise CliTestError("Error: No vnet configured!") - - self.test_class_instance.kwargs[self.key] = 'default' - return {self.parameter_name: name} - - def remove_resource(self, name, **kwargs): - pass +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +import os +from datetime import datetime +from azure.cli.testsdk.preparers import NoTrafficRecordingPreparer +from azure_devtools.scenario_tests import SingleValueReplacer +from azure.cli.testsdk.exceptions import CliTestError +from azure.cli.testsdk.reverse_dependency import get_dummy_cli + + +KEY_RESOURCE_GROUP = 'rg' +KEY_VIRTUAL_NETWORK = 'vnet' +KEY_VNET_SUBNET = 'subnet' + + +class VirtualNetworkPreparer(NoTrafficRecordingPreparer, SingleValueReplacer): + def __init__(self, name_prefix='clitest.vn', + parameter_name='virtual_network', + resource_group_name=None, + resource_group_key=KEY_RESOURCE_GROUP, + dev_setting_name='AZURE_CLI_TEST_DEV_VIRTUAL_NETWORK_NAME', + random_name_length=24, key=KEY_VIRTUAL_NETWORK): + if ' ' in name_prefix: + raise CliTestError( + 'Error: Space character in name prefix \'%s\'' % name_prefix) + super(VirtualNetworkPreparer, self).__init__( + name_prefix, random_name_length) + self.cli_ctx = get_dummy_cli() + self.parameter_name = parameter_name + self.key = key + self.resource_group_name = resource_group_name + self.resource_group_key = resource_group_key + self.dev_setting_name = os.environ.get(dev_setting_name, None) + + def create_resource(self, name, **kwargs): + if self.dev_setting_name: + return {self.parameter_name: self.dev_setting_name, } + + if not self.resource_group_name: + self.resource_group_name = self.test_class_instance.kwargs.get( + self.resource_group_key) + if not self.resource_group_name: + raise CliTestError("Error: No resource group configured!") + + tags = {'product': 'azurecli', 'cause': 'automation', + 'date': datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')} + if 'ENV_JOB_NAME' in os.environ: + tags['job'] = os.environ['ENV_JOB_NAME'] + tags = ' '.join(['{}={}'.format(key, value) + for key, value in tags.items()]) + template = 'az network vnet create --resource-group {} --name {} --tag ' + tags + self.live_only_execute(self.cli_ctx, template.format( + self.resource_group_name, name)) + + self.test_class_instance.kwargs[self.key] = name + return {self.parameter_name: name} + + def remove_resource(self, name, **kwargs): + # delete vnet if test is being recorded and if the vnet is not a dev rg + if not self.dev_setting_name: + self.live_only_execute( + self.cli_ctx, 'az network vnet delete --name {} --resource-group {}'.format(name, self.resource_group_name)) + + +class VnetSubnetPreparer(NoTrafficRecordingPreparer, SingleValueReplacer): + def __init__(self, name_prefix='clitest.vn', + parameter_name='subnet', + resource_group_name=None, + resource_group_key=KEY_RESOURCE_GROUP, + vnet_name=None, + vnet_key=KEY_VIRTUAL_NETWORK, + address_prefixes="11.0.0.0/24", + dev_setting_name='AZURE_CLI_TEST_DEV_VNET_SUBNET_NAME', + random_name_length=24, key=KEY_VNET_SUBNET): + if ' ' in name_prefix: + raise CliTestError( + 'Error: Space character in name prefix \'%s\'' % name_prefix) + super(VnetSubnetPreparer, self).__init__( + name_prefix, random_name_length) + self.cli_ctx = get_dummy_cli() + self.parameter_name = parameter_name + self.key = key + self.resource_group_name = resource_group_name + self.resource_group_key = resource_group_key + self.vnet_name = vnet_name + self.vnet_key = vnet_key + self.address_prefixes = address_prefixes + self.dev_setting_name = os.environ.get(dev_setting_name, None) + + def create_resource(self, name, **kwargs): + if self.dev_setting_name: + return {self.parameter_name: self.dev_setting_name, } + + if not self.resource_group_name: + self.resource_group_name = self.test_class_instance.kwargs.get( + self.resource_group_key) + if not self.resource_group_name: + raise CliTestError("Error: No resource group configured!") + if not self.vnet_name: + self.vnet_name = self.test_class_instance.kwargs.get(self.vnet_key) + if not self.vnet_name: + raise CliTestError("Error: No vnet configured!") + + self.test_class_instance.kwargs[self.key] = 'default' + return {self.parameter_name: name} + + def remove_resource(self, name, **kwargs): + pass diff --git a/src/portal/azext_portal/tests/latest/properties-update.json b/src/portal/azext_portal/tests/latest/properties-update.json deleted file mode 100644 index 2e3e9bd56d4..00000000000 --- a/src/portal/azext_portal/tests/latest/properties-update.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "lenses": { - "0": { - "order": 0, - "parts": { - "0": { - "position": { - "x": 6, - "y": 2, - "colSpan": 2, - "rowSpan": 2 - }, - "metadata": { - "inputs": [], - "type": "Extension/HubsExtension/PartType/ClockPart", - "settings": {} - } - } - } - } - }, - "metadata": { - "model": { - "timeRange": { - "value": { - "relative": { - "duration": 12, - "timeUnit": 1 - } - }, - "type": "MsPortalFx.Composition.Configuration.ValueTypes.TimeRange" - } - } - } -} \ No newline at end of file diff --git a/src/portal/azext_portal/tests/latest/properties.json b/src/portal/azext_portal/tests/latest/properties.json deleted file mode 100644 index 212a8ead593..00000000000 --- a/src/portal/azext_portal/tests/latest/properties.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "lenses": { - "0": { - "order": 0, - "parts": { - "0": { - "position": { - "x": 6, - "y": 2, - "colSpan": 2, - "rowSpan": 2 - }, - "metadata": { - "inputs": [], - "type": "Extension/HubsExtension/PartType/ClockPart", - "settings": {} - } - } - } - } - }, - "metadata": { - "model": { - "timeRange": { - "value": { - "relative": { - "duration": 24, - "timeUnit": 1 - } - }, - "type": "MsPortalFx.Composition.Configuration.ValueTypes.TimeRange" - } - } - } -} \ No newline at end of file diff --git a/src/portal/azext_portal/tests/latest/test_portal_scenario.py b/src/portal/azext_portal/tests/latest/test_portal_scenario.py index 314740bbbe6..f1c91d70e9f 100644 --- a/src/portal/azext_portal/tests/latest/test_portal_scenario.py +++ b/src/portal/azext_portal/tests/latest/test_portal_scenario.py @@ -1,111 +1,113 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -import os -import unittest - -from azure_devtools.scenario_tests import AllowLargeResponse -from azure.cli.testsdk import JMESPathCheck -from azure.cli.testsdk import JMESPathCheckExists -from azure.cli.testsdk import NoneCheck -from azure.cli.testsdk import ScenarioTest -from azure.cli.testsdk import ResourceGroupPreparer - - -TEST_DIR = os.path.abspath(os.path.join(os.path.abspath(__file__), '..')) - - -class PortalScenarioTest(ScenarioTest): - - @ResourceGroupPreparer(name_prefix='cli_test_portal_testRG'[:9], key='rg') - def test_portal(self, resource_group): - - self.kwargs.update({ - 'testDashboard': self.create_random_name(prefix='cli_test_dashboards'[:9], length=24) - }) - - self.cmd('az portal dashboard create ' - '--location "eastus" ' - '--input- "src/portal/azext_portal/tests/latest/properties.json" ' - '--tags aKey=aValue anotherKey=anotherValue ' - '--name "{testDashboard}" ' - '--resource-group "{rg}"', - checks=[JMESPathCheck('name', self.kwargs.get('testDashboard', ''))]) - - self.cmd('az portal dashboard show ' - '--name "{testDashboard}" ' - '--resource-group "{rg}"', - checks=[ - JMESPathCheck('name', self.kwargs.get( - 'testDashboard', '')), - JMESPathCheck('resourceGroup', self.kwargs.get('rg', '')), - JMESPathCheck( - 'tags', '{\'aKey\': \'aValue\', \'anotherKey\': \'anotherValue\'}'), - JMESPathCheck('lenses', '{\'0\': {\'metadata\': None, \'order\': 0, \'parts\': ' - '{\'0\': {\'metadata\': {\'inputs\': [], \'settings\': {}, \'type\': ' - '\'Extension/HubsExtension/PartType/ClockPart\'}, \'position\': {\'colSpan\': 2, ' - '\'metadata\': None, \'rowSpan\': 2, \'x\': 6, \'y\': 2}}}}}'), - JMESPathCheck('metadata', '{\'model\': {\'timeRange\': {\'type\': ' - '\'MsPortalFx.Composition.Configuration.ValueTypes.TimeRange\', \'value\': ' - '{\'relative\': {\'duration\': 24, \'timeUnit\': 1}}}}}')]) - - self.cmd('az portal dashboard list ' - '--resource-group "{rg}"', - checks=[JMESPathCheckExists('[?name==\'{}\']'.format(self.kwargs.get('testDashboard', '')))]) - - self.cmd('az portal dashboard list ' - '--resource-group=', - checks=[JMESPathCheckExists('[?name==\'{}\']'.format(self.kwargs.get('testDashboard', '')))]) - - self.cmd('az portal dashboard update ' - '--input-path "src/portal/azext_portal/tests/latest/properties-update.json" ' - '--name "{testDashboard}" ' - '--resource-group "{rg}"', - checks=[ - JMESPathCheck('name', self.kwargs.get( - 'testDashboard', '')), - JMESPathCheck('resourceGroup', self.kwargs.get('rg', '')), - JMESPathCheck( - 'tags', '{\'aKey\': \'aValue\', \'anotherKey\': \'anotherValue\'}'), - JMESPathCheck('lenses', '{\'0\': {\'metadata\': None, \'order\': 0, \'parts\': ' - '{\'0\': {\'metadata\': {\'inputs\': [], \'settings\': {}, \'type\': ' - '\'Extension/HubsExtension/PartType/ClockPart\'}, \'position\': {\'colSpan\': 2, ' - '\'metadata\': None, \'rowSpan\': 2, \'x\': 6, \'y\': 2}}}}}'), - JMESPathCheck('metadata', '{\'model\': {\'timeRange\': {\'type\': ' - '\'MsPortalFx.Composition.Configuration.ValueTypes.TimeRange\', \'value\': ' - '{\'relative\': {\'duration\': 12, \'timeUnit\': 1}}}}}')]) - - self.cmd('az portal dashboard delete ' - '--name "{testDashboard}" ' - '--resource-group "{rg}" ' - '--y', - checks=[]) - - self.cmd('az portal dashboard list ' - '--resource-group "{rg}"', - checks=[NoneCheck()]) - - self.cmd('az portal dashboard import ' - '--input-path "src/portal/azext_portal/tests/latest/dashboard.json" ' - '--name "{testDashboard}" ' - '--resource-group "{rg}"', - checks=[ - JMESPathCheck( - 'name', '7c0464ec-b1cd-4a98-a4a5-1ebe2d980260'), - JMESPathCheck('resourceGroup', self.kwargs.get('rg', '')), - JMESPathCheck('location', 'eastus'), - JMESPathCheck('type', 'Microsoft.Portal/dashboards'), - JMESPathCheck( - 'tags', '{\'hidden-title\': \'test dashboard\'}'), - JMESPathCheck('lenses', '{\'0\': {\'metadata\': None, \'order\': 0, \'parts\': ' - '{\'0\': {\'metadata\': {\'inputs\': [{\'isOptional\': True, \'name\': ' - '\'resourceType\', \'value\': \'Microsoft.Resources/subscriptions/resourcegroups\'},' - ' {\'isOptional\': True, \'name\': \'filter\'}, {\'isOptional\': True, \'name\':' - ' \'scope\'}, {\'isOptional\': True, \'name\': \'kind\'}], \'type\': ' - '\'Extension/HubsExtension/PartType/BrowseResourceGroupPinnedPart\'}, \'position\': ' - '{\'colSpan\': 6, \'metadata\': None, \'rowSpan\': 4, \'x\': 0, \'y\': 0}}}}}'), - JMESPathCheck('metadata', '{\'model\': {\'timeRange\': {\'type\': ' - '\'MsPortalFx.Composition.Configuration.ValueTypes.TimeRange\', \'value\': ' - '{\'relative\': {\'duration\': 24, \'timeUnit\': 1}}}}}')]) +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +import os +import unittest + +from azure_devtools.scenario_tests import AllowLargeResponse +from azure.cli.testsdk import ScenarioTest +from .. import try_manual +from azure.cli.testsdk import ResourceGroupPreparer + + +TEST_DIR = os.path.abspath(os.path.join(os.path.abspath(__file__), '..')) + + +@try_manual +def setup(test, rg): + pass + + +# EXAMPLE: /Dashboards/put/Create or update a Dashboard +@try_manual +def step__dashboards_put_create_or_update_a_dashboard(test, rg): + test.cmd('az portal dashboard create ' + '--location "eastus" ' + '--lenses "{{\\"aLens\\":{{\\"order\\":1,\\"parts\\":{{\\"aPart\\":{{\\"position\\":{{\\"colSpan\\":3,\\"r' + 'owSpan\\":4,\\"x\\":1,\\"y\\":2}}}},\\"bPart\\":{{\\"position\\":{{\\"colSpan\\":6,\\"rowSpan\\":6,\\"x\\' + '":5,\\"y\\":5}}}}}}}},\\"bLens\\":{{\\"order\\":2,\\"parts\\":{{}}}}}}" ' + '--metadata "{{\\"metadata\\":{{\\"ColSpan\\":2,\\"RowSpan\\":1,\\"X\\":4,\\"Y\\":3}}}}" ' + '--tags aKey="aValue" anotherKey="anotherValue" ' + '--name "{testDashboard}" ' + '--resource-group "{rg}"', + checks=[]) + + +# EXAMPLE: /Dashboards/get/Get a Dashboard +@try_manual +def step__dashboards_get_get_a_dashboard(test, rg): + test.cmd('az portal dashboard show ' + '--name "{testDashboard}" ' + '--resource-group "{rg}"', + checks=[]) + + +# EXAMPLE: /Dashboards/get/List all custom resource providers on the resourceGroup +@try_manual +def step__dashboards_get_list_all_custom_resource_providers_on_the_resourcegroup(test, rg): + test.cmd('az portal dashboard list ' + '--resource-group "{rg}"', + checks=[]) + + +# EXAMPLE: /Dashboards/get/List all custom resource providers on the subscription +@try_manual +def step__dashboards_get_list_all_custom_resource_providers_on_the_subscription(test, rg): + test.cmd('az portal dashboard list', + checks=[]) + + +# EXAMPLE: /Dashboards/patch/Update a Dashboard +@try_manual +def step__dashboards_patch_update_a_dashboard(test, rg): + test.cmd('az portal dashboard update ' + '--tags aKey="bValue" anotherKey="anotherValue2" ' + '--name "{testDashboard}" ' + '--resource-group "{rg}"', + checks=[]) + + +# EXAMPLE: /Dashboards/delete/Delete a Dashboard +@try_manual +def step__dashboards_delete_delete_a_dashboard(test, rg): + test.cmd('az portal dashboard delete ' + '--name "{testDashboard}" ' + '--resource-group "{rg}"', + checks=[]) + + +@try_manual +def cleanup(test, rg): + pass + + +@try_manual +def call_scenario(test, rg): + setup(test, rg) + step__dashboards_put_create_or_update_a_dashboard(test, rg) + step__dashboards_get_get_a_dashboard(test, rg) + step__dashboards_get_list_all_custom_resource_providers_on_the_resourcegroup(test, rg) + step__dashboards_get_list_all_custom_resource_providers_on_the_subscription(test, rg) + step__dashboards_patch_update_a_dashboard(test, rg) + step__dashboards_delete_delete_a_dashboard(test, rg) + cleanup(test, rg) + + +@try_manual +class PortalScenarioTest(ScenarioTest): + + @ResourceGroupPreparer(name_prefix='clitestportal_testRG'[:7], key='rg', parameter_name='rg') + def test_portal(self, rg): + + self.kwargs.update({ + 'testDashboard': 'testDashboard', + }) + + call_scenario(self, rg) diff --git a/src/portal/azext_portal/vendored_sdks/__init__.py b/src/portal/azext_portal/vendored_sdks/__init__.py index be1a152630c..ee0c4f36bd0 100644 --- a/src/portal/azext_portal/vendored_sdks/__init__.py +++ b/src/portal/azext_portal/vendored_sdks/__init__.py @@ -1,12 +1,12 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -__path__ = __import__('pkgutil').extend_path(__path__, __name__) \ No newline at end of file +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +__path__ = __import__('pkgutil').extend_path(__path__, __name__) diff --git a/src/portal/azext_portal/vendored_sdks/portal/__init__.py b/src/portal/azext_portal/vendored_sdks/portal/__init__.py index a2795e0ed3f..ba45337d2fe 100644 --- a/src/portal/azext_portal/vendored_sdks/portal/__init__.py +++ b/src/portal/azext_portal/vendored_sdks/portal/__init__.py @@ -7,4 +7,13 @@ # -------------------------------------------------------------------------- from ._portal import Portal +from ._version import VERSION + +__version__ = VERSION __all__ = ['Portal'] + +try: + from .patch import patch_sdk + patch_sdk() +except ImportError: + pass diff --git a/src/portal/azext_portal/vendored_sdks/portal/_configuration.py b/src/portal/azext_portal/vendored_sdks/portal/_configuration.py index 69420dd4e61..cdbdfba427e 100644 --- a/src/portal/azext_portal/vendored_sdks/portal/_configuration.py +++ b/src/portal/azext_portal/vendored_sdks/portal/_configuration.py @@ -6,20 +6,28 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any +from typing import TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies -VERSION = "unknown" +from ._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any + + from azure.core.credentials import TokenCredential + class PortalConfiguration(Configuration): - """Configuration for Portal + """Configuration for Portal. + Note that all parameters used to create this instance are saved as instance attributes. :param credential: Credential needed for the client to connect to Azure. - :type credential: azure.core.credentials.TokenCredential + :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). :type subscription_id: str """ @@ -40,8 +48,9 @@ def __init__( self.credential = credential self.subscription_id = subscription_id self.api_version = "2019-01-01-preview" + self.credential_scopes = ['https://management.azure.com/.default'] + kwargs.setdefault('sdk_moniker', 'mgmt-portal/{}'.format(VERSION)) self._configure(**kwargs) - self.user_agent_policy.add_user_agent('azsdk-python-portal/{}'.format(VERSION)) def _configure( self, @@ -57,4 +66,4 @@ def _configure( self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) self.authentication_policy = kwargs.get('authentication_policy') if self.credential and not self.authentication_policy: - self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, **kwargs) + self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/src/portal/azext_portal/vendored_sdks/portal/_portal.py b/src/portal/azext_portal/vendored_sdks/portal/_portal.py index 1ca59444489..8f9fec7dd0c 100644 --- a/src/portal/azext_portal/vendored_sdks/portal/_portal.py +++ b/src/portal/azext_portal/vendored_sdks/portal/_portal.py @@ -6,11 +6,15 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Optional +from typing import TYPE_CHECKING -from azure.core import PipelineClient +from azure.mgmt.core import ARMPipelineClient from msrest import Deserializer, Serializer +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Optional + from ._configuration import PortalConfiguration from .operations import OperationOperations from .operations import DashboardOperations @@ -21,11 +25,11 @@ class Portal(object): """Allows creation and deletion of Azure Shared Dashboards. :ivar operation: OperationOperations operations - :vartype operation: portal.operations.OperationOperations + :vartype operation: azure.mgmt.portal.operations.OperationOperations :ivar dashboard: DashboardOperations operations - :vartype dashboard: portal.operations.DashboardOperations + :vartype dashboard: azure.mgmt.portal.operations.DashboardOperations :param credential: Credential needed for the client to connect to Azure. - :type credential: azure.core.credentials.TokenCredential + :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). :type subscription_id: str :param str base_url: Service URL @@ -42,7 +46,7 @@ def __init__( if not base_url: base_url = 'https://management.azure.com' self._config = PortalConfiguration(credential, subscription_id, **kwargs) - self._client = PipelineClient(base_url=base_url, config=self._config, **kwargs) + self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) diff --git a/src/portal/azext_portal/commands.py b/src/portal/azext_portal/vendored_sdks/portal/_version.py similarity index 51% rename from src/portal/azext_portal/commands.py rename to src/portal/azext_portal/vendored_sdks/portal/_version.py index 42f0c1a991e..eae7c95b6fb 100644 --- a/src/portal/azext_portal/commands.py +++ b/src/portal/azext_portal/vendored_sdks/portal/_version.py @@ -1,12 +1,9 @@ -# -------------------------------------------------------------------------------------------- +# coding=utf-8 +# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- -# pylint: disable=wildcard-import -# pylint: disable=unused-wildcard-import +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- -from .generated.commands import * # noqa: F403 -try: - from .manual.commands import * # noqa: F403 -except ImportError: - pass +VERSION = "0.1.0" diff --git a/src/portal/azext_portal/vendored_sdks/portal/aio/_configuration_async.py b/src/portal/azext_portal/vendored_sdks/portal/aio/_configuration_async.py index f696a3c65d2..3660c892ebc 100644 --- a/src/portal/azext_portal/vendored_sdks/portal/aio/_configuration_async.py +++ b/src/portal/azext_portal/vendored_sdks/portal/aio/_configuration_async.py @@ -6,27 +6,33 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any +from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies -VERSION = "unknown" +from .._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + class PortalConfiguration(Configuration): - """Configuration for Portal + """Configuration for Portal. + Note that all parameters used to create this instance are saved as instance attributes. :param credential: Credential needed for the client to connect to Azure. - :type credential: azure.core.credentials.TokenCredential + :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). :type subscription_id: str """ def __init__( self, - credential: "TokenCredential", + credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any ) -> None: @@ -39,8 +45,9 @@ def __init__( self.credential = credential self.subscription_id = subscription_id self.api_version = "2019-01-01-preview" + self.credential_scopes = ['https://management.azure.com/.default'] + kwargs.setdefault('sdk_moniker', 'mgmt-portal/{}'.format(VERSION)) self._configure(**kwargs) - self.user_agent_policy.add_user_agent('azsdk-python-portal/{}'.format(VERSION)) def _configure( self, @@ -55,4 +62,4 @@ def _configure( self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) self.authentication_policy = kwargs.get('authentication_policy') if self.credential and not self.authentication_policy: - self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, **kwargs) + self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/src/portal/azext_portal/vendored_sdks/portal/aio/_portal_async.py b/src/portal/azext_portal/vendored_sdks/portal/aio/_portal_async.py index 878f1ca00ae..0ea4fddeb95 100644 --- a/src/portal/azext_portal/vendored_sdks/portal/aio/_portal_async.py +++ b/src/portal/azext_portal/vendored_sdks/portal/aio/_portal_async.py @@ -8,7 +8,7 @@ from typing import Any, Optional -from azure.core import AsyncPipelineClient +from azure.mgmt.core import AsyncARMPipelineClient from msrest import Deserializer, Serializer from ._configuration_async import PortalConfiguration @@ -21,11 +21,11 @@ class Portal(object): """Allows creation and deletion of Azure Shared Dashboards. :ivar operation: OperationOperations operations - :vartype operation: portal.aio.operations_async.OperationOperations + :vartype operation: azure.mgmt.portal.aio.operations_async.OperationOperations :ivar dashboard: DashboardOperations operations - :vartype dashboard: portal.aio.operations_async.DashboardOperations + :vartype dashboard: azure.mgmt.portal.aio.operations_async.DashboardOperations :param credential: Credential needed for the client to connect to Azure. - :type credential: azure.core.credentials.TokenCredential + :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). :type subscription_id: str :param str base_url: Service URL @@ -33,7 +33,7 @@ class Portal(object): def __init__( self, - credential: "TokenCredential", + credential: "AsyncTokenCredential", subscription_id: str, base_url: Optional[str] = None, **kwargs: Any @@ -41,7 +41,7 @@ def __init__( if not base_url: base_url = 'https://management.azure.com' self._config = PortalConfiguration(credential, subscription_id, **kwargs) - self._client = AsyncPipelineClient(base_url=base_url, config=self._config, **kwargs) + self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) diff --git a/src/portal/azext_portal/vendored_sdks/portal/aio/operations_async/_dashboard_operations_async.py b/src/portal/azext_portal/vendored_sdks/portal/aio/operations_async/_dashboard_operations_async.py index 000cbf46828..965be491c66 100644 --- a/src/portal/azext_portal/vendored_sdks/portal/aio/operations_async/_dashboard_operations_async.py +++ b/src/portal/azext_portal/vendored_sdks/portal/aio/operations_async/_dashboard_operations_async.py @@ -9,9 +9,10 @@ import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import map_error +from azure.core.exceptions import HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models @@ -21,10 +22,11 @@ class DashboardOperations: """DashboardOperations async operations. - You should not instantiate directly this class, but create a Client instance that will create it for you and attach it as attribute. + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. - :type models: ~portal.models + :type models: ~azure.mgmt.portal.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. @@ -60,19 +62,20 @@ async def create_or_update( :param tags: Resource tags. :type tags: dict[str, str] :param lenses: The dashboard lenses. - :type lenses: dict[str, ~portal.models.DashboardLens] + :type lenses: dict[str, ~azure.mgmt.portal.models.DashboardLens] :param metadata: The dashboard metadata. :type metadata: dict[str, object] :keyword callable cls: A custom type or function that will be passed the direct response - :return: Dashboard or Dashboard or the result of cls(response) - :rtype: ~portal.models.Dashboard or ~portal.models.Dashboard - :raises: ~portal.models.ErrorResponseException: + :return: Dashboard or the result of cls(response) + :rtype: ~azure.mgmt.portal.models.Dashboard or ~azure.mgmt.portal.models.Dashboard + :raises: ~azure.core.exceptions.HttpResponseError """ - cls: ClsType["models.Dashboard"] = kwargs.pop('cls', None ) - error_map = kwargs.pop('error_map', {}) + cls = kwargs.pop('cls', None) # type: ClsType["models.Dashboard"] + error_map = kwargs.pop('error_map', {404: ResourceNotFoundError, 409: ResourceExistsError}) - dashboard = models.Dashboard(location=location, tags=tags, lenses=lenses, metadata=metadata) + _dashboard = models.Dashboard(location=location, tags=tags, lenses=lenses, metadata=metadata) api_version = "2019-01-01-preview" + content_type = kwargs.pop("content_type", "application/json") # Construct URL url = self.create_or_update.metadata['url'] @@ -84,25 +87,27 @@ async def create_or_update( url = self._client.format_url(url, **path_format_arguments) # Construct parameters - query_parameters: Dict[str, Any] = {} + query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers - header_parameters: Dict[str, Any] = {} + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = 'application/json' - header_parameters['Content-Type'] = 'application/json' - - # Construct body - body_content = self._serialize.body(dashboard, 'Dashboard') # Construct and send request - request = self._client.put(url, query_parameters, header_parameters, body_content) + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(_dashboard, 'Dashboard') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise models.ErrorResponseException.from_response(response, self._deserialize) + error = self._deserialize(models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: @@ -132,10 +137,10 @@ async def delete( :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None - :raises: ~portal.models.ErrorResponseException: + :raises: ~azure.core.exceptions.HttpResponseError """ - cls: ClsType[None] = kwargs.pop('cls', None ) - error_map = kwargs.pop('error_map', {}) + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = kwargs.pop('error_map', {404: ResourceNotFoundError, 409: ResourceExistsError}) api_version = "2019-01-01-preview" # Construct URL @@ -148,11 +153,11 @@ async def delete( url = self._client.format_url(url, **path_format_arguments) # Construct parameters - query_parameters: Dict[str, Any] = {} + query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers - header_parameters: Dict[str, Any] = {} + header_parameters = {} # type: Dict[str, Any] # Construct and send request request = self._client.delete(url, query_parameters, header_parameters) @@ -161,7 +166,8 @@ async def delete( if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise models.ErrorResponseException.from_response(response, self._deserialize) + error = self._deserialize(models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) @@ -182,11 +188,11 @@ async def get( :type dashboard_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Dashboard or the result of cls(response) - :rtype: ~portal.models.Dashboard - :raises: ~portal.models.ErrorResponseException: + :rtype: ~azure.mgmt.portal.models.Dashboard + :raises: ~azure.core.exceptions.HttpResponseError """ - cls: ClsType["models.Dashboard"] = kwargs.pop('cls', None ) - error_map = kwargs.pop('error_map', {}) + cls = kwargs.pop('cls', None) # type: ClsType["models.Dashboard"] + error_map = kwargs.pop('error_map', {404: ResourceNotFoundError, 409: ResourceExistsError}) api_version = "2019-01-01-preview" # Construct URL @@ -199,11 +205,11 @@ async def get( url = self._client.format_url(url, **path_format_arguments) # Construct parameters - query_parameters: Dict[str, Any] = {} + query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers - header_parameters: Dict[str, Any] = {} + header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = 'application/json' # Construct and send request @@ -213,7 +219,8 @@ async def get( if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise models.ErrorResponseException.from_response(response, self._deserialize) + error = self._deserialize(models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('Dashboard', pipeline_response) @@ -241,19 +248,20 @@ async def update( :param tags: Resource tags. :type tags: dict[str, str] :param lenses: The dashboard lenses. - :type lenses: dict[str, ~portal.models.DashboardLens] + :type lenses: dict[str, ~azure.mgmt.portal.models.DashboardLens] :param metadata: The dashboard metadata. :type metadata: dict[str, object] :keyword callable cls: A custom type or function that will be passed the direct response :return: Dashboard or the result of cls(response) - :rtype: ~portal.models.Dashboard - :raises: ~portal.models.ErrorResponseException: + :rtype: ~azure.mgmt.portal.models.Dashboard + :raises: ~azure.core.exceptions.HttpResponseError """ - cls: ClsType["models.Dashboard"] = kwargs.pop('cls', None ) - error_map = kwargs.pop('error_map', {}) + cls = kwargs.pop('cls', None) # type: ClsType["models.Dashboard"] + error_map = kwargs.pop('error_map', {404: ResourceNotFoundError, 409: ResourceExistsError}) - dashboard = models.PatchableDashboard(tags=tags, lenses=lenses, metadata=metadata) + _dashboard = models.PatchableDashboard(tags=tags, lenses=lenses, metadata=metadata) api_version = "2019-01-01-preview" + content_type = kwargs.pop("content_type", "application/json") # Construct URL url = self.update.metadata['url'] @@ -265,25 +273,27 @@ async def update( url = self._client.format_url(url, **path_format_arguments) # Construct parameters - query_parameters: Dict[str, Any] = {} + query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers - header_parameters: Dict[str, Any] = {} + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = 'application/json' - header_parameters['Content-Type'] = 'application/json' - - # Construct body - body_content = self._serialize.body(dashboard, 'PatchableDashboard') # Construct and send request - request = self._client.patch(url, query_parameters, header_parameters, body_content) + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(_dashboard, 'PatchableDashboard') + body_content_kwargs['content'] = body_content + request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise models.ErrorResponseException.from_response(response, self._deserialize) + error = self._deserialize(models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('Dashboard', pipeline_response) @@ -304,11 +314,11 @@ def list_by_resource_group( :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: DashboardListResult or the result of cls(response) - :rtype: ~portal.models.DashboardListResult - :raises: ~portal.models.ErrorResponseException: + :rtype: ~azure.mgmt.portal.models.DashboardListResult + :raises: ~azure.core.exceptions.HttpResponseError """ - cls: ClsType["models.DashboardListResult"] = kwargs.pop('cls', None ) - error_map = kwargs.pop('error_map', {}) + cls = kwargs.pop('cls', None) # type: ClsType["models.DashboardListResult"] + error_map = kwargs.pop('error_map', {404: ResourceNotFoundError, 409: ResourceExistsError}) api_version = "2019-01-01-preview" def prepare_request(next_link=None): @@ -324,11 +334,11 @@ def prepare_request(next_link=None): url = next_link # Construct parameters - query_parameters: Dict[str, Any] = {} + query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers - header_parameters: Dict[str, Any] = {} + header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = 'application/json' # Construct and send request @@ -340,7 +350,7 @@ async def extract_data(pipeline_response): list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) - return deserialized.next_link, AsyncList(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) @@ -349,8 +359,9 @@ async def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: + error = self._deserialize(models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) - raise models.ErrorResponseException.from_response(response, self._deserialize) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response @@ -367,11 +378,11 @@ def list_by_subscription( :keyword callable cls: A custom type or function that will be passed the direct response :return: DashboardListResult or the result of cls(response) - :rtype: ~portal.models.DashboardListResult - :raises: ~portal.models.ErrorResponseException: + :rtype: ~azure.mgmt.portal.models.DashboardListResult + :raises: ~azure.core.exceptions.HttpResponseError """ - cls: ClsType["models.DashboardListResult"] = kwargs.pop('cls', None ) - error_map = kwargs.pop('error_map', {}) + cls = kwargs.pop('cls', None) # type: ClsType["models.DashboardListResult"] + error_map = kwargs.pop('error_map', {404: ResourceNotFoundError, 409: ResourceExistsError}) api_version = "2019-01-01-preview" def prepare_request(next_link=None): @@ -386,11 +397,11 @@ def prepare_request(next_link=None): url = next_link # Construct parameters - query_parameters: Dict[str, Any] = {} + query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers - header_parameters: Dict[str, Any] = {} + header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = 'application/json' # Construct and send request @@ -402,7 +413,7 @@ async def extract_data(pipeline_response): list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) - return deserialized.next_link, AsyncList(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) @@ -411,8 +422,9 @@ async def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: + error = self._deserialize(models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) - raise models.ErrorResponseException.from_response(response, self._deserialize) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response diff --git a/src/portal/azext_portal/vendored_sdks/portal/aio/operations_async/_operation_operations_async.py b/src/portal/azext_portal/vendored_sdks/portal/aio/operations_async/_operation_operations_async.py index aebe6bdf31d..5705d01e4eb 100644 --- a/src/portal/azext_portal/vendored_sdks/portal/aio/operations_async/_operation_operations_async.py +++ b/src/portal/azext_portal/vendored_sdks/portal/aio/operations_async/_operation_operations_async.py @@ -9,9 +9,10 @@ import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import map_error +from azure.core.exceptions import HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models @@ -21,10 +22,11 @@ class OperationOperations: """OperationOperations async operations. - You should not instantiate directly this class, but create a Client instance that will create it for you and attach it as attribute. + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. - :type models: ~portal.models + :type models: ~azure.mgmt.portal.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. @@ -47,11 +49,11 @@ def list( :keyword callable cls: A custom type or function that will be passed the direct response :return: ResourceProviderOperationList or the result of cls(response) - :rtype: ~portal.models.ResourceProviderOperationList - :raises: ~portal.models.ErrorResponseException: + :rtype: ~azure.mgmt.portal.models.ResourceProviderOperationList + :raises: ~azure.core.exceptions.HttpResponseError """ - cls: ClsType["models.ResourceProviderOperationList"] = kwargs.pop('cls', None ) - error_map = kwargs.pop('error_map', {}) + cls = kwargs.pop('cls', None) # type: ClsType["models.ResourceProviderOperationList"] + error_map = kwargs.pop('error_map', {404: ResourceNotFoundError, 409: ResourceExistsError}) api_version = "2019-01-01-preview" def prepare_request(next_link=None): @@ -62,11 +64,11 @@ def prepare_request(next_link=None): url = next_link # Construct parameters - query_parameters: Dict[str, Any] = {} + query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers - header_parameters: Dict[str, Any] = {} + header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = 'application/json' # Construct and send request @@ -78,7 +80,7 @@ async def extract_data(pipeline_response): list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) - return deserialized.next_link, AsyncList(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) @@ -87,8 +89,9 @@ async def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: + error = self._deserialize(models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) - raise models.ErrorResponseException.from_response(response, self._deserialize) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response diff --git a/src/portal/azext_portal/vendored_sdks/portal/models/__init__.py b/src/portal/azext_portal/vendored_sdks/portal/models/__init__.py index 84909621e71..aa954a6759d 100644 --- a/src/portal/azext_portal/vendored_sdks/portal/models/__init__.py +++ b/src/portal/azext_portal/vendored_sdks/portal/models/__init__.py @@ -12,9 +12,8 @@ from ._models_py3 import DashboardListResult from ._models_py3 import DashboardParts from ._models_py3 import DashboardPartsPosition - from ._models_py3 import DashboardProperties from ._models_py3 import ErrorDefinition - from ._models_py3 import ErrorResponse, ErrorResponseException + from ._models_py3 import ErrorResponse from ._models_py3 import PatchableDashboard from ._models_py3 import ResourceProviderOperation from ._models_py3 import ResourceProviderOperationDisplay @@ -25,9 +24,8 @@ from ._models import DashboardListResult # type: ignore from ._models import DashboardParts # type: ignore from ._models import DashboardPartsPosition # type: ignore - from ._models import DashboardProperties # type: ignore from ._models import ErrorDefinition # type: ignore - from ._models import ErrorResponse, ErrorResponseException # type: ignore + from ._models import ErrorResponse # type: ignore from ._models import PatchableDashboard # type: ignore from ._models import ResourceProviderOperation # type: ignore from ._models import ResourceProviderOperationDisplay # type: ignore @@ -39,9 +37,8 @@ 'DashboardListResult', 'DashboardParts', 'DashboardPartsPosition', - 'DashboardProperties', 'ErrorDefinition', - 'ErrorResponse', 'ErrorResponseException', + 'ErrorResponse', 'PatchableDashboard', 'ResourceProviderOperation', 'ResourceProviderOperationDisplay', diff --git a/src/portal/azext_portal/vendored_sdks/portal/models/_models.py b/src/portal/azext_portal/vendored_sdks/portal/models/_models.py index bc70d849819..b9ee1799b90 100644 --- a/src/portal/azext_portal/vendored_sdks/portal/models/_models.py +++ b/src/portal/azext_portal/vendored_sdks/portal/models/_models.py @@ -28,7 +28,7 @@ class Dashboard(msrest.serialization.Model): :param tags: A set of tags. Resource tags. :type tags: dict[str, str] :param lenses: The dashboard lenses. - :type lenses: dict[str, ~portal.models.DashboardLens] + :type lenses: dict[str, ~azure.mgmt.portal.models.DashboardLens] :param metadata: The dashboard metadata. :type metadata: dict[str, object] """ @@ -58,7 +58,7 @@ def __init__( self.id = None self.name = None self.type = None - self.location = kwargs.get('location', None) + self.location = kwargs['location'] self.tags = kwargs.get('tags', None) self.lenses = kwargs.get('lenses', None) self.metadata = kwargs.get('metadata', None) @@ -72,7 +72,7 @@ class DashboardLens(msrest.serialization.Model): :param order: Required. The lens order. :type order: int :param parts: Required. The dashboard parts. - :type parts: dict[str, ~portal.models.DashboardParts] + :type parts: dict[str, ~azure.mgmt.portal.models.DashboardParts] :param metadata: The dashboard len's metadata. :type metadata: dict[str, object] """ @@ -93,8 +93,8 @@ def __init__( **kwargs ): super(DashboardLens, self).__init__(**kwargs) - self.order = kwargs.get('order', None) - self.parts = kwargs.get('parts', None) + self.order = kwargs['order'] + self.parts = kwargs['parts'] self.metadata = kwargs.get('metadata', None) @@ -102,7 +102,7 @@ class DashboardListResult(msrest.serialization.Model): """List of dashboards. :param value: The array of custom resource provider manifests. - :type value: list[~portal.models.Dashboard] + :type value: list[~azure.mgmt.portal.models.Dashboard] :param next_link: The URL to use for getting the next set of results. :type next_link: str """ @@ -127,7 +127,7 @@ class DashboardParts(msrest.serialization.Model): All required parameters must be populated in order to send to Azure. :param position: Required. The dashboard's part position. - :type position: ~portal.models.DashboardPartsPosition + :type position: ~azure.mgmt.portal.models.DashboardPartsPosition :param metadata: The dashboard part's metadata. :type metadata: dict[str, object] """ @@ -146,7 +146,7 @@ def __init__( **kwargs ): super(DashboardParts, self).__init__(**kwargs) - self.position = kwargs.get('position', None) + self.position = kwargs['position'] self.metadata = kwargs.get('metadata', None) @@ -187,33 +187,10 @@ def __init__( **kwargs ): super(DashboardPartsPosition, self).__init__(**kwargs) - self.x = kwargs.get('x', None) - self.y = kwargs.get('y', None) - self.row_span = kwargs.get('row_span', None) - self.col_span = kwargs.get('col_span', None) - self.metadata = kwargs.get('metadata', None) - - -class DashboardProperties(msrest.serialization.Model): - """The shared dashboard properties. - - :param lenses: The dashboard lenses. - :type lenses: dict[str, ~portal.models.DashboardLens] - :param metadata: The dashboard metadata. - :type metadata: dict[str, object] - """ - - _attribute_map = { - 'lenses': {'key': 'lenses', 'type': '{DashboardLens}'}, - 'metadata': {'key': 'metadata', 'type': '{object}'}, - } - - def __init__( - self, - **kwargs - ): - super(DashboardProperties, self).__init__(**kwargs) - self.lenses = kwargs.get('lenses', None) + self.x = kwargs['x'] + self.y = kwargs['y'] + self.row_span = kwargs['row_span'] + self.col_span = kwargs['col_span'] self.metadata = kwargs.get('metadata', None) @@ -227,7 +204,7 @@ class ErrorDefinition(msrest.serialization.Model): :ivar message: Description of the error. :vartype message: str :ivar details: Internal error details. - :vartype details: list[~portal.models.ErrorDefinition] + :vartype details: list[~azure.mgmt.portal.models.ErrorDefinition] """ _validation = { @@ -252,38 +229,12 @@ def __init__( self.details = None -class ErrorResponseException(HttpResponseError): - """Server responded with exception of type: 'ErrorResponse'. - - :param response: Server response to be deserialized. - :param error_model: A deserialized model of the response body as model. - """ - - def __init__(self, response, error_model): - self.error = error_model - super(ErrorResponseException, self).__init__(response=response, error_model=error_model) - - @classmethod - def from_response(cls, response, deserialize): - """Deserialize this response as this exception, or a subclass of this exception. - - :param response: Server response to be deserialized. - :param deserialize: A deserializer - """ - model_name = 'ErrorResponse' - error = deserialize(model_name, response) - if error is None: - error = deserialize.dependencies[model_name]() - return error._EXCEPTION_TYPE(response, error) - - class ErrorResponse(msrest.serialization.Model): """Error response. - :param error: Error definition. - :type error: ~portal.models.ErrorDefinition + :param error: The error details. + :type error: ~azure.mgmt.portal.models.ErrorDefinition """ - _EXCEPTION_TYPE = ErrorResponseException _attribute_map = { 'error': {'key': 'error', 'type': 'ErrorDefinition'}, @@ -303,7 +254,7 @@ class PatchableDashboard(msrest.serialization.Model): :param tags: A set of tags. Resource tags. :type tags: dict[str, str] :param lenses: The dashboard lenses. - :type lenses: dict[str, ~portal.models.DashboardLens] + :type lenses: dict[str, ~azure.mgmt.portal.models.DashboardLens] :param metadata: The dashboard metadata. :type metadata: dict[str, object] """ @@ -332,7 +283,7 @@ class ResourceProviderOperation(msrest.serialization.Model): :param is_data_action: Indicates whether the operation applies to data-plane. :type is_data_action: str :param display: Display metadata associated with the operation. - :type display: ~portal.models.ResourceProviderOperationDisplay + :type display: ~azure.mgmt.portal.models.ResourceProviderOperationDisplay """ _attribute_map = { @@ -386,7 +337,7 @@ class ResourceProviderOperationList(msrest.serialization.Model): """Results of the request to list operations. :param value: List of operations supported by this resource provider. - :type value: list[~portal.models.ResourceProviderOperation] + :type value: list[~azure.mgmt.portal.models.ResourceProviderOperation] :param next_link: The URL to use for getting the next set of results. :type next_link: str """ diff --git a/src/portal/azext_portal/vendored_sdks/portal/models/_models_py3.py b/src/portal/azext_portal/vendored_sdks/portal/models/_models_py3.py index 47507e86168..3f5c8db9e11 100644 --- a/src/portal/azext_portal/vendored_sdks/portal/models/_models_py3.py +++ b/src/portal/azext_portal/vendored_sdks/portal/models/_models_py3.py @@ -30,7 +30,7 @@ class Dashboard(msrest.serialization.Model): :param tags: A set of tags. Resource tags. :type tags: dict[str, str] :param lenses: The dashboard lenses. - :type lenses: dict[str, ~portal.models.DashboardLens] + :type lenses: dict[str, ~azure.mgmt.portal.models.DashboardLens] :param metadata: The dashboard metadata. :type metadata: dict[str, object] """ @@ -79,7 +79,7 @@ class DashboardLens(msrest.serialization.Model): :param order: Required. The lens order. :type order: int :param parts: Required. The dashboard parts. - :type parts: dict[str, ~portal.models.DashboardParts] + :type parts: dict[str, ~azure.mgmt.portal.models.DashboardParts] :param metadata: The dashboard len's metadata. :type metadata: dict[str, object] """ @@ -113,7 +113,7 @@ class DashboardListResult(msrest.serialization.Model): """List of dashboards. :param value: The array of custom resource provider manifests. - :type value: list[~portal.models.Dashboard] + :type value: list[~azure.mgmt.portal.models.Dashboard] :param next_link: The URL to use for getting the next set of results. :type next_link: str """ @@ -141,7 +141,7 @@ class DashboardParts(msrest.serialization.Model): All required parameters must be populated in order to send to Azure. :param position: Required. The dashboard's part position. - :type position: ~portal.models.DashboardPartsPosition + :type position: ~azure.mgmt.portal.models.DashboardPartsPosition :param metadata: The dashboard part's metadata. :type metadata: dict[str, object] """ @@ -217,32 +217,6 @@ def __init__( self.metadata = metadata -class DashboardProperties(msrest.serialization.Model): - """The shared dashboard properties. - - :param lenses: The dashboard lenses. - :type lenses: dict[str, ~portal.models.DashboardLens] - :param metadata: The dashboard metadata. - :type metadata: dict[str, object] - """ - - _attribute_map = { - 'lenses': {'key': 'lenses', 'type': '{DashboardLens}'}, - 'metadata': {'key': 'metadata', 'type': '{object}'}, - } - - def __init__( - self, - *, - lenses: Optional[Dict[str, "DashboardLens"]] = None, - metadata: Optional[Dict[str, object]] = None, - **kwargs - ): - super(DashboardProperties, self).__init__(**kwargs) - self.lenses = lenses - self.metadata = metadata - - class ErrorDefinition(msrest.serialization.Model): """Error definition. @@ -253,7 +227,7 @@ class ErrorDefinition(msrest.serialization.Model): :ivar message: Description of the error. :vartype message: str :ivar details: Internal error details. - :vartype details: list[~portal.models.ErrorDefinition] + :vartype details: list[~azure.mgmt.portal.models.ErrorDefinition] """ _validation = { @@ -278,38 +252,12 @@ def __init__( self.details = None -class ErrorResponseException(HttpResponseError): - """Server responded with exception of type: 'ErrorResponse'. - - :param response: Server response to be deserialized. - :param error_model: A deserialized model of the response body as model. - """ - - def __init__(self, response, error_model): - self.error = error_model - super(ErrorResponseException, self).__init__(response=response, error_model=error_model) - - @classmethod - def from_response(cls, response, deserialize): - """Deserialize this response as this exception, or a subclass of this exception. - - :param response: Server response to be deserialized. - :param deserialize: A deserializer - """ - model_name = 'ErrorResponse' - error = deserialize(model_name, response) - if error is None: - error = deserialize.dependencies[model_name]() - return error._EXCEPTION_TYPE(response, error) - - class ErrorResponse(msrest.serialization.Model): """Error response. - :param error: Error definition. - :type error: ~portal.models.ErrorDefinition + :param error: The error details. + :type error: ~azure.mgmt.portal.models.ErrorDefinition """ - _EXCEPTION_TYPE = ErrorResponseException _attribute_map = { 'error': {'key': 'error', 'type': 'ErrorDefinition'}, @@ -331,7 +279,7 @@ class PatchableDashboard(msrest.serialization.Model): :param tags: A set of tags. Resource tags. :type tags: dict[str, str] :param lenses: The dashboard lenses. - :type lenses: dict[str, ~portal.models.DashboardLens] + :type lenses: dict[str, ~azure.mgmt.portal.models.DashboardLens] :param metadata: The dashboard metadata. :type metadata: dict[str, object] """ @@ -364,7 +312,7 @@ class ResourceProviderOperation(msrest.serialization.Model): :param is_data_action: Indicates whether the operation applies to data-plane. :type is_data_action: str :param display: Display metadata associated with the operation. - :type display: ~portal.models.ResourceProviderOperationDisplay + :type display: ~azure.mgmt.portal.models.ResourceProviderOperationDisplay """ _attribute_map = { @@ -427,7 +375,7 @@ class ResourceProviderOperationList(msrest.serialization.Model): """Results of the request to list operations. :param value: List of operations supported by this resource provider. - :type value: list[~portal.models.ResourceProviderOperation] + :type value: list[~azure.mgmt.portal.models.ResourceProviderOperation] :param next_link: The URL to use for getting the next set of results. :type next_link: str """ diff --git a/src/portal/azext_portal/vendored_sdks/portal/operations/_dashboard_operations.py b/src/portal/azext_portal/vendored_sdks/portal/operations/_dashboard_operations.py index 403f882f8a6..d31330de60b 100644 --- a/src/portal/azext_portal/vendored_sdks/portal/operations/_dashboard_operations.py +++ b/src/portal/azext_portal/vendored_sdks/portal/operations/_dashboard_operations.py @@ -5,28 +5,32 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union +from typing import TYPE_CHECKING import warnings -from azure.core.exceptions import map_error +from azure.core.exceptions import HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models -T = TypeVar('T') -ClsType = Optional[Callable[[ - PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class DashboardOperations(object): """DashboardOperations operations. - You should not instantiate directly this class, but create a Client instance that will create it for you and attach it as attribute. + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. - :type models: ~portal.models + :type models: ~azure.mgmt.portal.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. @@ -63,20 +67,20 @@ def create_or_update( :param tags: Resource tags. :type tags: dict[str, str] :param lenses: The dashboard lenses. - :type lenses: dict[str, ~portal.models.DashboardLens] + :type lenses: dict[str, ~azure.mgmt.portal.models.DashboardLens] :param metadata: The dashboard metadata. :type metadata: dict[str, object] :keyword callable cls: A custom type or function that will be passed the direct response - :return: Dashboard or Dashboard or the result of cls(response) - :rtype: ~portal.models.Dashboard or ~portal.models.Dashboard - :raises: ~portal.models.ErrorResponseException: + :return: Dashboard or the result of cls(response) + :rtype: ~azure.mgmt.portal.models.Dashboard or ~azure.mgmt.portal.models.Dashboard + :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.Dashboard"] - error_map = kwargs.pop('error_map', {}) + error_map = kwargs.pop('error_map', {404: ResourceNotFoundError, 409: ResourceExistsError}) - dashboard = models.Dashboard( - location=location, tags=tags, lenses=lenses, metadata=metadata) + _dashboard = models.Dashboard(location=location, tags=tags, lenses=lenses, metadata=metadata) api_version = "2019-01-01-preview" + content_type = kwargs.pop("content_type", "application/json") # Construct URL url = self.create_or_update.metadata['url'] @@ -88,30 +92,27 @@ def create_or_update( url = self._client.format_url(url, **path_format_arguments) # Construct parameters - query_parameters = {} - query_parameters['api-version'] = self._serialize.query( - "api_version", api_version, 'str') + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers - header_parameters = {} + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = 'application/json' - header_parameters['Content-Type'] = 'application/json' - - # Construct body - body_content = self._serialize.body(dashboard, 'Dashboard') # Construct and send request - request = self._client.put( - url, query_parameters, header_parameters, body_content) - pipeline_response = self._client._pipeline.run( - request, stream=False, **kwargs) + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(_dashboard, 'Dashboard') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, - response=response, error_map=error_map) - raise models.ErrorResponseException.from_response( - response, self._deserialize) + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize(models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: @@ -121,11 +122,10 @@ def create_or_update( deserialized = self._deserialize('Dashboard', pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update.metadata = { - 'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Portal/dashboards/{dashboardName}'} + create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Portal/dashboards/{dashboardName}'} def delete( self, @@ -143,10 +143,10 @@ def delete( :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None - :raises: ~portal.models.ErrorResponseException: + :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = kwargs.pop('error_map', {}) + error_map = kwargs.pop('error_map', {404: ResourceNotFoundError, 409: ResourceExistsError}) api_version = "2019-01-01-preview" # Construct URL @@ -159,30 +159,26 @@ def delete( url = self._client.format_url(url, **path_format_arguments) # Construct parameters - query_parameters = {} - query_parameters['api-version'] = self._serialize.query( - "api_version", api_version, 'str') + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers - header_parameters = {} + header_parameters = {} # type: Dict[str, Any] # Construct and send request request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run( - request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, - response=response, error_map=error_map) - raise models.ErrorResponseException.from_response( - response, self._deserialize) + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize(models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) - delete.metadata = { - 'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Portal/dashboards/{dashboardName}'} + delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Portal/dashboards/{dashboardName}'} def get( self, @@ -199,11 +195,11 @@ def get( :type dashboard_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Dashboard or the result of cls(response) - :rtype: ~portal.models.Dashboard - :raises: ~portal.models.ErrorResponseException: + :rtype: ~azure.mgmt.portal.models.Dashboard + :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.Dashboard"] - error_map = kwargs.pop('error_map', {}) + error_map = kwargs.pop('error_map', {404: ResourceNotFoundError, 409: ResourceExistsError}) api_version = "2019-01-01-preview" # Construct URL @@ -216,39 +212,36 @@ def get( url = self._client.format_url(url, **path_format_arguments) # Construct parameters - query_parameters = {} - query_parameters['api-version'] = self._serialize.query( - "api_version", api_version, 'str') + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers - header_parameters = {} + header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = 'application/json' # Construct and send request request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run( - request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: - map_error(status_code=response.status_code, - response=response, error_map=error_map) - raise models.ErrorResponseException.from_response( - response, self._deserialize) + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize(models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('Dashboard', pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = { - 'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Portal/dashboards/{dashboardName}'} + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Portal/dashboards/{dashboardName}'} def update( self, resource_group_name, # type: str dashboard_name, # type: str + tags=None, # type: Optional[Dict[str, str]] lenses=None, # type: Optional[Dict[str, "DashboardLens"]] metadata=None, # type: Optional[Dict[str, object]] **kwargs # type: Any @@ -260,20 +253,23 @@ def update( :type resource_group_name: str :param dashboard_name: The name of the dashboard. :type dashboard_name: str + :param tags: Resource tags. + :type tags: dict[str, str] :param lenses: The dashboard lenses. - :type lenses: dict[str, ~portal.models.DashboardLens] + :type lenses: dict[str, ~azure.mgmt.portal.models.DashboardLens] :param metadata: The dashboard metadata. :type metadata: dict[str, object] :keyword callable cls: A custom type or function that will be passed the direct response :return: Dashboard or the result of cls(response) - :rtype: ~portal.models.Dashboard - :raises: ~portal.models.ErrorResponseException: + :rtype: ~azure.mgmt.portal.models.Dashboard + :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.Dashboard"] - error_map = kwargs.pop('error_map', {}) + error_map = kwargs.pop('error_map', {404: ResourceNotFoundError, 409: ResourceExistsError}) - dashboard = models.PatchableDashboard(lenses=lenses, metadata=metadata) + _dashboard = models.PatchableDashboard(tags=tags, lenses=lenses, metadata=metadata) api_version = "2019-01-01-preview" + content_type = kwargs.pop("content_type", "application/json") # Construct URL url = self.update.metadata['url'] @@ -285,39 +281,35 @@ def update( url = self._client.format_url(url, **path_format_arguments) # Construct parameters - query_parameters = {} - query_parameters['api-version'] = self._serialize.query( - "api_version", api_version, 'str') + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers - header_parameters = {} + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = 'application/json' - header_parameters['Content-Type'] = 'application/json' - - # Construct body - body_content = self._serialize.body(dashboard, 'PatchableDashboard') # Construct and send request - request = self._client.patch( - url, query_parameters, header_parameters, body_content) - pipeline_response = self._client._pipeline.run( - request, stream=False, **kwargs) + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(_dashboard, 'PatchableDashboard') + body_content_kwargs['content'] = body_content + request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: - map_error(status_code=response.status_code, - response=response, error_map=error_map) - raise models.ErrorResponseException.from_response( - response, self._deserialize) + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize(models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('Dashboard', pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = { - 'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Portal/dashboards/{dashboardName}'} + update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Portal/dashboards/{dashboardName}'} def list_by_resource_group( self, @@ -331,12 +323,11 @@ def list_by_resource_group( :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: DashboardListResult or the result of cls(response) - :rtype: ~portal.models.DashboardListResult - :raises: ~portal.models.ErrorResponseException: + :rtype: ~azure.mgmt.portal.models.DashboardListResult + :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop( - 'cls', None) # type: ClsType["models.DashboardListResult"] - error_map = kwargs.pop('error_map', {}) + cls = kwargs.pop('cls', None) # type: ClsType["models.DashboardListResult"] + error_map = kwargs.pop('error_map', {404: ResourceNotFoundError, 409: ResourceExistsError}) api_version = "2019-01-01-preview" def prepare_request(next_link=None): @@ -352,47 +343,41 @@ def prepare_request(next_link=None): url = next_link # Construct parameters - query_parameters = {} - query_parameters['api-version'] = self._serialize.query( - "api_version", api_version, 'str') + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers - header_parameters = {} + header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = 'application/json' # Construct and send request - request = self._client.get( - url, query_parameters, header_parameters) + request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): - deserialized = self._deserialize( - 'DashboardListResult', pipeline_response) + deserialized = self._deserialize('DashboardListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) - return deserialized.next_link, iter(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( - request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: - map_error(status_code=response.status_code, - response=response, error_map=error_map) - raise models.ErrorResponseException.from_response( - response, self._deserialize) + error = self._deserialize(models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) - list_by_resource_group.metadata = { - 'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Portal/dashboards'} + list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Portal/dashboards'} def list_by_subscription( self, @@ -403,12 +388,11 @@ def list_by_subscription( :keyword callable cls: A custom type or function that will be passed the direct response :return: DashboardListResult or the result of cls(response) - :rtype: ~portal.models.DashboardListResult - :raises: ~portal.models.ErrorResponseException: + :rtype: ~azure.mgmt.portal.models.DashboardListResult + :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop( - 'cls', None) # type: ClsType["models.DashboardListResult"] - error_map = kwargs.pop('error_map', {}) + cls = kwargs.pop('cls', None) # type: ClsType["models.DashboardListResult"] + error_map = kwargs.pop('error_map', {404: ResourceNotFoundError, 409: ResourceExistsError}) api_version = "2019-01-01-preview" def prepare_request(next_link=None): @@ -423,118 +407,38 @@ def prepare_request(next_link=None): url = next_link # Construct parameters - query_parameters = {} - query_parameters['api-version'] = self._serialize.query( - "api_version", api_version, 'str') + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers - header_parameters = {} + header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = 'application/json' # Construct and send request - request = self._client.get( - url, query_parameters, header_parameters) + request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): - deserialized = self._deserialize( - 'DashboardListResult', pipeline_response) + deserialized = self._deserialize('DashboardListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) - return deserialized.next_link, iter(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( - request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: - map_error(status_code=response.status_code, - response=response, error_map=error_map) - raise models.ErrorResponseException.from_response( - response, self._deserialize) + error = self._deserialize(models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) - list_by_subscription.metadata = { - 'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Portal/dashboards'} - - def dashboard_import( - self, - resource_group_name, # type: str - dashboard_name, # type: str - dashboard, # type: "models.Dashboard" - **kwargs # type: Any - ): - # type: (...) -> "models.Dashboard" - """Creates or updates a Dashboard. - - :param resource_group_name: The name of the resource group. - :type resource_group_name: str - :param dashboard_name: The name of the dashboard. - :type dashboard_name: str - :param dashboard: The parameters required to create or update a dashboard. - :type dashboard: ~portal.models.Dashboard - :keyword callable cls: A custom type or function that will be passed the direct response - :return: Dashboard or Dashboard or the result of cls(response) - :rtype: ~portal.models.Dashboard or ~portal.models.Dashboard - :raises: ~portal.models.ErrorResponseException: - """ - cls = kwargs.pop('cls', None) # type: ClsType["models.Dashboard"] - error_map = kwargs.pop('error_map', {}) - api_version = "2019-01-01-preview" - - # Construct URL - url = self.create_or_update.metadata['url'] - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'dashboardName': self._serialize.url("dashboard_name", dashboard_name, 'str', max_length=64, min_length=3), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters['api-version'] = self._serialize.query( - "api_version", api_version, 'str') - - # Construct headers - header_parameters = {} - header_parameters['Accept'] = 'application/json' - header_parameters['Content-Type'] = 'application/json' - - # Construct body - body_content = self._serialize.body(dashboard, 'Dashboard') - - # Construct and send request - request = self._client.put( - url, query_parameters, header_parameters, body_content) - pipeline_response = self._client._pipeline.run( - request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, - response=response, error_map=error_map) - raise models.ErrorResponseException.from_response( - response, self._deserialize) - - deserialized = None - if response.status_code == 200: - deserialized = self._deserialize('Dashboard', pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize('Dashboard', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - create_or_update.metadata = { - 'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Portal/dashboards/{dashboardName}'} + list_by_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Portal/dashboards'} diff --git a/src/portal/azext_portal/vendored_sdks/portal/operations/_operation_operations.py b/src/portal/azext_portal/vendored_sdks/portal/operations/_operation_operations.py index 59145766d1b..4dd0fe05dcf 100644 --- a/src/portal/azext_portal/vendored_sdks/portal/operations/_operation_operations.py +++ b/src/portal/azext_portal/vendored_sdks/portal/operations/_operation_operations.py @@ -5,26 +5,32 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Generic, Optional, TypeVar +from typing import TYPE_CHECKING import warnings -from azure.core.exceptions import map_error +from azure.core.exceptions import HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models -T = TypeVar('T') -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class OperationOperations(object): """OperationOperations operations. - You should not instantiate directly this class, but create a Client instance that will create it for you and attach it as attribute. + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. - :type models: ~portal.models + :type models: ~azure.mgmt.portal.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. @@ -48,11 +54,11 @@ def list( :keyword callable cls: A custom type or function that will be passed the direct response :return: ResourceProviderOperationList or the result of cls(response) - :rtype: ~portal.models.ResourceProviderOperationList - :raises: ~portal.models.ErrorResponseException: + :rtype: ~azure.mgmt.portal.models.ResourceProviderOperationList + :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None ) # type: ClsType["models.ResourceProviderOperationList"] - error_map = kwargs.pop('error_map', {}) + cls = kwargs.pop('cls', None) # type: ClsType["models.ResourceProviderOperationList"] + error_map = kwargs.pop('error_map', {404: ResourceNotFoundError, 409: ResourceExistsError}) api_version = "2019-01-01-preview" def prepare_request(next_link=None): @@ -63,11 +69,11 @@ def prepare_request(next_link=None): url = next_link # Construct parameters - query_parameters = {} + query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers - header_parameters = {} + header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = 'application/json' # Construct and send request @@ -79,7 +85,7 @@ def extract_data(pipeline_response): list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) - return deserialized.next_link, iter(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) @@ -88,8 +94,9 @@ def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: + error = self._deserialize(models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) - raise models.ErrorResponseException.from_response(response, self._deserialize) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response diff --git a/src/portal/azext_portal/vendored_sdks/portal/py.typed b/src/portal/azext_portal/vendored_sdks/portal/py.typed new file mode 100644 index 00000000000..e5aff4f83af --- /dev/null +++ b/src/portal/azext_portal/vendored_sdks/portal/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/src/portal/report.md b/src/portal/report.md new file mode 100644 index 00000000000..54716e34135 --- /dev/null +++ b/src/portal/report.md @@ -0,0 +1,48 @@ +# Azure CLI Module Creation Report + +### portal dashboard create + +create a portal dashboard. + +|Option|Type|Description|Path (SDK)|Path (swagger)| +|------|----|-----------|----------|--------------| +|**--resource-group-name**|string|The name of the resource group.|resource_group_name| +|**--name**|string|The name of the dashboard.|name| +|**--location**|string|Resource location|location| +|**--tags**|dictionary|Resource tags|tags| +|**--lenses**|dictionary|The dashboard lenses.|lenses| +|**--metadata**|dictionary|The dashboard metadata.|metadata| +### portal dashboard delete + +delete a portal dashboard. + +|Option|Type|Description|Path (SDK)|Path (swagger)| +|------|----|-----------|----------|--------------| +|**--resource-group-name**|string|The name of the resource group.|resource_group_name| +|**--name**|string|The name of the dashboard.|name| +### portal dashboard list + +list a portal dashboard. + +|Option|Type|Description|Path (SDK)|Path (swagger)| +|------|----|-----------|----------|--------------| +|**--resource-group-name**|string|The name of the resource group.|resource_group_name| +### portal dashboard show + +show a portal dashboard. + +|Option|Type|Description|Path (SDK)|Path (swagger)| +|------|----|-----------|----------|--------------| +|**--resource-group-name**|string|The name of the resource group.|resource_group_name| +|**--name**|string|The name of the dashboard.|name| +### portal dashboard update + +update a portal dashboard. + +|Option|Type|Description|Path (SDK)|Path (swagger)| +|------|----|-----------|----------|--------------| +|**--resource-group-name**|string|The name of the resource group.|resource_group_name| +|**--name**|string|The name of the dashboard.|name| +|**--tags**|dictionary|Resource tags|tags| +|**--lenses**|dictionary|The dashboard lenses.|lenses| +|**--metadata**|dictionary|The dashboard metadata.|metadata| \ No newline at end of file diff --git a/src/portal/setup.cfg b/src/portal/setup.cfg index e69de29bb2d..2fdd96e5d39 100644 --- a/src/portal/setup.cfg +++ b/src/portal/setup.cfg @@ -0,0 +1 @@ +#setup.cfg \ No newline at end of file diff --git a/src/portal/setup.py b/src/portal/setup.py index d5d78350f42..3dc6a32536e 100644 --- a/src/portal/setup.py +++ b/src/portal/setup.py @@ -1,58 +1,53 @@ -#!/usr/bin/env python - -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - - -from codecs import open -from setuptools import setup, find_packages -try: - from azure_bdist_wheel import cmdclass -except ImportError: - from distutils import log as logger - logger.warn("Wheel is not available, disabling bdist_wheel hook") - -# TODO: Confirm this is the right version number you want and it matches your -# HISTORY.rst entry. -VERSION = '0.1.0' - -# The full list of classifiers is available at -# https://pypi.python.org/pypi?%3Aaction=list_classifiers -CLASSIFIERS = [ - 'Development Status :: 4 - Beta', - 'Intended Audience :: Developers', - 'Intended Audience :: System Administrators', - 'Programming Language :: Python', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'License :: OSI Approved :: MIT License', -] - -# TODO: Add any additional SDK dependencies here -DEPENDENCIES = [] - -with open('README.md', 'r', encoding='utf-8') as f: - README = f.read() -with open('HISTORY.rst', 'r', encoding='utf-8') as f: - HISTORY = f.read() - -setup( - name='portal', - version=VERSION, - description='Microsoft Azure Command-Line Tools Portal Extension', - # TODO: Update author and email, if applicable - author='Microsoft Corporation', - author_email='azpycli@microsoft.com', - # TODO: consider pointing directly to your source code instead of the generic repo - url='https://github.com/Azure/azure-cli-extensions', - long_description=README + '\n\n' + HISTORY, - license='MIT', - classifiers=CLASSIFIERS, - packages=find_packages(), - install_requires=DEPENDENCIES, - package_data={'azext_portal': ['azext_metadata.json']}, -) +#!/usr/bin/env python + +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + + +from codecs import open +from setuptools import setup, find_packages + +# TODO: Confirm this is the right version number you want and it matches your +# HISTORY.rst entry. +VERSION = '0.1.0' + +# The full list of classifiers is available at +# https://pypi.python.org/pypi?%3Aaction=list_classifiers +CLASSIFIERS = [ + 'Development Status :: 4 - Beta', + 'Intended Audience :: Developers', + 'Intended Audience :: System Administrators', + 'Programming Language :: Python', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'License :: OSI Approved :: MIT License', +] + +# TODO: Add any additional SDK dependencies here +DEPENDENCIES = [] + +with open('README.md', 'r', encoding='utf-8') as f: + README = f.read() +with open('HISTORY.rst', 'r', encoding='utf-8') as f: + HISTORY = f.read() + +setup( + name='portal', + version=VERSION, + description='Microsoft Azure Command-Line Tools Portal Extension', + # TODO: Update author and email, if applicable + author='Microsoft Corporation', + author_email='azpycli@microsoft.com', + # TODO: consider pointing directly to your source code instead of the generic repo + url='https://github.com/Azure/azure-cli-extensions', + long_description=README + '\n\n' + HISTORY, + license='MIT', + classifiers=CLASSIFIERS, + packages=find_packages(), + install_requires=DEPENDENCIES, + package_data={'azext_portal': ['azext_metadata.json']}, +)