diff --git a/.vscode/cspell.json b/.vscode/cspell.json index e47e8ecb50fa..4d4252cc605e 100644 --- a/.vscode/cspell.json +++ b/.vscode/cspell.json @@ -1678,7 +1678,14 @@ "ctxt", "unflattened", "deseralize", - "wday" + "wday", + "mros" + ] + }, + { + "filename": "sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/models/*.py", + "words": [ + "vcpus" ] }, { diff --git a/sdk/devcenter/azure-developer-devcenter/CHANGELOG.md b/sdk/devcenter/azure-developer-devcenter/CHANGELOG.md index 074c6e3c3962..aa4089286854 100644 --- a/sdk/devcenter/azure-developer-devcenter/CHANGELOG.md +++ b/sdk/devcenter/azure-developer-devcenter/CHANGELOG.md @@ -1,5 +1,76 @@ # Release History +## 1.0.0 (2024-05-02) + +This release targets Azure Dev Center 2023-04-01 General Available API, which is the same version as the previous 1.0.0-beta.3 release. The main improvement was the addition of models as Convenience API was enabled for the SDK. + +### Features Added + +- Added classes for each Dev Center concept. + - `models`: + - Catalog + - DevBox + - DevBoxAction + - DevBoxActionDelayResult + - DevBoxNextAction + - Environment + - EnvironmentDefinition + - EnvironmentDefinitionParameter + - EnvironmentType + - Error + - HardwareProfile + - ImageReference + - InnerError + - OperationDetails + - OSDisk + - Pool + - Project + - RemoteConnection + - Schedule + - StopOnDisconnectConfiguration + - StorageProfile + + - `enums`: + - DevBoxActionDelayStatus + - DevBoxActionType + - DevBoxProvisioningState + - EnvironmentProvisioningState + - EnvironmentTypeStatus + - HibernateSupport + - LocalAdministratorStatus + - OperationStatus + - OSType + - ParameterType + - PoolHealthStatus + - PowerState + - ScheduledFrequency + - ScheduledType + - SkuName + - StopOnDisconnectEnableStatus + + +- Updated each previous client method to return the correspondent model. E.g. The response type for `get_dev_box` was updated from `JSON` to `DevBox` model. + +### Breaking Changes + +- Removed `filter` and `top` as optional request parameters from all list operations + - list_pools + - list_schedules + - list_dev_boxes + - list_all_dev_boxes + - list_all_dev_boxes_by_user + - list_projects + - list_environments + - list_all_environments + - list_environment_definitions + - list_environment_definitions_by_catalog + - list_environment_types + - list_catalogs + +### Other Changes + + - Added more samples + ## 1.0.0b3 (2023-11-02) This release updates the Azure DevCenter library to use the 2023-04-01 GA API. @@ -42,3 +113,5 @@ This release updates the Azure DevCenter library to use the 2022-11-11-preview A ## 1.0.0b1 (2022-11-11) - Initial version for the DevCenter service + + diff --git a/sdk/devcenter/azure-developer-devcenter/README.md b/sdk/devcenter/azure-developer-devcenter/README.md index d134d19749d3..e28f7a44ffe9 100644 --- a/sdk/devcenter/azure-developer-devcenter/README.md +++ b/sdk/devcenter/azure-developer-devcenter/README.md @@ -8,121 +8,230 @@ Use the package for Azure DevCenter to: ## Getting started -### Installating the package +### Installing the package ```bash python -m pip install azure-developer-devcenter ``` -#### Prequisites +### Prerequisites - Python 3.7 or later is required to use this package. - You need an [Azure subscription][azure_sub] to use this package. -- You must have [configured](https://learn.microsoft.com/azure/dev-box/quickstart-configure-dev-box-service) a DevCenter, Project, Network Connection, Dev Box Definition, and Pool before you can create Dev Boxes -- You must have [configured](https://learn.microsoft.com/azure/deployment-environments/) a DevCenter, Project, Catalog, and Environment Type before you can create Environments +- For Dev Box operations you must have [configured](https://learn.microsoft.com/azure/dev-box/quickstart-configure-dev-box-service) a DevCenter, Project, Network Connection, Dev Box Definition, and Pool. +- For Deployment Environments operations you must have [configured](https://learn.microsoft.com/azure/deployment-environments/) a DevCenter, Project, Catalog, Environment Definition and Environment Type. -#### Create with an Azure Active Directory Credential -To use an [Azure Active Directory (AAD) token credential][authenticate_with_token], -provide an instance of the desired credential type obtained from the -[azure-identity][azure_identity_credentials] library. +### Create Client with an Azure Active Directory Credential -To authenticate with AAD, you must first [pip][pip] install [`azure-identity`][azure_identity_pip] +In order to interact with the Dev Center service, you will need to create an instance of a client. An **endpoint** and **credential** are necessary to instantiate the client object. + +For the endpoint use the Dev Center URI. It should have the format `https://{tenantId}-{devCenterName}.{devCenterRegion}.devcenter.azure.com`. + +For the credential use an [Azure Active Directory (AAD) token credential][authenticate_with_token], providing an instance of the desired credential type obtained from the [azure-identity][azure_identity_credentials] library. + +To authenticate with AAD, you must first install [azure-identity][azure_identity_pip] using [pip][pip] + +```bash +pip install azure-identity +``` After setup, you can choose which type of [credential][azure_identity_credentials] from azure.identity to use. -As an example, [DefaultAzureCredential][default_azure_credential] can be used to authenticate the client: +As an example, [DefaultAzureCredential][default_azure_credential] can be used to authenticate the client: Set the values of the client ID, tenant ID, and client secret of the AAD application as environment variables: `AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, `AZURE_CLIENT_SECRET` -Use the returned token credential to authenticate the client: +Use the returned token credential to authenticate the client. + + ```python ->>> import os ->>> from azure.developer.devcenter import DevCenterClient ->>> from azure.identity import DefaultAzureCredential ->>> tenant_id = os.environ['AZURE_TENANT_ID'] ->>> endpoint = os.environ["DEVCENTER_ENDPOINT"] ->>> client = DevCenterClient(endpoint, credential=DefaultAzureCredential()) +import os + +from azure.developer.devcenter import DevCenterClient +from azure.identity import DefaultAzureCredential + +# Set the values of the dev center endpoint, client ID, and client secret of the AAD application as environment variables: +# DEVCENTER_ENDPOINT, AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET +try: + endpoint = os.environ["DEVCENTER_ENDPOINT"] +except KeyError: + raise ValueError("Missing environment variable 'DEVCENTER_ENDPOINT' - please set it before running the example") + +# Build a client through AAD +client = DevCenterClient(endpoint, credential=DefaultAzureCredential()) ``` + + +With `DevCenterClient` you can execute operations in [Dev Center, Dev Box and Environments REST operations group](https://learn.microsoft.com/rest/api/devcenter/developer/operation-groups). + ## Examples +* [Create, Connect and Delete a Dev Box](#create-connect-and-delete-a-dev-box) +* [Deploy and Delete an Environment](#deploy-and-delete-an-environment) -### Dev Box Management -```python ->>> import os ->>> from azure.developer.devcenter import DevCenterClient ->>> from azure.identity import DefaultAzureCredential ->>> from azure.core.exceptions import HttpResponseError ->>> tenant_id = os.environ['AZURE_TENANT_ID'] ->>> endpoint = os.environ["DEVCENTER_ENDPOINT"] ->>> client = DevCenterClient(endpoint, credential=DefaultAzureCredential()) ->>> try: - # Fetch control plane resource dependencies - projects = list(client.list_projects(top=1)) - target_project_name = projects[0]['name'] - - pools = list(client.list_pools(target_project_name, top=1)) - target_pool_name = pools[0]['name'] - - # Stand up a new dev box - create_response = client.begin_create_dev_box(target_project_name, "me","Test_DevBox", {"poolName": target_pool_name}) - devbox_result = create_response.result() - - LOG.info(f"Provisioned dev box with status {devbox_result['provisioningState']}.") - - # Connect to the provisioned dev box - remote_connection_response = client.get_remote_connection(target_project_name, "me", "Test_DevBox") - LOG.info(f"Connect to the dev box using web URL {remote_connection_response['webUrl']}") - - # Tear down the dev box when finished - delete_response = client.begin_delete_dev_box(target_project_name, "me", "Test_DevBox") - delete_response.wait() - LOG.info("Deleted dev box successfully.") - except HttpResponseError as e: - print('service responds error: {}'.format(e.response.json())) +### Create, Connect and Delete a Dev Box -``` + -### Environment Management ```python ->>> import os ->>> from azure.developer.devcenter import DevCenterClient ->>> from azure.identity import DefaultAzureCredential ->>> from azure.core.exceptions import HttpResponseError ->>> tenant_id = os.environ['AZURE_TENANT_ID'] ->>> endpoint = os.environ["DEVCENTER_ENDPOINT"] ->>> client = DevCenterClient(endpoint, credential=DefaultAzureCredential()) ->>> try: - # Fetch control plane resource dependencies - target_project_name = list(client.list_projects(top=1))[0]['name'] - target_catalog_item_name = list(client.list_catalog_items(target_project_name, top=1))[0]['name'] - target_environment_type_name = list(client.list_environment_types(target_project_name, top=1))[0]['name'] - target_catalog_name = list(client.list_catalog_items(target_project_name, top=1))[0]['catalogName'] - - # Stand up a new environment - create_response = client.begin_create_or_update_environment(target_project_name, - "Dev_Environment", - {"catalogName": target_catalog_name, - "catalogItemName": target_catalog_item_name, - "environmentType": target_environment_type_name - }) - - environment_result = create_response.result() - - LOG.info(f"Provisioned environment with status {environment_result['provisioningState']}.") - - # Fetch deployment artifacts - environment = client.get_environment_by_user(target_project_name, "me", "Dev_Environment") - LOG.info(environment) - - # Tear down the environment when finished - delete_response = client.begin_delete_environment(target_project_name, "me", "Dev_Environment") - delete_response.wait() - LOG.info("Completed deletion for the environment.") - except HttpResponseError as e: - print('service responds error: {}'.format(e.response.json())) +import os + +from azure.developer.devcenter import DevCenterClient +from azure.identity import DefaultAzureCredential + +# Set the values of the dev center endpoint, client ID, and client secret of the AAD application as environment variables: +# DEVCENTER_ENDPOINT, AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET +try: + endpoint = os.environ["DEVCENTER_ENDPOINT"] +except KeyError: + raise ValueError("Missing environment variable 'DEVCENTER_ENDPOINT' - please set it before running the example") + +# Build a client through AAD +client = DevCenterClient(endpoint, credential=DefaultAzureCredential()) + +# List available Projects +projects = client.list_projects() +if projects: + print("\nList of projects: ") + for project in projects: + print(f"{project.name}") + + # Select first project in the list + target_project_name = list(projects)[0].name +else: + raise ValueError("Missing Project - please create one before running the example") + +# List available Pools +pools = client.list_pools(target_pool_name) +if pools: + print("\nList of pools: ") + for pool in pools: + print(f"{pool.name}") + + # Select first pool in the list + target_pool_name = list(pools)[0].name +else: + raise ValueError("Missing Pool - please create one before running the example") + +# Stand up a new Dev Box +print(f"\nStarting to create dev box in project {target_project_name} and pool {target_pool_name}") + +dev_box_poller = client.begin_create_dev_box( + target_project_name, "me", "Test_DevBox", {"poolName": target_pool_name} +) +dev_box = dev_box_poller.result() +print(f"Provisioned dev box with status {dev_box.provisioning_state}.") + +# Connect to the provisioned Dev Box +remote_connection = client.get_remote_connection(target_project_name, "me", dev_box.name) +print(f"Connect to the dev box using web URL {remote_connection.web_url}") + +# Tear down the Dev Box when finished +print(f"Starting to delete dev box.") + +delete_poller = client.begin_delete_dev_box(target_project_name, "me", "Test_DevBox") +delete_result = delete_poller.result() +print(f"Completed deletion for the dev box with status {delete_result.status}") +``` + + +### Deploy and Delete an Environment + + + +```python +import os + +from azure.developer.devcenter import DevCenterClient +from azure.identity import DefaultAzureCredential + +# Set the values of the dev center endpoint, client ID, and client secret of the AAD application as environment variables: +# DEVCENTER_ENDPOINT, AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET +try: + endpoint = os.environ["DEVCENTER_ENDPOINT"] +except KeyError: + raise ValueError("Missing environment variable 'DEVCENTER_ENDPOINT' - please set it before running the example") + +# Build a client through AAD +client = DevCenterClient(endpoint, credential=DefaultAzureCredential()) + +# List available Projects +projects = client.list_projects() +if projects: + print("\nList of projects: ") + for project in projects: + print(f"{project.name}") + + # Select first project in the list + target_project_name = list(projects)[0].name +else: + raise ValueError("Missing Project - please create one before running the example") + +# List available Catalogs +catalogs = client.list_catalogs(target_project_name) +if catalogs: + print("\nList of catalogs: ") + for catalog in catalogs: + print(f"{catalog.name}") + + # Select first catalog in the list + target_catalog_name = list(catalogs)[0].name +else: + raise ValueError("Missing Catalog - please create one before running the example") + +# List available Environment Definitions +environment_definitions = client.list_environment_definitions_by_catalog(target_project_name, target_catalog_name) +if environment_definitions: + print("\nList of environment definitions: ") + for environment_definition in environment_definitions: + print(f"{environment_definition.name}") + + # Select first environment definition in the list + target_environment_definition_name = list(environment_definitions)[0].name +else: + raise ValueError("Missing Environment Definition - please create one before running the example") + +# List available Environment Types +environment_types = client.list_environment_types(target_project_name) +if environment_types: + print("\nList of environment types: ") + for environment_type in environment_types: + print(f"{environment_type.name}") + + # Select first environment type in the list + target_environment_type_name = list(environment_types)[0].name +else: + raise ValueError("Missing Environment Type - please create one before running the example") + +print( + f"\nStarting to create environment in project {target_project_name} with catalog {target_catalog_name}, environment definition {target_environment_definition_name}, and environment type {target_environment_type_name}." +) + +# Stand up a new environment +environment_name = "MyDevEnv" +environment = { + "environmentType": target_environment_type_name, + "catalogName": target_catalog_name, + "environmentDefinitionName": target_environment_definition_name, +} + +environment_poller = client.begin_create_or_update_environment( + target_project_name, "me", environment_name, environment +) +environment_result = environment_poller.result() +print(f"Provisioned environment with status {environment_result.provisioning_state}.") + +# Tear down the environment when finished +print(f"Starting to delete environment.") +delete_poller = client.begin_delete_environment(target_project_name, "me", environment_name) +delete_result = delete_poller.result() +print(f"Completed deletion for the environment with status {delete_result.status}") ``` + + + ## Key concepts Dev Boxes refer to managed developer machines running in Azure. Dev Boxes are provisioned in Pools, which define the network and image used for a Dev Box. @@ -133,7 +242,7 @@ Errors can occur during initial requests and long-running operations, and will p Be sure to confirm that dependent resources, such as pools and catalogs, are set up properly and are in a healthy state. You will not be able to create resources with the package when your dependent resources are in a failed state. ## Next steps -Get started by exploring our samples and starting to use the package! +Get started by exploring our [samples][samples_folder] and starting to use the package! ## Contributing @@ -160,3 +269,4 @@ additional questions or comments. [default_azure_credential]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity#defaultazurecredential [pip]: https://pypi.org/project/pip/ [azure_sub]: https://azure.microsoft.com/free/ +[samples_folder]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/devcenter/azure-developer-devcenter/samples diff --git a/sdk/devcenter/azure-developer-devcenter/assets.json b/sdk/devcenter/azure-developer-devcenter/assets.json index a096725650b8..31d34b1f03da 100644 --- a/sdk/devcenter/azure-developer-devcenter/assets.json +++ b/sdk/devcenter/azure-developer-devcenter/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "python", "TagPrefix": "python/devcenter/azure-developer-devcenter", - "Tag": "python/devcenter/azure-developer-devcenter_5af4e830d5" + "Tag": "python/devcenter/azure-developer-devcenter_07fff99786" } diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_client.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_client.py index a3da49581dcd..df902c7477b9 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_client.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_client.py @@ -27,7 +27,7 @@ class DevCenterClient(DevCenterClientOperationsMixin): # pylint: disable=client :param endpoint: The DevCenter-specific URI to operate on. Required. :type endpoint: str - :param credential: Credential needed for the client to connect to Azure. Required. + :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials.TokenCredential :keyword api_version: The API version to use for this operation. Default value is "2023-04-01". Note that overriding this default value may result in unsupported behavior. diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_configuration.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_configuration.py index e41a403f2bbf..e37ae956cc25 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_configuration.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_configuration.py @@ -25,7 +25,7 @@ class DevCenterClientConfiguration: # pylint: disable=too-many-instance-attribu :param endpoint: The DevCenter-specific URI to operate on. Required. :type endpoint: str - :param credential: Credential needed for the client to connect to Azure. Required. + :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials.TokenCredential :keyword api_version: The API version to use for this operation. Default value is "2023-04-01". Note that overriding this default value may result in unsupported behavior. diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_model_base.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_model_base.py new file mode 100644 index 000000000000..4b0f59f73e4c --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_model_base.py @@ -0,0 +1,875 @@ +# 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=protected-access, arguments-differ, signature-differs, broad-except + +import calendar +import decimal +import functools +import sys +import logging +import base64 +import re +import typing +import enum +import email.utils +from datetime import datetime, date, time, timedelta, timezone +from json import JSONEncoder +from typing_extensions import Self +import isodate +from azure.core.exceptions import DeserializationError +from azure.core import CaseInsensitiveEnumMeta +from azure.core.pipeline import PipelineResponse +from azure.core.serialization import _Null + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping + +_LOGGER = logging.getLogger(__name__) + +__all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] + +TZ_UTC = timezone.utc +_T = typing.TypeVar("_T") + + +def _timedelta_as_isostr(td: timedelta) -> str: + """Converts a datetime.timedelta object into an ISO 8601 formatted string, e.g. 'P4DT12H30M05S' + + Function adapted from the Tin Can Python project: https://github.com/RusticiSoftware/TinCanPython + + :param timedelta td: The timedelta to convert + :rtype: str + :return: ISO8601 version of this timedelta + """ + + # Split seconds to larger units + seconds = td.total_seconds() + minutes, seconds = divmod(seconds, 60) + hours, minutes = divmod(minutes, 60) + days, hours = divmod(hours, 24) + + days, hours, minutes = list(map(int, (days, hours, minutes))) + seconds = round(seconds, 6) + + # Build date + date_str = "" + if days: + date_str = "%sD" % days + + if hours or minutes or seconds: + # Build time + time_str = "T" + + # Hours + bigger_exists = date_str or hours + if bigger_exists: + time_str += "{:02}H".format(hours) + + # Minutes + bigger_exists = bigger_exists or minutes + if bigger_exists: + time_str += "{:02}M".format(minutes) + + # Seconds + try: + if seconds.is_integer(): + seconds_string = "{:02}".format(int(seconds)) + else: + # 9 chars long w/ leading 0, 6 digits after decimal + seconds_string = "%09.6f" % seconds + # Remove trailing zeros + seconds_string = seconds_string.rstrip("0") + except AttributeError: # int.is_integer() raises + seconds_string = "{:02}".format(seconds) + + time_str += "{}S".format(seconds_string) + else: + time_str = "" + + return "P" + date_str + time_str + + +def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: + encoded = base64.b64encode(o).decode() + if format == "base64url": + return encoded.strip("=").replace("+", "-").replace("/", "_") + return encoded + + +def _serialize_datetime(o, format: typing.Optional[str] = None): + if hasattr(o, "year") and hasattr(o, "hour"): + if format == "rfc7231": + return email.utils.format_datetime(o, usegmt=True) + if format == "unix-timestamp": + return int(calendar.timegm(o.utctimetuple())) + + # astimezone() fails for naive times in Python 2.7, so make make sure o is aware (tzinfo is set) + if not o.tzinfo: + iso_formatted = o.replace(tzinfo=TZ_UTC).isoformat() + else: + iso_formatted = o.astimezone(TZ_UTC).isoformat() + # Replace the trailing "+00:00" UTC offset with "Z" (RFC 3339: https://www.ietf.org/rfc/rfc3339.txt) + return iso_formatted.replace("+00:00", "Z") + # Next try datetime.date or datetime.time + return o.isoformat() + + +def _is_readonly(p): + try: + return p._visibility == ["read"] # pylint: disable=protected-access + except AttributeError: + return False + + +class SdkJSONEncoder(JSONEncoder): + """A JSON encoder that's capable of serializing datetime objects and bytes.""" + + def __init__(self, *args, exclude_readonly: bool = False, format: typing.Optional[str] = None, **kwargs): + super().__init__(*args, **kwargs) + self.exclude_readonly = exclude_readonly + self.format = format + + def default(self, o): # pylint: disable=too-many-return-statements + if _is_model(o): + if self.exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + return {k: v for k, v in o.items() if k not in readonly_props} + return dict(o.items()) + try: + return super(SdkJSONEncoder, self).default(o) + except TypeError: + if isinstance(o, _Null): + return None + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, self.format) + try: + # First try datetime.datetime + return _serialize_datetime(o, self.format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return super(SdkJSONEncoder, self).default(o) + + +_VALID_DATE = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" + r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") +_VALID_RFC7231 = re.compile( + r"(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s\d{2}\s" + r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" +) + + +def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + attr = attr.upper() + match = _VALID_DATE.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + return date_obj + + +def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize RFC7231 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + match = _VALID_RFC7231.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + return email.utils.parsedate_to_datetime(attr) + + +def _deserialize_datetime_unix_timestamp(attr: typing.Union[float, datetime]) -> datetime: + """Deserialize unix timestamp into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + return datetime.fromtimestamp(attr, TZ_UTC) + + +def _deserialize_date(attr: typing.Union[str, date]) -> date: + """Deserialize ISO-8601 formatted string into Date object. + :param str attr: response string to be deserialized. + :rtype: date + :returns: The date object from that input + """ + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + if isinstance(attr, date): + return attr + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) # type: ignore + + +def _deserialize_time(attr: typing.Union[str, time]) -> time: + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :returns: The time object from that input + """ + if isinstance(attr, time): + return attr + return isodate.parse_time(attr) + + +def _deserialize_bytes(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + return bytes(base64.b64decode(attr)) + + +def _deserialize_bytes_base64(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return bytes(base64.b64decode(encoded)) + + +def _deserialize_duration(attr): + if isinstance(attr, timedelta): + return attr + return isodate.parse_duration(attr) + + +def _deserialize_decimal(attr): + if isinstance(attr, decimal.Decimal): + return attr + return decimal.Decimal(str(attr)) + + +_DESERIALIZE_MAPPING = { + datetime: _deserialize_datetime, + date: _deserialize_date, + time: _deserialize_time, + bytes: _deserialize_bytes, + bytearray: _deserialize_bytes, + timedelta: _deserialize_duration, + typing.Any: lambda x: x, + decimal.Decimal: _deserialize_decimal, +} + +_DESERIALIZE_MAPPING_WITHFORMAT = { + "rfc3339": _deserialize_datetime, + "rfc7231": _deserialize_datetime_rfc7231, + "unix-timestamp": _deserialize_datetime_unix_timestamp, + "base64": _deserialize_bytes, + "base64url": _deserialize_bytes_base64, +} + + +def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): + if rf and rf._format: + return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) + return _DESERIALIZE_MAPPING.get(annotation) + + +def _get_type_alias_type(module_name: str, alias_name: str): + types = { + k: v + for k, v in sys.modules[module_name].__dict__.items() + if isinstance(v, typing._GenericAlias) # type: ignore + } + if alias_name not in types: + return alias_name + return types[alias_name] + + +def _get_model(module_name: str, model_name: str): + models = {k: v for k, v in sys.modules[module_name].__dict__.items() if isinstance(v, type)} + module_end = module_name.rsplit(".", 1)[0] + models.update({k: v for k, v in sys.modules[module_end].__dict__.items() if isinstance(v, type)}) + if isinstance(model_name, str): + model_name = model_name.split(".")[-1] + if model_name not in models: + return model_name + return models[model_name] + + +_UNSET = object() + + +class _MyMutableMapping(MutableMapping[str, typing.Any]): # pylint: disable=unsubscriptable-object + def __init__(self, data: typing.Dict[str, typing.Any]) -> None: + self._data = data + + def __contains__(self, key: typing.Any) -> bool: + return key in self._data + + def __getitem__(self, key: str) -> typing.Any: + return self._data.__getitem__(key) + + def __setitem__(self, key: str, value: typing.Any) -> None: + self._data.__setitem__(key, value) + + def __delitem__(self, key: str) -> None: + self._data.__delitem__(key) + + def __iter__(self) -> typing.Iterator[typing.Any]: + return self._data.__iter__() + + def __len__(self) -> int: + return self._data.__len__() + + def __ne__(self, other: typing.Any) -> bool: + return not self.__eq__(other) + + def keys(self) -> typing.KeysView[str]: + return self._data.keys() + + def values(self) -> typing.ValuesView[typing.Any]: + return self._data.values() + + def items(self) -> typing.ItemsView[str, typing.Any]: + return self._data.items() + + def get(self, key: str, default: typing.Any = None) -> typing.Any: + try: + return self[key] + except KeyError: + return default + + @typing.overload + def pop(self, key: str) -> typing.Any: ... + + @typing.overload + def pop(self, key: str, default: _T) -> _T: ... + + @typing.overload + def pop(self, key: str, default: typing.Any) -> typing.Any: ... + + def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + if default is _UNSET: + return self._data.pop(key) + return self._data.pop(key, default) + + def popitem(self) -> typing.Tuple[str, typing.Any]: + return self._data.popitem() + + def clear(self) -> None: + self._data.clear() + + def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: + self._data.update(*args, **kwargs) + + @typing.overload + def setdefault(self, key: str, default: None = None) -> None: ... + + @typing.overload + def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... + + def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + if default is _UNSET: + return self._data.setdefault(key) + return self._data.setdefault(key, default) + + def __eq__(self, other: typing.Any) -> bool: + try: + other_model = self.__class__(other) + except Exception: + return False + return self._data == other_model._data + + def __repr__(self) -> str: + return str(self._data) + + +def _is_model(obj: typing.Any) -> bool: + return getattr(obj, "_is_model", False) + + +def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements + if isinstance(o, list): + return [_serialize(x, format) for x in o] + if isinstance(o, dict): + return {k: _serialize(v, format) for k, v in o.items()} + if isinstance(o, set): + return {_serialize(x, format) for x in o} + if isinstance(o, tuple): + return tuple(_serialize(x, format) for x in o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, format) + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, enum.Enum): + return o.value + try: + # First try datetime.datetime + return _serialize_datetime(o, format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return o + + +def _get_rest_field( + attr_to_rest_field: typing.Dict[str, "_RestField"], rest_name: str +) -> typing.Optional["_RestField"]: + try: + return next(rf for rf in attr_to_rest_field.values() if rf._rest_name == rest_name) + except StopIteration: + return None + + +def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typing.Any: + if not rf: + return _serialize(value, None) + if rf._is_multipart_file_input: + return value + if rf._is_model: + return _deserialize(rf._type, value) + return _serialize(value, rf._format) + + +class Model(_MyMutableMapping): + _is_model = True + + def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: + class_name = self.__class__.__name__ + if len(args) > 1: + raise TypeError(f"{class_name}.__init__() takes 2 positional arguments but {len(args) + 1} were given") + dict_to_pass = { + rest_field._rest_name: rest_field._default + for rest_field in self._attr_to_rest_field.values() + if rest_field._default is not _UNSET + } + if args: + dict_to_pass.update( + {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()} + ) + else: + non_attr_kwargs = [k for k in kwargs if k not in self._attr_to_rest_field] + if non_attr_kwargs: + # actual type errors only throw the first wrong keyword arg they see, so following that. + raise TypeError(f"{class_name}.__init__() got an unexpected keyword argument '{non_attr_kwargs[0]}'") + dict_to_pass.update( + { + self._attr_to_rest_field[k]._rest_name: _create_value(self._attr_to_rest_field[k], v) + for k, v in kwargs.items() + if v is not None + } + ) + super().__init__(dict_to_pass) + + def copy(self) -> "Model": + return Model(self.__dict__) + + def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: # pylint: disable=unused-argument + # we know the last three classes in mro are going to be 'Model', 'dict', and 'object' + mros = cls.__mro__[:-3][::-1] # ignore model, dict, and object parents, and reverse the mro order + attr_to_rest_field: typing.Dict[str, _RestField] = { # map attribute name to rest_field property + k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type") + } + annotations = { + k: v + for mro_class in mros + if hasattr(mro_class, "__annotations__") # pylint: disable=no-member + for k, v in mro_class.__annotations__.items() # pylint: disable=no-member + } + for attr, rf in attr_to_rest_field.items(): + rf._module = cls.__module__ + if not rf._type: + rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None)) + if not rf._rest_name_input: + rf._rest_name_input = attr + cls._attr_to_rest_field: typing.Dict[str, _RestField] = dict(attr_to_rest_field.items()) + + return super().__new__(cls) # pylint: disable=no-value-for-parameter + + def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: + for base in cls.__bases__: + if hasattr(base, "__mapping__"): # pylint: disable=no-member + base.__mapping__[discriminator or cls.__name__] = cls # type: ignore # pylint: disable=no-member + + @classmethod + def _get_discriminator(cls, exist_discriminators) -> typing.Optional[str]: + for v in cls.__dict__.values(): + if ( + isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators + ): # pylint: disable=protected-access + return v._rest_name # pylint: disable=protected-access + return None + + @classmethod + def _deserialize(cls, data, exist_discriminators): + if not hasattr(cls, "__mapping__"): # pylint: disable=no-member + return cls(data) + discriminator = cls._get_discriminator(exist_discriminators) + exist_discriminators.append(discriminator) + mapped_cls = cls.__mapping__.get(data.get(discriminator), cls) # pyright: ignore # pylint: disable=no-member + if mapped_cls == cls: + return cls(data) + return mapped_cls._deserialize(data, exist_discriminators) # pylint: disable=protected-access + + def as_dict(self, *, exclude_readonly: bool = False) -> typing.Dict[str, typing.Any]: + """Return a dict that can be JSONify using json.dump. + + :keyword bool exclude_readonly: Whether to remove the readonly properties. + :returns: A dict JSON compatible object + :rtype: dict + """ + + result = {} + if exclude_readonly: + readonly_props = [p._rest_name for p in self._attr_to_rest_field.values() if _is_readonly(p)] + for k, v in self.items(): + if exclude_readonly and k in readonly_props: # pyright: ignore + continue + is_multipart_file_input = False + try: + is_multipart_file_input = next( + rf for rf in self._attr_to_rest_field.values() if rf._rest_name == k + )._is_multipart_file_input + except StopIteration: + pass + result[k] = v if is_multipart_file_input else Model._as_dict_value(v, exclude_readonly=exclude_readonly) + return result + + @staticmethod + def _as_dict_value(v: typing.Any, exclude_readonly: bool = False) -> typing.Any: + if v is None or isinstance(v, _Null): + return None + if isinstance(v, (list, tuple, set)): + return type(v)(Model._as_dict_value(x, exclude_readonly=exclude_readonly) for x in v) + if isinstance(v, dict): + return {dk: Model._as_dict_value(dv, exclude_readonly=exclude_readonly) for dk, dv in v.items()} + return v.as_dict(exclude_readonly=exclude_readonly) if hasattr(v, "as_dict") else v + + +def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj): + if _is_model(obj): + return obj + return _deserialize(model_deserializer, obj) + + +def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): + if obj is None: + return obj + return _deserialize_with_callable(if_obj_deserializer, obj) + + +def _deserialize_with_union(deserializers, obj): + for deserializer in deserializers: + try: + return _deserialize(deserializer, obj) + except DeserializationError: + pass + raise DeserializationError() + + +def _deserialize_dict( + value_deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj: typing.Dict[typing.Any, typing.Any], +): + if obj is None: + return obj + return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} + + +def _deserialize_multiple_sequence( + entry_deserializers: typing.List[typing.Optional[typing.Callable]], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + return type(obj)(_deserialize(deserializer, entry, module) for entry, deserializer in zip(obj, entry_deserializers)) + + +def _deserialize_sequence( + deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) + + +def _get_deserialize_callable_from_annotation( # pylint: disable=R0911, R0915, R0912 + annotation: typing.Any, + module: typing.Optional[str], + rf: typing.Optional["_RestField"] = None, +) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + if not annotation or annotation in [int, float]: + return None + + # is it a type alias? + if isinstance(annotation, str): + if module is not None: + annotation = _get_type_alias_type(module, annotation) + + # is it a forward ref / in quotes? + if isinstance(annotation, (str, typing.ForwardRef)): + try: + model_name = annotation.__forward_arg__ # type: ignore + except AttributeError: + model_name = annotation + if module is not None: + annotation = _get_model(module, model_name) + + try: + if module and _is_model(annotation): + if rf: + rf._is_model = True + + return functools.partial(_deserialize_model, annotation) # pyright: ignore + except Exception: + pass + + # is it a literal? + try: + if annotation.__origin__ is typing.Literal: # pyright: ignore + return None + except AttributeError: + pass + + # is it optional? + try: + if any(a for a in annotation.__args__ if a == type(None)): # pyright: ignore + if_obj_deserializer = _get_deserialize_callable_from_annotation( + next(a for a in annotation.__args__ if a != type(None)), module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_with_optional, if_obj_deserializer) + except AttributeError: + pass + + if getattr(annotation, "__origin__", None) is typing.Union: + # initial ordering is we make `string` the last deserialization option, because it is often them most generic + deserializers = [ + _get_deserialize_callable_from_annotation(arg, module, rf) + for arg in sorted( + annotation.__args__, key=lambda x: hasattr(x, "__name__") and x.__name__ == "str" # pyright: ignore + ) + ] + + return functools.partial(_deserialize_with_union, deserializers) + + try: + if annotation._name == "Dict": # pyright: ignore + value_deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[1], module, rf # pyright: ignore + ) + + return functools.partial( + _deserialize_dict, + value_deserializer, + module, + ) + except (AttributeError, IndexError): + pass + try: + if annotation._name in ["List", "Set", "Tuple", "Sequence"]: # pyright: ignore + if len(annotation.__args__) > 1: # pyright: ignore + + entry_deserializers = [ + _get_deserialize_callable_from_annotation(dt, module, rf) + for dt in annotation.__args__ # pyright: ignore + ] + return functools.partial(_deserialize_multiple_sequence, entry_deserializers, module) + deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[0], module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_sequence, deserializer, module) + except (TypeError, IndexError, AttributeError, SyntaxError): + pass + + def _deserialize_default( + deserializer, + obj, + ): + if obj is None: + return obj + try: + return _deserialize_with_callable(deserializer, obj) + except Exception: + pass + return obj + + if get_deserializer(annotation, rf): + return functools.partial(_deserialize_default, get_deserializer(annotation, rf)) + + return functools.partial(_deserialize_default, annotation) + + +def _deserialize_with_callable( + deserializer: typing.Optional[typing.Callable[[typing.Any], typing.Any]], + value: typing.Any, +): + try: + if value is None or isinstance(value, _Null): + return None + if deserializer is None: + return value + if isinstance(deserializer, CaseInsensitiveEnumMeta): + try: + return deserializer(value) + except ValueError: + # for unknown value, return raw value + return value + if isinstance(deserializer, type) and issubclass(deserializer, Model): + return deserializer._deserialize(value, []) + return typing.cast(typing.Callable[[typing.Any], typing.Any], deserializer)(value) + except Exception as e: + raise DeserializationError() from e + + +def _deserialize( + deserializer: typing.Any, + value: typing.Any, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + if isinstance(value, PipelineResponse): + value = value.http_response.json() + if rf is None and format: + rf = _RestField(format=format) + if not isinstance(deserializer, functools.partial): + deserializer = _get_deserialize_callable_from_annotation(deserializer, module, rf) + return _deserialize_with_callable(deserializer, value) + + +class _RestField: + def __init__( + self, + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + is_discriminator: bool = False, + visibility: typing.Optional[typing.List[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + ): + self._type = type + self._rest_name_input = name + self._module: typing.Optional[str] = None + self._is_discriminator = is_discriminator + self._visibility = visibility + self._is_model = False + self._default = default + self._format = format + self._is_multipart_file_input = is_multipart_file_input + + @property + def _class_type(self) -> typing.Any: + return getattr(self._type, "args", [None])[0] + + @property + def _rest_name(self) -> str: + if self._rest_name_input is None: + raise ValueError("Rest name was never set") + return self._rest_name_input + + def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin + # by this point, type and rest_name will have a value bc we default + # them in __new__ of the Model class + item = obj.get(self._rest_name) + if item is None: + return item + if self._is_model: + return item + return _deserialize(self._type, _serialize(item, self._format), rf=self) + + def __set__(self, obj: Model, value) -> None: + if value is None: + # we want to wipe out entries if users set attr to None + try: + obj.__delitem__(self._rest_name) + except KeyError: + pass + return + if self._is_model: + if not _is_model(value): + value = _deserialize(self._type, value) + obj.__setitem__(self._rest_name, value) + return + obj.__setitem__(self._rest_name, _serialize(value, self._format)) + + def _get_deserialize_callable_from_annotation( + self, annotation: typing.Any + ) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + return _get_deserialize_callable_from_annotation(annotation, self._module, self) + + +def rest_field( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[typing.List[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, +) -> typing.Any: + return _RestField( + name=name, + type=type, + visibility=visibility, + default=default, + format=format, + is_multipart_file_input=is_multipart_file_input, + ) + + +def rest_discriminator( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin +) -> typing.Any: + return _RestField(name=name, type=type, is_discriminator=True) diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_operations/_operations.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_operations/_operations.py index 47f6fa485673..825ae666ecff 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_operations/_operations.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_operations/_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -8,8 +8,9 @@ # -------------------------------------------------------------------------- import datetime from io import IOBase +import json import sys -from typing import Any, Callable, Dict, IO, Iterable, List, Optional, TypeVar, Union, cast, overload +from typing import Any, Callable, Dict, IO, Iterable, List, Optional, Type, TypeVar, Union, cast, overload import urllib.parse from azure.core.exceptions import ( @@ -28,6 +29,8 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict +from .. import models as _models +from .._model_base import SdkJSONEncoder, _deserialize from .._serialization import Serializer from .._vendor import DevCenterClientMixinABC @@ -43,9 +46,7 @@ _SERIALIZER.client_side_validation = False -def build_dev_center_list_projects_request( - *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any -) -> HttpRequest: +def build_dev_center_list_projects_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -57,10 +58,6 @@ def build_dev_center_list_projects_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if filter is not None: - _params["filter"] = _SERIALIZER.query("filter", filter, "str") - if top is not None: - _params["top"] = _SERIALIZER.query("top", top, "int") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -92,9 +89,7 @@ def build_dev_center_get_project_request(project_name: str, **kwargs: Any) -> Ht return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_dev_center_list_pools_request( - project_name: str, *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any -) -> HttpRequest: +def build_dev_center_list_pools_request(project_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -111,10 +106,6 @@ def build_dev_center_list_pools_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if filter is not None: - _params["filter"] = _SERIALIZER.query("filter", filter, "str") - if top is not None: - _params["top"] = _SERIALIZER.query("top", top, "int") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -147,9 +138,7 @@ def build_dev_center_get_pool_request(project_name: str, pool_name: str, **kwarg return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_dev_center_list_schedules_request( - project_name: str, pool_name: str, *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any -) -> HttpRequest: +def build_dev_center_list_schedules_request(project_name: str, pool_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -167,10 +156,6 @@ def build_dev_center_list_schedules_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if filter is not None: - _params["filter"] = _SERIALIZER.query("filter", filter, "str") - if top is not None: - _params["top"] = _SERIALIZER.query("top", top, "int") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -206,9 +191,7 @@ def build_dev_center_get_schedule_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_dev_center_list_all_dev_boxes_request( # pylint: disable=name-too-long - *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any -) -> HttpRequest: +def build_dev_center_list_all_dev_boxes_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -220,10 +203,6 @@ def build_dev_center_list_all_dev_boxes_request( # pylint: disable=name-too-lon # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if filter is not None: - _params["filter"] = _SERIALIZER.query("filter", filter, "str") - if top is not None: - _params["top"] = _SERIALIZER.query("top", top, "int") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -232,7 +211,7 @@ def build_dev_center_list_all_dev_boxes_request( # pylint: disable=name-too-lon def build_dev_center_list_all_dev_boxes_by_user_request( # pylint: disable=name-too-long - user_id: str, *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + user_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -250,10 +229,6 @@ def build_dev_center_list_all_dev_boxes_by_user_request( # pylint: disable=name # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if filter is not None: - _params["filter"] = _SERIALIZER.query("filter", filter, "str") - if top is not None: - _params["top"] = _SERIALIZER.query("top", top, "int") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -261,9 +236,7 @@ def build_dev_center_list_all_dev_boxes_by_user_request( # pylint: disable=name return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_dev_center_list_dev_boxes_request( - project_name: str, user_id: str, *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any -) -> HttpRequest: +def build_dev_center_list_dev_boxes_request(project_name: str, user_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -281,10 +254,6 @@ def build_dev_center_list_dev_boxes_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if filter is not None: - _params["filter"] = _SERIALIZER.query("filter", filter, "str") - if top is not None: - _params["top"] = _SERIALIZER.query("top", top, "int") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -344,9 +313,9 @@ def build_dev_center_create_dev_box_request( _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) @@ -553,9 +522,12 @@ def build_dev_center_get_dev_box_action_request( # pylint: disable=name-too-lon def build_dev_center_skip_dev_box_action_request( # pylint: disable=name-too-long project_name: str, user_id: str, dev_box_name: str, action_name: str, **kwargs: Any ) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + # Construct URL _url = "/projects/{projectName}/users/{userId}/devboxes/{devBoxName}/actions/{actionName}:skip" path_format_arguments = { @@ -570,7 +542,10 @@ def build_dev_center_skip_dev_box_action_request( # pylint: disable=name-too-lo # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - return HttpRequest(method="POST", url=_url, params=_params, **kwargs) + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_dev_center_delay_dev_box_action_request( # pylint: disable=name-too-long @@ -639,7 +614,7 @@ def build_dev_center_delay_all_dev_box_actions_request( # pylint: disable=name- def build_dev_center_list_all_environments_request( # pylint: disable=name-too-long - project_name: str, *, top: Optional[int] = None, **kwargs: Any + project_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -657,8 +632,6 @@ def build_dev_center_list_all_environments_request( # pylint: disable=name-too- # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if top is not None: - _params["top"] = _SERIALIZER.query("top", top, "int") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -667,7 +640,7 @@ def build_dev_center_list_all_environments_request( # pylint: disable=name-too- def build_dev_center_list_environments_request( # pylint: disable=name-too-long - project_name: str, user_id: str, *, top: Optional[int] = None, **kwargs: Any + project_name: str, user_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -686,8 +659,6 @@ def build_dev_center_list_environments_request( # pylint: disable=name-too-long # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if top is not None: - _params["top"] = _SERIALIZER.query("top", top, "int") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -747,9 +718,9 @@ def build_dev_center_create_or_update_environment_request( # pylint: disable=na _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) @@ -782,9 +753,7 @@ def build_dev_center_delete_environment_request( # pylint: disable=name-too-lon return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_dev_center_list_catalogs_request( - project_name: str, *, top: Optional[int] = None, **kwargs: Any -) -> HttpRequest: +def build_dev_center_list_catalogs_request(project_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -801,8 +770,6 @@ def build_dev_center_list_catalogs_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if top is not None: - _params["top"] = _SERIALIZER.query("top", top, "int") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -836,7 +803,7 @@ def build_dev_center_get_catalog_request(project_name: str, catalog_name: str, * def build_dev_center_list_environment_definitions_request( # pylint: disable=name-too-long - project_name: str, *, top: Optional[int] = None, **kwargs: Any + project_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -854,8 +821,6 @@ def build_dev_center_list_environment_definitions_request( # pylint: disable=na # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if top is not None: - _params["top"] = _SERIALIZER.query("top", top, "int") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -864,7 +829,7 @@ def build_dev_center_list_environment_definitions_request( # pylint: disable=na def build_dev_center_list_environment_definitions_by_catalog_request( # pylint: disable=name-too-long - project_name: str, catalog_name: str, *, top: Optional[int] = None, **kwargs: Any + project_name: str, catalog_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -883,8 +848,6 @@ def build_dev_center_list_environment_definitions_by_catalog_request( # pylint: # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if top is not None: - _params["top"] = _SERIALIZER.query("top", top, "int") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -921,7 +884,7 @@ def build_dev_center_get_environment_definition_request( # pylint: disable=name def build_dev_center_list_environment_types_request( # pylint: disable=name-too-long - project_name: str, *, top: Optional[int] = None, **kwargs: Any + project_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -939,8 +902,6 @@ def build_dev_center_list_environment_types_request( # pylint: disable=name-too # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if top is not None: - _params["top"] = _SERIALIZER.query("top", top, "int") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -949,19 +910,14 @@ def build_dev_center_list_environment_types_request( # pylint: disable=name-too class DevCenterClientOperationsMixin(DevCenterClientMixinABC): # pylint: disable=too-many-public-methods + @distributed_trace - def list_projects( - self, *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> Iterable[JSON]: + def list_projects(self, **kwargs: Any) -> Iterable["_models.Project"]: + # pylint: disable=line-too-long """Lists all projects. - :keyword filter: An OData filter clause to apply to the operation. Default value is None. - :paramtype filter: str - :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. - Default value is None. - :paramtype top: int - :return: An iterator like instance of JSON object - :rtype: ~azure.core.paging.ItemPaged[JSON] + :return: An iterator like instance of Project + :rtype: ~azure.core.paging.ItemPaged[~azure.developer.devcenter.models.Project] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -978,9 +934,9 @@ def list_projects( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[JSON]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.Project]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -992,8 +948,6 @@ def prepare_request(next_link=None): if not next_link: _request = build_dev_center_list_projects_request( - filter=filter, - top=top, api_version=self._config.api_version, headers=_headers, params=_params, @@ -1029,7 +983,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["value"] + list_of_elem = _deserialize(List[_models.Project], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -1054,15 +1008,14 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) @distributed_trace - def get_project(self, project_name: str, **kwargs: Any) -> JSON: + def get_project(self, project_name: str, **kwargs: Any) -> _models.Project: + # pylint: disable=line-too-long """Gets a project. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: JSON object - :rtype: JSON + :return: Project. The Project is compatible with MutableMapping + :rtype: ~azure.developer.devcenter.models.Project :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -1076,7 +1029,7 @@ def get_project(self, project_name: str, **kwargs: Any) -> JSON: number of Dev Boxes a single user can create across all pools in the project. } """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1087,7 +1040,7 @@ def get_project(self, project_name: str, **kwargs: Any) -> JSON: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.Project] = kwargs.pop("cls", None) _request = build_dev_center_get_project_request( project_name=project_name, @@ -1116,31 +1069,22 @@ def get_project(self, project_name: str, **kwargs: Any) -> JSON: if _stream: deserialized = response.iter_bytes() else: - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.Project, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore @distributed_trace - def list_pools( - self, project_name: str, *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> Iterable[JSON]: + def list_pools(self, project_name: str, **kwargs: Any) -> Iterable["_models.Pool"]: + # pylint: disable=line-too-long """Lists available pools. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str - :keyword filter: An OData filter clause to apply to the operation. Default value is None. - :paramtype filter: str - :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. - Default value is None. - :paramtype top: int - :return: An iterator like instance of JSON object - :rtype: ~azure.core.paging.ItemPaged[JSON] + :return: An iterator like instance of Pool + :rtype: ~azure.core.paging.ItemPaged[~azure.developer.devcenter.models.Pool] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -1157,7 +1101,18 @@ def list_pools( "hardwareProfile": { "memoryGB": 0, # Optional. The amount of memory available for the Dev Box. - "skuName": "str", # Optional. The name of the SKU. + "skuName": "str", # Optional. The name of the SKU. Known values are: + "general_i_8c32gb256ssd_v2", "general_i_8c32gb512ssd_v2", + "general_i_8c32gb1024ssd_v2", "general_i_8c32gb2048ssd_v2", + "general_i_16c64gb256ssd_v2", "general_i_16c64gb512ssd_v2", + "general_i_16c64gb1024ssd_v2", "general_i_16c64gb2048ssd_v2", + "general_i_32c128gb512ssd_v2", "general_i_32c128gb1024ssd_v2", + "general_i_32c128gb2048ssd_v2", "general_a_8c32gb256ssd_v2", + "general_a_8c32gb512ssd_v2", "general_a_8c32gb1024ssd_v2", + "general_a_8c32gb2048ssd_v2", "general_a_16c64gb256ssd_v2", + "general_a_16c64gb512ssd_v2", "general_a_16c64gb1024ssd_v2", + "general_a_16c64gb2048ssd_v2", "general_a_32c128gb512ssd_v2", + "general_a_32c128gb1024ssd_v2", and "general_a_32c128gb2048ssd_v2". "vCPUs": 0 # Optional. The number of vCPUs available for the Dev Box. }, @@ -1197,9 +1152,9 @@ def list_pools( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[JSON]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.Pool]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1212,8 +1167,6 @@ def prepare_request(next_link=None): _request = build_dev_center_list_pools_request( project_name=project_name, - filter=filter, - top=top, api_version=self._config.api_version, headers=_headers, params=_params, @@ -1249,7 +1202,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["value"] + list_of_elem = _deserialize(List[_models.Pool], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -1274,17 +1227,16 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) @distributed_trace - def get_pool(self, project_name: str, pool_name: str, **kwargs: Any) -> JSON: + def get_pool(self, project_name: str, pool_name: str, **kwargs: Any) -> _models.Pool: + # pylint: disable=line-too-long """Gets a pool. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str - :param pool_name: The name of a pool of Dev Boxes. Required. + :param pool_name: Pool name. Required. :type pool_name: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: JSON object - :rtype: JSON + :return: Pool. The Pool is compatible with MutableMapping + :rtype: ~azure.developer.devcenter.models.Pool :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -1301,7 +1253,18 @@ def get_pool(self, project_name: str, pool_name: str, **kwargs: Any) -> JSON: "hardwareProfile": { "memoryGB": 0, # Optional. The amount of memory available for the Dev Box. - "skuName": "str", # Optional. The name of the SKU. + "skuName": "str", # Optional. The name of the SKU. Known values are: + "general_i_8c32gb256ssd_v2", "general_i_8c32gb512ssd_v2", + "general_i_8c32gb1024ssd_v2", "general_i_8c32gb2048ssd_v2", + "general_i_16c64gb256ssd_v2", "general_i_16c64gb512ssd_v2", + "general_i_16c64gb1024ssd_v2", "general_i_16c64gb2048ssd_v2", + "general_i_32c128gb512ssd_v2", "general_i_32c128gb1024ssd_v2", + "general_i_32c128gb2048ssd_v2", "general_a_8c32gb256ssd_v2", + "general_a_8c32gb512ssd_v2", "general_a_8c32gb1024ssd_v2", + "general_a_8c32gb2048ssd_v2", "general_a_16c64gb256ssd_v2", + "general_a_16c64gb512ssd_v2", "general_a_16c64gb1024ssd_v2", + "general_a_16c64gb2048ssd_v2", "general_a_32c128gb512ssd_v2", + "general_a_32c128gb1024ssd_v2", and "general_a_32c128gb2048ssd_v2". "vCPUs": 0 # Optional. The number of vCPUs available for the Dev Box. }, @@ -1338,7 +1301,7 @@ def get_pool(self, project_name: str, pool_name: str, **kwargs: Any) -> JSON: } } """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1349,7 +1312,7 @@ def get_pool(self, project_name: str, pool_name: str, **kwargs: Any) -> JSON: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.Pool] = kwargs.pop("cls", None) _request = build_dev_center_get_pool_request( project_name=project_name, @@ -1379,39 +1342,23 @@ def get_pool(self, project_name: str, pool_name: str, **kwargs: Any) -> JSON: if _stream: deserialized = response.iter_bytes() else: - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.Pool, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore @distributed_trace - def list_schedules( - self, - project_name: str, - pool_name: str, - *, - filter: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any - ) -> Iterable[JSON]: - """Lists available schedules for a pool. + def list_schedules(self, project_name: str, pool_name: str, **kwargs: Any) -> Iterable["_models.Schedule"]: + """Lists all schedules within a pool that are configured by your project administrator. :param project_name: The DevCenter Project upon which to execute operations. Required. :type project_name: str :param pool_name: The name of a pool of Dev Boxes. Required. :type pool_name: str - :keyword filter: An OData filter clause to apply to the operation. Default value is None. - :paramtype filter: str - :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. - Default value is None. - :paramtype top: int - :return: An iterator like instance of JSON object - :rtype: ~azure.core.paging.ItemPaged[JSON] + :return: An iterator like instance of Schedule + :rtype: ~azure.core.paging.ItemPaged[~azure.developer.devcenter.models.Schedule] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -1433,9 +1380,9 @@ def list_schedules( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[JSON]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.Schedule]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1449,8 +1396,6 @@ def prepare_request(next_link=None): _request = build_dev_center_list_schedules_request( project_name=project_name, pool_name=pool_name, - filter=filter, - top=top, api_version=self._config.api_version, headers=_headers, params=_params, @@ -1486,7 +1431,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["value"] + list_of_elem = _deserialize(List[_models.Schedule], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -1511,19 +1456,17 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) @distributed_trace - def get_schedule(self, project_name: str, pool_name: str, schedule_name: str, **kwargs: Any) -> JSON: + def get_schedule(self, project_name: str, pool_name: str, schedule_name: str, **kwargs: Any) -> _models.Schedule: """Gets a schedule. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str - :param pool_name: The name of a pool of Dev Boxes. Required. + :param pool_name: Pool name. Required. :type pool_name: str - :param schedule_name: The name of a schedule. Required. + :param schedule_name: Display name for the Schedule. Required. :type schedule_name: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: JSON object - :rtype: JSON + :return: Schedule. The Schedule is compatible with MutableMapping + :rtype: ~azure.developer.devcenter.models.Schedule :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -1542,7 +1485,7 @@ def get_schedule(self, project_name: str, pool_name: str, schedule_name: str, ** "StopDevBox" } """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1553,7 +1496,7 @@ def get_schedule(self, project_name: str, pool_name: str, schedule_name: str, ** _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.Schedule] = kwargs.pop("cls", None) _request = build_dev_center_get_schedule_request( project_name=project_name, @@ -1584,29 +1527,20 @@ def get_schedule(self, project_name: str, pool_name: str, schedule_name: str, ** if _stream: deserialized = response.iter_bytes() else: - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.Schedule, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore @distributed_trace - def list_all_dev_boxes( - self, *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> Iterable[JSON]: + def list_all_dev_boxes(self, **kwargs: Any) -> Iterable["_models.DevBox"]: + # pylint: disable=line-too-long """Lists Dev Boxes that the caller has access to in the DevCenter. - :keyword filter: An OData filter clause to apply to the operation. Default value is None. - :paramtype filter: str - :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. - Default value is None. - :paramtype top: int - :return: An iterator like instance of JSON object - :rtype: ~azure.core.paging.ItemPaged[JSON] + :return: An iterator like instance of DevBox + :rtype: ~azure.core.paging.ItemPaged[~azure.developer.devcenter.models.DevBox] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -1639,7 +1573,18 @@ def list_all_dev_boxes( "hardwareProfile": { "memoryGB": 0, # Optional. The amount of memory available for the Dev Box. - "skuName": "str", # Optional. The name of the SKU. + "skuName": "str", # Optional. The name of the SKU. Known values are: + "general_i_8c32gb256ssd_v2", "general_i_8c32gb512ssd_v2", + "general_i_8c32gb1024ssd_v2", "general_i_8c32gb2048ssd_v2", + "general_i_16c64gb256ssd_v2", "general_i_16c64gb512ssd_v2", + "general_i_16c64gb1024ssd_v2", "general_i_16c64gb2048ssd_v2", + "general_i_32c128gb512ssd_v2", "general_i_32c128gb1024ssd_v2", + "general_i_32c128gb2048ssd_v2", "general_a_8c32gb256ssd_v2", + "general_a_8c32gb512ssd_v2", "general_a_8c32gb1024ssd_v2", + "general_a_8c32gb2048ssd_v2", "general_a_16c64gb256ssd_v2", + "general_a_16c64gb512ssd_v2", "general_a_16c64gb1024ssd_v2", + "general_a_16c64gb2048ssd_v2", "general_a_32c128gb512ssd_v2", + "general_a_32c128gb1024ssd_v2", and "general_a_32c128gb2048ssd_v2". "vCPUs": 0 # Optional. The number of vCPUs available for the Dev Box. }, @@ -1668,7 +1613,9 @@ def list_all_dev_boxes( "projectName": "str", # Optional. Name of the project this Dev Box belongs to. "provisioningState": "str", # Optional. The current provisioning state of - the Dev Box. + the Dev Box. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Deleting", "Updating", "Starting", "Stopping", "Provisioning", + "ProvisionedWithWarning", "InGracePeriod", and "NotProvisioned". "storageProfile": { "osDisk": { "diskSizeGB": 0 # Optional. The size of the OS Disk in @@ -1684,9 +1631,9 @@ def list_all_dev_boxes( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[JSON]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.DevBox]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1698,8 +1645,6 @@ def prepare_request(next_link=None): if not next_link: _request = build_dev_center_list_all_dev_boxes_request( - filter=filter, - top=top, api_version=self._config.api_version, headers=_headers, params=_params, @@ -1735,7 +1680,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["value"] + list_of_elem = _deserialize(List[_models.DevBox], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -1760,21 +1705,15 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) @distributed_trace - def list_all_dev_boxes_by_user( - self, user_id: str, *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> Iterable[JSON]: + def list_all_dev_boxes_by_user(self, user_id: str, **kwargs: Any) -> Iterable["_models.DevBox"]: + # pylint: disable=line-too-long """Lists Dev Boxes in the Dev Center for a particular user. :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str - :keyword filter: An OData filter clause to apply to the operation. Default value is None. - :paramtype filter: str - :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. - Default value is None. - :paramtype top: int - :return: An iterator like instance of JSON object - :rtype: ~azure.core.paging.ItemPaged[JSON] + :return: An iterator like instance of DevBox + :rtype: ~azure.core.paging.ItemPaged[~azure.developer.devcenter.models.DevBox] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -1807,7 +1746,18 @@ def list_all_dev_boxes_by_user( "hardwareProfile": { "memoryGB": 0, # Optional. The amount of memory available for the Dev Box. - "skuName": "str", # Optional. The name of the SKU. + "skuName": "str", # Optional. The name of the SKU. Known values are: + "general_i_8c32gb256ssd_v2", "general_i_8c32gb512ssd_v2", + "general_i_8c32gb1024ssd_v2", "general_i_8c32gb2048ssd_v2", + "general_i_16c64gb256ssd_v2", "general_i_16c64gb512ssd_v2", + "general_i_16c64gb1024ssd_v2", "general_i_16c64gb2048ssd_v2", + "general_i_32c128gb512ssd_v2", "general_i_32c128gb1024ssd_v2", + "general_i_32c128gb2048ssd_v2", "general_a_8c32gb256ssd_v2", + "general_a_8c32gb512ssd_v2", "general_a_8c32gb1024ssd_v2", + "general_a_8c32gb2048ssd_v2", "general_a_16c64gb256ssd_v2", + "general_a_16c64gb512ssd_v2", "general_a_16c64gb1024ssd_v2", + "general_a_16c64gb2048ssd_v2", "general_a_32c128gb512ssd_v2", + "general_a_32c128gb1024ssd_v2", and "general_a_32c128gb2048ssd_v2". "vCPUs": 0 # Optional. The number of vCPUs available for the Dev Box. }, @@ -1836,7 +1786,9 @@ def list_all_dev_boxes_by_user( "projectName": "str", # Optional. Name of the project this Dev Box belongs to. "provisioningState": "str", # Optional. The current provisioning state of - the Dev Box. + the Dev Box. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Deleting", "Updating", "Starting", "Stopping", "Provisioning", + "ProvisionedWithWarning", "InGracePeriod", and "NotProvisioned". "storageProfile": { "osDisk": { "diskSizeGB": 0 # Optional. The size of the OS Disk in @@ -1852,9 +1804,9 @@ def list_all_dev_boxes_by_user( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[JSON]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.DevBox]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1867,8 +1819,6 @@ def prepare_request(next_link=None): _request = build_dev_center_list_all_dev_boxes_by_user_request( user_id=user_id, - filter=filter, - top=top, api_version=self._config.api_version, headers=_headers, params=_params, @@ -1904,7 +1854,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["value"] + list_of_elem = _deserialize(List[_models.DevBox], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -1929,9 +1879,8 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) @distributed_trace - def list_dev_boxes( - self, project_name: str, user_id: str, *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> Iterable[JSON]: + def list_dev_boxes(self, project_name: str, user_id: str, **kwargs: Any) -> Iterable["_models.DevBox"]: + # pylint: disable=line-too-long """Lists Dev Boxes in the project for a particular user. :param project_name: The DevCenter Project upon which to execute operations. Required. @@ -1939,13 +1888,8 @@ def list_dev_boxes( :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str - :keyword filter: An OData filter clause to apply to the operation. Default value is None. - :paramtype filter: str - :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. - Default value is None. - :paramtype top: int - :return: An iterator like instance of JSON object - :rtype: ~azure.core.paging.ItemPaged[JSON] + :return: An iterator like instance of DevBox + :rtype: ~azure.core.paging.ItemPaged[~azure.developer.devcenter.models.DevBox] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -1978,7 +1922,18 @@ def list_dev_boxes( "hardwareProfile": { "memoryGB": 0, # Optional. The amount of memory available for the Dev Box. - "skuName": "str", # Optional. The name of the SKU. + "skuName": "str", # Optional. The name of the SKU. Known values are: + "general_i_8c32gb256ssd_v2", "general_i_8c32gb512ssd_v2", + "general_i_8c32gb1024ssd_v2", "general_i_8c32gb2048ssd_v2", + "general_i_16c64gb256ssd_v2", "general_i_16c64gb512ssd_v2", + "general_i_16c64gb1024ssd_v2", "general_i_16c64gb2048ssd_v2", + "general_i_32c128gb512ssd_v2", "general_i_32c128gb1024ssd_v2", + "general_i_32c128gb2048ssd_v2", "general_a_8c32gb256ssd_v2", + "general_a_8c32gb512ssd_v2", "general_a_8c32gb1024ssd_v2", + "general_a_8c32gb2048ssd_v2", "general_a_16c64gb256ssd_v2", + "general_a_16c64gb512ssd_v2", "general_a_16c64gb1024ssd_v2", + "general_a_16c64gb2048ssd_v2", "general_a_32c128gb512ssd_v2", + "general_a_32c128gb1024ssd_v2", and "general_a_32c128gb2048ssd_v2". "vCPUs": 0 # Optional. The number of vCPUs available for the Dev Box. }, @@ -2007,7 +1962,9 @@ def list_dev_boxes( "projectName": "str", # Optional. Name of the project this Dev Box belongs to. "provisioningState": "str", # Optional. The current provisioning state of - the Dev Box. + the Dev Box. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Deleting", "Updating", "Starting", "Stopping", "Provisioning", + "ProvisionedWithWarning", "InGracePeriod", and "NotProvisioned". "storageProfile": { "osDisk": { "diskSizeGB": 0 # Optional. The size of the OS Disk in @@ -2023,9 +1980,9 @@ def list_dev_boxes( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[JSON]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.DevBox]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2039,8 +1996,6 @@ def prepare_request(next_link=None): _request = build_dev_center_list_dev_boxes_request( project_name=project_name, user_id=user_id, - filter=filter, - top=top, api_version=self._config.api_version, headers=_headers, params=_params, @@ -2076,7 +2031,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["value"] + list_of_elem = _deserialize(List[_models.DevBox], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -2101,20 +2056,19 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) @distributed_trace - def get_dev_box(self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any) -> JSON: + def get_dev_box(self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any) -> _models.DevBox: + # pylint: disable=line-too-long """Gets a Dev Box. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str - :param dev_box_name: The name of a Dev Box. Required. + :param dev_box_name: Display name for the Dev Box. Required. :type dev_box_name: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: JSON object - :rtype: JSON + :return: DevBox. The DevBox is compatible with MutableMapping + :rtype: ~azure.developer.devcenter.models.DevBox :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -2147,7 +2101,18 @@ def get_dev_box(self, project_name: str, user_id: str, dev_box_name: str, **kwar "hardwareProfile": { "memoryGB": 0, # Optional. The amount of memory available for the Dev Box. - "skuName": "str", # Optional. The name of the SKU. + "skuName": "str", # Optional. The name of the SKU. Known values are: + "general_i_8c32gb256ssd_v2", "general_i_8c32gb512ssd_v2", + "general_i_8c32gb1024ssd_v2", "general_i_8c32gb2048ssd_v2", + "general_i_16c64gb256ssd_v2", "general_i_16c64gb512ssd_v2", + "general_i_16c64gb1024ssd_v2", "general_i_16c64gb2048ssd_v2", + "general_i_32c128gb512ssd_v2", "general_i_32c128gb1024ssd_v2", + "general_i_32c128gb2048ssd_v2", "general_a_8c32gb256ssd_v2", + "general_a_8c32gb512ssd_v2", "general_a_8c32gb1024ssd_v2", + "general_a_8c32gb2048ssd_v2", "general_a_16c64gb256ssd_v2", + "general_a_16c64gb512ssd_v2", "general_a_16c64gb1024ssd_v2", + "general_a_16c64gb2048ssd_v2", "general_a_32c128gb512ssd_v2", + "general_a_32c128gb1024ssd_v2", and "general_a_32c128gb2048ssd_v2". "vCPUs": 0 # Optional. The number of vCPUs available for the Dev Box. }, @@ -2176,7 +2141,9 @@ def get_dev_box(self, project_name: str, user_id: str, dev_box_name: str, **kwar "projectName": "str", # Optional. Name of the project this Dev Box belongs to. "provisioningState": "str", # Optional. The current provisioning state of - the Dev Box. + the Dev Box. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Deleting", "Updating", "Starting", "Stopping", "Provisioning", + "ProvisionedWithWarning", "InGracePeriod", and "NotProvisioned". "storageProfile": { "osDisk": { "diskSizeGB": 0 # Optional. The size of the OS Disk in @@ -2189,7 +2156,7 @@ def get_dev_box(self, project_name: str, user_id: str, dev_box_name: str, **kwar assigned to. } """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2200,7 +2167,7 @@ def get_dev_box(self, project_name: str, user_id: str, dev_box_name: str, **kwar _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.DevBox] = kwargs.pop("cls", None) _request = build_dev_center_get_dev_box_request( project_name=project_name, @@ -2231,20 +2198,22 @@ def get_dev_box(self, project_name: str, user_id: str, dev_box_name: str, **kwar if _stream: deserialized = response.iter_bytes() else: - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.DevBox, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore def _create_dev_box_initial( - self, project_name: str, user_id: str, dev_box_name: str, body: Union[JSON, IO], **kwargs: Any + self, + project_name: str, + user_id: str, + dev_box_name: str, + body: Union[_models.DevBox, JSON, IO[bytes]], + **kwargs: Any ) -> JSON: - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2259,12 +2228,11 @@ def _create_dev_box_initial( cls: ClsType[JSON] = kwargs.pop("cls", None) content_type = content_type or "application/json" - _json = None _content = None if isinstance(body, (IOBase, bytes)): _content = body else: - _json = body + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_dev_center_create_dev_box_request( project_name=project_name, @@ -2272,7 +2240,6 @@ def _create_dev_box_initial( dev_box_name=dev_box_name, content_type=content_type, api_version=self._config.api_version, - json=_json, content=_content, headers=_headers, params=_params, @@ -2297,10 +2264,7 @@ def _create_dev_box_initial( response_headers = {} if response.status_code == 200: - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(JSON, response.json()) if response.status_code == 201: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) @@ -2308,15 +2272,12 @@ def _create_dev_box_initial( "str", response.headers.get("Operation-Location") ) - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(JSON, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), response_headers) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore @overload def begin_create_dev_box( @@ -2324,34 +2285,30 @@ def begin_create_dev_box( project_name: str, user_id: str, dev_box_name: str, - body: JSON, + body: _models.DevBox, *, content_type: str = "application/json", **kwargs: Any - ) -> LROPoller[JSON]: + ) -> LROPoller[_models.DevBox]: + # pylint: disable=line-too-long """Creates or replaces a Dev Box. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: The DevCenter Project upon which to execute the operation. Required. :type project_name: str :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str :param dev_box_name: The name of a Dev Box. Required. :type dev_box_name: str - :param body: Represents a environment. Required. - :type body: JSON + :param body: Represents the body request of a Dev Box creation. Dev Box Pool name is required. + Optionally set the owner of the Dev Box as local administrator. Required. + :type body: ~azure.developer.devcenter.models.DevBox :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns JSON object - :rtype: ~azure.core.polling.LROPoller[JSON] + :return: An instance of LROPoller that returns DevBox. The DevBox is compatible with + MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.developer.devcenter.models.DevBox] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -2384,7 +2341,18 @@ def begin_create_dev_box( "hardwareProfile": { "memoryGB": 0, # Optional. The amount of memory available for the Dev Box. - "skuName": "str", # Optional. The name of the SKU. + "skuName": "str", # Optional. The name of the SKU. Known values are: + "general_i_8c32gb256ssd_v2", "general_i_8c32gb512ssd_v2", + "general_i_8c32gb1024ssd_v2", "general_i_8c32gb2048ssd_v2", + "general_i_16c64gb256ssd_v2", "general_i_16c64gb512ssd_v2", + "general_i_16c64gb1024ssd_v2", "general_i_16c64gb2048ssd_v2", + "general_i_32c128gb512ssd_v2", "general_i_32c128gb1024ssd_v2", + "general_i_32c128gb2048ssd_v2", "general_a_8c32gb256ssd_v2", + "general_a_8c32gb512ssd_v2", "general_a_8c32gb1024ssd_v2", + "general_a_8c32gb2048ssd_v2", "general_a_16c64gb256ssd_v2", + "general_a_16c64gb512ssd_v2", "general_a_16c64gb1024ssd_v2", + "general_a_16c64gb2048ssd_v2", "general_a_32c128gb512ssd_v2", + "general_a_32c128gb1024ssd_v2", and "general_a_32c128gb2048ssd_v2". "vCPUs": 0 # Optional. The number of vCPUs available for the Dev Box. }, @@ -2413,7 +2381,9 @@ def begin_create_dev_box( "projectName": "str", # Optional. Name of the project this Dev Box belongs to. "provisioningState": "str", # Optional. The current provisioning state of - the Dev Box. + the Dev Box. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Deleting", "Updating", "Starting", "Stopping", "Provisioning", + "ProvisionedWithWarning", "InGracePeriod", and "NotProvisioned". "storageProfile": { "osDisk": { "diskSizeGB": 0 # Optional. The size of the OS Disk in @@ -2453,7 +2423,18 @@ def begin_create_dev_box( "hardwareProfile": { "memoryGB": 0, # Optional. The amount of memory available for the Dev Box. - "skuName": "str", # Optional. The name of the SKU. + "skuName": "str", # Optional. The name of the SKU. Known values are: + "general_i_8c32gb256ssd_v2", "general_i_8c32gb512ssd_v2", + "general_i_8c32gb1024ssd_v2", "general_i_8c32gb2048ssd_v2", + "general_i_16c64gb256ssd_v2", "general_i_16c64gb512ssd_v2", + "general_i_16c64gb1024ssd_v2", "general_i_16c64gb2048ssd_v2", + "general_i_32c128gb512ssd_v2", "general_i_32c128gb1024ssd_v2", + "general_i_32c128gb2048ssd_v2", "general_a_8c32gb256ssd_v2", + "general_a_8c32gb512ssd_v2", "general_a_8c32gb1024ssd_v2", + "general_a_8c32gb2048ssd_v2", "general_a_16c64gb256ssd_v2", + "general_a_16c64gb512ssd_v2", "general_a_16c64gb1024ssd_v2", + "general_a_16c64gb2048ssd_v2", "general_a_32c128gb512ssd_v2", + "general_a_32c128gb1024ssd_v2", and "general_a_32c128gb2048ssd_v2". "vCPUs": 0 # Optional. The number of vCPUs available for the Dev Box. }, @@ -2482,7 +2463,9 @@ def begin_create_dev_box( "projectName": "str", # Optional. Name of the project this Dev Box belongs to. "provisioningState": "str", # Optional. The current provisioning state of - the Dev Box. + the Dev Box. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Deleting", "Updating", "Starting", "Stopping", "Provisioning", + "ProvisionedWithWarning", "InGracePeriod", and "NotProvisioned". "storageProfile": { "osDisk": { "diskSizeGB": 0 # Optional. The size of the OS Disk in @@ -2502,34 +2485,148 @@ def begin_create_dev_box( project_name: str, user_id: str, dev_box_name: str, - body: IO, + body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> LROPoller[JSON]: + ) -> LROPoller[_models.DevBox]: + # pylint: disable=line-too-long """Creates or replaces a Dev Box. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: The DevCenter Project upon which to execute the operation. Required. + :type project_name: str + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Required. + :type user_id: str + :param dev_box_name: The name of a Dev Box. Required. + :type dev_box_name: str + :param body: Represents the body request of a Dev Box creation. Dev Box Pool name is required. + Optionally set the owner of the Dev Box as local administrator. Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns DevBox. The DevBox is compatible with + MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.developer.devcenter.models.DevBox] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200, 201 + response == { + "name": "str", # Display name for the Dev Box. Required. + "poolName": "str", # The name of the Dev Box pool this machine belongs to. + Required. + "actionState": "str", # Optional. The current action state of the Dev Box. + This is state is based on previous action performed by user. + "createdTime": "2020-02-20 00:00:00", # Optional. Creation time of this Dev + Box. + "error": { + "code": "str", # One of a server-defined set of error codes. + Required. + "message": "str", # A human-readable representation of the error. + Required. + "details": [ + ... + ], + "innererror": { + "code": "str", # Optional. One of a server-defined set of + error codes. + "innererror": ... + }, + "target": "str" # Optional. The target of the error. + }, + "hardwareProfile": { + "memoryGB": 0, # Optional. The amount of memory available for the + Dev Box. + "skuName": "str", # Optional. The name of the SKU. Known values are: + "general_i_8c32gb256ssd_v2", "general_i_8c32gb512ssd_v2", + "general_i_8c32gb1024ssd_v2", "general_i_8c32gb2048ssd_v2", + "general_i_16c64gb256ssd_v2", "general_i_16c64gb512ssd_v2", + "general_i_16c64gb1024ssd_v2", "general_i_16c64gb2048ssd_v2", + "general_i_32c128gb512ssd_v2", "general_i_32c128gb1024ssd_v2", + "general_i_32c128gb2048ssd_v2", "general_a_8c32gb256ssd_v2", + "general_a_8c32gb512ssd_v2", "general_a_8c32gb1024ssd_v2", + "general_a_8c32gb2048ssd_v2", "general_a_16c64gb256ssd_v2", + "general_a_16c64gb512ssd_v2", "general_a_16c64gb1024ssd_v2", + "general_a_16c64gb2048ssd_v2", "general_a_32c128gb512ssd_v2", + "general_a_32c128gb1024ssd_v2", and "general_a_32c128gb2048ssd_v2". + "vCPUs": 0 # Optional. The number of vCPUs available for the Dev + Box. + }, + "hibernateSupport": "str", # Optional. Indicates whether hibernate is + enabled/disabled or unknown. Known values are: "Enabled", "Disabled", and + "OsUnsupported". + "imageReference": { + "name": "str", # Optional. The name of the image used. + "operatingSystem": "str", # Optional. The operating system of the + image. + "osBuildNumber": "str", # Optional. The operating system build + number of the image. + "publishedDate": "2020-02-20 00:00:00", # Optional. The datetime + that the backing image version was published. + "version": "str" # Optional. The version of the image. + }, + "localAdministrator": "str", # Optional. Indicates whether the owner of the + Dev Box is a local administrator. Known values are: "Enabled" and "Disabled". + "location": "str", # Optional. Azure region where this Dev Box is located. + This will be the same region as the Virtual Network it is attached to. + "osType": "str", # Optional. The operating system type of this Dev Box. + "Windows" + "powerState": "str", # Optional. The current power state of the Dev Box. + Known values are: "Unknown", "Running", "Deallocated", "PoweredOff", and + "Hibernated". + "projectName": "str", # Optional. Name of the project this Dev Box belongs + to. + "provisioningState": "str", # Optional. The current provisioning state of + the Dev Box. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Deleting", "Updating", "Starting", "Stopping", "Provisioning", + "ProvisionedWithWarning", "InGracePeriod", and "NotProvisioned". + "storageProfile": { + "osDisk": { + "diskSizeGB": 0 # Optional. The size of the OS Disk in + gigabytes. + } + }, + "uniqueId": "str", # Optional. A unique identifier for the Dev Box. This is + a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + "user": "str" # Optional. The AAD object id of the user this Dev Box is + assigned to. + } + """ + + @overload + def begin_create_dev_box( + self, + project_name: str, + user_id: str, + dev_box_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DevBox]: + # pylint: disable=line-too-long + """Creates or replaces a Dev Box. + + :param project_name: The DevCenter Project upon which to execute the operation. Required. :type project_name: str :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str :param dev_box_name: The name of a Dev Box. Required. :type dev_box_name: str - :param body: Represents a environment. Required. - :type body: IO + :param body: Represents the body request of a Dev Box creation. Dev Box Pool name is required. + Optionally set the owner of the Dev Box as local administrator. Required. + :type body: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns JSON object - :rtype: ~azure.core.polling.LROPoller[JSON] + :return: An instance of LROPoller that returns DevBox. The DevBox is compatible with + MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.developer.devcenter.models.DevBox] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -2562,7 +2659,18 @@ def begin_create_dev_box( "hardwareProfile": { "memoryGB": 0, # Optional. The amount of memory available for the Dev Box. - "skuName": "str", # Optional. The name of the SKU. + "skuName": "str", # Optional. The name of the SKU. Known values are: + "general_i_8c32gb256ssd_v2", "general_i_8c32gb512ssd_v2", + "general_i_8c32gb1024ssd_v2", "general_i_8c32gb2048ssd_v2", + "general_i_16c64gb256ssd_v2", "general_i_16c64gb512ssd_v2", + "general_i_16c64gb1024ssd_v2", "general_i_16c64gb2048ssd_v2", + "general_i_32c128gb512ssd_v2", "general_i_32c128gb1024ssd_v2", + "general_i_32c128gb2048ssd_v2", "general_a_8c32gb256ssd_v2", + "general_a_8c32gb512ssd_v2", "general_a_8c32gb1024ssd_v2", + "general_a_8c32gb2048ssd_v2", "general_a_16c64gb256ssd_v2", + "general_a_16c64gb512ssd_v2", "general_a_16c64gb1024ssd_v2", + "general_a_16c64gb2048ssd_v2", "general_a_32c128gb512ssd_v2", + "general_a_32c128gb1024ssd_v2", and "general_a_32c128gb2048ssd_v2". "vCPUs": 0 # Optional. The number of vCPUs available for the Dev Box. }, @@ -2591,7 +2699,9 @@ def begin_create_dev_box( "projectName": "str", # Optional. Name of the project this Dev Box belongs to. "provisioningState": "str", # Optional. The current provisioning state of - the Dev Box. + the Dev Box. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Deleting", "Updating", "Starting", "Stopping", "Provisioning", + "ProvisionedWithWarning", "InGracePeriod", and "NotProvisioned". "storageProfile": { "osDisk": { "diskSizeGB": 0 # Optional. The size of the OS Disk in @@ -2607,31 +2717,30 @@ def begin_create_dev_box( @distributed_trace def begin_create_dev_box( - self, project_name: str, user_id: str, dev_box_name: str, body: Union[JSON, IO], **kwargs: Any - ) -> LROPoller[JSON]: + self, + project_name: str, + user_id: str, + dev_box_name: str, + body: Union[_models.DevBox, JSON, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.DevBox]: + # pylint: disable=line-too-long """Creates or replaces a Dev Box. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: The DevCenter Project upon which to execute the operation. Required. :type project_name: str :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str :param dev_box_name: The name of a Dev Box. Required. :type dev_box_name: str - :param body: Represents a environment. Is either a JSON type or a IO type. Required. - :type body: JSON or IO - :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default - value is None. - :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns JSON object - :rtype: ~azure.core.polling.LROPoller[JSON] + :param body: Represents the body request of a Dev Box creation. Dev Box Pool name is required. + Optionally set the owner of the Dev Box as local administrator. Is one of the following types: + DevBox, JSON, IO[bytes] Required. + :type body: ~azure.developer.devcenter.models.DevBox or JSON or IO[bytes] + :return: An instance of LROPoller that returns DevBox. The DevBox is compatible with + MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.developer.devcenter.models.DevBox] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -2664,7 +2773,18 @@ def begin_create_dev_box( "hardwareProfile": { "memoryGB": 0, # Optional. The amount of memory available for the Dev Box. - "skuName": "str", # Optional. The name of the SKU. + "skuName": "str", # Optional. The name of the SKU. Known values are: + "general_i_8c32gb256ssd_v2", "general_i_8c32gb512ssd_v2", + "general_i_8c32gb1024ssd_v2", "general_i_8c32gb2048ssd_v2", + "general_i_16c64gb256ssd_v2", "general_i_16c64gb512ssd_v2", + "general_i_16c64gb1024ssd_v2", "general_i_16c64gb2048ssd_v2", + "general_i_32c128gb512ssd_v2", "general_i_32c128gb1024ssd_v2", + "general_i_32c128gb2048ssd_v2", "general_a_8c32gb256ssd_v2", + "general_a_8c32gb512ssd_v2", "general_a_8c32gb1024ssd_v2", + "general_a_8c32gb2048ssd_v2", "general_a_16c64gb256ssd_v2", + "general_a_16c64gb512ssd_v2", "general_a_16c64gb1024ssd_v2", + "general_a_16c64gb2048ssd_v2", "general_a_32c128gb512ssd_v2", + "general_a_32c128gb1024ssd_v2", and "general_a_32c128gb2048ssd_v2". "vCPUs": 0 # Optional. The number of vCPUs available for the Dev Box. }, @@ -2693,7 +2813,9 @@ def begin_create_dev_box( "projectName": "str", # Optional. Name of the project this Dev Box belongs to. "provisioningState": "str", # Optional. The current provisioning state of - the Dev Box. + the Dev Box. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Deleting", "Updating", "Starting", "Stopping", "Provisioning", + "ProvisionedWithWarning", "InGracePeriod", and "NotProvisioned". "storageProfile": { "osDisk": { "diskSizeGB": 0 # Optional. The size of the OS Disk in @@ -2733,7 +2855,18 @@ def begin_create_dev_box( "hardwareProfile": { "memoryGB": 0, # Optional. The amount of memory available for the Dev Box. - "skuName": "str", # Optional. The name of the SKU. + "skuName": "str", # Optional. The name of the SKU. Known values are: + "general_i_8c32gb256ssd_v2", "general_i_8c32gb512ssd_v2", + "general_i_8c32gb1024ssd_v2", "general_i_8c32gb2048ssd_v2", + "general_i_16c64gb256ssd_v2", "general_i_16c64gb512ssd_v2", + "general_i_16c64gb1024ssd_v2", "general_i_16c64gb2048ssd_v2", + "general_i_32c128gb512ssd_v2", "general_i_32c128gb1024ssd_v2", + "general_i_32c128gb2048ssd_v2", "general_a_8c32gb256ssd_v2", + "general_a_8c32gb512ssd_v2", "general_a_8c32gb1024ssd_v2", + "general_a_8c32gb2048ssd_v2", "general_a_16c64gb256ssd_v2", + "general_a_16c64gb512ssd_v2", "general_a_16c64gb1024ssd_v2", + "general_a_16c64gb2048ssd_v2", "general_a_32c128gb512ssd_v2", + "general_a_32c128gb1024ssd_v2", and "general_a_32c128gb2048ssd_v2". "vCPUs": 0 # Optional. The number of vCPUs available for the Dev Box. }, @@ -2762,7 +2895,9 @@ def begin_create_dev_box( "projectName": "str", # Optional. Name of the project this Dev Box belongs to. "provisioningState": "str", # Optional. The current provisioning state of - the Dev Box. + the Dev Box. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Deleting", "Updating", "Starting", "Stopping", "Provisioning", + "ProvisionedWithWarning", "InGracePeriod", and "NotProvisioned". "storageProfile": { "osDisk": { "diskSizeGB": 0 # Optional. The size of the OS Disk in @@ -2779,7 +2914,7 @@ def begin_create_dev_box( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.DevBox] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) @@ -2799,10 +2934,7 @@ def begin_create_dev_box( def get_long_running_output(pipeline_response): response = pipeline_response.http_response - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.DevBox, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized @@ -2820,18 +2952,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller[JSON].from_continuation_token( + return LROPoller[_models.DevBox].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller[JSON](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return LROPoller[_models.DevBox]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) def _delete_dev_box_initial( self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any ) -> Optional[JSON]: - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2878,10 +3012,7 @@ def _delete_dev_box_initial( "str", response.headers.get("Operation-Location") ) - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(JSON, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -2891,7 +3022,8 @@ def _delete_dev_box_initial( @distributed_trace def begin_delete_dev_box( self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any - ) -> LROPoller[JSON]: + ) -> LROPoller[_models.OperationDetails]: + # pylint: disable=line-too-long """Deletes a Dev Box. :param project_name: The DevCenter Project upon which to execute operations. Required. @@ -2901,15 +3033,9 @@ def begin_delete_dev_box( :type user_id: str :param dev_box_name: The name of a Dev Box. Required. :type dev_box_name: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns JSON object - :rtype: ~azure.core.polling.LROPoller[JSON] + :return: An instance of LROPoller that returns OperationDetails. The OperationDetails is + compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.developer.devcenter.models.OperationDetails] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -2917,15 +3043,26 @@ def begin_delete_dev_box( # response body for status code(s): 202 response == { + "id": "str", # Fully qualified ID for the operation status. Required. + "name": "str", # The operation id name. Required. "status": "str", # Provisioning state of the resource. Required. Known - values are: "Running", "Completed", "Canceled", and "Failed". + values are: "NotStarted", "Running", "Succeeded", "Failed", and "Canceled". "endTime": "2020-02-20 00:00:00", # Optional. The end time of the operation. "error": { - "code": "str", # Optional. The error code. - "message": "str" # Optional. The error message. + "code": "str", # One of a server-defined set of error codes. + Required. + "message": "str", # A human-readable representation of the error. + Required. + "details": [ + ... + ], + "innererror": { + "code": "str", # Optional. One of a server-defined set of + error codes. + "innererror": ... + }, + "target": "str" # Optional. The target of the error. }, - "id": "str", # Optional. Fully qualified ID for the operation status. - "name": "str", # Optional. The operation id name. "percentComplete": 0.0, # Optional. Percent of the operation that is complete. "properties": {}, # Optional. Custom operation properties, populated only @@ -2938,7 +3075,7 @@ def begin_delete_dev_box( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.OperationDetails] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) @@ -2962,10 +3099,7 @@ def get_long_running_output(pipeline_response): "str", response.headers.get("Operation-Location") ) - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.OperationDetails, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized @@ -2983,16 +3117,18 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller[JSON].from_continuation_token( + return LROPoller[_models.OperationDetails].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller[JSON](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return LROPoller[_models.OperationDetails]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) def _start_dev_box_initial(self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any) -> JSON: - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3034,36 +3170,30 @@ def _start_dev_box_initial(self, project_name: str, user_id: str, dev_box_name: response_headers = {} response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(JSON, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), response_headers) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore @distributed_trace - def begin_start_dev_box(self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any) -> LROPoller[JSON]: + def begin_start_dev_box( + self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any + ) -> LROPoller[_models.OperationDetails]: + # pylint: disable=line-too-long """Starts a Dev Box. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str - :param dev_box_name: The name of a Dev Box. Required. + :param dev_box_name: Display name for the Dev Box. Required. :type dev_box_name: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns JSON object - :rtype: ~azure.core.polling.LROPoller[JSON] + :return: An instance of LROPoller that returns OperationDetails. The OperationDetails is + compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.developer.devcenter.models.OperationDetails] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -3071,15 +3201,26 @@ def begin_start_dev_box(self, project_name: str, user_id: str, dev_box_name: str # response body for status code(s): 202 response == { + "id": "str", # Fully qualified ID for the operation status. Required. + "name": "str", # The operation id name. Required. "status": "str", # Provisioning state of the resource. Required. Known - values are: "Running", "Completed", "Canceled", and "Failed". + values are: "NotStarted", "Running", "Succeeded", "Failed", and "Canceled". "endTime": "2020-02-20 00:00:00", # Optional. The end time of the operation. "error": { - "code": "str", # Optional. The error code. - "message": "str" # Optional. The error message. + "code": "str", # One of a server-defined set of error codes. + Required. + "message": "str", # A human-readable representation of the error. + Required. + "details": [ + ... + ], + "innererror": { + "code": "str", # Optional. One of a server-defined set of + error codes. + "innererror": ... + }, + "target": "str" # Optional. The target of the error. }, - "id": "str", # Optional. Fully qualified ID for the operation status. - "name": "str", # Optional. The operation id name. "percentComplete": 0.0, # Optional. Percent of the operation that is complete. "properties": {}, # Optional. Custom operation properties, populated only @@ -3092,7 +3233,7 @@ def begin_start_dev_box(self, project_name: str, user_id: str, dev_box_name: str _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.OperationDetails] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) @@ -3115,10 +3256,7 @@ def get_long_running_output(pipeline_response): "str", response.headers.get("Operation-Location") ) - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.OperationDetails, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized @@ -3136,18 +3274,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller[JSON].from_continuation_token( + return LROPoller[_models.OperationDetails].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller[JSON](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return LROPoller[_models.OperationDetails]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) def _stop_dev_box_initial( self, project_name: str, user_id: str, dev_box_name: str, *, hibernate: Optional[bool] = None, **kwargs: Any ) -> JSON: - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3190,40 +3330,32 @@ def _stop_dev_box_initial( response_headers = {} response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(JSON, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), response_headers) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore @distributed_trace def begin_stop_dev_box( self, project_name: str, user_id: str, dev_box_name: str, *, hibernate: Optional[bool] = None, **kwargs: Any - ) -> LROPoller[JSON]: + ) -> LROPoller[_models.OperationDetails]: + # pylint: disable=line-too-long """Stops a Dev Box. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str - :param dev_box_name: The name of a Dev Box. Required. + :param dev_box_name: Display name for the Dev Box. Required. :type dev_box_name: str :keyword hibernate: Optional parameter to hibernate the dev box. Default value is None. :paramtype hibernate: bool - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns JSON object - :rtype: ~azure.core.polling.LROPoller[JSON] + :return: An instance of LROPoller that returns OperationDetails. The OperationDetails is + compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.developer.devcenter.models.OperationDetails] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -3231,15 +3363,26 @@ def begin_stop_dev_box( # response body for status code(s): 202 response == { + "id": "str", # Fully qualified ID for the operation status. Required. + "name": "str", # The operation id name. Required. "status": "str", # Provisioning state of the resource. Required. Known - values are: "Running", "Completed", "Canceled", and "Failed". + values are: "NotStarted", "Running", "Succeeded", "Failed", and "Canceled". "endTime": "2020-02-20 00:00:00", # Optional. The end time of the operation. "error": { - "code": "str", # Optional. The error code. - "message": "str" # Optional. The error message. + "code": "str", # One of a server-defined set of error codes. + Required. + "message": "str", # A human-readable representation of the error. + Required. + "details": [ + ... + ], + "innererror": { + "code": "str", # Optional. One of a server-defined set of + error codes. + "innererror": ... + }, + "target": "str" # Optional. The target of the error. }, - "id": "str", # Optional. Fully qualified ID for the operation status. - "name": "str", # Optional. The operation id name. "percentComplete": 0.0, # Optional. Percent of the operation that is complete. "properties": {}, # Optional. Custom operation properties, populated only @@ -3252,7 +3395,7 @@ def begin_stop_dev_box( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.OperationDetails] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) @@ -3276,10 +3419,7 @@ def get_long_running_output(pipeline_response): "str", response.headers.get("Operation-Location") ) - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.OperationDetails, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized @@ -3297,16 +3437,18 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller[JSON].from_continuation_token( + return LROPoller[_models.OperationDetails].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller[JSON](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return LROPoller[_models.OperationDetails]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) def _restart_dev_box_initial(self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any) -> JSON: - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3348,38 +3490,30 @@ def _restart_dev_box_initial(self, project_name: str, user_id: str, dev_box_name response_headers = {} response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(JSON, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), response_headers) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore @distributed_trace def begin_restart_dev_box( self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any - ) -> LROPoller[JSON]: + ) -> LROPoller[_models.OperationDetails]: + # pylint: disable=line-too-long """Restarts a Dev Box. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str - :param dev_box_name: The name of a Dev Box. Required. + :param dev_box_name: Display name for the Dev Box. Required. :type dev_box_name: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns JSON object - :rtype: ~azure.core.polling.LROPoller[JSON] + :return: An instance of LROPoller that returns OperationDetails. The OperationDetails is + compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.developer.devcenter.models.OperationDetails] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -3387,15 +3521,26 @@ def begin_restart_dev_box( # response body for status code(s): 202 response == { + "id": "str", # Fully qualified ID for the operation status. Required. + "name": "str", # The operation id name. Required. "status": "str", # Provisioning state of the resource. Required. Known - values are: "Running", "Completed", "Canceled", and "Failed". + values are: "NotStarted", "Running", "Succeeded", "Failed", and "Canceled". "endTime": "2020-02-20 00:00:00", # Optional. The end time of the operation. "error": { - "code": "str", # Optional. The error code. - "message": "str" # Optional. The error message. + "code": "str", # One of a server-defined set of error codes. + Required. + "message": "str", # A human-readable representation of the error. + Required. + "details": [ + ... + ], + "innererror": { + "code": "str", # Optional. One of a server-defined set of + error codes. + "innererror": ... + }, + "target": "str" # Optional. The target of the error. }, - "id": "str", # Optional. Fully qualified ID for the operation status. - "name": "str", # Optional. The operation id name. "percentComplete": 0.0, # Optional. Percent of the operation that is complete. "properties": {}, # Optional. Custom operation properties, populated only @@ -3408,7 +3553,7 @@ def begin_restart_dev_box( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.OperationDetails] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) @@ -3431,10 +3576,7 @@ def get_long_running_output(pipeline_response): "str", response.headers.get("Operation-Location") ) - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.OperationDetails, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized @@ -3452,16 +3594,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller[JSON].from_continuation_token( + return LROPoller[_models.OperationDetails].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller[JSON](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return LROPoller[_models.OperationDetails]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) @distributed_trace - def get_remote_connection(self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any) -> JSON: + def get_remote_connection( + self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any + ) -> _models.RemoteConnection: """Gets RDP Connection info. :param project_name: The DevCenter Project upon which to execute operations. Required. @@ -3471,10 +3617,8 @@ def get_remote_connection(self, project_name: str, user_id: str, dev_box_name: s :type user_id: str :param dev_box_name: The name of a Dev Box. Required. :type dev_box_name: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: JSON object - :rtype: JSON + :return: RemoteConnection. The RemoteConnection is compatible with MutableMapping + :rtype: ~azure.developer.devcenter.models.RemoteConnection :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -3487,7 +3631,7 @@ def get_remote_connection(self, project_name: str, user_id: str, dev_box_name: s "webUrl": "str" # Optional. URL to open a browser based RDP session. } """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3498,7 +3642,7 @@ def get_remote_connection(self, project_name: str, user_id: str, dev_box_name: s _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.RemoteConnection] = kwargs.pop("cls", None) _request = build_dev_center_get_remote_connection_request( project_name=project_name, @@ -3529,29 +3673,28 @@ def get_remote_connection(self, project_name: str, user_id: str, dev_box_name: s if _stream: deserialized = response.iter_bytes() else: - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.RemoteConnection, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore @distributed_trace - def list_dev_box_actions(self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any) -> Iterable[JSON]: + def list_dev_box_actions( + self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any + ) -> Iterable["_models.DevBoxAction"]: """Lists actions on a Dev Box. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str - :param dev_box_name: The name of a Dev Box. Required. + :param dev_box_name: Display name for the Dev Box. Required. :type dev_box_name: str - :return: An iterator like instance of JSON object - :rtype: ~azure.core.paging.ItemPaged[JSON] + :return: An iterator like instance of DevBoxAction + :rtype: ~azure.core.paging.ItemPaged[~azure.developer.devcenter.models.DevBoxAction] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -3574,9 +3717,9 @@ def list_dev_box_actions(self, project_name: str, user_id: str, dev_box_name: st _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[JSON]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.DevBoxAction]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3626,7 +3769,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["value"] + list_of_elem = _deserialize(List[_models.DevBoxAction], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -3653,22 +3796,20 @@ def get_next(next_link=None): @distributed_trace def get_dev_box_action( self, project_name: str, user_id: str, dev_box_name: str, action_name: str, **kwargs: Any - ) -> JSON: + ) -> _models.DevBoxAction: """Gets an action. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str - :param dev_box_name: The name of a Dev Box. Required. + :param dev_box_name: Display name for the Dev Box. Required. :type dev_box_name: str - :param action_name: The name of an action that will take place on a Dev Box. Required. + :param action_name: The name of the action. Required. :type action_name: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: JSON object - :rtype: JSON + :return: DevBoxAction. The DevBoxAction is compatible with MutableMapping + :rtype: ~azure.developer.devcenter.models.DevBoxAction :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -3688,7 +3829,7 @@ def get_dev_box_action( the action could occur (UTC). } """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3699,7 +3840,7 @@ def get_dev_box_action( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.DevBoxAction] = kwargs.pop("cls", None) _request = build_dev_center_get_dev_box_action_request( project_name=project_name, @@ -3731,15 +3872,12 @@ def get_dev_box_action( if _stream: deserialized = response.iter_bytes() else: - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.DevBoxAction, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore @distributed_trace def skip_dev_box_action( # pylint: disable=inconsistent-return-statements @@ -3747,22 +3885,20 @@ def skip_dev_box_action( # pylint: disable=inconsistent-return-statements ) -> None: """Skips an occurrence of an action. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str - :param dev_box_name: The name of a Dev Box. Required. + :param dev_box_name: Display name for the Dev Box. Required. :type dev_box_name: str - :param action_name: The name of an action that will take place on a Dev Box. Required. + :param action_name: The name of the action. Required. :type action_name: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3789,7 +3925,7 @@ def skip_dev_box_action( # pylint: disable=inconsistent-return-statements } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = kwargs.pop("stream", False) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -3815,24 +3951,22 @@ def delay_dev_box_action( *, delay_until: datetime.datetime, **kwargs: Any - ) -> JSON: + ) -> _models.DevBoxAction: """Delays the occurrence of an action. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str - :param dev_box_name: The name of a Dev Box. Required. + :param dev_box_name: Display name for the Dev Box. Required. :type dev_box_name: str - :param action_name: The name of an action that will take place on a Dev Box. Required. + :param action_name: The name of the action. Required. :type action_name: str :keyword delay_until: The time to delay the Dev Box action or actions until. Required. :paramtype delay_until: ~datetime.datetime - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: JSON object - :rtype: JSON + :return: DevBoxAction. The DevBoxAction is compatible with MutableMapping + :rtype: ~azure.developer.devcenter.models.DevBoxAction :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -3852,7 +3986,7 @@ def delay_dev_box_action( the action could occur (UTC). } """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3863,7 +3997,7 @@ def delay_dev_box_action( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.DevBoxAction] = kwargs.pop("cls", None) _request = build_dev_center_delay_dev_box_action_request( project_name=project_name, @@ -3896,33 +4030,31 @@ def delay_dev_box_action( if _stream: deserialized = response.iter_bytes() else: - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.DevBoxAction, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore @distributed_trace def delay_all_dev_box_actions( self, project_name: str, user_id: str, dev_box_name: str, *, delay_until: datetime.datetime, **kwargs: Any - ) -> Iterable[JSON]: + ) -> Iterable["_models.DevBoxActionDelayResult"]: + # pylint: disable=line-too-long """Delays all actions. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str - :param dev_box_name: The name of a Dev Box. Required. + :param dev_box_name: Display name for the Dev Box. Required. :type dev_box_name: str :keyword delay_until: The time to delay the Dev Box action or actions until. Required. :paramtype delay_until: ~datetime.datetime - :return: An iterator like instance of JSON object - :rtype: ~azure.core.paging.ItemPaged[JSON] + :return: An iterator like instance of DevBoxActionDelayResult + :rtype: ~azure.core.paging.ItemPaged[~azure.developer.devcenter.models.DevBoxActionDelayResult] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -3966,9 +4098,9 @@ def delay_all_dev_box_actions( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[JSON]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.DevBoxActionDelayResult]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4019,7 +4151,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["value"] + list_of_elem = _deserialize(List[_models.DevBoxActionDelayResult], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -4044,16 +4176,14 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) @distributed_trace - def list_all_environments(self, project_name: str, *, top: Optional[int] = None, **kwargs: Any) -> Iterable[JSON]: + def list_all_environments(self, project_name: str, **kwargs: Any) -> Iterable["_models.Environment"]: + # pylint: disable=line-too-long """Lists the environments for a project. :param project_name: The DevCenter Project upon which to execute operations. Required. :type project_name: str - :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. - Default value is None. - :paramtype top: int - :return: An iterator like instance of JSON object - :rtype: ~azure.core.paging.ItemPaged[JSON] + :return: An iterator like instance of Environment + :rtype: ~azure.core.paging.ItemPaged[~azure.developer.devcenter.models.Environment] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -4065,6 +4195,7 @@ def list_all_environments(self, project_name: str, *, top: Optional[int] = None, "environmentDefinitionName": "str", # Name of the environment definition. Required. "environmentType": "str", # Environment type. Required. + "name": "str", # Environment name. Required. "error": { "code": "str", # One of a server-defined set of error codes. Required. @@ -4080,10 +4211,13 @@ def list_all_environments(self, project_name: str, *, top: Optional[int] = None, }, "target": "str" # Optional. The target of the error. }, - "name": "str", # Optional. Environment name. - "parameters": {}, # Optional. Parameters object for the environment. + "parameters": { + "str": {} # Optional. Parameters object for the environment. + }, "provisioningState": "str", # Optional. The provisioning state of the - environment. + environment. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Accepted", "Deleting", "Updating", "Preparing", "Running", "Syncing", + "MovingResources", "TransientFailure", and "StorageProvisioningFailed". "resourceGroupId": "str", # Optional. The identifier of the resource group containing the environment's resources. "user": "str" # Optional. The AAD object id of the owner of this @@ -4093,9 +4227,9 @@ def list_all_environments(self, project_name: str, *, top: Optional[int] = None, _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[JSON]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.Environment]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4108,7 +4242,6 @@ def prepare_request(next_link=None): _request = build_dev_center_list_all_environments_request( project_name=project_name, - top=top, api_version=self._config.api_version, headers=_headers, params=_params, @@ -4144,7 +4277,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["value"] + list_of_elem = _deserialize(List[_models.Environment], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -4169,9 +4302,8 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) @distributed_trace - def list_environments( - self, project_name: str, user_id: str, *, top: Optional[int] = None, **kwargs: Any - ) -> Iterable[JSON]: + def list_environments(self, project_name: str, user_id: str, **kwargs: Any) -> Iterable["_models.Environment"]: + # pylint: disable=line-too-long """Lists the environments for a project and user. :param project_name: The DevCenter Project upon which to execute operations. Required. @@ -4179,11 +4311,8 @@ def list_environments( :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str - :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. - Default value is None. - :paramtype top: int - :return: An iterator like instance of JSON object - :rtype: ~azure.core.paging.ItemPaged[JSON] + :return: An iterator like instance of Environment + :rtype: ~azure.core.paging.ItemPaged[~azure.developer.devcenter.models.Environment] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -4195,6 +4324,7 @@ def list_environments( "environmentDefinitionName": "str", # Name of the environment definition. Required. "environmentType": "str", # Environment type. Required. + "name": "str", # Environment name. Required. "error": { "code": "str", # One of a server-defined set of error codes. Required. @@ -4210,10 +4340,13 @@ def list_environments( }, "target": "str" # Optional. The target of the error. }, - "name": "str", # Optional. Environment name. - "parameters": {}, # Optional. Parameters object for the environment. + "parameters": { + "str": {} # Optional. Parameters object for the environment. + }, "provisioningState": "str", # Optional. The provisioning state of the - environment. + environment. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Accepted", "Deleting", "Updating", "Preparing", "Running", "Syncing", + "MovingResources", "TransientFailure", and "StorageProvisioningFailed". "resourceGroupId": "str", # Optional. The identifier of the resource group containing the environment's resources. "user": "str" # Optional. The AAD object id of the owner of this @@ -4223,9 +4356,9 @@ def list_environments( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[JSON]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.Environment]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4239,7 +4372,6 @@ def prepare_request(next_link=None): _request = build_dev_center_list_environments_request( project_name=project_name, user_id=user_id, - top=top, api_version=self._config.api_version, headers=_headers, params=_params, @@ -4275,7 +4407,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["value"] + list_of_elem = _deserialize(List[_models.Environment], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -4300,20 +4432,21 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) @distributed_trace - def get_environment(self, project_name: str, user_id: str, environment_name: str, **kwargs: Any) -> JSON: + def get_environment( + self, project_name: str, user_id: str, environment_name: str, **kwargs: Any + ) -> _models.Environment: + # pylint: disable=line-too-long """Gets an environment. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str - :param environment_name: The name of the environment. Required. + :param environment_name: Environment name. Required. :type environment_name: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: JSON object - :rtype: JSON + :return: Environment. The Environment is compatible with MutableMapping + :rtype: ~azure.developer.devcenter.models.Environment :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -4325,6 +4458,7 @@ def get_environment(self, project_name: str, user_id: str, environment_name: str "environmentDefinitionName": "str", # Name of the environment definition. Required. "environmentType": "str", # Environment type. Required. + "name": "str", # Environment name. Required. "error": { "code": "str", # One of a server-defined set of error codes. Required. @@ -4340,17 +4474,20 @@ def get_environment(self, project_name: str, user_id: str, environment_name: str }, "target": "str" # Optional. The target of the error. }, - "name": "str", # Optional. Environment name. - "parameters": {}, # Optional. Parameters object for the environment. + "parameters": { + "str": {} # Optional. Parameters object for the environment. + }, "provisioningState": "str", # Optional. The provisioning state of the - environment. + environment. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Accepted", "Deleting", "Updating", "Preparing", "Running", "Syncing", + "MovingResources", "TransientFailure", and "StorageProvisioningFailed". "resourceGroupId": "str", # Optional. The identifier of the resource group containing the environment's resources. "user": "str" # Optional. The AAD object id of the owner of this Environment. } """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4361,7 +4498,7 @@ def get_environment(self, project_name: str, user_id: str, environment_name: str _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.Environment] = kwargs.pop("cls", None) _request = build_dev_center_get_environment_request( project_name=project_name, @@ -4392,20 +4529,22 @@ def get_environment(self, project_name: str, user_id: str, environment_name: str if _stream: deserialized = response.iter_bytes() else: - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.Environment, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore def _create_or_update_environment_initial( - self, project_name: str, user_id: str, environment_name: str, body: Union[JSON, IO], **kwargs: Any + self, + project_name: str, + user_id: str, + environment_name: str, + body: Union[_models.Environment, JSON, IO[bytes]], + **kwargs: Any ) -> JSON: - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4420,12 +4559,11 @@ def _create_or_update_environment_initial( cls: ClsType[JSON] = kwargs.pop("cls", None) content_type = content_type or "application/json" - _json = None _content = None if isinstance(body, (IOBase, bytes)): _content = body else: - _json = body + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_dev_center_create_or_update_environment_request( project_name=project_name, @@ -4433,7 +4571,6 @@ def _create_or_update_environment_initial( environment_name=environment_name, content_type=content_type, api_version=self._config.api_version, - json=_json, content=_content, headers=_headers, params=_params, @@ -4459,15 +4596,12 @@ def _create_or_update_environment_initial( response_headers = {} response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(JSON, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), response_headers) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore @overload def begin_create_or_update_environment( @@ -4475,11 +4609,12 @@ def begin_create_or_update_environment( project_name: str, user_id: str, environment_name: str, - body: JSON, + body: _models.Environment, *, content_type: str = "application/json", **kwargs: Any - ) -> LROPoller[JSON]: + ) -> LROPoller[_models.Environment]: + # pylint: disable=line-too-long """Creates or updates an environment. :param project_name: The DevCenter Project upon which to execute operations. Required. @@ -4490,19 +4625,13 @@ def begin_create_or_update_environment( :param environment_name: The name of the environment. Required. :type environment_name: str :param body: Represents an environment. Required. - :type body: JSON + :type body: ~azure.developer.devcenter.models.Environment :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns JSON object - :rtype: ~azure.core.polling.LROPoller[JSON] + :return: An instance of LROPoller that returns Environment. The Environment is compatible with + MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.developer.devcenter.models.Environment] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -4514,6 +4643,7 @@ def begin_create_or_update_environment( "environmentDefinitionName": "str", # Name of the environment definition. Required. "environmentType": "str", # Environment type. Required. + "name": "str", # Environment name. Required. "error": { "code": "str", # One of a server-defined set of error codes. Required. @@ -4529,10 +4659,13 @@ def begin_create_or_update_environment( }, "target": "str" # Optional. The target of the error. }, - "name": "str", # Optional. Environment name. - "parameters": {}, # Optional. Parameters object for the environment. + "parameters": { + "str": {} # Optional. Parameters object for the environment. + }, "provisioningState": "str", # Optional. The provisioning state of the - environment. + environment. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Accepted", "Deleting", "Updating", "Preparing", "Running", "Syncing", + "MovingResources", "TransientFailure", and "StorageProvisioningFailed". "resourceGroupId": "str", # Optional. The identifier of the resource group containing the environment's resources. "user": "str" # Optional. The AAD object id of the owner of this @@ -4545,6 +4678,7 @@ def begin_create_or_update_environment( "environmentDefinitionName": "str", # Name of the environment definition. Required. "environmentType": "str", # Environment type. Required. + "name": "str", # Environment name. Required. "error": { "code": "str", # One of a server-defined set of error codes. Required. @@ -4560,10 +4694,13 @@ def begin_create_or_update_environment( }, "target": "str" # Optional. The target of the error. }, - "name": "str", # Optional. Environment name. - "parameters": {}, # Optional. Parameters object for the environment. + "parameters": { + "str": {} # Optional. Parameters object for the environment. + }, "provisioningState": "str", # Optional. The provisioning state of the - environment. + environment. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Accepted", "Deleting", "Updating", "Preparing", "Running", "Syncing", + "MovingResources", "TransientFailure", and "StorageProvisioningFailed". "resourceGroupId": "str", # Optional. The identifier of the resource group containing the environment's resources. "user": "str" # Optional. The AAD object id of the owner of this @@ -4577,11 +4714,12 @@ def begin_create_or_update_environment( project_name: str, user_id: str, environment_name: str, - body: IO, + body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> LROPoller[JSON]: + ) -> LROPoller[_models.Environment]: + # pylint: disable=line-too-long """Creates or updates an environment. :param project_name: The DevCenter Project upon which to execute operations. Required. @@ -4592,19 +4730,83 @@ def begin_create_or_update_environment( :param environment_name: The name of the environment. Required. :type environment_name: str :param body: Represents an environment. Required. - :type body: IO + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns Environment. The Environment is compatible with + MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.developer.devcenter.models.Environment] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 201 + response == { + "catalogName": "str", # Name of the catalog. Required. + "environmentDefinitionName": "str", # Name of the environment definition. + Required. + "environmentType": "str", # Environment type. Required. + "name": "str", # Environment name. Required. + "error": { + "code": "str", # One of a server-defined set of error codes. + Required. + "message": "str", # A human-readable representation of the error. + Required. + "details": [ + ... + ], + "innererror": { + "code": "str", # Optional. One of a server-defined set of + error codes. + "innererror": ... + }, + "target": "str" # Optional. The target of the error. + }, + "parameters": { + "str": {} # Optional. Parameters object for the environment. + }, + "provisioningState": "str", # Optional. The provisioning state of the + environment. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Accepted", "Deleting", "Updating", "Preparing", "Running", "Syncing", + "MovingResources", "TransientFailure", and "StorageProvisioningFailed". + "resourceGroupId": "str", # Optional. The identifier of the resource group + containing the environment's resources. + "user": "str" # Optional. The AAD object id of the owner of this + Environment. + } + """ + + @overload + def begin_create_or_update_environment( + self, + project_name: str, + user_id: str, + environment_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.Environment]: + # pylint: disable=line-too-long + """Creates or updates an environment. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Required. + :type user_id: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Represents an environment. Required. + :type body: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns JSON object - :rtype: ~azure.core.polling.LROPoller[JSON] + :return: An instance of LROPoller that returns Environment. The Environment is compatible with + MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.developer.devcenter.models.Environment] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -4616,6 +4818,7 @@ def begin_create_or_update_environment( "environmentDefinitionName": "str", # Name of the environment definition. Required. "environmentType": "str", # Environment type. Required. + "name": "str", # Environment name. Required. "error": { "code": "str", # One of a server-defined set of error codes. Required. @@ -4631,10 +4834,13 @@ def begin_create_or_update_environment( }, "target": "str" # Optional. The target of the error. }, - "name": "str", # Optional. Environment name. - "parameters": {}, # Optional. Parameters object for the environment. + "parameters": { + "str": {} # Optional. Parameters object for the environment. + }, "provisioningState": "str", # Optional. The provisioning state of the - environment. + environment. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Accepted", "Deleting", "Updating", "Preparing", "Running", "Syncing", + "MovingResources", "TransientFailure", and "StorageProvisioningFailed". "resourceGroupId": "str", # Optional. The identifier of the resource group containing the environment's resources. "user": "str" # Optional. The AAD object id of the owner of this @@ -4644,8 +4850,14 @@ def begin_create_or_update_environment( @distributed_trace def begin_create_or_update_environment( - self, project_name: str, user_id: str, environment_name: str, body: Union[JSON, IO], **kwargs: Any - ) -> LROPoller[JSON]: + self, + project_name: str, + user_id: str, + environment_name: str, + body: Union[_models.Environment, JSON, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.Environment]: + # pylint: disable=line-too-long """Creates or updates an environment. :param project_name: The DevCenter Project upon which to execute operations. Required. @@ -4655,20 +4867,12 @@ def begin_create_or_update_environment( :type user_id: str :param environment_name: The name of the environment. Required. :type environment_name: str - :param body: Represents an environment. Is either a JSON type or a IO type. Required. - :type body: JSON or IO - :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default - value is None. - :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns JSON object - :rtype: ~azure.core.polling.LROPoller[JSON] + :param body: Represents an environment. Is one of the following types: Environment, JSON, + IO[bytes] Required. + :type body: ~azure.developer.devcenter.models.Environment or JSON or IO[bytes] + :return: An instance of LROPoller that returns Environment. The Environment is compatible with + MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.developer.devcenter.models.Environment] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -4680,6 +4884,7 @@ def begin_create_or_update_environment( "environmentDefinitionName": "str", # Name of the environment definition. Required. "environmentType": "str", # Environment type. Required. + "name": "str", # Environment name. Required. "error": { "code": "str", # One of a server-defined set of error codes. Required. @@ -4695,10 +4900,13 @@ def begin_create_or_update_environment( }, "target": "str" # Optional. The target of the error. }, - "name": "str", # Optional. Environment name. - "parameters": {}, # Optional. Parameters object for the environment. + "parameters": { + "str": {} # Optional. Parameters object for the environment. + }, "provisioningState": "str", # Optional. The provisioning state of the - environment. + environment. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Accepted", "Deleting", "Updating", "Preparing", "Running", "Syncing", + "MovingResources", "TransientFailure", and "StorageProvisioningFailed". "resourceGroupId": "str", # Optional. The identifier of the resource group containing the environment's resources. "user": "str" # Optional. The AAD object id of the owner of this @@ -4711,6 +4919,7 @@ def begin_create_or_update_environment( "environmentDefinitionName": "str", # Name of the environment definition. Required. "environmentType": "str", # Environment type. Required. + "name": "str", # Environment name. Required. "error": { "code": "str", # One of a server-defined set of error codes. Required. @@ -4726,10 +4935,13 @@ def begin_create_or_update_environment( }, "target": "str" # Optional. The target of the error. }, - "name": "str", # Optional. Environment name. - "parameters": {}, # Optional. Parameters object for the environment. + "parameters": { + "str": {} # Optional. Parameters object for the environment. + }, "provisioningState": "str", # Optional. The provisioning state of the - environment. + environment. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Accepted", "Deleting", "Updating", "Preparing", "Running", "Syncing", + "MovingResources", "TransientFailure", and "StorageProvisioningFailed". "resourceGroupId": "str", # Optional. The identifier of the resource group containing the environment's resources. "user": "str" # Optional. The AAD object id of the owner of this @@ -4740,7 +4952,7 @@ def begin_create_or_update_environment( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.Environment] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) @@ -4765,10 +4977,7 @@ def get_long_running_output(pipeline_response): "str", response.headers.get("Operation-Location") ) - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.Environment, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized @@ -4786,18 +4995,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller[JSON].from_continuation_token( + return LROPoller[_models.Environment].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller[JSON](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return LROPoller[_models.Environment]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) def _delete_environment_initial( self, project_name: str, user_id: str, environment_name: str, **kwargs: Any ) -> Optional[JSON]: - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4844,10 +5055,7 @@ def _delete_environment_initial( "str", response.headers.get("Operation-Location") ) - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(JSON, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -4857,7 +5065,8 @@ def _delete_environment_initial( @distributed_trace def begin_delete_environment( self, project_name: str, user_id: str, environment_name: str, **kwargs: Any - ) -> LROPoller[JSON]: + ) -> LROPoller[_models.OperationDetails]: + # pylint: disable=line-too-long """Deletes an environment and all its associated resources. :param project_name: The DevCenter Project upon which to execute operations. Required. @@ -4867,15 +5076,9 @@ def begin_delete_environment( :type user_id: str :param environment_name: The name of the environment. Required. :type environment_name: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns JSON object - :rtype: ~azure.core.polling.LROPoller[JSON] + :return: An instance of LROPoller that returns OperationDetails. The OperationDetails is + compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.developer.devcenter.models.OperationDetails] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -4883,15 +5086,26 @@ def begin_delete_environment( # response body for status code(s): 202 response == { + "id": "str", # Fully qualified ID for the operation status. Required. + "name": "str", # The operation id name. Required. "status": "str", # Provisioning state of the resource. Required. Known - values are: "Running", "Completed", "Canceled", and "Failed". + values are: "NotStarted", "Running", "Succeeded", "Failed", and "Canceled". "endTime": "2020-02-20 00:00:00", # Optional. The end time of the operation. "error": { - "code": "str", # Optional. The error code. - "message": "str" # Optional. The error message. + "code": "str", # One of a server-defined set of error codes. + Required. + "message": "str", # A human-readable representation of the error. + Required. + "details": [ + ... + ], + "innererror": { + "code": "str", # Optional. One of a server-defined set of + error codes. + "innererror": ... + }, + "target": "str" # Optional. The target of the error. }, - "id": "str", # Optional. Fully qualified ID for the operation status. - "name": "str", # Optional. The operation id name. "percentComplete": 0.0, # Optional. Percent of the operation that is complete. "properties": {}, # Optional. Custom operation properties, populated only @@ -4904,7 +5118,7 @@ def begin_delete_environment( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.OperationDetails] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) @@ -4928,10 +5142,7 @@ def get_long_running_output(pipeline_response): "str", response.headers.get("Operation-Location") ) - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.OperationDetails, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized @@ -4949,25 +5160,24 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller[JSON].from_continuation_token( + return LROPoller[_models.OperationDetails].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller[JSON](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return LROPoller[_models.OperationDetails]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) @distributed_trace - def list_catalogs(self, project_name: str, *, top: Optional[int] = None, **kwargs: Any) -> Iterable[JSON]: + def list_catalogs(self, project_name: str, **kwargs: Any) -> Iterable["_models.Catalog"]: """Lists all of the catalogs available for a project. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str - :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. - Default value is None. - :paramtype top: int - :return: An iterator like instance of JSON object - :rtype: ~azure.core.paging.ItemPaged[JSON] + :return: An iterator like instance of Catalog + :rtype: ~azure.core.paging.ItemPaged[~azure.developer.devcenter.models.Catalog] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -4981,9 +5191,9 @@ def list_catalogs(self, project_name: str, *, top: Optional[int] = None, **kwarg _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[JSON]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.Catalog]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4996,7 +5206,6 @@ def prepare_request(next_link=None): _request = build_dev_center_list_catalogs_request( project_name=project_name, - top=top, api_version=self._config.api_version, headers=_headers, params=_params, @@ -5032,7 +5241,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["value"] + list_of_elem = _deserialize(List[_models.Catalog], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -5057,17 +5266,15 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) @distributed_trace - def get_catalog(self, project_name: str, catalog_name: str, **kwargs: Any) -> JSON: + def get_catalog(self, project_name: str, catalog_name: str, **kwargs: Any) -> _models.Catalog: """Gets the specified catalog within the project. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str - :param catalog_name: The name of the catalog. Required. + :param catalog_name: Name of the catalog. Required. :type catalog_name: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: JSON object - :rtype: JSON + :return: Catalog. The Catalog is compatible with MutableMapping + :rtype: ~azure.developer.devcenter.models.Catalog :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -5078,7 +5285,7 @@ def get_catalog(self, project_name: str, catalog_name: str, **kwargs: Any) -> JS "name": "str" # Name of the catalog. Required. } """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -5089,7 +5296,7 @@ def get_catalog(self, project_name: str, catalog_name: str, **kwargs: Any) -> JS _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.Catalog] = kwargs.pop("cls", None) _request = build_dev_center_get_catalog_request( project_name=project_name, @@ -5119,29 +5326,24 @@ def get_catalog(self, project_name: str, catalog_name: str, **kwargs: Any) -> JS if _stream: deserialized = response.iter_bytes() else: - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.Catalog, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore @distributed_trace def list_environment_definitions( - self, project_name: str, *, top: Optional[int] = None, **kwargs: Any - ) -> Iterable[JSON]: + self, project_name: str, **kwargs: Any + ) -> Iterable["_models.EnvironmentDefinition"]: + # pylint: disable=line-too-long """Lists all environment definitions available for a project. :param project_name: The DevCenter Project upon which to execute operations. Required. :type project_name: str - :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. - Default value is None. - :paramtype top: int - :return: An iterator like instance of JSON object - :rtype: ~azure.core.paging.ItemPaged[JSON] + :return: An iterator like instance of EnvironmentDefinition + :rtype: ~azure.core.paging.ItemPaged[~azure.developer.devcenter.models.EnvironmentDefinition] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -5183,9 +5385,9 @@ def list_environment_definitions( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[JSON]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.EnvironmentDefinition]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -5198,7 +5400,6 @@ def prepare_request(next_link=None): _request = build_dev_center_list_environment_definitions_request( project_name=project_name, - top=top, api_version=self._config.api_version, headers=_headers, params=_params, @@ -5234,7 +5435,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["value"] + list_of_elem = _deserialize(List[_models.EnvironmentDefinition], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -5260,19 +5461,17 @@ def get_next(next_link=None): @distributed_trace def list_environment_definitions_by_catalog( - self, project_name: str, catalog_name: str, *, top: Optional[int] = None, **kwargs: Any - ) -> Iterable[JSON]: + self, project_name: str, catalog_name: str, **kwargs: Any + ) -> Iterable["_models.EnvironmentDefinition"]: + # pylint: disable=line-too-long """Lists all environment definitions available within a catalog. :param project_name: The DevCenter Project upon which to execute operations. Required. :type project_name: str :param catalog_name: The name of the catalog. Required. :type catalog_name: str - :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. - Default value is None. - :paramtype top: int - :return: An iterator like instance of JSON object - :rtype: ~azure.core.paging.ItemPaged[JSON] + :return: An iterator like instance of EnvironmentDefinition + :rtype: ~azure.core.paging.ItemPaged[~azure.developer.devcenter.models.EnvironmentDefinition] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -5314,9 +5513,9 @@ def list_environment_definitions_by_catalog( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[JSON]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.EnvironmentDefinition]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -5330,7 +5529,6 @@ def prepare_request(next_link=None): _request = build_dev_center_list_environment_definitions_by_catalog_request( project_name=project_name, catalog_name=catalog_name, - top=top, api_version=self._config.api_version, headers=_headers, params=_params, @@ -5366,7 +5564,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["value"] + list_of_elem = _deserialize(List[_models.EnvironmentDefinition], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -5393,19 +5591,18 @@ def get_next(next_link=None): @distributed_trace def get_environment_definition( self, project_name: str, catalog_name: str, definition_name: str, **kwargs: Any - ) -> JSON: + ) -> _models.EnvironmentDefinition: + # pylint: disable=line-too-long """Get an environment definition from a catalog. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str - :param catalog_name: The name of the catalog. Required. + :param catalog_name: Name of the catalog. Required. :type catalog_name: str - :param definition_name: The name of the environment definition. Required. + :param definition_name: Name of the environment definition. Required. :type definition_name: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: JSON object - :rtype: JSON + :return: EnvironmentDefinition. The EnvironmentDefinition is compatible with MutableMapping + :rtype: ~azure.developer.devcenter.models.EnvironmentDefinition :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -5444,7 +5641,7 @@ def get_environment_definition( entrypoint file. } """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -5455,7 +5652,7 @@ def get_environment_definition( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.EnvironmentDefinition] = kwargs.pop("cls", None) _request = build_dev_center_get_environment_definition_request( project_name=project_name, @@ -5486,27 +5683,22 @@ def get_environment_definition( if _stream: deserialized = response.iter_bytes() else: - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.EnvironmentDefinition, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore @distributed_trace - def list_environment_types(self, project_name: str, *, top: Optional[int] = None, **kwargs: Any) -> Iterable[JSON]: + def list_environment_types(self, project_name: str, **kwargs: Any) -> Iterable["_models.EnvironmentType"]: + # pylint: disable=line-too-long """Lists all environment types configured for a project. :param project_name: The DevCenter Project upon which to execute operations. Required. :type project_name: str - :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. - Default value is None. - :paramtype top: int - :return: An iterator like instance of JSON object - :rtype: ~azure.core.paging.ItemPaged[JSON] + :return: An iterator like instance of EnvironmentType + :rtype: ~azure.core.paging.ItemPaged[~azure.developer.devcenter.models.EnvironmentType] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -5525,9 +5717,9 @@ def list_environment_types(self, project_name: str, *, top: Optional[int] = None _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[JSON]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.EnvironmentType]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -5540,7 +5732,6 @@ def prepare_request(next_link=None): _request = build_dev_center_list_environment_types_request( project_name=project_name, - top=top, api_version=self._config.api_version, headers=_headers, params=_params, @@ -5576,7 +5767,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["value"] + list_of_elem = _deserialize(List[_models.EnvironmentType], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_serialization.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_serialization.py index 1247eb71a98f..2f781d740827 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_serialization.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_serialization.py @@ -64,7 +64,7 @@ import isodate # type: ignore from azure.core.exceptions import DeserializationError, SerializationError -from azure.core.serialization import NULL as AzureCoreNull +from azure.core.serialization import NULL as CoreNull _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") @@ -170,13 +170,6 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], return None -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str - unicode_str = str - _LOGGER = logging.getLogger(__name__) try: @@ -545,7 +538,7 @@ class Serializer(object): "multiple": lambda x, y: x % y != 0, } - def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): + def __init__(self, classes: Optional[Mapping[str, type]] = None): self.serialize_type = { "iso-8601": Serializer.serialize_iso, "rfc-1123": Serializer.serialize_rfc, @@ -561,7 +554,7 @@ def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): "[]": self.serialize_iter, "{}": self.serialize_dict, } - self.dependencies: Dict[str, Type[ModelType]] = dict(classes) if classes else {} + self.dependencies: Dict[str, type] = dict(classes) if classes else {} self.key_transformer = full_restapi_key_transformer self.client_side_validation = True @@ -649,7 +642,7 @@ def _serialize(self, target_obj, data_type=None, **kwargs): else: # That's a basic type # Integrate namespace if necessary local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) + local_node.text = str(new_attr) serialized.append(local_node) # type: ignore else: # JSON for k in reversed(keys): # type: ignore @@ -730,7 +723,6 @@ def url(self, name, data, data_type, **kwargs): if kwargs.get("skip_quote") is True: output = str(output) - # https://github.com/Azure/autorest.python/issues/2063 output = output.replace("{", quote("{")).replace("}", quote("}")) else: output = quote(str(output), safe="") @@ -746,7 +738,7 @@ def query(self, name, data, data_type, **kwargs): :param str data_type: The type to be serialized from. :keyword bool skip_quote: Whether to skip quote the serialized result. Defaults to False. - :rtype: str + :rtype: str, list :raises: TypeError if serialization fails. :raises: ValueError if data is None """ @@ -806,7 +798,7 @@ def serialize_data(self, data, data_type, **kwargs): raise ValueError("No value for given attribute") try: - if data is AzureCoreNull: + if data is CoreNull: return None if data_type in self.basic_types.values(): return self.serialize_basic(data, data_type, **kwargs) @@ -995,7 +987,7 @@ def serialize_object(self, attr, **kwargs): return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) if obj_type is _long_type: return self.serialize_long(attr) - if obj_type is unicode_str: + if obj_type is str: return self.serialize_unicode(attr) if obj_type is datetime.datetime: return self.serialize_iso(attr) @@ -1211,7 +1203,6 @@ def rest_key_extractor(attr, attr_desc, data): if working_data is None: # If at any point while following flatten JSON path see None, it means # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 return None key = ".".join(dict_keys[1:]) @@ -1232,7 +1223,6 @@ def rest_key_case_insensitive_extractor(attr, attr_desc, data): if working_data is None: # If at any point while following flatten JSON path see None, it means # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 return None key = ".".join(dict_keys[1:]) @@ -1373,7 +1363,7 @@ class Deserializer(object): valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): + def __init__(self, classes: Optional[Mapping[str, type]] = None): self.deserialize_type = { "iso-8601": Deserializer.deserialize_iso, "rfc-1123": Deserializer.deserialize_rfc, @@ -1393,7 +1383,7 @@ def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): "duration": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } - self.dependencies: Dict[str, Type[ModelType]] = dict(classes) if classes else {} + self.dependencies: Dict[str, type] = dict(classes) if classes else {} self.key_extractors = [rest_key_extractor, xml_key_extractor] # Additional properties only works if the "rest_key_extractor" is used to # extract the keys. Making it to work whatever the key extractor is too much @@ -1446,7 +1436,7 @@ def _deserialize(self, target_obj, data): response, class_name = self._classify_target(target_obj, data) - if isinstance(response, basestring): + if isinstance(response, str): return self.deserialize_data(data, response) elif isinstance(response, type) and issubclass(response, Enum): return self.deserialize_enum(data, response) @@ -1517,14 +1507,14 @@ def _classify_target(self, target, data): if target is None: return None, None - if isinstance(target, basestring): + if isinstance(target, str): try: target = self.dependencies[target] except KeyError: return target, target try: - target = target._classify(data, self.dependencies) + target = target._classify(data, self.dependencies) # type: ignore except AttributeError: pass # Target is not a Model, no classify return target, target.__class__.__name__ # type: ignore @@ -1580,7 +1570,7 @@ def _unpack_content(raw_data, content_type=None): if hasattr(raw_data, "_content_consumed"): return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore return raw_data @@ -1702,7 +1692,7 @@ def deserialize_object(self, attr, **kwargs): if isinstance(attr, ET.Element): # Do no recurse on XML, just return the tree as-is return attr - if isinstance(attr, basestring): + if isinstance(attr, str): return self.deserialize_basic(attr, "str") obj_type = type(attr) if obj_type in self.basic_types: @@ -1759,7 +1749,7 @@ def deserialize_basic(self, attr, data_type): if data_type == "bool": if attr in [True, False, 1, 0]: return bool(attr) - elif isinstance(attr, basestring): + elif isinstance(attr, str): if attr.lower() in ["true", "1"]: return True elif attr.lower() in ["false", "0"]: @@ -1863,7 +1853,7 @@ def deserialize_decimal(attr): if isinstance(attr, ET.Element): attr = attr.text try: - return decimal.Decimal(attr) # type: ignore + return decimal.Decimal(str(attr)) # type: ignore except decimal.DecimalException as err: msg = "Invalid decimal {}".format(attr) raise DeserializationError(msg) from err @@ -1999,6 +1989,7 @@ def deserialize_unix(attr): if isinstance(attr, ET.Element): attr = int(attr.text) # type: ignore try: + attr = int(attr) date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) except ValueError as err: msg = "Cannot deserialize to unix datetime object." diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_version.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_version.py index c43fdbc2e239..0ec13ea52bbf 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_version.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "1.0.0b3" +VERSION = "1.0.0" diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_client.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_client.py index 2de85d47cb31..e94fae1092d9 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_client.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_client.py @@ -27,7 +27,7 @@ class DevCenterClient(DevCenterClientOperationsMixin): # pylint: disable=client :param endpoint: The DevCenter-specific URI to operate on. Required. :type endpoint: str - :param credential: Credential needed for the client to connect to Azure. Required. + :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :keyword api_version: The API version to use for this operation. Default value is "2023-04-01". Note that overriding this default value may result in unsupported behavior. diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_configuration.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_configuration.py index fc5cbe64dbe5..7f1449d13d56 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_configuration.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_configuration.py @@ -25,7 +25,7 @@ class DevCenterClientConfiguration: # pylint: disable=too-many-instance-attribu :param endpoint: The DevCenter-specific URI to operate on. Required. :type endpoint: str - :param credential: Credential needed for the client to connect to Azure. Required. + :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :keyword api_version: The API version to use for this operation. Default value is "2023-04-01". Note that overriding this default value may result in unsupported behavior. diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_operations/_operations.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_operations/_operations.py index 3cc142ca73f0..d265d51dfc79 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_operations/_operations.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_operations/_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -8,8 +8,9 @@ # -------------------------------------------------------------------------- import datetime from io import IOBase +import json import sys -from typing import Any, AsyncIterable, Callable, Dict, IO, List, Optional, TypeVar, Union, cast, overload +from typing import Any, AsyncIterable, Callable, Dict, IO, List, Optional, Type, TypeVar, Union, cast, overload import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList @@ -29,6 +30,8 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict +from ... import models as _models +from ..._model_base import SdkJSONEncoder, _deserialize from ..._operations._operations import ( build_dev_center_create_dev_box_request, build_dev_center_create_or_update_environment_request, @@ -75,19 +78,14 @@ class DevCenterClientOperationsMixin(DevCenterClientMixinABC): # pylint: disable=too-many-public-methods + @distributed_trace - def list_projects( - self, *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> AsyncIterable[JSON]: + def list_projects(self, **kwargs: Any) -> AsyncIterable["_models.Project"]: + # pylint: disable=line-too-long """Lists all projects. - :keyword filter: An OData filter clause to apply to the operation. Default value is None. - :paramtype filter: str - :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. - Default value is None. - :paramtype top: int - :return: An iterator like instance of JSON object - :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON] + :return: An iterator like instance of Project + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.developer.devcenter.models.Project] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -104,9 +102,9 @@ def list_projects( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[JSON]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.Project]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -118,8 +116,6 @@ def prepare_request(next_link=None): if not next_link: _request = build_dev_center_list_projects_request( - filter=filter, - top=top, api_version=self._config.api_version, headers=_headers, params=_params, @@ -155,7 +151,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["value"] + list_of_elem = _deserialize(List[_models.Project], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -180,15 +176,14 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) @distributed_trace_async - async def get_project(self, project_name: str, **kwargs: Any) -> JSON: + async def get_project(self, project_name: str, **kwargs: Any) -> _models.Project: + # pylint: disable=line-too-long """Gets a project. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: JSON object - :rtype: JSON + :return: Project. The Project is compatible with MutableMapping + :rtype: ~azure.developer.devcenter.models.Project :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -202,7 +197,7 @@ async def get_project(self, project_name: str, **kwargs: Any) -> JSON: number of Dev Boxes a single user can create across all pools in the project. } """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -213,7 +208,7 @@ async def get_project(self, project_name: str, **kwargs: Any) -> JSON: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.Project] = kwargs.pop("cls", None) _request = build_dev_center_get_project_request( project_name=project_name, @@ -242,31 +237,22 @@ async def get_project(self, project_name: str, **kwargs: Any) -> JSON: if _stream: deserialized = response.iter_bytes() else: - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.Project, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore @distributed_trace - def list_pools( - self, project_name: str, *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> AsyncIterable[JSON]: + def list_pools(self, project_name: str, **kwargs: Any) -> AsyncIterable["_models.Pool"]: + # pylint: disable=line-too-long """Lists available pools. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str - :keyword filter: An OData filter clause to apply to the operation. Default value is None. - :paramtype filter: str - :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. - Default value is None. - :paramtype top: int - :return: An iterator like instance of JSON object - :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON] + :return: An iterator like instance of Pool + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.developer.devcenter.models.Pool] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -283,7 +269,18 @@ def list_pools( "hardwareProfile": { "memoryGB": 0, # Optional. The amount of memory available for the Dev Box. - "skuName": "str", # Optional. The name of the SKU. + "skuName": "str", # Optional. The name of the SKU. Known values are: + "general_i_8c32gb256ssd_v2", "general_i_8c32gb512ssd_v2", + "general_i_8c32gb1024ssd_v2", "general_i_8c32gb2048ssd_v2", + "general_i_16c64gb256ssd_v2", "general_i_16c64gb512ssd_v2", + "general_i_16c64gb1024ssd_v2", "general_i_16c64gb2048ssd_v2", + "general_i_32c128gb512ssd_v2", "general_i_32c128gb1024ssd_v2", + "general_i_32c128gb2048ssd_v2", "general_a_8c32gb256ssd_v2", + "general_a_8c32gb512ssd_v2", "general_a_8c32gb1024ssd_v2", + "general_a_8c32gb2048ssd_v2", "general_a_16c64gb256ssd_v2", + "general_a_16c64gb512ssd_v2", "general_a_16c64gb1024ssd_v2", + "general_a_16c64gb2048ssd_v2", "general_a_32c128gb512ssd_v2", + "general_a_32c128gb1024ssd_v2", and "general_a_32c128gb2048ssd_v2". "vCPUs": 0 # Optional. The number of vCPUs available for the Dev Box. }, @@ -323,9 +320,9 @@ def list_pools( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[JSON]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.Pool]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -338,8 +335,6 @@ def prepare_request(next_link=None): _request = build_dev_center_list_pools_request( project_name=project_name, - filter=filter, - top=top, api_version=self._config.api_version, headers=_headers, params=_params, @@ -375,7 +370,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["value"] + list_of_elem = _deserialize(List[_models.Pool], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -400,17 +395,16 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) @distributed_trace_async - async def get_pool(self, project_name: str, pool_name: str, **kwargs: Any) -> JSON: + async def get_pool(self, project_name: str, pool_name: str, **kwargs: Any) -> _models.Pool: + # pylint: disable=line-too-long """Gets a pool. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str - :param pool_name: The name of a pool of Dev Boxes. Required. + :param pool_name: Pool name. Required. :type pool_name: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: JSON object - :rtype: JSON + :return: Pool. The Pool is compatible with MutableMapping + :rtype: ~azure.developer.devcenter.models.Pool :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -427,7 +421,18 @@ async def get_pool(self, project_name: str, pool_name: str, **kwargs: Any) -> JS "hardwareProfile": { "memoryGB": 0, # Optional. The amount of memory available for the Dev Box. - "skuName": "str", # Optional. The name of the SKU. + "skuName": "str", # Optional. The name of the SKU. Known values are: + "general_i_8c32gb256ssd_v2", "general_i_8c32gb512ssd_v2", + "general_i_8c32gb1024ssd_v2", "general_i_8c32gb2048ssd_v2", + "general_i_16c64gb256ssd_v2", "general_i_16c64gb512ssd_v2", + "general_i_16c64gb1024ssd_v2", "general_i_16c64gb2048ssd_v2", + "general_i_32c128gb512ssd_v2", "general_i_32c128gb1024ssd_v2", + "general_i_32c128gb2048ssd_v2", "general_a_8c32gb256ssd_v2", + "general_a_8c32gb512ssd_v2", "general_a_8c32gb1024ssd_v2", + "general_a_8c32gb2048ssd_v2", "general_a_16c64gb256ssd_v2", + "general_a_16c64gb512ssd_v2", "general_a_16c64gb1024ssd_v2", + "general_a_16c64gb2048ssd_v2", "general_a_32c128gb512ssd_v2", + "general_a_32c128gb1024ssd_v2", and "general_a_32c128gb2048ssd_v2". "vCPUs": 0 # Optional. The number of vCPUs available for the Dev Box. }, @@ -464,7 +469,7 @@ async def get_pool(self, project_name: str, pool_name: str, **kwargs: Any) -> JS } } """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -475,7 +480,7 @@ async def get_pool(self, project_name: str, pool_name: str, **kwargs: Any) -> JS _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.Pool] = kwargs.pop("cls", None) _request = build_dev_center_get_pool_request( project_name=project_name, @@ -505,39 +510,23 @@ async def get_pool(self, project_name: str, pool_name: str, **kwargs: Any) -> JS if _stream: deserialized = response.iter_bytes() else: - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.Pool, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore @distributed_trace - def list_schedules( - self, - project_name: str, - pool_name: str, - *, - filter: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any - ) -> AsyncIterable[JSON]: - """Lists available schedules for a pool. + def list_schedules(self, project_name: str, pool_name: str, **kwargs: Any) -> AsyncIterable["_models.Schedule"]: + """Lists all schedules within a pool that are configured by your project administrator. :param project_name: The DevCenter Project upon which to execute operations. Required. :type project_name: str :param pool_name: The name of a pool of Dev Boxes. Required. :type pool_name: str - :keyword filter: An OData filter clause to apply to the operation. Default value is None. - :paramtype filter: str - :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. - Default value is None. - :paramtype top: int - :return: An iterator like instance of JSON object - :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON] + :return: An iterator like instance of Schedule + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.developer.devcenter.models.Schedule] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -559,9 +548,9 @@ def list_schedules( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[JSON]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.Schedule]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -575,8 +564,6 @@ def prepare_request(next_link=None): _request = build_dev_center_list_schedules_request( project_name=project_name, pool_name=pool_name, - filter=filter, - top=top, api_version=self._config.api_version, headers=_headers, params=_params, @@ -612,7 +599,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["value"] + list_of_elem = _deserialize(List[_models.Schedule], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -637,19 +624,19 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) @distributed_trace_async - async def get_schedule(self, project_name: str, pool_name: str, schedule_name: str, **kwargs: Any) -> JSON: + async def get_schedule( + self, project_name: str, pool_name: str, schedule_name: str, **kwargs: Any + ) -> _models.Schedule: """Gets a schedule. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str - :param pool_name: The name of a pool of Dev Boxes. Required. + :param pool_name: Pool name. Required. :type pool_name: str - :param schedule_name: The name of a schedule. Required. + :param schedule_name: Display name for the Schedule. Required. :type schedule_name: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: JSON object - :rtype: JSON + :return: Schedule. The Schedule is compatible with MutableMapping + :rtype: ~azure.developer.devcenter.models.Schedule :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -668,7 +655,7 @@ async def get_schedule(self, project_name: str, pool_name: str, schedule_name: s "StopDevBox" } """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -679,7 +666,7 @@ async def get_schedule(self, project_name: str, pool_name: str, schedule_name: s _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.Schedule] = kwargs.pop("cls", None) _request = build_dev_center_get_schedule_request( project_name=project_name, @@ -710,29 +697,20 @@ async def get_schedule(self, project_name: str, pool_name: str, schedule_name: s if _stream: deserialized = response.iter_bytes() else: - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.Schedule, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore @distributed_trace - def list_all_dev_boxes( - self, *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> AsyncIterable[JSON]: + def list_all_dev_boxes(self, **kwargs: Any) -> AsyncIterable["_models.DevBox"]: + # pylint: disable=line-too-long """Lists Dev Boxes that the caller has access to in the DevCenter. - :keyword filter: An OData filter clause to apply to the operation. Default value is None. - :paramtype filter: str - :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. - Default value is None. - :paramtype top: int - :return: An iterator like instance of JSON object - :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON] + :return: An iterator like instance of DevBox + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.developer.devcenter.models.DevBox] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -765,7 +743,18 @@ def list_all_dev_boxes( "hardwareProfile": { "memoryGB": 0, # Optional. The amount of memory available for the Dev Box. - "skuName": "str", # Optional. The name of the SKU. + "skuName": "str", # Optional. The name of the SKU. Known values are: + "general_i_8c32gb256ssd_v2", "general_i_8c32gb512ssd_v2", + "general_i_8c32gb1024ssd_v2", "general_i_8c32gb2048ssd_v2", + "general_i_16c64gb256ssd_v2", "general_i_16c64gb512ssd_v2", + "general_i_16c64gb1024ssd_v2", "general_i_16c64gb2048ssd_v2", + "general_i_32c128gb512ssd_v2", "general_i_32c128gb1024ssd_v2", + "general_i_32c128gb2048ssd_v2", "general_a_8c32gb256ssd_v2", + "general_a_8c32gb512ssd_v2", "general_a_8c32gb1024ssd_v2", + "general_a_8c32gb2048ssd_v2", "general_a_16c64gb256ssd_v2", + "general_a_16c64gb512ssd_v2", "general_a_16c64gb1024ssd_v2", + "general_a_16c64gb2048ssd_v2", "general_a_32c128gb512ssd_v2", + "general_a_32c128gb1024ssd_v2", and "general_a_32c128gb2048ssd_v2". "vCPUs": 0 # Optional. The number of vCPUs available for the Dev Box. }, @@ -794,7 +783,9 @@ def list_all_dev_boxes( "projectName": "str", # Optional. Name of the project this Dev Box belongs to. "provisioningState": "str", # Optional. The current provisioning state of - the Dev Box. + the Dev Box. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Deleting", "Updating", "Starting", "Stopping", "Provisioning", + "ProvisionedWithWarning", "InGracePeriod", and "NotProvisioned". "storageProfile": { "osDisk": { "diskSizeGB": 0 # Optional. The size of the OS Disk in @@ -810,9 +801,9 @@ def list_all_dev_boxes( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[JSON]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.DevBox]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -824,8 +815,6 @@ def prepare_request(next_link=None): if not next_link: _request = build_dev_center_list_all_dev_boxes_request( - filter=filter, - top=top, api_version=self._config.api_version, headers=_headers, params=_params, @@ -861,7 +850,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["value"] + list_of_elem = _deserialize(List[_models.DevBox], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -886,21 +875,15 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) @distributed_trace - def list_all_dev_boxes_by_user( - self, user_id: str, *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> AsyncIterable[JSON]: + def list_all_dev_boxes_by_user(self, user_id: str, **kwargs: Any) -> AsyncIterable["_models.DevBox"]: + # pylint: disable=line-too-long """Lists Dev Boxes in the Dev Center for a particular user. :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str - :keyword filter: An OData filter clause to apply to the operation. Default value is None. - :paramtype filter: str - :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. - Default value is None. - :paramtype top: int - :return: An iterator like instance of JSON object - :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON] + :return: An iterator like instance of DevBox + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.developer.devcenter.models.DevBox] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -933,7 +916,18 @@ def list_all_dev_boxes_by_user( "hardwareProfile": { "memoryGB": 0, # Optional. The amount of memory available for the Dev Box. - "skuName": "str", # Optional. The name of the SKU. + "skuName": "str", # Optional. The name of the SKU. Known values are: + "general_i_8c32gb256ssd_v2", "general_i_8c32gb512ssd_v2", + "general_i_8c32gb1024ssd_v2", "general_i_8c32gb2048ssd_v2", + "general_i_16c64gb256ssd_v2", "general_i_16c64gb512ssd_v2", + "general_i_16c64gb1024ssd_v2", "general_i_16c64gb2048ssd_v2", + "general_i_32c128gb512ssd_v2", "general_i_32c128gb1024ssd_v2", + "general_i_32c128gb2048ssd_v2", "general_a_8c32gb256ssd_v2", + "general_a_8c32gb512ssd_v2", "general_a_8c32gb1024ssd_v2", + "general_a_8c32gb2048ssd_v2", "general_a_16c64gb256ssd_v2", + "general_a_16c64gb512ssd_v2", "general_a_16c64gb1024ssd_v2", + "general_a_16c64gb2048ssd_v2", "general_a_32c128gb512ssd_v2", + "general_a_32c128gb1024ssd_v2", and "general_a_32c128gb2048ssd_v2". "vCPUs": 0 # Optional. The number of vCPUs available for the Dev Box. }, @@ -962,7 +956,9 @@ def list_all_dev_boxes_by_user( "projectName": "str", # Optional. Name of the project this Dev Box belongs to. "provisioningState": "str", # Optional. The current provisioning state of - the Dev Box. + the Dev Box. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Deleting", "Updating", "Starting", "Stopping", "Provisioning", + "ProvisionedWithWarning", "InGracePeriod", and "NotProvisioned". "storageProfile": { "osDisk": { "diskSizeGB": 0 # Optional. The size of the OS Disk in @@ -978,9 +974,9 @@ def list_all_dev_boxes_by_user( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[JSON]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.DevBox]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -993,8 +989,6 @@ def prepare_request(next_link=None): _request = build_dev_center_list_all_dev_boxes_by_user_request( user_id=user_id, - filter=filter, - top=top, api_version=self._config.api_version, headers=_headers, params=_params, @@ -1030,7 +1024,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["value"] + list_of_elem = _deserialize(List[_models.DevBox], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -1055,9 +1049,8 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) @distributed_trace - def list_dev_boxes( - self, project_name: str, user_id: str, *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> AsyncIterable[JSON]: + def list_dev_boxes(self, project_name: str, user_id: str, **kwargs: Any) -> AsyncIterable["_models.DevBox"]: + # pylint: disable=line-too-long """Lists Dev Boxes in the project for a particular user. :param project_name: The DevCenter Project upon which to execute operations. Required. @@ -1065,13 +1058,8 @@ def list_dev_boxes( :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str - :keyword filter: An OData filter clause to apply to the operation. Default value is None. - :paramtype filter: str - :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. - Default value is None. - :paramtype top: int - :return: An iterator like instance of JSON object - :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON] + :return: An iterator like instance of DevBox + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.developer.devcenter.models.DevBox] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -1104,7 +1092,18 @@ def list_dev_boxes( "hardwareProfile": { "memoryGB": 0, # Optional. The amount of memory available for the Dev Box. - "skuName": "str", # Optional. The name of the SKU. + "skuName": "str", # Optional. The name of the SKU. Known values are: + "general_i_8c32gb256ssd_v2", "general_i_8c32gb512ssd_v2", + "general_i_8c32gb1024ssd_v2", "general_i_8c32gb2048ssd_v2", + "general_i_16c64gb256ssd_v2", "general_i_16c64gb512ssd_v2", + "general_i_16c64gb1024ssd_v2", "general_i_16c64gb2048ssd_v2", + "general_i_32c128gb512ssd_v2", "general_i_32c128gb1024ssd_v2", + "general_i_32c128gb2048ssd_v2", "general_a_8c32gb256ssd_v2", + "general_a_8c32gb512ssd_v2", "general_a_8c32gb1024ssd_v2", + "general_a_8c32gb2048ssd_v2", "general_a_16c64gb256ssd_v2", + "general_a_16c64gb512ssd_v2", "general_a_16c64gb1024ssd_v2", + "general_a_16c64gb2048ssd_v2", "general_a_32c128gb512ssd_v2", + "general_a_32c128gb1024ssd_v2", and "general_a_32c128gb2048ssd_v2". "vCPUs": 0 # Optional. The number of vCPUs available for the Dev Box. }, @@ -1133,7 +1132,9 @@ def list_dev_boxes( "projectName": "str", # Optional. Name of the project this Dev Box belongs to. "provisioningState": "str", # Optional. The current provisioning state of - the Dev Box. + the Dev Box. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Deleting", "Updating", "Starting", "Stopping", "Provisioning", + "ProvisionedWithWarning", "InGracePeriod", and "NotProvisioned". "storageProfile": { "osDisk": { "diskSizeGB": 0 # Optional. The size of the OS Disk in @@ -1149,9 +1150,9 @@ def list_dev_boxes( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[JSON]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.DevBox]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1165,8 +1166,6 @@ def prepare_request(next_link=None): _request = build_dev_center_list_dev_boxes_request( project_name=project_name, user_id=user_id, - filter=filter, - top=top, api_version=self._config.api_version, headers=_headers, params=_params, @@ -1202,7 +1201,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["value"] + list_of_elem = _deserialize(List[_models.DevBox], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -1227,20 +1226,19 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) @distributed_trace_async - async def get_dev_box(self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any) -> JSON: + async def get_dev_box(self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any) -> _models.DevBox: + # pylint: disable=line-too-long """Gets a Dev Box. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str - :param dev_box_name: The name of a Dev Box. Required. + :param dev_box_name: Display name for the Dev Box. Required. :type dev_box_name: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: JSON object - :rtype: JSON + :return: DevBox. The DevBox is compatible with MutableMapping + :rtype: ~azure.developer.devcenter.models.DevBox :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -1273,7 +1271,18 @@ async def get_dev_box(self, project_name: str, user_id: str, dev_box_name: str, "hardwareProfile": { "memoryGB": 0, # Optional. The amount of memory available for the Dev Box. - "skuName": "str", # Optional. The name of the SKU. + "skuName": "str", # Optional. The name of the SKU. Known values are: + "general_i_8c32gb256ssd_v2", "general_i_8c32gb512ssd_v2", + "general_i_8c32gb1024ssd_v2", "general_i_8c32gb2048ssd_v2", + "general_i_16c64gb256ssd_v2", "general_i_16c64gb512ssd_v2", + "general_i_16c64gb1024ssd_v2", "general_i_16c64gb2048ssd_v2", + "general_i_32c128gb512ssd_v2", "general_i_32c128gb1024ssd_v2", + "general_i_32c128gb2048ssd_v2", "general_a_8c32gb256ssd_v2", + "general_a_8c32gb512ssd_v2", "general_a_8c32gb1024ssd_v2", + "general_a_8c32gb2048ssd_v2", "general_a_16c64gb256ssd_v2", + "general_a_16c64gb512ssd_v2", "general_a_16c64gb1024ssd_v2", + "general_a_16c64gb2048ssd_v2", "general_a_32c128gb512ssd_v2", + "general_a_32c128gb1024ssd_v2", and "general_a_32c128gb2048ssd_v2". "vCPUs": 0 # Optional. The number of vCPUs available for the Dev Box. }, @@ -1302,7 +1311,9 @@ async def get_dev_box(self, project_name: str, user_id: str, dev_box_name: str, "projectName": "str", # Optional. Name of the project this Dev Box belongs to. "provisioningState": "str", # Optional. The current provisioning state of - the Dev Box. + the Dev Box. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Deleting", "Updating", "Starting", "Stopping", "Provisioning", + "ProvisionedWithWarning", "InGracePeriod", and "NotProvisioned". "storageProfile": { "osDisk": { "diskSizeGB": 0 # Optional. The size of the OS Disk in @@ -1315,7 +1326,7 @@ async def get_dev_box(self, project_name: str, user_id: str, dev_box_name: str, assigned to. } """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1326,7 +1337,7 @@ async def get_dev_box(self, project_name: str, user_id: str, dev_box_name: str, _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.DevBox] = kwargs.pop("cls", None) _request = build_dev_center_get_dev_box_request( project_name=project_name, @@ -1357,20 +1368,22 @@ async def get_dev_box(self, project_name: str, user_id: str, dev_box_name: str, if _stream: deserialized = response.iter_bytes() else: - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.DevBox, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore async def _create_dev_box_initial( - self, project_name: str, user_id: str, dev_box_name: str, body: Union[JSON, IO], **kwargs: Any + self, + project_name: str, + user_id: str, + dev_box_name: str, + body: Union[_models.DevBox, JSON, IO[bytes]], + **kwargs: Any ) -> JSON: - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1385,12 +1398,11 @@ async def _create_dev_box_initial( cls: ClsType[JSON] = kwargs.pop("cls", None) content_type = content_type or "application/json" - _json = None _content = None if isinstance(body, (IOBase, bytes)): _content = body else: - _json = body + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_dev_center_create_dev_box_request( project_name=project_name, @@ -1398,7 +1410,6 @@ async def _create_dev_box_initial( dev_box_name=dev_box_name, content_type=content_type, api_version=self._config.api_version, - json=_json, content=_content, headers=_headers, params=_params, @@ -1423,10 +1434,7 @@ async def _create_dev_box_initial( response_headers = {} if response.status_code == 200: - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(JSON, response.json()) if response.status_code == 201: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) @@ -1434,15 +1442,12 @@ async def _create_dev_box_initial( "str", response.headers.get("Operation-Location") ) - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(JSON, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), response_headers) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore @overload async def begin_create_dev_box( @@ -1450,34 +1455,30 @@ async def begin_create_dev_box( project_name: str, user_id: str, dev_box_name: str, - body: JSON, + body: _models.DevBox, *, content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller[JSON]: + ) -> AsyncLROPoller[_models.DevBox]: + # pylint: disable=line-too-long """Creates or replaces a Dev Box. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: The DevCenter Project upon which to execute the operation. Required. :type project_name: str :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str :param dev_box_name: The name of a Dev Box. Required. :type dev_box_name: str - :param body: Represents a environment. Required. - :type body: JSON + :param body: Represents the body request of a Dev Box creation. Dev Box Pool name is required. + Optionally set the owner of the Dev Box as local administrator. Required. + :type body: ~azure.developer.devcenter.models.DevBox :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False - for this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns JSON object - :rtype: ~azure.core.polling.AsyncLROPoller[JSON] + :return: An instance of AsyncLROPoller that returns DevBox. The DevBox is compatible with + MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.developer.devcenter.models.DevBox] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -1510,7 +1511,18 @@ async def begin_create_dev_box( "hardwareProfile": { "memoryGB": 0, # Optional. The amount of memory available for the Dev Box. - "skuName": "str", # Optional. The name of the SKU. + "skuName": "str", # Optional. The name of the SKU. Known values are: + "general_i_8c32gb256ssd_v2", "general_i_8c32gb512ssd_v2", + "general_i_8c32gb1024ssd_v2", "general_i_8c32gb2048ssd_v2", + "general_i_16c64gb256ssd_v2", "general_i_16c64gb512ssd_v2", + "general_i_16c64gb1024ssd_v2", "general_i_16c64gb2048ssd_v2", + "general_i_32c128gb512ssd_v2", "general_i_32c128gb1024ssd_v2", + "general_i_32c128gb2048ssd_v2", "general_a_8c32gb256ssd_v2", + "general_a_8c32gb512ssd_v2", "general_a_8c32gb1024ssd_v2", + "general_a_8c32gb2048ssd_v2", "general_a_16c64gb256ssd_v2", + "general_a_16c64gb512ssd_v2", "general_a_16c64gb1024ssd_v2", + "general_a_16c64gb2048ssd_v2", "general_a_32c128gb512ssd_v2", + "general_a_32c128gb1024ssd_v2", and "general_a_32c128gb2048ssd_v2". "vCPUs": 0 # Optional. The number of vCPUs available for the Dev Box. }, @@ -1539,7 +1551,9 @@ async def begin_create_dev_box( "projectName": "str", # Optional. Name of the project this Dev Box belongs to. "provisioningState": "str", # Optional. The current provisioning state of - the Dev Box. + the Dev Box. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Deleting", "Updating", "Starting", "Stopping", "Provisioning", + "ProvisionedWithWarning", "InGracePeriod", and "NotProvisioned". "storageProfile": { "osDisk": { "diskSizeGB": 0 # Optional. The size of the OS Disk in @@ -1579,7 +1593,18 @@ async def begin_create_dev_box( "hardwareProfile": { "memoryGB": 0, # Optional. The amount of memory available for the Dev Box. - "skuName": "str", # Optional. The name of the SKU. + "skuName": "str", # Optional. The name of the SKU. Known values are: + "general_i_8c32gb256ssd_v2", "general_i_8c32gb512ssd_v2", + "general_i_8c32gb1024ssd_v2", "general_i_8c32gb2048ssd_v2", + "general_i_16c64gb256ssd_v2", "general_i_16c64gb512ssd_v2", + "general_i_16c64gb1024ssd_v2", "general_i_16c64gb2048ssd_v2", + "general_i_32c128gb512ssd_v2", "general_i_32c128gb1024ssd_v2", + "general_i_32c128gb2048ssd_v2", "general_a_8c32gb256ssd_v2", + "general_a_8c32gb512ssd_v2", "general_a_8c32gb1024ssd_v2", + "general_a_8c32gb2048ssd_v2", "general_a_16c64gb256ssd_v2", + "general_a_16c64gb512ssd_v2", "general_a_16c64gb1024ssd_v2", + "general_a_16c64gb2048ssd_v2", "general_a_32c128gb512ssd_v2", + "general_a_32c128gb1024ssd_v2", and "general_a_32c128gb2048ssd_v2". "vCPUs": 0 # Optional. The number of vCPUs available for the Dev Box. }, @@ -1608,7 +1633,9 @@ async def begin_create_dev_box( "projectName": "str", # Optional. Name of the project this Dev Box belongs to. "provisioningState": "str", # Optional. The current provisioning state of - the Dev Box. + the Dev Box. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Deleting", "Updating", "Starting", "Stopping", "Provisioning", + "ProvisionedWithWarning", "InGracePeriod", and "NotProvisioned". "storageProfile": { "osDisk": { "diskSizeGB": 0 # Optional. The size of the OS Disk in @@ -1628,34 +1655,148 @@ async def begin_create_dev_box( project_name: str, user_id: str, dev_box_name: str, - body: IO, + body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller[JSON]: + ) -> AsyncLROPoller[_models.DevBox]: + # pylint: disable=line-too-long """Creates or replaces a Dev Box. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: The DevCenter Project upon which to execute the operation. Required. + :type project_name: str + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Required. + :type user_id: str + :param dev_box_name: The name of a Dev Box. Required. + :type dev_box_name: str + :param body: Represents the body request of a Dev Box creation. Dev Box Pool name is required. + Optionally set the owner of the Dev Box as local administrator. Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns DevBox. The DevBox is compatible with + MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.developer.devcenter.models.DevBox] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200, 201 + response == { + "name": "str", # Display name for the Dev Box. Required. + "poolName": "str", # The name of the Dev Box pool this machine belongs to. + Required. + "actionState": "str", # Optional. The current action state of the Dev Box. + This is state is based on previous action performed by user. + "createdTime": "2020-02-20 00:00:00", # Optional. Creation time of this Dev + Box. + "error": { + "code": "str", # One of a server-defined set of error codes. + Required. + "message": "str", # A human-readable representation of the error. + Required. + "details": [ + ... + ], + "innererror": { + "code": "str", # Optional. One of a server-defined set of + error codes. + "innererror": ... + }, + "target": "str" # Optional. The target of the error. + }, + "hardwareProfile": { + "memoryGB": 0, # Optional. The amount of memory available for the + Dev Box. + "skuName": "str", # Optional. The name of the SKU. Known values are: + "general_i_8c32gb256ssd_v2", "general_i_8c32gb512ssd_v2", + "general_i_8c32gb1024ssd_v2", "general_i_8c32gb2048ssd_v2", + "general_i_16c64gb256ssd_v2", "general_i_16c64gb512ssd_v2", + "general_i_16c64gb1024ssd_v2", "general_i_16c64gb2048ssd_v2", + "general_i_32c128gb512ssd_v2", "general_i_32c128gb1024ssd_v2", + "general_i_32c128gb2048ssd_v2", "general_a_8c32gb256ssd_v2", + "general_a_8c32gb512ssd_v2", "general_a_8c32gb1024ssd_v2", + "general_a_8c32gb2048ssd_v2", "general_a_16c64gb256ssd_v2", + "general_a_16c64gb512ssd_v2", "general_a_16c64gb1024ssd_v2", + "general_a_16c64gb2048ssd_v2", "general_a_32c128gb512ssd_v2", + "general_a_32c128gb1024ssd_v2", and "general_a_32c128gb2048ssd_v2". + "vCPUs": 0 # Optional. The number of vCPUs available for the Dev + Box. + }, + "hibernateSupport": "str", # Optional. Indicates whether hibernate is + enabled/disabled or unknown. Known values are: "Enabled", "Disabled", and + "OsUnsupported". + "imageReference": { + "name": "str", # Optional. The name of the image used. + "operatingSystem": "str", # Optional. The operating system of the + image. + "osBuildNumber": "str", # Optional. The operating system build + number of the image. + "publishedDate": "2020-02-20 00:00:00", # Optional. The datetime + that the backing image version was published. + "version": "str" # Optional. The version of the image. + }, + "localAdministrator": "str", # Optional. Indicates whether the owner of the + Dev Box is a local administrator. Known values are: "Enabled" and "Disabled". + "location": "str", # Optional. Azure region where this Dev Box is located. + This will be the same region as the Virtual Network it is attached to. + "osType": "str", # Optional. The operating system type of this Dev Box. + "Windows" + "powerState": "str", # Optional. The current power state of the Dev Box. + Known values are: "Unknown", "Running", "Deallocated", "PoweredOff", and + "Hibernated". + "projectName": "str", # Optional. Name of the project this Dev Box belongs + to. + "provisioningState": "str", # Optional. The current provisioning state of + the Dev Box. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Deleting", "Updating", "Starting", "Stopping", "Provisioning", + "ProvisionedWithWarning", "InGracePeriod", and "NotProvisioned". + "storageProfile": { + "osDisk": { + "diskSizeGB": 0 # Optional. The size of the OS Disk in + gigabytes. + } + }, + "uniqueId": "str", # Optional. A unique identifier for the Dev Box. This is + a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + "user": "str" # Optional. The AAD object id of the user this Dev Box is + assigned to. + } + """ + + @overload + async def begin_create_dev_box( + self, + project_name: str, + user_id: str, + dev_box_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DevBox]: + # pylint: disable=line-too-long + """Creates or replaces a Dev Box. + + :param project_name: The DevCenter Project upon which to execute the operation. Required. :type project_name: str :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str :param dev_box_name: The name of a Dev Box. Required. :type dev_box_name: str - :param body: Represents a environment. Required. - :type body: IO + :param body: Represents the body request of a Dev Box creation. Dev Box Pool name is required. + Optionally set the owner of the Dev Box as local administrator. Required. + :type body: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False - for this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns JSON object - :rtype: ~azure.core.polling.AsyncLROPoller[JSON] + :return: An instance of AsyncLROPoller that returns DevBox. The DevBox is compatible with + MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.developer.devcenter.models.DevBox] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -1688,7 +1829,18 @@ async def begin_create_dev_box( "hardwareProfile": { "memoryGB": 0, # Optional. The amount of memory available for the Dev Box. - "skuName": "str", # Optional. The name of the SKU. + "skuName": "str", # Optional. The name of the SKU. Known values are: + "general_i_8c32gb256ssd_v2", "general_i_8c32gb512ssd_v2", + "general_i_8c32gb1024ssd_v2", "general_i_8c32gb2048ssd_v2", + "general_i_16c64gb256ssd_v2", "general_i_16c64gb512ssd_v2", + "general_i_16c64gb1024ssd_v2", "general_i_16c64gb2048ssd_v2", + "general_i_32c128gb512ssd_v2", "general_i_32c128gb1024ssd_v2", + "general_i_32c128gb2048ssd_v2", "general_a_8c32gb256ssd_v2", + "general_a_8c32gb512ssd_v2", "general_a_8c32gb1024ssd_v2", + "general_a_8c32gb2048ssd_v2", "general_a_16c64gb256ssd_v2", + "general_a_16c64gb512ssd_v2", "general_a_16c64gb1024ssd_v2", + "general_a_16c64gb2048ssd_v2", "general_a_32c128gb512ssd_v2", + "general_a_32c128gb1024ssd_v2", and "general_a_32c128gb2048ssd_v2". "vCPUs": 0 # Optional. The number of vCPUs available for the Dev Box. }, @@ -1717,7 +1869,9 @@ async def begin_create_dev_box( "projectName": "str", # Optional. Name of the project this Dev Box belongs to. "provisioningState": "str", # Optional. The current provisioning state of - the Dev Box. + the Dev Box. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Deleting", "Updating", "Starting", "Stopping", "Provisioning", + "ProvisionedWithWarning", "InGracePeriod", and "NotProvisioned". "storageProfile": { "osDisk": { "diskSizeGB": 0 # Optional. The size of the OS Disk in @@ -1733,31 +1887,30 @@ async def begin_create_dev_box( @distributed_trace_async async def begin_create_dev_box( - self, project_name: str, user_id: str, dev_box_name: str, body: Union[JSON, IO], **kwargs: Any - ) -> AsyncLROPoller[JSON]: + self, + project_name: str, + user_id: str, + dev_box_name: str, + body: Union[_models.DevBox, JSON, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.DevBox]: + # pylint: disable=line-too-long """Creates or replaces a Dev Box. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: The DevCenter Project upon which to execute the operation. Required. :type project_name: str :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str :param dev_box_name: The name of a Dev Box. Required. :type dev_box_name: str - :param body: Represents a environment. Is either a JSON type or a IO type. Required. - :type body: JSON or IO - :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default - value is None. - :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False - for this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns JSON object - :rtype: ~azure.core.polling.AsyncLROPoller[JSON] + :param body: Represents the body request of a Dev Box creation. Dev Box Pool name is required. + Optionally set the owner of the Dev Box as local administrator. Is one of the following types: + DevBox, JSON, IO[bytes] Required. + :type body: ~azure.developer.devcenter.models.DevBox or JSON or IO[bytes] + :return: An instance of AsyncLROPoller that returns DevBox. The DevBox is compatible with + MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.developer.devcenter.models.DevBox] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -1790,7 +1943,18 @@ async def begin_create_dev_box( "hardwareProfile": { "memoryGB": 0, # Optional. The amount of memory available for the Dev Box. - "skuName": "str", # Optional. The name of the SKU. + "skuName": "str", # Optional. The name of the SKU. Known values are: + "general_i_8c32gb256ssd_v2", "general_i_8c32gb512ssd_v2", + "general_i_8c32gb1024ssd_v2", "general_i_8c32gb2048ssd_v2", + "general_i_16c64gb256ssd_v2", "general_i_16c64gb512ssd_v2", + "general_i_16c64gb1024ssd_v2", "general_i_16c64gb2048ssd_v2", + "general_i_32c128gb512ssd_v2", "general_i_32c128gb1024ssd_v2", + "general_i_32c128gb2048ssd_v2", "general_a_8c32gb256ssd_v2", + "general_a_8c32gb512ssd_v2", "general_a_8c32gb1024ssd_v2", + "general_a_8c32gb2048ssd_v2", "general_a_16c64gb256ssd_v2", + "general_a_16c64gb512ssd_v2", "general_a_16c64gb1024ssd_v2", + "general_a_16c64gb2048ssd_v2", "general_a_32c128gb512ssd_v2", + "general_a_32c128gb1024ssd_v2", and "general_a_32c128gb2048ssd_v2". "vCPUs": 0 # Optional. The number of vCPUs available for the Dev Box. }, @@ -1819,7 +1983,9 @@ async def begin_create_dev_box( "projectName": "str", # Optional. Name of the project this Dev Box belongs to. "provisioningState": "str", # Optional. The current provisioning state of - the Dev Box. + the Dev Box. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Deleting", "Updating", "Starting", "Stopping", "Provisioning", + "ProvisionedWithWarning", "InGracePeriod", and "NotProvisioned". "storageProfile": { "osDisk": { "diskSizeGB": 0 # Optional. The size of the OS Disk in @@ -1859,7 +2025,18 @@ async def begin_create_dev_box( "hardwareProfile": { "memoryGB": 0, # Optional. The amount of memory available for the Dev Box. - "skuName": "str", # Optional. The name of the SKU. + "skuName": "str", # Optional. The name of the SKU. Known values are: + "general_i_8c32gb256ssd_v2", "general_i_8c32gb512ssd_v2", + "general_i_8c32gb1024ssd_v2", "general_i_8c32gb2048ssd_v2", + "general_i_16c64gb256ssd_v2", "general_i_16c64gb512ssd_v2", + "general_i_16c64gb1024ssd_v2", "general_i_16c64gb2048ssd_v2", + "general_i_32c128gb512ssd_v2", "general_i_32c128gb1024ssd_v2", + "general_i_32c128gb2048ssd_v2", "general_a_8c32gb256ssd_v2", + "general_a_8c32gb512ssd_v2", "general_a_8c32gb1024ssd_v2", + "general_a_8c32gb2048ssd_v2", "general_a_16c64gb256ssd_v2", + "general_a_16c64gb512ssd_v2", "general_a_16c64gb1024ssd_v2", + "general_a_16c64gb2048ssd_v2", "general_a_32c128gb512ssd_v2", + "general_a_32c128gb1024ssd_v2", and "general_a_32c128gb2048ssd_v2". "vCPUs": 0 # Optional. The number of vCPUs available for the Dev Box. }, @@ -1888,7 +2065,9 @@ async def begin_create_dev_box( "projectName": "str", # Optional. Name of the project this Dev Box belongs to. "provisioningState": "str", # Optional. The current provisioning state of - the Dev Box. + the Dev Box. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Deleting", "Updating", "Starting", "Stopping", "Provisioning", + "ProvisionedWithWarning", "InGracePeriod", and "NotProvisioned". "storageProfile": { "osDisk": { "diskSizeGB": 0 # Optional. The size of the OS Disk in @@ -1905,7 +2084,7 @@ async def begin_create_dev_box( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.DevBox] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) @@ -1925,10 +2104,7 @@ async def begin_create_dev_box( def get_long_running_output(pipeline_response): response = pipeline_response.http_response - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.DevBox, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized @@ -1947,18 +2123,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller[JSON].from_continuation_token( + return AsyncLROPoller[_models.DevBox].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller[JSON](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return AsyncLROPoller[_models.DevBox]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) async def _delete_dev_box_initial( self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any ) -> Optional[JSON]: - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2005,10 +2183,7 @@ async def _delete_dev_box_initial( "str", response.headers.get("Operation-Location") ) - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(JSON, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -2018,7 +2193,8 @@ async def _delete_dev_box_initial( @distributed_trace_async async def begin_delete_dev_box( self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any - ) -> AsyncLROPoller[JSON]: + ) -> AsyncLROPoller[_models.OperationDetails]: + # pylint: disable=line-too-long """Deletes a Dev Box. :param project_name: The DevCenter Project upon which to execute operations. Required. @@ -2028,15 +2204,9 @@ async def begin_delete_dev_box( :type user_id: str :param dev_box_name: The name of a Dev Box. Required. :type dev_box_name: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False - for this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns JSON object - :rtype: ~azure.core.polling.AsyncLROPoller[JSON] + :return: An instance of AsyncLROPoller that returns OperationDetails. The OperationDetails is + compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.developer.devcenter.models.OperationDetails] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -2044,15 +2214,26 @@ async def begin_delete_dev_box( # response body for status code(s): 202 response == { + "id": "str", # Fully qualified ID for the operation status. Required. + "name": "str", # The operation id name. Required. "status": "str", # Provisioning state of the resource. Required. Known - values are: "Running", "Completed", "Canceled", and "Failed". + values are: "NotStarted", "Running", "Succeeded", "Failed", and "Canceled". "endTime": "2020-02-20 00:00:00", # Optional. The end time of the operation. "error": { - "code": "str", # Optional. The error code. - "message": "str" # Optional. The error message. + "code": "str", # One of a server-defined set of error codes. + Required. + "message": "str", # A human-readable representation of the error. + Required. + "details": [ + ... + ], + "innererror": { + "code": "str", # Optional. One of a server-defined set of + error codes. + "innererror": ... + }, + "target": "str" # Optional. The target of the error. }, - "id": "str", # Optional. Fully qualified ID for the operation status. - "name": "str", # Optional. The operation id name. "percentComplete": 0.0, # Optional. Percent of the operation that is complete. "properties": {}, # Optional. Custom operation properties, populated only @@ -2065,7 +2246,7 @@ async def begin_delete_dev_box( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.OperationDetails] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) @@ -2089,10 +2270,7 @@ def get_long_running_output(pipeline_response): "str", response.headers.get("Operation-Location") ) - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.OperationDetails, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized @@ -2111,16 +2289,18 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller[JSON].from_continuation_token( + return AsyncLROPoller[_models.OperationDetails].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller[JSON](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return AsyncLROPoller[_models.OperationDetails]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) async def _start_dev_box_initial(self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any) -> JSON: - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2162,38 +2342,30 @@ async def _start_dev_box_initial(self, project_name: str, user_id: str, dev_box_ response_headers = {} response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(JSON, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), response_headers) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore @distributed_trace_async async def begin_start_dev_box( self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any - ) -> AsyncLROPoller[JSON]: + ) -> AsyncLROPoller[_models.OperationDetails]: + # pylint: disable=line-too-long """Starts a Dev Box. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str - :param dev_box_name: The name of a Dev Box. Required. + :param dev_box_name: Display name for the Dev Box. Required. :type dev_box_name: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False - for this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns JSON object - :rtype: ~azure.core.polling.AsyncLROPoller[JSON] + :return: An instance of AsyncLROPoller that returns OperationDetails. The OperationDetails is + compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.developer.devcenter.models.OperationDetails] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -2201,15 +2373,26 @@ async def begin_start_dev_box( # response body for status code(s): 202 response == { + "id": "str", # Fully qualified ID for the operation status. Required. + "name": "str", # The operation id name. Required. "status": "str", # Provisioning state of the resource. Required. Known - values are: "Running", "Completed", "Canceled", and "Failed". + values are: "NotStarted", "Running", "Succeeded", "Failed", and "Canceled". "endTime": "2020-02-20 00:00:00", # Optional. The end time of the operation. "error": { - "code": "str", # Optional. The error code. - "message": "str" # Optional. The error message. + "code": "str", # One of a server-defined set of error codes. + Required. + "message": "str", # A human-readable representation of the error. + Required. + "details": [ + ... + ], + "innererror": { + "code": "str", # Optional. One of a server-defined set of + error codes. + "innererror": ... + }, + "target": "str" # Optional. The target of the error. }, - "id": "str", # Optional. Fully qualified ID for the operation status. - "name": "str", # Optional. The operation id name. "percentComplete": 0.0, # Optional. Percent of the operation that is complete. "properties": {}, # Optional. Custom operation properties, populated only @@ -2222,7 +2405,7 @@ async def begin_start_dev_box( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.OperationDetails] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) @@ -2245,10 +2428,7 @@ def get_long_running_output(pipeline_response): "str", response.headers.get("Operation-Location") ) - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.OperationDetails, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized @@ -2267,18 +2447,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller[JSON].from_continuation_token( + return AsyncLROPoller[_models.OperationDetails].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller[JSON](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return AsyncLROPoller[_models.OperationDetails]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) async def _stop_dev_box_initial( self, project_name: str, user_id: str, dev_box_name: str, *, hibernate: Optional[bool] = None, **kwargs: Any ) -> JSON: - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2321,40 +2503,32 @@ async def _stop_dev_box_initial( response_headers = {} response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(JSON, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), response_headers) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore @distributed_trace_async async def begin_stop_dev_box( self, project_name: str, user_id: str, dev_box_name: str, *, hibernate: Optional[bool] = None, **kwargs: Any - ) -> AsyncLROPoller[JSON]: + ) -> AsyncLROPoller[_models.OperationDetails]: + # pylint: disable=line-too-long """Stops a Dev Box. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str - :param dev_box_name: The name of a Dev Box. Required. + :param dev_box_name: Display name for the Dev Box. Required. :type dev_box_name: str :keyword hibernate: Optional parameter to hibernate the dev box. Default value is None. :paramtype hibernate: bool - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False - for this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns JSON object - :rtype: ~azure.core.polling.AsyncLROPoller[JSON] + :return: An instance of AsyncLROPoller that returns OperationDetails. The OperationDetails is + compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.developer.devcenter.models.OperationDetails] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -2362,15 +2536,26 @@ async def begin_stop_dev_box( # response body for status code(s): 202 response == { + "id": "str", # Fully qualified ID for the operation status. Required. + "name": "str", # The operation id name. Required. "status": "str", # Provisioning state of the resource. Required. Known - values are: "Running", "Completed", "Canceled", and "Failed". + values are: "NotStarted", "Running", "Succeeded", "Failed", and "Canceled". "endTime": "2020-02-20 00:00:00", # Optional. The end time of the operation. "error": { - "code": "str", # Optional. The error code. - "message": "str" # Optional. The error message. + "code": "str", # One of a server-defined set of error codes. + Required. + "message": "str", # A human-readable representation of the error. + Required. + "details": [ + ... + ], + "innererror": { + "code": "str", # Optional. One of a server-defined set of + error codes. + "innererror": ... + }, + "target": "str" # Optional. The target of the error. }, - "id": "str", # Optional. Fully qualified ID for the operation status. - "name": "str", # Optional. The operation id name. "percentComplete": 0.0, # Optional. Percent of the operation that is complete. "properties": {}, # Optional. Custom operation properties, populated only @@ -2383,7 +2568,7 @@ async def begin_stop_dev_box( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.OperationDetails] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) @@ -2407,10 +2592,7 @@ def get_long_running_output(pipeline_response): "str", response.headers.get("Operation-Location") ) - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.OperationDetails, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized @@ -2429,16 +2611,18 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller[JSON].from_continuation_token( + return AsyncLROPoller[_models.OperationDetails].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller[JSON](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return AsyncLROPoller[_models.OperationDetails]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) async def _restart_dev_box_initial(self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any) -> JSON: - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2480,38 +2664,30 @@ async def _restart_dev_box_initial(self, project_name: str, user_id: str, dev_bo response_headers = {} response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(JSON, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), response_headers) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore @distributed_trace_async async def begin_restart_dev_box( self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any - ) -> AsyncLROPoller[JSON]: + ) -> AsyncLROPoller[_models.OperationDetails]: + # pylint: disable=line-too-long """Restarts a Dev Box. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str - :param dev_box_name: The name of a Dev Box. Required. + :param dev_box_name: Display name for the Dev Box. Required. :type dev_box_name: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False - for this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns JSON object - :rtype: ~azure.core.polling.AsyncLROPoller[JSON] + :return: An instance of AsyncLROPoller that returns OperationDetails. The OperationDetails is + compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.developer.devcenter.models.OperationDetails] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -2519,15 +2695,26 @@ async def begin_restart_dev_box( # response body for status code(s): 202 response == { + "id": "str", # Fully qualified ID for the operation status. Required. + "name": "str", # The operation id name. Required. "status": "str", # Provisioning state of the resource. Required. Known - values are: "Running", "Completed", "Canceled", and "Failed". + values are: "NotStarted", "Running", "Succeeded", "Failed", and "Canceled". "endTime": "2020-02-20 00:00:00", # Optional. The end time of the operation. "error": { - "code": "str", # Optional. The error code. - "message": "str" # Optional. The error message. + "code": "str", # One of a server-defined set of error codes. + Required. + "message": "str", # A human-readable representation of the error. + Required. + "details": [ + ... + ], + "innererror": { + "code": "str", # Optional. One of a server-defined set of + error codes. + "innererror": ... + }, + "target": "str" # Optional. The target of the error. }, - "id": "str", # Optional. Fully qualified ID for the operation status. - "name": "str", # Optional. The operation id name. "percentComplete": 0.0, # Optional. Percent of the operation that is complete. "properties": {}, # Optional. Custom operation properties, populated only @@ -2540,7 +2727,7 @@ async def begin_restart_dev_box( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.OperationDetails] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) @@ -2563,10 +2750,7 @@ def get_long_running_output(pipeline_response): "str", response.headers.get("Operation-Location") ) - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.OperationDetails, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized @@ -2585,16 +2769,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller[JSON].from_continuation_token( + return AsyncLROPoller[_models.OperationDetails].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller[JSON](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return AsyncLROPoller[_models.OperationDetails]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) @distributed_trace_async - async def get_remote_connection(self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any) -> JSON: + async def get_remote_connection( + self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any + ) -> _models.RemoteConnection: """Gets RDP Connection info. :param project_name: The DevCenter Project upon which to execute operations. Required. @@ -2604,10 +2792,8 @@ async def get_remote_connection(self, project_name: str, user_id: str, dev_box_n :type user_id: str :param dev_box_name: The name of a Dev Box. Required. :type dev_box_name: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: JSON object - :rtype: JSON + :return: RemoteConnection. The RemoteConnection is compatible with MutableMapping + :rtype: ~azure.developer.devcenter.models.RemoteConnection :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -2620,7 +2806,7 @@ async def get_remote_connection(self, project_name: str, user_id: str, dev_box_n "webUrl": "str" # Optional. URL to open a browser based RDP session. } """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2631,7 +2817,7 @@ async def get_remote_connection(self, project_name: str, user_id: str, dev_box_n _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.RemoteConnection] = kwargs.pop("cls", None) _request = build_dev_center_get_remote_connection_request( project_name=project_name, @@ -2662,31 +2848,28 @@ async def get_remote_connection(self, project_name: str, user_id: str, dev_box_n if _stream: deserialized = response.iter_bytes() else: - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.RemoteConnection, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore @distributed_trace def list_dev_box_actions( self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any - ) -> AsyncIterable[JSON]: + ) -> AsyncIterable["_models.DevBoxAction"]: """Lists actions on a Dev Box. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str - :param dev_box_name: The name of a Dev Box. Required. + :param dev_box_name: Display name for the Dev Box. Required. :type dev_box_name: str - :return: An iterator like instance of JSON object - :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON] + :return: An iterator like instance of DevBoxAction + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.developer.devcenter.models.DevBoxAction] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -2709,9 +2892,9 @@ def list_dev_box_actions( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[JSON]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.DevBoxAction]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2761,7 +2944,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["value"] + list_of_elem = _deserialize(List[_models.DevBoxAction], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -2788,22 +2971,20 @@ async def get_next(next_link=None): @distributed_trace_async async def get_dev_box_action( self, project_name: str, user_id: str, dev_box_name: str, action_name: str, **kwargs: Any - ) -> JSON: + ) -> _models.DevBoxAction: """Gets an action. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str - :param dev_box_name: The name of a Dev Box. Required. + :param dev_box_name: Display name for the Dev Box. Required. :type dev_box_name: str - :param action_name: The name of an action that will take place on a Dev Box. Required. + :param action_name: The name of the action. Required. :type action_name: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: JSON object - :rtype: JSON + :return: DevBoxAction. The DevBoxAction is compatible with MutableMapping + :rtype: ~azure.developer.devcenter.models.DevBoxAction :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -2823,7 +3004,7 @@ async def get_dev_box_action( the action could occur (UTC). } """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2834,7 +3015,7 @@ async def get_dev_box_action( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.DevBoxAction] = kwargs.pop("cls", None) _request = build_dev_center_get_dev_box_action_request( project_name=project_name, @@ -2866,15 +3047,12 @@ async def get_dev_box_action( if _stream: deserialized = response.iter_bytes() else: - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.DevBoxAction, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore @distributed_trace_async async def skip_dev_box_action( # pylint: disable=inconsistent-return-statements @@ -2882,22 +3060,20 @@ async def skip_dev_box_action( # pylint: disable=inconsistent-return-statements ) -> None: """Skips an occurrence of an action. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str - :param dev_box_name: The name of a Dev Box. Required. + :param dev_box_name: Display name for the Dev Box. Required. :type dev_box_name: str - :param action_name: The name of an action that will take place on a Dev Box. Required. + :param action_name: The name of the action. Required. :type action_name: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2924,7 +3100,7 @@ async def skip_dev_box_action( # pylint: disable=inconsistent-return-statements } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = kwargs.pop("stream", False) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -2950,24 +3126,22 @@ async def delay_dev_box_action( *, delay_until: datetime.datetime, **kwargs: Any - ) -> JSON: + ) -> _models.DevBoxAction: """Delays the occurrence of an action. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str - :param dev_box_name: The name of a Dev Box. Required. + :param dev_box_name: Display name for the Dev Box. Required. :type dev_box_name: str - :param action_name: The name of an action that will take place on a Dev Box. Required. + :param action_name: The name of the action. Required. :type action_name: str :keyword delay_until: The time to delay the Dev Box action or actions until. Required. :paramtype delay_until: ~datetime.datetime - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: JSON object - :rtype: JSON + :return: DevBoxAction. The DevBoxAction is compatible with MutableMapping + :rtype: ~azure.developer.devcenter.models.DevBoxAction :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -2987,7 +3161,7 @@ async def delay_dev_box_action( the action could occur (UTC). } """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2998,7 +3172,7 @@ async def delay_dev_box_action( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.DevBoxAction] = kwargs.pop("cls", None) _request = build_dev_center_delay_dev_box_action_request( project_name=project_name, @@ -3031,33 +3205,32 @@ async def delay_dev_box_action( if _stream: deserialized = response.iter_bytes() else: - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.DevBoxAction, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore @distributed_trace def delay_all_dev_box_actions( self, project_name: str, user_id: str, dev_box_name: str, *, delay_until: datetime.datetime, **kwargs: Any - ) -> AsyncIterable[JSON]: + ) -> AsyncIterable["_models.DevBoxActionDelayResult"]: + # pylint: disable=line-too-long """Delays all actions. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str - :param dev_box_name: The name of a Dev Box. Required. + :param dev_box_name: Display name for the Dev Box. Required. :type dev_box_name: str :keyword delay_until: The time to delay the Dev Box action or actions until. Required. :paramtype delay_until: ~datetime.datetime - :return: An iterator like instance of JSON object - :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON] + :return: An iterator like instance of DevBoxActionDelayResult + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.developer.devcenter.models.DevBoxActionDelayResult] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -3101,9 +3274,9 @@ def delay_all_dev_box_actions( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[JSON]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.DevBoxActionDelayResult]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3154,7 +3327,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["value"] + list_of_elem = _deserialize(List[_models.DevBoxActionDelayResult], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -3179,18 +3352,14 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) @distributed_trace - def list_all_environments( - self, project_name: str, *, top: Optional[int] = None, **kwargs: Any - ) -> AsyncIterable[JSON]: + def list_all_environments(self, project_name: str, **kwargs: Any) -> AsyncIterable["_models.Environment"]: + # pylint: disable=line-too-long """Lists the environments for a project. :param project_name: The DevCenter Project upon which to execute operations. Required. :type project_name: str - :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. - Default value is None. - :paramtype top: int - :return: An iterator like instance of JSON object - :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON] + :return: An iterator like instance of Environment + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.developer.devcenter.models.Environment] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -3202,6 +3371,7 @@ def list_all_environments( "environmentDefinitionName": "str", # Name of the environment definition. Required. "environmentType": "str", # Environment type. Required. + "name": "str", # Environment name. Required. "error": { "code": "str", # One of a server-defined set of error codes. Required. @@ -3217,10 +3387,13 @@ def list_all_environments( }, "target": "str" # Optional. The target of the error. }, - "name": "str", # Optional. Environment name. - "parameters": {}, # Optional. Parameters object for the environment. + "parameters": { + "str": {} # Optional. Parameters object for the environment. + }, "provisioningState": "str", # Optional. The provisioning state of the - environment. + environment. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Accepted", "Deleting", "Updating", "Preparing", "Running", "Syncing", + "MovingResources", "TransientFailure", and "StorageProvisioningFailed". "resourceGroupId": "str", # Optional. The identifier of the resource group containing the environment's resources. "user": "str" # Optional. The AAD object id of the owner of this @@ -3230,9 +3403,9 @@ def list_all_environments( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[JSON]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.Environment]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3245,7 +3418,6 @@ def prepare_request(next_link=None): _request = build_dev_center_list_all_environments_request( project_name=project_name, - top=top, api_version=self._config.api_version, headers=_headers, params=_params, @@ -3281,7 +3453,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["value"] + list_of_elem = _deserialize(List[_models.Environment], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -3306,9 +3478,8 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) @distributed_trace - def list_environments( - self, project_name: str, user_id: str, *, top: Optional[int] = None, **kwargs: Any - ) -> AsyncIterable[JSON]: + def list_environments(self, project_name: str, user_id: str, **kwargs: Any) -> AsyncIterable["_models.Environment"]: + # pylint: disable=line-too-long """Lists the environments for a project and user. :param project_name: The DevCenter Project upon which to execute operations. Required. @@ -3316,11 +3487,8 @@ def list_environments( :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str - :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. - Default value is None. - :paramtype top: int - :return: An iterator like instance of JSON object - :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON] + :return: An iterator like instance of Environment + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.developer.devcenter.models.Environment] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -3332,6 +3500,7 @@ def list_environments( "environmentDefinitionName": "str", # Name of the environment definition. Required. "environmentType": "str", # Environment type. Required. + "name": "str", # Environment name. Required. "error": { "code": "str", # One of a server-defined set of error codes. Required. @@ -3347,10 +3516,13 @@ def list_environments( }, "target": "str" # Optional. The target of the error. }, - "name": "str", # Optional. Environment name. - "parameters": {}, # Optional. Parameters object for the environment. + "parameters": { + "str": {} # Optional. Parameters object for the environment. + }, "provisioningState": "str", # Optional. The provisioning state of the - environment. + environment. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Accepted", "Deleting", "Updating", "Preparing", "Running", "Syncing", + "MovingResources", "TransientFailure", and "StorageProvisioningFailed". "resourceGroupId": "str", # Optional. The identifier of the resource group containing the environment's resources. "user": "str" # Optional. The AAD object id of the owner of this @@ -3360,9 +3532,9 @@ def list_environments( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[JSON]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.Environment]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3376,7 +3548,6 @@ def prepare_request(next_link=None): _request = build_dev_center_list_environments_request( project_name=project_name, user_id=user_id, - top=top, api_version=self._config.api_version, headers=_headers, params=_params, @@ -3412,7 +3583,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["value"] + list_of_elem = _deserialize(List[_models.Environment], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -3437,20 +3608,21 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) @distributed_trace_async - async def get_environment(self, project_name: str, user_id: str, environment_name: str, **kwargs: Any) -> JSON: + async def get_environment( + self, project_name: str, user_id: str, environment_name: str, **kwargs: Any + ) -> _models.Environment: + # pylint: disable=line-too-long """Gets an environment. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the authentication context. Required. :type user_id: str - :param environment_name: The name of the environment. Required. + :param environment_name: Environment name. Required. :type environment_name: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: JSON object - :rtype: JSON + :return: Environment. The Environment is compatible with MutableMapping + :rtype: ~azure.developer.devcenter.models.Environment :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -3462,6 +3634,7 @@ async def get_environment(self, project_name: str, user_id: str, environment_nam "environmentDefinitionName": "str", # Name of the environment definition. Required. "environmentType": "str", # Environment type. Required. + "name": "str", # Environment name. Required. "error": { "code": "str", # One of a server-defined set of error codes. Required. @@ -3477,17 +3650,20 @@ async def get_environment(self, project_name: str, user_id: str, environment_nam }, "target": "str" # Optional. The target of the error. }, - "name": "str", # Optional. Environment name. - "parameters": {}, # Optional. Parameters object for the environment. + "parameters": { + "str": {} # Optional. Parameters object for the environment. + }, "provisioningState": "str", # Optional. The provisioning state of the - environment. + environment. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Accepted", "Deleting", "Updating", "Preparing", "Running", "Syncing", + "MovingResources", "TransientFailure", and "StorageProvisioningFailed". "resourceGroupId": "str", # Optional. The identifier of the resource group containing the environment's resources. "user": "str" # Optional. The AAD object id of the owner of this Environment. } """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3498,7 +3674,7 @@ async def get_environment(self, project_name: str, user_id: str, environment_nam _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.Environment] = kwargs.pop("cls", None) _request = build_dev_center_get_environment_request( project_name=project_name, @@ -3529,20 +3705,22 @@ async def get_environment(self, project_name: str, user_id: str, environment_nam if _stream: deserialized = response.iter_bytes() else: - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.Environment, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore async def _create_or_update_environment_initial( - self, project_name: str, user_id: str, environment_name: str, body: Union[JSON, IO], **kwargs: Any + self, + project_name: str, + user_id: str, + environment_name: str, + body: Union[_models.Environment, JSON, IO[bytes]], + **kwargs: Any ) -> JSON: - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3557,12 +3735,11 @@ async def _create_or_update_environment_initial( cls: ClsType[JSON] = kwargs.pop("cls", None) content_type = content_type or "application/json" - _json = None _content = None if isinstance(body, (IOBase, bytes)): _content = body else: - _json = body + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_dev_center_create_or_update_environment_request( project_name=project_name, @@ -3570,7 +3747,6 @@ async def _create_or_update_environment_initial( environment_name=environment_name, content_type=content_type, api_version=self._config.api_version, - json=_json, content=_content, headers=_headers, params=_params, @@ -3596,15 +3772,12 @@ async def _create_or_update_environment_initial( response_headers = {} response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(JSON, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), response_headers) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore @overload async def begin_create_or_update_environment( @@ -3612,11 +3785,12 @@ async def begin_create_or_update_environment( project_name: str, user_id: str, environment_name: str, - body: JSON, + body: _models.Environment, *, content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller[JSON]: + ) -> AsyncLROPoller[_models.Environment]: + # pylint: disable=line-too-long """Creates or updates an environment. :param project_name: The DevCenter Project upon which to execute operations. Required. @@ -3627,19 +3801,13 @@ async def begin_create_or_update_environment( :param environment_name: The name of the environment. Required. :type environment_name: str :param body: Represents an environment. Required. - :type body: JSON + :type body: ~azure.developer.devcenter.models.Environment :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False - for this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns JSON object - :rtype: ~azure.core.polling.AsyncLROPoller[JSON] + :return: An instance of AsyncLROPoller that returns Environment. The Environment is compatible + with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.developer.devcenter.models.Environment] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -3651,6 +3819,42 @@ async def begin_create_or_update_environment( "environmentDefinitionName": "str", # Name of the environment definition. Required. "environmentType": "str", # Environment type. Required. + "name": "str", # Environment name. Required. + "error": { + "code": "str", # One of a server-defined set of error codes. + Required. + "message": "str", # A human-readable representation of the error. + Required. + "details": [ + ... + ], + "innererror": { + "code": "str", # Optional. One of a server-defined set of + error codes. + "innererror": ... + }, + "target": "str" # Optional. The target of the error. + }, + "parameters": { + "str": {} # Optional. Parameters object for the environment. + }, + "provisioningState": "str", # Optional. The provisioning state of the + environment. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Accepted", "Deleting", "Updating", "Preparing", "Running", "Syncing", + "MovingResources", "TransientFailure", and "StorageProvisioningFailed". + "resourceGroupId": "str", # Optional. The identifier of the resource group + containing the environment's resources. + "user": "str" # Optional. The AAD object id of the owner of this + Environment. + } + + # response body for status code(s): 201 + response == { + "catalogName": "str", # Name of the catalog. Required. + "environmentDefinitionName": "str", # Name of the environment definition. + Required. + "environmentType": "str", # Environment type. Required. + "name": "str", # Environment name. Required. "error": { "code": "str", # One of a server-defined set of error codes. Required. @@ -3666,15 +3870,53 @@ async def begin_create_or_update_environment( }, "target": "str" # Optional. The target of the error. }, - "name": "str", # Optional. Environment name. - "parameters": {}, # Optional. Parameters object for the environment. + "parameters": { + "str": {} # Optional. Parameters object for the environment. + }, "provisioningState": "str", # Optional. The provisioning state of the - environment. + environment. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Accepted", "Deleting", "Updating", "Preparing", "Running", "Syncing", + "MovingResources", "TransientFailure", and "StorageProvisioningFailed". "resourceGroupId": "str", # Optional. The identifier of the resource group containing the environment's resources. "user": "str" # Optional. The AAD object id of the owner of this Environment. } + """ + + @overload + async def begin_create_or_update_environment( + self, + project_name: str, + user_id: str, + environment_name: str, + body: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.Environment]: + # pylint: disable=line-too-long + """Creates or updates an environment. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Required. + :type user_id: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Represents an environment. Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns Environment. The Environment is compatible + with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.developer.devcenter.models.Environment] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python # response body for status code(s): 201 response == { @@ -3682,6 +3924,7 @@ async def begin_create_or_update_environment( "environmentDefinitionName": "str", # Name of the environment definition. Required. "environmentType": "str", # Environment type. Required. + "name": "str", # Environment name. Required. "error": { "code": "str", # One of a server-defined set of error codes. Required. @@ -3697,10 +3940,13 @@ async def begin_create_or_update_environment( }, "target": "str" # Optional. The target of the error. }, - "name": "str", # Optional. Environment name. - "parameters": {}, # Optional. Parameters object for the environment. + "parameters": { + "str": {} # Optional. Parameters object for the environment. + }, "provisioningState": "str", # Optional. The provisioning state of the - environment. + environment. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Accepted", "Deleting", "Updating", "Preparing", "Running", "Syncing", + "MovingResources", "TransientFailure", and "StorageProvisioningFailed". "resourceGroupId": "str", # Optional. The identifier of the resource group containing the environment's resources. "user": "str" # Optional. The AAD object id of the owner of this @@ -3714,11 +3960,12 @@ async def begin_create_or_update_environment( project_name: str, user_id: str, environment_name: str, - body: IO, + body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller[JSON]: + ) -> AsyncLROPoller[_models.Environment]: + # pylint: disable=line-too-long """Creates or updates an environment. :param project_name: The DevCenter Project upon which to execute operations. Required. @@ -3729,19 +3976,13 @@ async def begin_create_or_update_environment( :param environment_name: The name of the environment. Required. :type environment_name: str :param body: Represents an environment. Required. - :type body: IO + :type body: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False - for this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns JSON object - :rtype: ~azure.core.polling.AsyncLROPoller[JSON] + :return: An instance of AsyncLROPoller that returns Environment. The Environment is compatible + with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.developer.devcenter.models.Environment] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -3753,6 +3994,7 @@ async def begin_create_or_update_environment( "environmentDefinitionName": "str", # Name of the environment definition. Required. "environmentType": "str", # Environment type. Required. + "name": "str", # Environment name. Required. "error": { "code": "str", # One of a server-defined set of error codes. Required. @@ -3768,10 +4010,13 @@ async def begin_create_or_update_environment( }, "target": "str" # Optional. The target of the error. }, - "name": "str", # Optional. Environment name. - "parameters": {}, # Optional. Parameters object for the environment. + "parameters": { + "str": {} # Optional. Parameters object for the environment. + }, "provisioningState": "str", # Optional. The provisioning state of the - environment. + environment. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Accepted", "Deleting", "Updating", "Preparing", "Running", "Syncing", + "MovingResources", "TransientFailure", and "StorageProvisioningFailed". "resourceGroupId": "str", # Optional. The identifier of the resource group containing the environment's resources. "user": "str" # Optional. The AAD object id of the owner of this @@ -3781,8 +4026,14 @@ async def begin_create_or_update_environment( @distributed_trace_async async def begin_create_or_update_environment( - self, project_name: str, user_id: str, environment_name: str, body: Union[JSON, IO], **kwargs: Any - ) -> AsyncLROPoller[JSON]: + self, + project_name: str, + user_id: str, + environment_name: str, + body: Union[_models.Environment, JSON, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.Environment]: + # pylint: disable=line-too-long """Creates or updates an environment. :param project_name: The DevCenter Project upon which to execute operations. Required. @@ -3792,20 +4043,12 @@ async def begin_create_or_update_environment( :type user_id: str :param environment_name: The name of the environment. Required. :type environment_name: str - :param body: Represents an environment. Is either a JSON type or a IO type. Required. - :type body: JSON or IO - :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default - value is None. - :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False - for this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns JSON object - :rtype: ~azure.core.polling.AsyncLROPoller[JSON] + :param body: Represents an environment. Is one of the following types: Environment, JSON, + IO[bytes] Required. + :type body: ~azure.developer.devcenter.models.Environment or JSON or IO[bytes] + :return: An instance of AsyncLROPoller that returns Environment. The Environment is compatible + with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.developer.devcenter.models.Environment] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -3817,6 +4060,7 @@ async def begin_create_or_update_environment( "environmentDefinitionName": "str", # Name of the environment definition. Required. "environmentType": "str", # Environment type. Required. + "name": "str", # Environment name. Required. "error": { "code": "str", # One of a server-defined set of error codes. Required. @@ -3832,10 +4076,13 @@ async def begin_create_or_update_environment( }, "target": "str" # Optional. The target of the error. }, - "name": "str", # Optional. Environment name. - "parameters": {}, # Optional. Parameters object for the environment. + "parameters": { + "str": {} # Optional. Parameters object for the environment. + }, "provisioningState": "str", # Optional. The provisioning state of the - environment. + environment. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Accepted", "Deleting", "Updating", "Preparing", "Running", "Syncing", + "MovingResources", "TransientFailure", and "StorageProvisioningFailed". "resourceGroupId": "str", # Optional. The identifier of the resource group containing the environment's resources. "user": "str" # Optional. The AAD object id of the owner of this @@ -3848,6 +4095,7 @@ async def begin_create_or_update_environment( "environmentDefinitionName": "str", # Name of the environment definition. Required. "environmentType": "str", # Environment type. Required. + "name": "str", # Environment name. Required. "error": { "code": "str", # One of a server-defined set of error codes. Required. @@ -3863,10 +4111,13 @@ async def begin_create_or_update_environment( }, "target": "str" # Optional. The target of the error. }, - "name": "str", # Optional. Environment name. - "parameters": {}, # Optional. Parameters object for the environment. + "parameters": { + "str": {} # Optional. Parameters object for the environment. + }, "provisioningState": "str", # Optional. The provisioning state of the - environment. + environment. Known values are: "Succeeded", "Failed", "Canceled", "Creating", + "Accepted", "Deleting", "Updating", "Preparing", "Running", "Syncing", + "MovingResources", "TransientFailure", and "StorageProvisioningFailed". "resourceGroupId": "str", # Optional. The identifier of the resource group containing the environment's resources. "user": "str" # Optional. The AAD object id of the owner of this @@ -3877,7 +4128,7 @@ async def begin_create_or_update_environment( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.Environment] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) @@ -3902,10 +4153,7 @@ def get_long_running_output(pipeline_response): "str", response.headers.get("Operation-Location") ) - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.Environment, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized @@ -3924,18 +4172,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller[JSON].from_continuation_token( + return AsyncLROPoller[_models.Environment].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller[JSON](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return AsyncLROPoller[_models.Environment]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) async def _delete_environment_initial( self, project_name: str, user_id: str, environment_name: str, **kwargs: Any ) -> Optional[JSON]: - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3982,10 +4232,7 @@ async def _delete_environment_initial( "str", response.headers.get("Operation-Location") ) - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(JSON, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -3995,7 +4242,8 @@ async def _delete_environment_initial( @distributed_trace_async async def begin_delete_environment( self, project_name: str, user_id: str, environment_name: str, **kwargs: Any - ) -> AsyncLROPoller[JSON]: + ) -> AsyncLROPoller[_models.OperationDetails]: + # pylint: disable=line-too-long """Deletes an environment and all its associated resources. :param project_name: The DevCenter Project upon which to execute operations. Required. @@ -4005,15 +4253,9 @@ async def begin_delete_environment( :type user_id: str :param environment_name: The name of the environment. Required. :type environment_name: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False - for this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns JSON object - :rtype: ~azure.core.polling.AsyncLROPoller[JSON] + :return: An instance of AsyncLROPoller that returns OperationDetails. The OperationDetails is + compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.developer.devcenter.models.OperationDetails] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -4021,15 +4263,26 @@ async def begin_delete_environment( # response body for status code(s): 202 response == { + "id": "str", # Fully qualified ID for the operation status. Required. + "name": "str", # The operation id name. Required. "status": "str", # Provisioning state of the resource. Required. Known - values are: "Running", "Completed", "Canceled", and "Failed". + values are: "NotStarted", "Running", "Succeeded", "Failed", and "Canceled". "endTime": "2020-02-20 00:00:00", # Optional. The end time of the operation. "error": { - "code": "str", # Optional. The error code. - "message": "str" # Optional. The error message. + "code": "str", # One of a server-defined set of error codes. + Required. + "message": "str", # A human-readable representation of the error. + Required. + "details": [ + ... + ], + "innererror": { + "code": "str", # Optional. One of a server-defined set of + error codes. + "innererror": ... + }, + "target": "str" # Optional. The target of the error. }, - "id": "str", # Optional. Fully qualified ID for the operation status. - "name": "str", # Optional. The operation id name. "percentComplete": 0.0, # Optional. Percent of the operation that is complete. "properties": {}, # Optional. Custom operation properties, populated only @@ -4042,7 +4295,7 @@ async def begin_delete_environment( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.OperationDetails] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) @@ -4066,10 +4319,7 @@ def get_long_running_output(pipeline_response): "str", response.headers.get("Operation-Location") ) - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.OperationDetails, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized @@ -4088,25 +4338,24 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller[JSON].from_continuation_token( + return AsyncLROPoller[_models.OperationDetails].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller[JSON](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return AsyncLROPoller[_models.OperationDetails]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) @distributed_trace - def list_catalogs(self, project_name: str, *, top: Optional[int] = None, **kwargs: Any) -> AsyncIterable[JSON]: + def list_catalogs(self, project_name: str, **kwargs: Any) -> AsyncIterable["_models.Catalog"]: """Lists all of the catalogs available for a project. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str - :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. - Default value is None. - :paramtype top: int - :return: An iterator like instance of JSON object - :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON] + :return: An iterator like instance of Catalog + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.developer.devcenter.models.Catalog] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -4120,9 +4369,9 @@ def list_catalogs(self, project_name: str, *, top: Optional[int] = None, **kwarg _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[JSON]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.Catalog]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4135,7 +4384,6 @@ def prepare_request(next_link=None): _request = build_dev_center_list_catalogs_request( project_name=project_name, - top=top, api_version=self._config.api_version, headers=_headers, params=_params, @@ -4171,7 +4419,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["value"] + list_of_elem = _deserialize(List[_models.Catalog], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -4196,17 +4444,15 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) @distributed_trace_async - async def get_catalog(self, project_name: str, catalog_name: str, **kwargs: Any) -> JSON: + async def get_catalog(self, project_name: str, catalog_name: str, **kwargs: Any) -> _models.Catalog: """Gets the specified catalog within the project. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str - :param catalog_name: The name of the catalog. Required. + :param catalog_name: Name of the catalog. Required. :type catalog_name: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: JSON object - :rtype: JSON + :return: Catalog. The Catalog is compatible with MutableMapping + :rtype: ~azure.developer.devcenter.models.Catalog :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -4217,7 +4463,7 @@ async def get_catalog(self, project_name: str, catalog_name: str, **kwargs: Any) "name": "str" # Name of the catalog. Required. } """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4228,7 +4474,7 @@ async def get_catalog(self, project_name: str, catalog_name: str, **kwargs: Any) _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.Catalog] = kwargs.pop("cls", None) _request = build_dev_center_get_catalog_request( project_name=project_name, @@ -4258,29 +4504,25 @@ async def get_catalog(self, project_name: str, catalog_name: str, **kwargs: Any) if _stream: deserialized = response.iter_bytes() else: - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.Catalog, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore @distributed_trace def list_environment_definitions( - self, project_name: str, *, top: Optional[int] = None, **kwargs: Any - ) -> AsyncIterable[JSON]: + self, project_name: str, **kwargs: Any + ) -> AsyncIterable["_models.EnvironmentDefinition"]: + # pylint: disable=line-too-long """Lists all environment definitions available for a project. :param project_name: The DevCenter Project upon which to execute operations. Required. :type project_name: str - :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. - Default value is None. - :paramtype top: int - :return: An iterator like instance of JSON object - :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON] + :return: An iterator like instance of EnvironmentDefinition + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.developer.devcenter.models.EnvironmentDefinition] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -4322,9 +4564,9 @@ def list_environment_definitions( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[JSON]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.EnvironmentDefinition]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4337,7 +4579,6 @@ def prepare_request(next_link=None): _request = build_dev_center_list_environment_definitions_request( project_name=project_name, - top=top, api_version=self._config.api_version, headers=_headers, params=_params, @@ -4373,7 +4614,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["value"] + list_of_elem = _deserialize(List[_models.EnvironmentDefinition], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -4399,19 +4640,18 @@ async def get_next(next_link=None): @distributed_trace def list_environment_definitions_by_catalog( - self, project_name: str, catalog_name: str, *, top: Optional[int] = None, **kwargs: Any - ) -> AsyncIterable[JSON]: + self, project_name: str, catalog_name: str, **kwargs: Any + ) -> AsyncIterable["_models.EnvironmentDefinition"]: + # pylint: disable=line-too-long """Lists all environment definitions available within a catalog. :param project_name: The DevCenter Project upon which to execute operations. Required. :type project_name: str :param catalog_name: The name of the catalog. Required. :type catalog_name: str - :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. - Default value is None. - :paramtype top: int - :return: An iterator like instance of JSON object - :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON] + :return: An iterator like instance of EnvironmentDefinition + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.developer.devcenter.models.EnvironmentDefinition] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -4453,9 +4693,9 @@ def list_environment_definitions_by_catalog( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[JSON]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.EnvironmentDefinition]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4469,7 +4709,6 @@ def prepare_request(next_link=None): _request = build_dev_center_list_environment_definitions_by_catalog_request( project_name=project_name, catalog_name=catalog_name, - top=top, api_version=self._config.api_version, headers=_headers, params=_params, @@ -4505,7 +4744,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["value"] + list_of_elem = _deserialize(List[_models.EnvironmentDefinition], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -4532,19 +4771,18 @@ async def get_next(next_link=None): @distributed_trace_async async def get_environment_definition( self, project_name: str, catalog_name: str, definition_name: str, **kwargs: Any - ) -> JSON: + ) -> _models.EnvironmentDefinition: + # pylint: disable=line-too-long """Get an environment definition from a catalog. - :param project_name: The DevCenter Project upon which to execute operations. Required. + :param project_name: Name of the project. Required. :type project_name: str - :param catalog_name: The name of the catalog. Required. + :param catalog_name: Name of the catalog. Required. :type catalog_name: str - :param definition_name: The name of the environment definition. Required. + :param definition_name: Name of the environment definition. Required. :type definition_name: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: JSON object - :rtype: JSON + :return: EnvironmentDefinition. The EnvironmentDefinition is compatible with MutableMapping + :rtype: ~azure.developer.devcenter.models.EnvironmentDefinition :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -4583,7 +4821,7 @@ async def get_environment_definition( entrypoint file. } """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4594,7 +4832,7 @@ async def get_environment_definition( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[_models.EnvironmentDefinition] = kwargs.pop("cls", None) _request = build_dev_center_get_environment_definition_request( project_name=project_name, @@ -4625,29 +4863,23 @@ async def get_environment_definition( if _stream: deserialized = response.iter_bytes() else: - if response.content: - deserialized = response.json() - else: - deserialized = None + deserialized = _deserialize(_models.EnvironmentDefinition, response.json()) if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore - return cast(JSON, deserialized) # type: ignore + return deserialized # type: ignore @distributed_trace - def list_environment_types( - self, project_name: str, *, top: Optional[int] = None, **kwargs: Any - ) -> AsyncIterable[JSON]: + def list_environment_types(self, project_name: str, **kwargs: Any) -> AsyncIterable["_models.EnvironmentType"]: + # pylint: disable=line-too-long """Lists all environment types configured for a project. :param project_name: The DevCenter Project upon which to execute operations. Required. :type project_name: str - :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. - Default value is None. - :paramtype top: int - :return: An iterator like instance of JSON object - :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON] + :return: An iterator like instance of EnvironmentType + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.developer.devcenter.models.EnvironmentType] :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -4666,9 +4898,9 @@ def list_environment_types( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[JSON]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.EnvironmentType]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4681,7 +4913,6 @@ def prepare_request(next_link=None): _request = build_dev_center_list_environment_types_request( project_name=project_name, - top=top, api_version=self._config.api_version, headers=_headers, params=_params, @@ -4717,7 +4948,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["value"] + list_of_elem = _deserialize(List[_models.EnvironmentType], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/models/__init__.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/models/__init__.py new file mode 100644 index 000000000000..89f8c60752cf --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/models/__init__.py @@ -0,0 +1,91 @@ +# 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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._models import Catalog +from ._models import DevBox +from ._models import DevBoxAction +from ._models import DevBoxActionDelayResult +from ._models import DevBoxNextAction +from ._models import Environment +from ._models import EnvironmentDefinition +from ._models import EnvironmentDefinitionParameter +from ._models import EnvironmentType +from ._models import Error +from ._models import HardwareProfile +from ._models import ImageReference +from ._models import InnerError +from ._models import OSDisk +from ._models import OperationDetails +from ._models import Pool +from ._models import Project +from ._models import RemoteConnection +from ._models import Schedule +from ._models import StopOnDisconnectConfiguration +from ._models import StorageProfile + +from ._enums import DevBoxActionDelayStatus +from ._enums import DevBoxActionType +from ._enums import DevBoxProvisioningState +from ._enums import EnvironmentProvisioningState +from ._enums import EnvironmentTypeStatus +from ._enums import HibernateSupport +from ._enums import LocalAdministratorStatus +from ._enums import OSType +from ._enums import OperationStatus +from ._enums import ParameterType +from ._enums import PoolHealthStatus +from ._enums import PowerState +from ._enums import ScheduledFrequency +from ._enums import ScheduledType +from ._enums import SkuName +from ._enums import StopOnDisconnectStatus +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "Catalog", + "DevBox", + "DevBoxAction", + "DevBoxActionDelayResult", + "DevBoxNextAction", + "Environment", + "EnvironmentDefinition", + "EnvironmentDefinitionParameter", + "EnvironmentType", + "Error", + "HardwareProfile", + "ImageReference", + "InnerError", + "OSDisk", + "OperationDetails", + "Pool", + "Project", + "RemoteConnection", + "Schedule", + "StopOnDisconnectConfiguration", + "StorageProfile", + "DevBoxActionDelayStatus", + "DevBoxActionType", + "DevBoxProvisioningState", + "EnvironmentProvisioningState", + "EnvironmentTypeStatus", + "HibernateSupport", + "LocalAdministratorStatus", + "OSType", + "OperationStatus", + "ParameterType", + "PoolHealthStatus", + "PowerState", + "ScheduledFrequency", + "ScheduledType", + "SkuName", + "StopOnDisconnectStatus", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/models/_enums.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/models/_enums.py new file mode 100644 index 000000000000..ca1fa8869828 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/models/_enums.py @@ -0,0 +1,260 @@ +# 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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class DevBoxActionDelayStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The result of the delay operation on this action.""" + + SUCCEEDED = "Succeeded" + """The delay operation succeeded.""" + FAILED = "Failed" + """The delay operation failed.""" + + +class DevBoxActionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of action which will take place on a Dev Box.""" + + STOP = "Stop" + """The action will stop the Dev Box.""" + + +class DevBoxProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Indicates the provisioning state of the Dev Box.""" + + SUCCEEDED = "Succeeded" + """Dev Box was successfully provisioned.""" + FAILED = "Failed" + """Dev Box failed to provision.""" + CANCELED = "Canceled" + """Dev Box provision was canceled.""" + CREATING = "Creating" + """Dev Box is being created.""" + DELETING = "Deleting" + """Dev Box is being deleted.""" + UPDATING = "Updating" + """Dev Box is updating.""" + STARTING = "Starting" + """Dev Box is starting.""" + STOPPING = "Stopping" + """Dev Box is stopping.""" + PROVISIONING = "Provisioning" + """Dev Box is provisioning.""" + PROVISIONED_WITH_WARNING = "ProvisionedWithWarning" + """Dev Box was provisioned with warning.""" + IN_GRACE_PERIOD = "InGracePeriod" + """Dev Box is in grace period.""" + NOT_PROVISIONED = "NotProvisioned" + """Dev Box is not provisioned.""" + + +class EnvironmentProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The provisioning state of the environment.""" + + SUCCEEDED = "Succeeded" + """The environment was successfully provisioned.""" + FAILED = "Failed" + """The environment failed to provision.""" + CANCELED = "Canceled" + """The environment provisioning was canceled.""" + CREATING = "Creating" + """The environment is creating.""" + ACCEPTED = "Accepted" + """The environment was accepted.""" + DELETING = "Deleting" + """The environment is deleting.""" + UPDATING = "Updating" + """The environment is updating.""" + PREPARING = "Preparing" + """The environment is preparing.""" + RUNNING = "Running" + """The environment is running.""" + SYNCING = "Syncing" + """The environment is Syncing.""" + MOVING_RESOURCES = "MovingResources" + """The environment is moving resources.""" + TRANSIENT_FAILURE = "TransientFailure" + """The environment has a transient failure.""" + STORAGE_PROVISIONING_FAILED = "StorageProvisioningFailed" + """The environment storage provisioning failed.""" + + +class EnvironmentTypeStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Indicates whether an environment type is enabled for use in a project.""" + + ENABLED = "Enabled" + """The environment type is enabled for use in the project.""" + DISABLED = "Disabled" + """The environment type is not enabled for use in the project.""" + + +class HibernateSupport(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Indicates whether hibernate is supported and enabled, disabled, or unsupported by the operating + system. Unknown hibernate support is represented as null. + """ + + ENABLED = "Enabled" + """Hibernate is enabled.""" + DISABLED = "Disabled" + """Hibernate is not enabled.""" + OS_UNSUPPORTED = "OsUnsupported" + """Hibernate is not supported by the operating system.""" + + +class LocalAdministratorStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Indicates whether owners of Dev Boxes in a pool are local administrators on the Dev Boxes.""" + + ENABLED = "Enabled" + """Owners of Dev Boxes in the pool are local administrators on the Dev Boxes.""" + DISABLED = "Disabled" + """Owners of Dev Boxes in the pool are not local administrators on the Dev Boxes.""" + + +class OperationStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Enum describing allowed operation states.""" + + NOT_STARTED = "NotStarted" + """The operation has not started.""" + RUNNING = "Running" + """The operation is in progress.""" + SUCCEEDED = "Succeeded" + """The operation has completed successfully.""" + FAILED = "Failed" + """The operation has failed.""" + CANCELED = "Canceled" + """The operation has been canceled by the user.""" + + +class OSType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The operating system type.""" + + WINDOWS = "Windows" + """The Windows operating system.""" + + +class ParameterType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of data a parameter accepts.""" + + ARRAY = "array" + """The parameter accepts an array of values.""" + BOOLEAN = "boolean" + """The parameter accepts a boolean value.""" + INTEGER = "integer" + """The parameter accepts an integer value.""" + NUMBER = "number" + """The parameter accepts a number value.""" + OBJECT = "object" + """The parameter accepts an object value.""" + STRING = "string" + """The parameter accepts a string value.""" + + +class PoolHealthStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Pool status indicating whether a pool is available to create Dev Boxes.""" + + UNKNOWN = "Unknown" + """The pool health status is not known.""" + PENDING = "Pending" + """The pool health status waiting for health checks to run.""" + HEALTHY = "Healthy" + """The pool health status is healthy.""" + WARNING = "Warning" + """The pool health status has one or more warnings.""" + UNHEALTHY = "Unhealthy" + """The pool health status is not healthy.""" + + +class PowerState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The power states of a Dev Box.""" + + UNKNOWN = "Unknown" + """The Dev Box power state is not known.""" + RUNNING = "Running" + """The Dev Box is running.""" + DEALLOCATED = "Deallocated" + """The Dev Box is deallocated.""" + POWERED_OFF = "PoweredOff" + """The Dev Box is powered off.""" + HIBERNATED = "Hibernated" + """The Dev Box is hibernated.""" + + +class ScheduledFrequency(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The frequency of task execution.""" + + DAILY = "Daily" + """The scheduled task will run every day.""" + + +class ScheduledType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The supported types for a scheduled task.""" + + STOP_DEV_BOX = "StopDevBox" + """The scheduled task will stop impacted Dev Boxes.""" + + +class SkuName(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Indicates the Dev Box compute.""" + + GENERAL_I_8C32GB256SSD_V2 = "general_i_8c32gb256ssd_v2" + """Intel, 8 vCPU, 32 GB RAM, 256 GB Storage.""" + GENERAL_I_8C32GB512SSD_V2 = "general_i_8c32gb512ssd_v2" + """Intel, 8 vCPU, 32 GB RAM, 512 GB Storage.""" + GENERAL_I_8C32GB1024SSD_V2 = "general_i_8c32gb1024ssd_v2" + """Intel, 8 vCPU, 32 GB RAM, 1024 GB Storage.""" + GENERAL_I_8C32GB2048SSD_V2 = "general_i_8c32gb2048ssd_v2" + """Intel, 8 vCPU, 32 GB RAM, 2048 GB Storage.""" + GENERAL_I_16C64GB256SSD_V2 = "general_i_16c64gb256ssd_v2" + """Intel, 16 vCPU, 64 GB RAM, 256 GB Storage.""" + GENERAL_I_16C64GB512SSD_V2 = "general_i_16c64gb512ssd_v2" + """Intel, 16 vCPU, 64 GB RAM, 512 GB Storage.""" + GENERAL_I_16C64GB1024SSD_V2 = "general_i_16c64gb1024ssd_v2" + """Intel, 16 vCPU, 64 GB RAM, 1024 GB Storage.""" + GENERAL_I_16C64GB2048SSD_V2 = "general_i_16c64gb2048ssd_v2" + """Intel, 16 vCPU, 64 GB RAM, 2048 GB Storage.""" + GENERAL_I_32C128GB512SSD_V2 = "general_i_32c128gb512ssd_v2" + """Intel, 32 vCPU, 128 GB RAM, 512 GB Storage.""" + GENERAL_I_32C128GB1024SSD_V2 = "general_i_32c128gb1024ssd_v2" + """Intel, 32 vCPU, 128 GB RAM, 1024 GB Storage.""" + GENERAL_I_32C128GB2048SSD_V2 = "general_i_32c128gb2048ssd_v2" + """Intel, 32 vCPU, 128 GB RAM, 2048 GB Storage.""" + GENERAL_A_8C32GB256SSD_V2 = "general_a_8c32gb256ssd_v2" + """AMD, 8 vCPU, 32 GB RAM, 256 GB Storage.""" + GENERAL_A_8C32GB512SSD_V2 = "general_a_8c32gb512ssd_v2" + """AMD, 8 vCPU, 32 GB RAM, 512 GB Storage.""" + GENERAL_A_8C32GB1024SSD_V2 = "general_a_8c32gb1024ssd_v2" + """AMD, 8 vCPU, 32 GB RAM, 1024 GB Storage.""" + GENERAL_A_8C32GB2048SSD_V2 = "general_a_8c32gb2048ssd_v2" + """AMD, 8 vCPU, 32 GB RAM, 2048 GB Storage.""" + GENERAL_A_16C64GB256SSD_V2 = "general_a_16c64gb256ssd_v2" + """AMD, 16 vCPU, 64 GB RAM, 256 GB Storage.""" + GENERAL_A_16C64GB512SSD_V2 = "general_a_16c64gb512ssd_v2" + """AMD, 16 vCPU, 64 GB RAM, 512 GB Storage.""" + GENERAL_A_16C64GB1024SSD_V2 = "general_a_16c64gb1024ssd_v2" + """AMD, 16 vCPU, 64 GB RAM, 1024 GB Storage.""" + GENERAL_A_16C64GB2048SSD_V2 = "general_a_16c64gb2048ssd_v2" + """AMD, 16 vCPU, 64 GB RAM, 2048 GB Storage.""" + GENERAL_A_32C128GB512SSD_V2 = "general_a_32c128gb512ssd_v2" + """AMD, 32 vCPU, 128 GB RAM, 512 GB Storage.""" + GENERAL_A_32C128GB1024SSD_V2 = "general_a_32c128gb1024ssd_v2" + """AMD, 32 vCPU, 128 GB RAM, 1024 GB Storage.""" + GENERAL_A_32C128GB2048SSD_V2 = "general_a_32c128gb2048ssd_v2" + """AMD, 32 vCPU, 128 GB RAM, 2048 GB Storage.""" + + +class StopOnDisconnectStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Indicates whether the feature to stop the devbox on disconnect once the grace period has lapsed + is enabled. + """ + + ENABLED = "Enabled" + """Stop on disconnect is enabled on the Dev Box.""" + DISABLED = "Disabled" + """Stop on disconnect is not enabled on the Dev Box.""" diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/models/_models.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/models/_models.py new file mode 100644 index 000000000000..9154decbf8f0 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/models/_models.py @@ -0,0 +1,1059 @@ +# coding=utf-8 +# pylint: disable=too-many-lines +# -------------------------------------------------------------------------- +# 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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import datetime +from typing import Any, Dict, List, Mapping, Optional, TYPE_CHECKING, Union, overload + +from .. import _model_base +from .._model_base import rest_field + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models + + +class Catalog(_model_base.Model): + """A catalog. + + Readonly variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar name: Name of the catalog. Required. + :vartype name: str + """ + + name: str = rest_field(visibility=["read"]) + """Name of the catalog. Required.""" + + +class DevBox(_model_base.Model): # pylint: disable=too-many-instance-attributes + """A Dev Box. + + Readonly variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar name: Display name for the Dev Box. Required. + :vartype name: str + :ivar project_name: Name of the project this Dev Box belongs to. + :vartype project_name: str + :ivar pool_name: The name of the Dev Box pool this machine belongs to. Required. + :vartype pool_name: str + :ivar hibernate_support: Indicates whether hibernate is enabled/disabled or unknown. Known + values are: "Enabled", "Disabled", and "OsUnsupported". + :vartype hibernate_support: str or ~azure.developer.devcenter.models.HibernateSupport + :ivar provisioning_state: The current provisioning state of the Dev Box. Known values are: + "Succeeded", "Failed", "Canceled", "Creating", "Deleting", "Updating", "Starting", "Stopping", + "Provisioning", "ProvisionedWithWarning", "InGracePeriod", and "NotProvisioned". + :vartype provisioning_state: str or ~azure.developer.devcenter.models.DevBoxProvisioningState + :ivar action_state: The current action state of the Dev Box. This is state is based on previous + action performed by user. + :vartype action_state: str + :ivar power_state: The current power state of the Dev Box. Known values are: "Unknown", + "Running", "Deallocated", "PoweredOff", and "Hibernated". + :vartype power_state: str or ~azure.developer.devcenter.models.PowerState + :ivar unique_id: A unique identifier for the Dev Box. This is a GUID-formatted string (e.g. + 00000000-0000-0000-0000-000000000000). + :vartype unique_id: str + :ivar error: Provisioning or action error details. Populated only for error states. + :vartype error: ~azure.developer.devcenter.models.Error + :ivar location: Azure region where this Dev Box is located. This will be the same region as the + Virtual Network it is attached to. + :vartype location: str + :ivar os_type: The operating system type of this Dev Box. "Windows" + :vartype os_type: str or ~azure.developer.devcenter.models.OSType + :ivar user: The AAD object id of the user this Dev Box is assigned to. + :vartype user: str + :ivar hardware_profile: Information about the Dev Box's hardware resources. + :vartype hardware_profile: ~azure.developer.devcenter.models.HardwareProfile + :ivar storage_profile: Storage settings for this Dev Box. + :vartype storage_profile: ~azure.developer.devcenter.models.StorageProfile + :ivar image_reference: Information about the image used for this Dev Box. + :vartype image_reference: ~azure.developer.devcenter.models.ImageReference + :ivar created_time: Creation time of this Dev Box. + :vartype created_time: ~datetime.datetime + :ivar local_administrator: Indicates whether the owner of the Dev Box is a local administrator. + Known values are: "Enabled" and "Disabled". + :vartype local_administrator: str or ~azure.developer.devcenter.models.LocalAdministratorStatus + """ + + name: str = rest_field(visibility=["read"]) + """Display name for the Dev Box. Required.""" + project_name: Optional[str] = rest_field(name="projectName", visibility=["read"]) + """Name of the project this Dev Box belongs to.""" + pool_name: str = rest_field(name="poolName", visibility=["read", "create"]) + """The name of the Dev Box pool this machine belongs to. Required.""" + hibernate_support: Optional[Union[str, "_models.HibernateSupport"]] = rest_field( + name="hibernateSupport", visibility=["read"] + ) + """Indicates whether hibernate is enabled/disabled or unknown. Known values are: \"Enabled\", + \"Disabled\", and \"OsUnsupported\".""" + provisioning_state: Optional[Union[str, "_models.DevBoxProvisioningState"]] = rest_field( + name="provisioningState", visibility=["read"] + ) + """The current provisioning state of the Dev Box. Known values are: \"Succeeded\", \"Failed\", + \"Canceled\", \"Creating\", \"Deleting\", \"Updating\", \"Starting\", \"Stopping\", + \"Provisioning\", \"ProvisionedWithWarning\", \"InGracePeriod\", and \"NotProvisioned\".""" + action_state: Optional[str] = rest_field(name="actionState", visibility=["read"]) + """The current action state of the Dev Box. This is state is based on previous + action performed by user.""" + power_state: Optional[Union[str, "_models.PowerState"]] = rest_field(name="powerState", visibility=["read"]) + """The current power state of the Dev Box. Known values are: \"Unknown\", \"Running\", + \"Deallocated\", \"PoweredOff\", and \"Hibernated\".""" + unique_id: Optional[str] = rest_field(name="uniqueId", visibility=["read"]) + """A unique identifier for the Dev Box. This is a GUID-formatted string (e.g. + 00000000-0000-0000-0000-000000000000).""" + error: Optional["_models.Error"] = rest_field(visibility=["read"]) + """Provisioning or action error details. Populated only for error states.""" + location: Optional[str] = rest_field(visibility=["read"]) + """Azure region where this Dev Box is located. This will be the same region as the + Virtual Network it is attached to.""" + os_type: Optional[Union[str, "_models.OSType"]] = rest_field(name="osType", visibility=["read"]) + """The operating system type of this Dev Box. \"Windows\"""" + user: Optional[str] = rest_field(visibility=["read"]) + """The AAD object id of the user this Dev Box is assigned to.""" + hardware_profile: Optional["_models.HardwareProfile"] = rest_field(name="hardwareProfile", visibility=["read"]) + """Information about the Dev Box's hardware resources.""" + storage_profile: Optional["_models.StorageProfile"] = rest_field(name="storageProfile", visibility=["read"]) + """Storage settings for this Dev Box.""" + image_reference: Optional["_models.ImageReference"] = rest_field(name="imageReference", visibility=["read"]) + """Information about the image used for this Dev Box.""" + created_time: Optional[datetime.datetime] = rest_field(name="createdTime", visibility=["read"], format="rfc3339") + """Creation time of this Dev Box.""" + local_administrator: Optional[Union[str, "_models.LocalAdministratorStatus"]] = rest_field( + name="localAdministrator", visibility=["read", "create"] + ) + """Indicates whether the owner of the Dev Box is a local administrator. Known values are: + \"Enabled\" and \"Disabled\".""" + + @overload + def __init__( + self, + *, + pool_name: str, + local_administrator: Optional[Union[str, "_models.LocalAdministratorStatus"]] = None, + ): ... + + @overload + def __init__(self, mapping: Mapping[str, Any]): + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + super().__init__(*args, **kwargs) + + +class DevBoxAction(_model_base.Model): + """An action which will take place on a Dev Box. + + Readonly variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar name: The name of the action. Required. + :vartype name: str + :ivar action_type: The action that will be taken. Required. "Stop" + :vartype action_type: str or ~azure.developer.devcenter.models.DevBoxActionType + :ivar source_id: The id of the resource which triggered this action. Required. + :vartype source_id: str + :ivar suspended_until: The earliest time that the action could occur (UTC). + :vartype suspended_until: ~datetime.datetime + :ivar next: Details about the next run of this action. + :vartype next: ~azure.developer.devcenter.models.DevBoxNextAction + """ + + name: str = rest_field(visibility=["read"]) + """The name of the action. Required.""" + action_type: Union[str, "_models.DevBoxActionType"] = rest_field(name="actionType") + """The action that will be taken. Required. \"Stop\"""" + source_id: str = rest_field(name="sourceId") + """The id of the resource which triggered this action. Required.""" + suspended_until: Optional[datetime.datetime] = rest_field(name="suspendedUntil", format="rfc3339") + """The earliest time that the action could occur (UTC).""" + next: Optional["_models.DevBoxNextAction"] = rest_field() + """Details about the next run of this action.""" + + @overload + def __init__( + self, + *, + action_type: Union[str, "_models.DevBoxActionType"], + source_id: str, + suspended_until: Optional[datetime.datetime] = None, + next: Optional["_models.DevBoxNextAction"] = None, + ): ... + + @overload + def __init__(self, mapping: Mapping[str, Any]): + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + super().__init__(*args, **kwargs) + + +class DevBoxActionDelayResult(_model_base.Model): + """The action delay result. + + All required parameters must be populated in order to send to server. + + :ivar name: The name of the action. Required. + :vartype name: str + :ivar result: The result of the delay operation on this action. Required. Known values are: + "Succeeded" and "Failed". + :vartype result: str or ~azure.developer.devcenter.models.DevBoxActionDelayStatus + :ivar action: The delayed action. + :vartype action: ~azure.developer.devcenter.models.DevBoxAction + :ivar error: Information about the error that occurred. Only populated on error. + :vartype error: ~azure.developer.devcenter.models.Error + """ + + name: str = rest_field() + """The name of the action. Required.""" + result: Union[str, "_models.DevBoxActionDelayStatus"] = rest_field() + """The result of the delay operation on this action. Required. Known values are: \"Succeeded\" and + \"Failed\".""" + action: Optional["_models.DevBoxAction"] = rest_field() + """The delayed action.""" + error: Optional["_models.Error"] = rest_field() + """Information about the error that occurred. Only populated on error.""" + + @overload + def __init__( + self, + *, + name: str, + result: Union[str, "_models.DevBoxActionDelayStatus"], + action: Optional["_models.DevBoxAction"] = None, + error: Optional["_models.Error"] = None, + ): ... + + @overload + def __init__(self, mapping: Mapping[str, Any]): + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + super().__init__(*args, **kwargs) + + +class DevBoxNextAction(_model_base.Model): + """Details about the next run of an action. + + All required parameters must be populated in order to send to server. + + :ivar scheduled_time: The time the action will be triggered (UTC). Required. + :vartype scheduled_time: ~datetime.datetime + """ + + scheduled_time: datetime.datetime = rest_field(name="scheduledTime", format="rfc3339") + """The time the action will be triggered (UTC). Required.""" + + @overload + def __init__( + self, + *, + scheduled_time: datetime.datetime, + ): ... + + @overload + def __init__(self, mapping: Mapping[str, Any]): + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + super().__init__(*args, **kwargs) + + +class Environment(_model_base.Model): + """Properties of an environment. + + Readonly variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar parameters: Parameters object for the environment. + :vartype parameters: dict[str, any] + :ivar name: Environment name. Required. + :vartype name: str + :ivar environment_type: Environment type. Required. + :vartype environment_type: str + :ivar user: The AAD object id of the owner of this Environment. + :vartype user: str + :ivar provisioning_state: The provisioning state of the environment. Known values are: + "Succeeded", "Failed", "Canceled", "Creating", "Accepted", "Deleting", "Updating", "Preparing", + "Running", "Syncing", "MovingResources", "TransientFailure", and "StorageProvisioningFailed". + :vartype provisioning_state: str or + ~azure.developer.devcenter.models.EnvironmentProvisioningState + :ivar resource_group_id: The identifier of the resource group containing the environment's + resources. + :vartype resource_group_id: str + :ivar catalog_name: Name of the catalog. Required. + :vartype catalog_name: str + :ivar environment_definition_name: Name of the environment definition. Required. + :vartype environment_definition_name: str + :ivar error: Provisioning error details. Populated only for error states. + :vartype error: ~azure.developer.devcenter.models.Error + """ + + parameters: Optional[Dict[str, Any]] = rest_field() + """Parameters object for the environment.""" + name: str = rest_field(visibility=["read"]) + """Environment name. Required.""" + environment_type: str = rest_field(name="environmentType", visibility=["read", "create"]) + """Environment type. Required.""" + user: Optional[str] = rest_field(visibility=["read"]) + """The AAD object id of the owner of this Environment.""" + provisioning_state: Optional[Union[str, "_models.EnvironmentProvisioningState"]] = rest_field( + name="provisioningState", visibility=["read"] + ) + """The provisioning state of the environment. Known values are: \"Succeeded\", \"Failed\", + \"Canceled\", \"Creating\", \"Accepted\", \"Deleting\", \"Updating\", \"Preparing\", + \"Running\", \"Syncing\", \"MovingResources\", \"TransientFailure\", and + \"StorageProvisioningFailed\".""" + resource_group_id: Optional[str] = rest_field(name="resourceGroupId", visibility=["read"]) + """The identifier of the resource group containing the environment's resources.""" + catalog_name: str = rest_field(name="catalogName", visibility=["read", "create"]) + """Name of the catalog. Required.""" + environment_definition_name: str = rest_field(name="environmentDefinitionName", visibility=["read", "create"]) + """Name of the environment definition. Required.""" + error: Optional["_models.Error"] = rest_field(visibility=["read"]) + """Provisioning error details. Populated only for error states.""" + + @overload + def __init__( + self, + *, + environment_type: str, + catalog_name: str, + environment_definition_name: str, + parameters: Optional[Dict[str, Any]] = None, + ): ... + + @overload + def __init__(self, mapping: Mapping[str, Any]): + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + super().__init__(*args, **kwargs) + + +class EnvironmentDefinition(_model_base.Model): + """An environment definition. + + Readonly variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: The ID of the environment definition. Required. + :vartype id: str + :ivar name: Name of the environment definition. Required. + :vartype name: str + :ivar catalog_name: Name of the catalog. Required. + :vartype catalog_name: str + :ivar description: A short description of the environment definition. + :vartype description: str + :ivar parameters: Input parameters passed to an environment. + :vartype parameters: list[~azure.developer.devcenter.models.EnvironmentDefinitionParameter] + :ivar parameters_schema: JSON schema defining the parameters object passed to an environment. + :vartype parameters_schema: str + :ivar template_path: Path to the Environment Definition entrypoint file. + :vartype template_path: str + """ + + id: str = rest_field() + """The ID of the environment definition. Required.""" + name: str = rest_field(visibility=["read"]) + """Name of the environment definition. Required.""" + catalog_name: str = rest_field(name="catalogName") + """Name of the catalog. Required.""" + description: Optional[str] = rest_field() + """A short description of the environment definition.""" + parameters: Optional[List["_models.EnvironmentDefinitionParameter"]] = rest_field() + """Input parameters passed to an environment.""" + parameters_schema: Optional[str] = rest_field(name="parametersSchema") + """JSON schema defining the parameters object passed to an environment.""" + template_path: Optional[str] = rest_field(name="templatePath") + """Path to the Environment Definition entrypoint file.""" + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + catalog_name: str, + description: Optional[str] = None, + parameters: Optional[List["_models.EnvironmentDefinitionParameter"]] = None, + parameters_schema: Optional[str] = None, + template_path: Optional[str] = None, + ): ... + + @overload + def __init__(self, mapping: Mapping[str, Any]): + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + super().__init__(*args, **kwargs) + + +class EnvironmentDefinitionParameter(_model_base.Model): + """Properties of an Environment Definition parameter. + + All required parameters must be populated in order to send to server. + + :ivar id: Unique ID of the parameter. Required. + :vartype id: str + :ivar name: Display name of the parameter. + :vartype name: str + :ivar description: Description of the parameter. + :vartype description: str + :ivar default: Default value of the parameter. + :vartype default: str + :ivar type: A string of one of the basic JSON types (number, integer, array, object, + boolean, string). Required. Known values are: "array", "boolean", "integer", "number", + "object", and "string". + :vartype type: str or ~azure.developer.devcenter.models.ParameterType + :ivar read_only: Whether or not this parameter is read-only. If true, default should have a + value. + :vartype read_only: bool + :ivar required: Whether or not this parameter is required. Required. + :vartype required: bool + :ivar allowed: An array of allowed values. + :vartype allowed: list[str] + """ + + id: str = rest_field() + """Unique ID of the parameter. Required.""" + name: Optional[str] = rest_field() + """Display name of the parameter.""" + description: Optional[str] = rest_field() + """Description of the parameter.""" + default: Optional[str] = rest_field() + """Default value of the parameter.""" + type: Union[str, "_models.ParameterType"] = rest_field() + """A string of one of the basic JSON types (number, integer, array, object, + boolean, string). Required. Known values are: \"array\", \"boolean\", \"integer\", \"number\", + \"object\", and \"string\".""" + read_only: Optional[bool] = rest_field(name="readOnly") + """Whether or not this parameter is read-only. If true, default should have a + value.""" + required: bool = rest_field() + """Whether or not this parameter is required. Required.""" + allowed: Optional[List[str]] = rest_field() + """An array of allowed values.""" + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + type: Union[str, "_models.ParameterType"], + required: bool, + name: Optional[str] = None, + description: Optional[str] = None, + default: Optional[str] = None, + read_only: Optional[bool] = None, + allowed: Optional[List[str]] = None, + ): ... + + @overload + def __init__(self, mapping: Mapping[str, Any]): + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + super().__init__(*args, **kwargs) + + +class EnvironmentType(_model_base.Model): + """Properties of an environment type. + + All required parameters must be populated in order to send to server. + + :ivar name: Name of the environment type. Required. + :vartype name: str + :ivar deployment_target_id: Id of a subscription or management group that the environment type + will be + mapped to. The environment's resources will be deployed into this subscription + or management group. Required. + :vartype deployment_target_id: str + :ivar status: Indicates whether this environment type is enabled for use in this project. + Required. Known values are: "Enabled" and "Disabled". + :vartype status: str or ~azure.developer.devcenter.models.EnvironmentTypeStatus + """ + + name: str = rest_field() + """Name of the environment type. Required.""" + deployment_target_id: str = rest_field(name="deploymentTargetId") + """Id of a subscription or management group that the environment type will be + mapped to. The environment's resources will be deployed into this subscription + or management group. Required.""" + status: Union[str, "_models.EnvironmentTypeStatus"] = rest_field() + """Indicates whether this environment type is enabled for use in this project. Required. Known + values are: \"Enabled\" and \"Disabled\".""" + + @overload + def __init__( + self, + *, + name: str, + deployment_target_id: str, + status: Union[str, "_models.EnvironmentTypeStatus"], + ): ... + + @overload + def __init__(self, mapping: Mapping[str, Any]): + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + super().__init__(*args, **kwargs) + + +class Error(_model_base.Model): + """The error object. + + All required parameters must be populated in order to send to server. + + :ivar code: One of a server-defined set of error codes. Required. + :vartype code: str + :ivar message: A human-readable representation of the error. Required. + :vartype message: str + :ivar target: The target of the error. + :vartype target: str + :ivar details: An array of details about specific errors that led to this reported error. + :vartype details: list[~azure.developer.devcenter.models.Error] + :ivar innererror: An object containing more specific information than the current object about + the error. + :vartype innererror: ~azure.developer.devcenter.models.InnerError + """ + + code: str = rest_field() + """One of a server-defined set of error codes. Required.""" + message: str = rest_field() + """A human-readable representation of the error. Required.""" + target: Optional[str] = rest_field() + """The target of the error.""" + details: Optional[List["_models.Error"]] = rest_field() + """An array of details about specific errors that led to this reported error.""" + innererror: Optional["_models.InnerError"] = rest_field() + """An object containing more specific information than the current object about the error.""" + + @overload + def __init__( + self, + *, + code: str, + message: str, + target: Optional[str] = None, + details: Optional[List["_models.Error"]] = None, + innererror: Optional["_models.InnerError"] = None, + ): ... + + @overload + def __init__(self, mapping: Mapping[str, Any]): + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + super().__init__(*args, **kwargs) + + +class HardwareProfile(_model_base.Model): + """Hardware specifications for the Dev Box. + + Readonly variables are only populated by the server, and will be ignored when sending a request. + + :ivar sku_name: The name of the SKU. Known values are: "general_i_8c32gb256ssd_v2", + "general_i_8c32gb512ssd_v2", "general_i_8c32gb1024ssd_v2", "general_i_8c32gb2048ssd_v2", + "general_i_16c64gb256ssd_v2", "general_i_16c64gb512ssd_v2", "general_i_16c64gb1024ssd_v2", + "general_i_16c64gb2048ssd_v2", "general_i_32c128gb512ssd_v2", "general_i_32c128gb1024ssd_v2", + "general_i_32c128gb2048ssd_v2", "general_a_8c32gb256ssd_v2", "general_a_8c32gb512ssd_v2", + "general_a_8c32gb1024ssd_v2", "general_a_8c32gb2048ssd_v2", "general_a_16c64gb256ssd_v2", + "general_a_16c64gb512ssd_v2", "general_a_16c64gb1024ssd_v2", "general_a_16c64gb2048ssd_v2", + "general_a_32c128gb512ssd_v2", "general_a_32c128gb1024ssd_v2", and + "general_a_32c128gb2048ssd_v2". + :vartype sku_name: str or ~azure.developer.devcenter.models.SkuName + :ivar vcpus: The number of vCPUs available for the Dev Box. + :vartype vcpus: int + :ivar memory_gb: The amount of memory available for the Dev Box. + :vartype memory_gb: int + """ + + sku_name: Optional[Union[str, "_models.SkuName"]] = rest_field(name="skuName", visibility=["read"]) + """The name of the SKU. Known values are: \"general_i_8c32gb256ssd_v2\", + \"general_i_8c32gb512ssd_v2\", \"general_i_8c32gb1024ssd_v2\", \"general_i_8c32gb2048ssd_v2\", + \"general_i_16c64gb256ssd_v2\", \"general_i_16c64gb512ssd_v2\", + \"general_i_16c64gb1024ssd_v2\", \"general_i_16c64gb2048ssd_v2\", + \"general_i_32c128gb512ssd_v2\", \"general_i_32c128gb1024ssd_v2\", + \"general_i_32c128gb2048ssd_v2\", \"general_a_8c32gb256ssd_v2\", \"general_a_8c32gb512ssd_v2\", + \"general_a_8c32gb1024ssd_v2\", \"general_a_8c32gb2048ssd_v2\", \"general_a_16c64gb256ssd_v2\", + \"general_a_16c64gb512ssd_v2\", \"general_a_16c64gb1024ssd_v2\", + \"general_a_16c64gb2048ssd_v2\", \"general_a_32c128gb512ssd_v2\", + \"general_a_32c128gb1024ssd_v2\", and \"general_a_32c128gb2048ssd_v2\".""" + vcpus: Optional[int] = rest_field(name="vCPUs", visibility=["read"]) + """The number of vCPUs available for the Dev Box.""" + memory_gb: Optional[int] = rest_field(name="memoryGB", visibility=["read"]) + """The amount of memory available for the Dev Box.""" + + +class ImageReference(_model_base.Model): + """Specifies information about the image used. + + Readonly variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: The name of the image used. + :vartype name: str + :ivar version: The version of the image. + :vartype version: str + :ivar operating_system: The operating system of the image. + :vartype operating_system: str + :ivar os_build_number: The operating system build number of the image. + :vartype os_build_number: str + :ivar published_date: The datetime that the backing image version was published. + :vartype published_date: ~datetime.datetime + """ + + name: Optional[str] = rest_field(visibility=["read"]) + """The name of the image used.""" + version: Optional[str] = rest_field(visibility=["read"]) + """The version of the image.""" + operating_system: Optional[str] = rest_field(name="operatingSystem", visibility=["read"]) + """The operating system of the image.""" + os_build_number: Optional[str] = rest_field(name="osBuildNumber", visibility=["read"]) + """The operating system build number of the image.""" + published_date: Optional[datetime.datetime] = rest_field( + name="publishedDate", visibility=["read"], format="rfc3339" + ) + """The datetime that the backing image version was published.""" + + +class InnerError(_model_base.Model): + """An object containing more specific information about the error. As per Microsoft One API + guidelines - + https://github.com/Microsoft/api-guidelines/blob/vNext/Guidelines.md#7102-error-condition-responses. + + :ivar code: One of a server-defined set of error codes. + :vartype code: str + :ivar innererror: Inner error. + :vartype innererror: ~azure.developer.devcenter.models.InnerError + """ + + code: Optional[str] = rest_field() + """One of a server-defined set of error codes.""" + innererror: Optional["_models.InnerError"] = rest_field() + """Inner error.""" + + @overload + def __init__( + self, + *, + code: Optional[str] = None, + innererror: Optional["_models.InnerError"] = None, + ): ... + + @overload + def __init__(self, mapping: Mapping[str, Any]): + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + super().__init__(*args, **kwargs) + + +class OperationDetails(_model_base.Model): + """The current status of an async operation. + + Readonly variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: Fully qualified ID for the operation status. Required. + :vartype id: str + :ivar name: The operation id name. Required. + :vartype name: str + :ivar status: Provisioning state of the resource. Required. Known values are: "NotStarted", + "Running", "Succeeded", "Failed", and "Canceled". + :vartype status: str or ~azure.developer.devcenter.models.OperationStatus + :ivar resource_id: The id of the resource. + :vartype resource_id: str + :ivar start_time: The start time of the operation. + :vartype start_time: ~datetime.datetime + :ivar end_time: The end time of the operation. + :vartype end_time: ~datetime.datetime + :ivar percent_complete: Percent of the operation that is complete. + :vartype percent_complete: float + :ivar properties: Custom operation properties, populated only for a successful operation. + :vartype properties: any + :ivar error: Operation Error message. + :vartype error: ~azure.developer.devcenter.models.Error + """ + + id: str = rest_field(visibility=["read"]) + """Fully qualified ID for the operation status. Required.""" + name: str = rest_field(visibility=["read"]) + """The operation id name. Required.""" + status: Union[str, "_models.OperationStatus"] = rest_field() + """Provisioning state of the resource. Required. Known values are: \"NotStarted\", \"Running\", + \"Succeeded\", \"Failed\", and \"Canceled\".""" + resource_id: Optional[str] = rest_field(name="resourceId") + """The id of the resource.""" + start_time: Optional[datetime.datetime] = rest_field(name="startTime", format="rfc3339") + """The start time of the operation.""" + end_time: Optional[datetime.datetime] = rest_field(name="endTime", format="rfc3339") + """The end time of the operation.""" + percent_complete: Optional[float] = rest_field(name="percentComplete") + """Percent of the operation that is complete.""" + properties: Optional[Any] = rest_field() + """Custom operation properties, populated only for a successful operation.""" + error: Optional["_models.Error"] = rest_field() + """Operation Error message.""" + + @overload + def __init__( + self, + *, + status: Union[str, "_models.OperationStatus"], + resource_id: Optional[str] = None, + start_time: Optional[datetime.datetime] = None, + end_time: Optional[datetime.datetime] = None, + percent_complete: Optional[float] = None, + properties: Optional[Any] = None, + error: Optional["_models.Error"] = None, + ): ... + + @overload + def __init__(self, mapping: Mapping[str, Any]): + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + super().__init__(*args, **kwargs) + + +class OSDisk(_model_base.Model): + """Settings for the operating system disk. + + Readonly variables are only populated by the server, and will be ignored when sending a request. + + :ivar disk_size_gb: The size of the OS Disk in gigabytes. + :vartype disk_size_gb: int + """ + + disk_size_gb: Optional[int] = rest_field(name="diskSizeGB", visibility=["read"]) + """The size of the OS Disk in gigabytes.""" + + +class Pool(_model_base.Model): + """A pool of Dev Boxes. + + Readonly variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar name: Pool name. Required. + :vartype name: str + :ivar location: Azure region where Dev Boxes in the pool are located. Required. + :vartype location: str + :ivar os_type: The operating system type of Dev Boxes in this pool. "Windows" + :vartype os_type: str or ~azure.developer.devcenter.models.OSType + :ivar hardware_profile: Hardware settings for the Dev Boxes created in this pool. + :vartype hardware_profile: ~azure.developer.devcenter.models.HardwareProfile + :ivar hibernate_support: Indicates whether hibernate is enabled/disabled or unknown. Known + values are: "Enabled", "Disabled", and "OsUnsupported". + :vartype hibernate_support: str or ~azure.developer.devcenter.models.HibernateSupport + :ivar storage_profile: Storage settings for Dev Box created in this pool. + :vartype storage_profile: ~azure.developer.devcenter.models.StorageProfile + :ivar image_reference: Image settings for Dev Boxes create in this pool. + :vartype image_reference: ~azure.developer.devcenter.models.ImageReference + :ivar local_administrator: Indicates whether owners of Dev Boxes in this pool are local + administrators on + the Dev Boxes. Known values are: "Enabled" and "Disabled". + :vartype local_administrator: str or ~azure.developer.devcenter.models.LocalAdministratorStatus + :ivar stop_on_disconnect: Stop on disconnect configuration settings for Dev Boxes created in + this pool. + :vartype stop_on_disconnect: ~azure.developer.devcenter.models.StopOnDisconnectConfiguration + :ivar health_status: Overall health status of the Pool. Indicates whether or not the Pool is + available to create Dev Boxes. Required. Known values are: "Unknown", "Pending", "Healthy", + "Warning", and "Unhealthy". + :vartype health_status: str or ~azure.developer.devcenter.models.PoolHealthStatus + """ + + name: str = rest_field(visibility=["read"]) + """Pool name. Required.""" + location: str = rest_field() + """Azure region where Dev Boxes in the pool are located. Required.""" + os_type: Optional[Union[str, "_models.OSType"]] = rest_field(name="osType") + """The operating system type of Dev Boxes in this pool. \"Windows\"""" + hardware_profile: Optional["_models.HardwareProfile"] = rest_field(name="hardwareProfile") + """Hardware settings for the Dev Boxes created in this pool.""" + hibernate_support: Optional[Union[str, "_models.HibernateSupport"]] = rest_field(name="hibernateSupport") + """Indicates whether hibernate is enabled/disabled or unknown. Known values are: \"Enabled\", + \"Disabled\", and \"OsUnsupported\".""" + storage_profile: Optional["_models.StorageProfile"] = rest_field(name="storageProfile") + """Storage settings for Dev Box created in this pool.""" + image_reference: Optional["_models.ImageReference"] = rest_field(name="imageReference") + """Image settings for Dev Boxes create in this pool.""" + local_administrator: Optional[Union[str, "_models.LocalAdministratorStatus"]] = rest_field( + name="localAdministrator" + ) + """Indicates whether owners of Dev Boxes in this pool are local administrators on + the Dev Boxes. Known values are: \"Enabled\" and \"Disabled\".""" + stop_on_disconnect: Optional["_models.StopOnDisconnectConfiguration"] = rest_field(name="stopOnDisconnect") + """Stop on disconnect configuration settings for Dev Boxes created in this pool.""" + health_status: Union[str, "_models.PoolHealthStatus"] = rest_field(name="healthStatus") + """Overall health status of the Pool. Indicates whether or not the Pool is + available to create Dev Boxes. Required. Known values are: \"Unknown\", \"Pending\", + \"Healthy\", \"Warning\", and \"Unhealthy\".""" + + @overload + def __init__( + self, + *, + location: str, + health_status: Union[str, "_models.PoolHealthStatus"], + os_type: Optional[Union[str, "_models.OSType"]] = None, + hardware_profile: Optional["_models.HardwareProfile"] = None, + hibernate_support: Optional[Union[str, "_models.HibernateSupport"]] = None, + storage_profile: Optional["_models.StorageProfile"] = None, + image_reference: Optional["_models.ImageReference"] = None, + local_administrator: Optional[Union[str, "_models.LocalAdministratorStatus"]] = None, + stop_on_disconnect: Optional["_models.StopOnDisconnectConfiguration"] = None, + ): ... + + @overload + def __init__(self, mapping: Mapping[str, Any]): + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + super().__init__(*args, **kwargs) + + +class Project(_model_base.Model): + """Project details. + + Readonly variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar name: Name of the project. Required. + :vartype name: str + :ivar description: Description of the project. + :vartype description: str + :ivar max_dev_boxes_per_user: When specified, indicates the maximum number of Dev Boxes a + single user can + create across all pools in the project. + :vartype max_dev_boxes_per_user: int + """ + + name: str = rest_field(visibility=["read"]) + """Name of the project. Required.""" + description: Optional[str] = rest_field() + """Description of the project.""" + max_dev_boxes_per_user: Optional[int] = rest_field(name="maxDevBoxesPerUser") + """When specified, indicates the maximum number of Dev Boxes a single user can + create across all pools in the project.""" + + @overload + def __init__( + self, + *, + description: Optional[str] = None, + max_dev_boxes_per_user: Optional[int] = None, + ): ... + + @overload + def __init__(self, mapping: Mapping[str, Any]): + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + super().__init__(*args, **kwargs) + + +class RemoteConnection(_model_base.Model): + """Provides remote connection information for a Dev Box. + + :ivar web_url: URL to open a browser based RDP session. + :vartype web_url: str + :ivar rdp_connection_url: Link to open a Remote Desktop session. + :vartype rdp_connection_url: str + """ + + web_url: Optional[str] = rest_field(name="webUrl") + """URL to open a browser based RDP session.""" + rdp_connection_url: Optional[str] = rest_field(name="rdpConnectionUrl") + """Link to open a Remote Desktop session.""" + + @overload + def __init__( + self, + *, + web_url: Optional[str] = None, + rdp_connection_url: Optional[str] = None, + ): ... + + @overload + def __init__(self, mapping: Mapping[str, Any]): + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + super().__init__(*args, **kwargs) + + +class Schedule(_model_base.Model): + """A Schedule to execute action. + + Readonly variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar name: Display name for the Schedule. Required. + :vartype name: str + :ivar type: Supported type this scheduled task represents. Required. "StopDevBox" + :vartype type: str or ~azure.developer.devcenter.models.ScheduledType + :ivar frequency: The frequency of this scheduled task. Required. "Daily" + :vartype frequency: str or ~azure.developer.devcenter.models.ScheduledFrequency + :ivar time: The target time to trigger the action. The format is HH:MM. Required. + :vartype time: str + :ivar time_zone: The IANA timezone id at which the schedule should execute. Required. + :vartype time_zone: str + """ + + name: str = rest_field(visibility=["read"]) + """Display name for the Schedule. Required.""" + type: Union[str, "_models.ScheduledType"] = rest_field() + """Supported type this scheduled task represents. Required. \"StopDevBox\"""" + frequency: Union[str, "_models.ScheduledFrequency"] = rest_field() + """The frequency of this scheduled task. Required. \"Daily\"""" + time: str = rest_field() + """The target time to trigger the action. The format is HH:MM. Required.""" + time_zone: str = rest_field(name="timeZone") + """The IANA timezone id at which the schedule should execute. Required.""" + + @overload + def __init__( + self, + *, + type: Union[str, "_models.ScheduledType"], + frequency: Union[str, "_models.ScheduledFrequency"], + time: str, + time_zone: str, + ): ... + + @overload + def __init__(self, mapping: Mapping[str, Any]): + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + super().__init__(*args, **kwargs) + + +class StopOnDisconnectConfiguration(_model_base.Model): + """Stop on disconnect configuration settings for Dev Boxes created in this pool. + + All required parameters must be populated in order to send to server. + + :ivar status: Indicates whether the feature to stop the devbox on disconnect once the grace + period has lapsed is enabled. Required. Known values are: "Enabled" and "Disabled". + :vartype status: str or ~azure.developer.devcenter.models.StopOnDisconnectStatus + :ivar grace_period_minutes: The specified time in minutes to wait before stopping a Dev Box + once disconnect + is detected. + :vartype grace_period_minutes: int + """ + + status: Union[str, "_models.StopOnDisconnectStatus"] = rest_field() + """Indicates whether the feature to stop the devbox on disconnect once the grace + period has lapsed is enabled. Required. Known values are: \"Enabled\" and \"Disabled\".""" + grace_period_minutes: Optional[int] = rest_field(name="gracePeriodMinutes") + """The specified time in minutes to wait before stopping a Dev Box once disconnect + is detected.""" + + @overload + def __init__( + self, + *, + status: Union[str, "_models.StopOnDisconnectStatus"], + grace_period_minutes: Optional[int] = None, + ): ... + + @overload + def __init__(self, mapping: Mapping[str, Any]): + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + super().__init__(*args, **kwargs) + + +class StorageProfile(_model_base.Model): + """Storage settings for the Dev Box's disks. + + :ivar os_disk: Settings for the operating system disk. + :vartype os_disk: ~azure.developer.devcenter.models.OSDisk + """ + + os_disk: Optional["_models.OSDisk"] = rest_field(name="osDisk") + """Settings for the operating system disk.""" + + @overload + def __init__( + self, + *, + os_disk: Optional["_models.OSDisk"] = None, + ): ... + + @overload + def __init__(self, mapping: Mapping[str, Any]): + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + super().__init__(*args, **kwargs) diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/models/_patch.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/models/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/devcenter/azure-developer-devcenter/samples/async_samples/deployment_environments_async_sample.py b/sdk/devcenter/azure-developer-devcenter/samples/async_samples/deployment_environments_async_sample.py new file mode 100644 index 000000000000..c09e6cd08891 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/samples/async_samples/deployment_environments_async_sample.py @@ -0,0 +1,148 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +""" +FILE: deployment_environments_async_sample.py + +DESCRIPTION: + This sample demonstrates how to create and delete Environments using python DevCenterClient. For this sample, + you must have previously configured a DevCenter, Project, Catalog, Environment Definition and Environment Type. + More details on how to configure those requirements at https://learn.microsoft.com/azure/deployment-environments/ + +USAGE: + python deployment_environments_async_sample.py + + Set the environment variables with your own values before running the sample: + 1) DEVCENTER_ENDPOINT - the endpoint for your devcenter +""" + +import os +import asyncio + +from azure.developer.devcenter.aio import DevCenterClient +from azure.identity import DefaultAzureCredential + + +async def environment_create_and_delete_async(): + # [START environment_create_and_delete_async] + # Set the values of the dev center endpoint, client ID, and client secret of the AAD application as environment variables: + # DEVCENTER_ENDPOINT, AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET + try: + endpoint = os.environ["DEVCENTER_ENDPOINT"] + except KeyError: + raise ValueError("Missing environment variable 'DEVCENTER_ENDPOINT' - please set it before running the example") + + # Build a client through AAD + client = DevCenterClient(endpoint, credential=DefaultAzureCredential()) + + async with client: + # List available Projects + projects = [] + async for project in client.list_projects(): + projects.append(project) + if projects: + print("\nList of projects: ") + for project in projects: + print(f"{project.name}") + + # Select first project in the list + target_project_name = projects[0].name + else: + raise ValueError("Missing Project - please create one before running the example") + + # List available Catalogs + catalogs = [] + async for catalog in client.list_catalogs(target_project_name): + catalogs.append(catalog) + if catalogs: + print("\nList of catalogs: ") + for catalog in catalogs: + print(f"{catalog.name}") + + # Select first catalog in the list + target_catalog_name = catalogs[0].name + else: + raise ValueError("Missing Catalog - please create one before running the example") + + # List available Environment Definitions + environment_definitions = [] + async for environment_definition in client.list_environment_definitions_by_catalog(target_project_name, target_catalog_name): + environment_definitions.append(environment_definition) + if environment_definitions: + print("\nList of environment definitions: ") + for environment_definition in environment_definitions: + print(f"{environment_definition.name}") + + # Select first environment definition in the list + target_environment_definition_name = environment_definitions[0].name + else: + raise ValueError("Missing Environment Definition - please create one before running the example") + + # List available Environment Types + environment_types = [] + async for environment_type in client.list_environment_types(target_project_name): + environment_types.append(environment_type) + if environment_types: + print("\nList of environment types: ") + for environment_type in environment_types: + print(f"{environment_type.name}") + + # Select first environment type in the list + target_environment_type_name = environment_types[0].name + else: + raise ValueError("Missing Environment Type - please create one before running the example") + + print( + f"\nStarting to create environment in project {target_project_name} with catalog {target_catalog_name}, environment definition {target_environment_definition_name}, and environment type {target_environment_type_name}." + ) + + # Stand up a new environment + environment_name = "MyDevEnv" + environment = { + "environmentType": target_environment_type_name, + "catalogName": target_catalog_name, + "environmentDefinitionName": target_environment_definition_name, + } + + environment_poller = await client.begin_create_or_update_environment( + target_project_name, "me", environment_name, environment + ) + environment_result = await environment_poller.result() + print(f"Provisioned environment with status {environment_result.provisioning_state}.") + + # Tear down the environment when finished + print(f"Starting to delete environment.") + delete_poller = await client.begin_delete_environment(target_project_name, "me", environment_name) + delete_result = await delete_poller.result() + print(f"Completed deletion for the environment with status {delete_result.status}") + # [END environment_create_and_delete_async] + +async def main(): + await environment_create_and_delete_async() + +if __name__ == '__main__': + asyncio.run(main()) diff --git a/sdk/devcenter/azure-developer-devcenter/samples/async_samples/dev_box_action_async_sample.py b/sdk/devcenter/azure-developer-devcenter/samples/async_samples/dev_box_action_async_sample.py new file mode 100644 index 000000000000..f07a385725d8 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/samples/async_samples/dev_box_action_async_sample.py @@ -0,0 +1,99 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +import os +import asyncio + +from azure.developer.devcenter.aio import DevCenterClient +from azure.identity import DefaultAzureCredential +from datetime import timedelta + +""" +FILE: dev_box_action_async_sample.py + +DESCRIPTION: + This sample demonstrates how to get, delay and skip a dev box action using python DevCenterClient. + For this sample, you must have a running dev box created from a pool with auto-stop enabled. More details + on how to configure auto-stop at https://learn.microsoft.com/azure/dev-box/how-to-configure-stop-schedule + and sample on how to create a dev box at dev_box_create_sample.py in this folder + +USAGE: + python dev_box_action_async_sample.py + + Set the environment variables with your own values before running the sample: + 1) DEVCENTER_ENDPOINT - the endpoint for your devcenter +""" + +async def dev_box_action_async(): + + # Set the values of the dev center endpoint, client ID, and client secret of the AAD application as environment variables: + # DEVCENTER_ENDPOINT, AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET + try: + endpoint = os.environ["DEVCENTER_ENDPOINT"] + except KeyError: + raise ValueError("Missing environment variable 'DEVCENTER_ENDPOINT' - please set it before running the example") + + # Build a client through AAD + client = DevCenterClient(endpoint, credential=DefaultAzureCredential()) + + async with client: + # List Dev Boxes + dev_boxes = [] + async for dev_box in client.list_all_dev_boxes_by_user("me"): + dev_boxes.append(dev_box) + if dev_boxes: + print("List of dev boxes: ") + for dev_box in dev_boxes: + print(f"{dev_box.name}") + + # Select first dev box in the list + target_dev_box = dev_boxes[0] + else: + raise ValueError("Missing Dev Box - please create one before running the example.") + + # Get the schedule default action. This action should exist for dev boxes created with auto-stop enabled + action = await client.get_dev_box_action(target_dev_box.project_name, "me", target_dev_box.name, "schedule-default") + next_action_time = action.next.scheduled_time + print(f"\nAction {action.Name} is schedule to {action.ActionType} at {next_action_time}.") + + # Delay the action in 1hr + delay_until = next_action_time + timedelta(hours=1) + delayed_action = await client.delay_dev_box_action( + target_dev_box.project_name, "me", target_dev_box.name, action.name, delay_until=delay_until + ) + print( + f"\nAction {delayed_action.Name} has been delayed and is now schedule to {delayed_action.ActionType} at {delayed_action.NextAction.ScheduledTime}." + ) + + # Skip the default schedule action + await client.skip_dev_box_action(target_dev_box.project_name, "me", target_dev_box.name, "schedule-default") + print(f"\nThe scheduled auto-stop action in dev box {target_dev_box.name} has been skipped") + +async def main(): + await dev_box_action_async() + +if __name__ == '__main__': + asyncio.run(main()) diff --git a/sdk/devcenter/azure-developer-devcenter/samples/async_samples/dev_box_create_async_sample.py b/sdk/devcenter/azure-developer-devcenter/samples/async_samples/dev_box_create_async_sample.py new file mode 100644 index 000000000000..a2335ad58a19 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/samples/async_samples/dev_box_create_async_sample.py @@ -0,0 +1,114 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +""" +FILE: dev_box_create_async_sample.py + +DESCRIPTION: + This sample demonstrates how to create, connect and delete a dev box using python DevCenterClient. For this sample, + you must have previously configured DevCenter, Project, Network Connection, Dev Box Definition, and Pool.More details + on how to configure those requirements at https://learn.microsoft.com/azure/dev-box/quickstart-configure-dev-box-service + + +USAGE: + python dev_box_create_async_sample.py + + Set the environment variables with your own values before running the sample: + 1) DEVCENTER_ENDPOINT - the endpoint for your devcenter +""" +import os +import asyncio + +from azure.developer.devcenter.aio import DevCenterClient +from azure.identity import DefaultAzureCredential + +async def dev_box_create_connect_delete_async(): + # [START dev_box_create_connect_delete_async] + # Set the values of the dev center endpoint, client ID, and client secret of the AAD application as environment variables: + # DEVCENTER_ENDPOINT, AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET + try: + endpoint = os.environ["DEVCENTER_ENDPOINT"] + except KeyError: + raise ValueError("Missing environment variable 'DEVCENTER_ENDPOINT' - please set it before running the example") + + # Build a client through AAD + client = DevCenterClient(endpoint, credential=DefaultAzureCredential()) + + async with client: + # List available Projects + projects = [] + async for project in client.list_projects(): + projects.append(project) + if projects: + print("\nList of projects: ") + for project in projects: + print(f"{project.name}") + + # Select first project in the list + target_project_name = projects[0].name + else: + raise ValueError("Missing Project - please create one before running the example") + + # List available Pools + pools = [] + async for pool in client.list_pools(target_project_name): + pools.append(pool) + if pools: + print("\nList of pools: ") + for pool in pools: + print(f"{pool.name}") + + # Select first pool in the list + target_pool_name = pools[0].name + else: + raise ValueError("Missing Pool - please create one before running the example") + + # Stand up a new Dev Box + print(f"\nStarting to create dev box in project {target_project_name} and pool {target_pool_name}") + + dev_box_poller = await client.begin_create_dev_box( + target_project_name, "me", "Test_DevBox", {"poolName": target_pool_name} + ) + dev_box = await dev_box_poller.result() + print(f"Provisioned dev box with status {dev_box.provisioning_state}.") + + # Connect to the provisioned Dev Box + remote_connection = await client.get_remote_connection(target_project_name, "me", dev_box.name) + print(f"Connect to the dev box using web URL {remote_connection.web_url}") + + # Tear down the Dev Box when finished + print(f"Starting to delete dev box.") + + delete_poller = await client.begin_delete_dev_box(target_project_name, "me", "Test_DevBox") + delete_result = await delete_poller.result() + print(f"Completed deletion for the dev box with status {delete_result.status}") + # [END dev_box_create_connect_delete_async] + +async def main(): + await dev_box_create_connect_delete_async() + +if __name__ == '__main__': + asyncio.run(main()) diff --git a/sdk/devcenter/azure-developer-devcenter/samples/async_samples/dev_box_restart_async_sample.py b/sdk/devcenter/azure-developer-devcenter/samples/async_samples/dev_box_restart_async_sample.py new file mode 100644 index 000000000000..8cff68746acd --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/samples/async_samples/dev_box_restart_async_sample.py @@ -0,0 +1,101 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +import os +import asyncio + +from azure.developer.devcenter.aio import DevCenterClient +from azure.developer.devcenter.models import PowerState +from azure.identity import DefaultAzureCredential + +""" +FILE: dev_box_restart_async_sample.py + +DESCRIPTION: + This sample demonstrates how to restart, stop and start a dev box using python DevCenterClient. + For this sample, you must have a running dev box. More details on how to create a dev box + at dev_box_create_sample.py sample in this folder + +USAGE: + python devbox_restart_async_sample.py + + Set the environment variables with your own values before running the sample: + 1) DEVCENTER_ENDPOINT - the endpoint for your devcenter +""" + +async def dev_box_restart_stop_start_async(): + + # Set the values of the dev center endpoint, client ID, and client secret of the AAD application as environment variables: + # DEVCENTER_ENDPOINT, AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET + try: + endpoint = os.environ["DEVCENTER_ENDPOINT"] + except KeyError: + raise ValueError("Missing environment variable 'DEVCENTER_ENDPOINT' - please set it before running the example") + + # Build a client through AAD + client = DevCenterClient(endpoint, credential=DefaultAzureCredential()) + + async with client: + # List Dev Boxes + dev_boxes = [] + async for dev_box in client.list_all_dev_boxes_by_user("me"): + dev_boxes.append(dev_box) + if dev_boxes: + print("List of dev boxes: ") + for dev_box in dev_boxes: + print(f"{dev_box.name}") + + # Select first dev box in the list + target_dev_box = dev_boxes[0] + else: + raise ValueError("Missing Dev Box - please create one before running the example.") + + # Get the target dev box properties + project_name = target_dev_box.project_name + user = target_dev_box.user + dev_box_name = target_dev_box.name + + # Stop dev box if it's running + if target_dev_box.power_state == PowerState.Running: + stop_poller = await client.begin_stop_dev_box(project_name, user, dev_box_name) + stop_result = await stop_poller.result() + print(f"Stopping dev box completed with status {stop_result.status}") + + # At this point we should have a stopped dev box . Let's start it + start_poller = await client.begin_start_dev_box(project_name, user, dev_box_name) + start_result = await start_poller.result() + print(f"Starting dev box completed with status {start_result.status}") + + # Restart the dev box + restart_poller = await client.begin_restart_dev_box(project_name, user, dev_box_name) + restart_result = await restart_poller.result() + print(f"Done restarting the dev box with status {start_result.status}") + +async def main(): + await dev_box_restart_stop_start_async() + +if __name__ == '__main__': + asyncio.run(main()) diff --git a/sdk/devcenter/azure-developer-devcenter/samples/create_client_sample.py b/sdk/devcenter/azure-developer-devcenter/samples/create_client_sample.py new file mode 100644 index 000000000000..70836ae439c7 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/samples/create_client_sample.py @@ -0,0 +1,61 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +""" +FILE: create_client_sample.py + +DESCRIPTION: + This sample demonstrates how to create a Dev Center client. For this sample, you must + have previously configured a Dev Center in Azure. More details on how to configure it at + https://learn.microsoft.com/azure/deployment-environments/quickstart-create-and-configure-devcenter#create-a-dev-center + +USAGE: + python create_client_sample.py + + Set the environment variables with your own values before running the sample: + 1) DEVCENTER_ENDPOINT - the endpoint for your devcenter +""" + +def create_dev_center_client(): + # [START create_dev_center_client] + import os + + from azure.developer.devcenter import DevCenterClient + from azure.identity import DefaultAzureCredential + + # Set the values of the dev center endpoint, client ID, and client secret of the AAD application as environment variables: + # DEVCENTER_ENDPOINT, AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET + try: + endpoint = os.environ["DEVCENTER_ENDPOINT"] + except KeyError: + raise ValueError("Missing environment variable 'DEVCENTER_ENDPOINT' - please set it before running the example") + + # Build a client through AAD + client = DevCenterClient(endpoint, credential=DefaultAzureCredential()) + # [END create_dev_center_client] + +if __name__ == "__main__": + create_dev_center_client() diff --git a/sdk/devcenter/azure-developer-devcenter/samples/deployment_environments_sample.py b/sdk/devcenter/azure-developer-devcenter/samples/deployment_environments_sample.py new file mode 100644 index 000000000000..4ffaf5d12603 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/samples/deployment_environments_sample.py @@ -0,0 +1,135 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +""" +FILE: deployment_environments_sample.py + +DESCRIPTION: + This sample demonstrates how to create and delete Environments using python DevCenterClient. For this sample, + you must have previously configured a DevCenter, Project, Catalog, Environment Definition and Environment Type. + More details on how to configure those requirements at https://learn.microsoft.com/azure/deployment-environments/ + +USAGE: + python deployment_environments_sample.py + + Set the environment variables with your own values before running the sample: + 1) DEVCENTER_ENDPOINT - the endpoint for your devcenter +""" + +def environment_create_and_delete(): + # [START environment_create_and_delete] + import os + + from azure.developer.devcenter import DevCenterClient + from azure.identity import DefaultAzureCredential + + # Set the values of the dev center endpoint, client ID, and client secret of the AAD application as environment variables: + # DEVCENTER_ENDPOINT, AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET + try: + endpoint = os.environ["DEVCENTER_ENDPOINT"] + except KeyError: + raise ValueError("Missing environment variable 'DEVCENTER_ENDPOINT' - please set it before running the example") + + # Build a client through AAD + client = DevCenterClient(endpoint, credential=DefaultAzureCredential()) + + # List available Projects + projects = client.list_projects() + if projects: + print("\nList of projects: ") + for project in projects: + print(f"{project.name}") + + # Select first project in the list + target_project_name = list(projects)[0].name + else: + raise ValueError("Missing Project - please create one before running the example") + + # List available Catalogs + catalogs = client.list_catalogs(target_project_name) + if catalogs: + print("\nList of catalogs: ") + for catalog in catalogs: + print(f"{catalog.name}") + + # Select first catalog in the list + target_catalog_name = list(catalogs)[0].name + else: + raise ValueError("Missing Catalog - please create one before running the example") + + # List available Environment Definitions + environment_definitions = client.list_environment_definitions_by_catalog(target_project_name, target_catalog_name) + if environment_definitions: + print("\nList of environment definitions: ") + for environment_definition in environment_definitions: + print(f"{environment_definition.name}") + + # Select first environment definition in the list + target_environment_definition_name = list(environment_definitions)[0].name + else: + raise ValueError("Missing Environment Definition - please create one before running the example") + + # List available Environment Types + environment_types = client.list_environment_types(target_project_name) + if environment_types: + print("\nList of environment types: ") + for environment_type in environment_types: + print(f"{environment_type.name}") + + # Select first environment type in the list + target_environment_type_name = list(environment_types)[0].name + else: + raise ValueError("Missing Environment Type - please create one before running the example") + + print( + f"\nStarting to create environment in project {target_project_name} with catalog {target_catalog_name}, environment definition {target_environment_definition_name}, and environment type {target_environment_type_name}." + ) + + # Stand up a new environment + environment_name = "MyDevEnv" + environment = { + "environmentType": target_environment_type_name, + "catalogName": target_catalog_name, + "environmentDefinitionName": target_environment_definition_name, + } + + environment_poller = client.begin_create_or_update_environment( + target_project_name, "me", environment_name, environment + ) + environment_result = environment_poller.result() + print(f"Provisioned environment with status {environment_result.provisioning_state}.") + + # Tear down the environment when finished + print(f"Starting to delete environment.") + delete_poller = client.begin_delete_environment(target_project_name, "me", environment_name) + delete_result = delete_poller.result() + print(f"Completed deletion for the environment with status {delete_result.status}") + # [END environment_create_and_delete] + + +if __name__ == "__main__": + environment_create_and_delete() diff --git a/sdk/devcenter/azure-developer-devcenter/samples/dev_box_action_sample.py b/sdk/devcenter/azure-developer-devcenter/samples/dev_box_action_sample.py new file mode 100644 index 000000000000..c8cebbaa68b5 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/samples/dev_box_action_sample.py @@ -0,0 +1,94 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +import os + +from azure.developer.devcenter import DevCenterClient +from azure.identity import DefaultAzureCredential +from datetime import timedelta + +""" +FILE: dev_box_action_sample.py + +DESCRIPTION: + This sample demonstrates how to get, delay and skip a dev box action using python DevCenterClient. + For this sample, you must have a running dev box created from a pool with auto-stop enabled. More details + on how to configure auto-stop at https://learn.microsoft.com/azure/dev-box/how-to-configure-stop-schedule + and sample on how to create a dev box at dev_box_create_sample.py in this folder + +USAGE: + python dev_box_action_sample.py + + Set the environment variables with your own values before running the sample: + 1) DEVCENTER_ENDPOINT - the endpoint for your devcenter +""" + + +def dev_box_action(): + + # Set the values of the dev center endpoint, client ID, and client secret of the AAD application as environment variables: + # DEVCENTER_ENDPOINT, AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET + try: + endpoint = os.environ["DEVCENTER_ENDPOINT"] + except KeyError: + raise ValueError("Missing environment variable 'DEVCENTER_ENDPOINT' - please set it before running the example") + + # Build a client through AAD + client = DevCenterClient(endpoint, credential=DefaultAzureCredential()) + + # List Dev Boxes + dev_boxes = client.list_all_dev_boxes_by_user("me") + if dev_boxes: + print("List of dev boxes: ") + for dev_box in dev_boxes: + print(f"{dev_box.name}") + + # Select first dev box in the list + target_dev_box = list(dev_boxes)[0] + else: + raise ValueError("Missing Dev Box - please create one before running the example.") + + # Get the schedule default action. This action should exist for dev boxes created with auto-stop enabled + action = client.get_dev_box_action(target_dev_box.project_name, "me", target_dev_box.name, "schedule-default") + next_action_time = action.next.scheduled_time + print(f"\nAction {action.Name} is schedule to {action.ActionType} at {next_action_time}.") + + # Delay the action in 1hr + delay_until = next_action_time + timedelta(hours=1) + delayed_action = client.delay_dev_box_action( + target_dev_box.project_name, "me", target_dev_box.name, action.name, delay_until=delay_until + ) + print( + f"\nAction {delayed_action.Name} has been delayed and is now schedule to {delayed_action.ActionType} at {delayed_action.NextAction.ScheduledTime}." + ) + + # Skip the default schedule action + client.skip_dev_box_action(target_dev_box.project_name, "me", target_dev_box.name, "schedule-default") + print(f"\nThe scheduled auto-stop action in dev box {target_dev_box.name} has been skipped") + + +if __name__ == "__main__": + dev_box_action() diff --git a/sdk/devcenter/azure-developer-devcenter/samples/create_devbox_sample.py b/sdk/devcenter/azure-developer-devcenter/samples/dev_box_create_sample.py similarity index 56% rename from sdk/devcenter/azure-developer-devcenter/samples/create_devbox_sample.py rename to sdk/devcenter/azure-developer-devcenter/samples/dev_box_create_sample.py index 6aee26bb25ac..c8cefb4c41c8 100644 --- a/sdk/devcenter/azure-developer-devcenter/samples/create_devbox_sample.py +++ b/sdk/devcenter/azure-developer-devcenter/samples/dev_box_create_sample.py @@ -24,15 +24,8 @@ # IN THE SOFTWARE. # # -------------------------------------------------------------------------- -import logging -import os - -from azure.developer.devcenter import DevCenterClient -from azure.identity import DefaultAzureCredential -from azure.core.exceptions import HttpResponseError - """ -FILE: create_devbox_sample.py +FILE: dev_box_create_sample.py DESCRIPTION: This sample demonstrates how to create, connect and delete a dev box using python DevCenterClient. For this sample, @@ -41,21 +34,21 @@ USAGE: - python create_devbox_sample.py + python dev_box_create_sample.py Set the environment variables with your own values before running the sample: 1) DEVCENTER_ENDPOINT - the endpoint for your devcenter """ -def get_project_name(LOG, client): - projects = list(client.projects.list_by_dev_center(top=1)) - return projects[0].name - +def dev_box_create_connect_delete(): + # [START dev_box_create_connect_delete] + import os -def main(): + from azure.developer.devcenter import DevCenterClient + from azure.identity import DefaultAzureCredential # Set the values of the dev center endpoint, client ID, and client secret of the AAD application as environment variables: - # DEVCENTER_ENDPOINT, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET + # DEVCENTER_ENDPOINT, AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET try: endpoint = os.environ["DEVCENTER_ENDPOINT"] except KeyError: @@ -64,30 +57,50 @@ def main(): # Build a client through AAD client = DevCenterClient(endpoint, credential=DefaultAzureCredential()) - # Fetch control plane resource dependencies - projects = list(client.list_projects(top=1)) - target_project_name = projects[0]["name"] - - pools = list(client.list_pools(target_project_name, top=1)) - target_pool_name = pools[0]["name"] - - # Stand up a new dev box - create_response = client.begin_create_dev_box( + # List available Projects + projects = client.list_projects() + if projects: + print("\nList of projects: ") + for project in projects: + print(f"{project.name}") + + # Select first project in the list + target_project_name = list(projects)[0].name + else: + raise ValueError("Missing Project - please create one before running the example") + + # List available Pools + pools = client.list_pools(target_pool_name) + if pools: + print("\nList of pools: ") + for pool in pools: + print(f"{pool.name}") + + # Select first pool in the list + target_pool_name = list(pools)[0].name + else: + raise ValueError("Missing Pool - please create one before running the example") + + # Stand up a new Dev Box + print(f"\nStarting to create dev box in project {target_project_name} and pool {target_pool_name}") + + dev_box_poller = client.begin_create_dev_box( target_project_name, "me", "Test_DevBox", {"poolName": target_pool_name} ) - devbox_result = create_response.result() - - print(f"Provisioned dev box with status {devbox_result['provisioningState']}.") + dev_box = dev_box_poller.result() + print(f"Provisioned dev box with status {dev_box.provisioning_state}.") - # Connect to the provisioned dev box - remote_connection_response = client.get_remote_connection(target_project_name, "me", "Test_DevBox") - print(f"Connect to the dev box using web URL {remote_connection_response['webUrl']}") + # Connect to the provisioned Dev Box + remote_connection = client.get_remote_connection(target_project_name, "me", dev_box.name) + print(f"Connect to the dev box using web URL {remote_connection.web_url}") - # Tear down the dev box when finished - delete_response = client.begin_delete_dev_box(target_project_name, "me", "Test_DevBox") - delete_response.wait() - print("Deleted dev box successfully.") + # Tear down the Dev Box when finished + print(f"Starting to delete dev box.") + delete_poller = client.begin_delete_dev_box(target_project_name, "me", "Test_DevBox") + delete_result = delete_poller.result() + print(f"Completed deletion for the dev box with status {delete_result.status}") + # [END dev_box_create_connect_delete] if __name__ == "__main__": - main() + dev_box_create_connect_delete() diff --git a/sdk/devcenter/azure-developer-devcenter/samples/create_environment_sample.py b/sdk/devcenter/azure-developer-devcenter/samples/dev_box_restart_sample.py similarity index 52% rename from sdk/devcenter/azure-developer-devcenter/samples/create_environment_sample.py rename to sdk/devcenter/azure-developer-devcenter/samples/dev_box_restart_sample.py index 280e350372ef..785b3105ef6d 100644 --- a/sdk/devcenter/azure-developer-devcenter/samples/create_environment_sample.py +++ b/sdk/devcenter/azure-developer-devcenter/samples/dev_box_restart_sample.py @@ -24,32 +24,32 @@ # IN THE SOFTWARE. # # -------------------------------------------------------------------------- -import logging import os from azure.developer.devcenter import DevCenterClient +from azure.developer.devcenter.models import PowerState from azure.identity import DefaultAzureCredential -from azure.core.exceptions import HttpResponseError """ -FILE: create_environment_sample.py +FILE: dev_box_restart_sample.py DESCRIPTION: - This sample demonstrates how to create and delete Environments using python DevCenterClient. For this sample, - you must have previously configured a DevCenter, Project, Catalog, and Environment Type. More details - on how to configure those requirements at https://learn.microsoft.com/azure/deployment-environments/ + This sample demonstrates how to restart, stop and start a dev box using python DevCenterClient. + For this sample, you must have a running dev box. More details on how to create a dev box + at dev_box_create_sample.py sample in this folder USAGE: - python create_environment_sample.py + python devbox_restart_sample.py Set the environment variables with your own values before running the sample: 1) DEVCENTER_ENDPOINT - the endpoint for your devcenter """ -def main(): + +def dev_box_restart_stop_start(): # Set the values of the dev center endpoint, client ID, and client secret of the AAD application as environment variables: - # DEVCENTER_ENDPOINT, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET + # DEVCENTER_ENDPOINT, AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET try: endpoint = os.environ["DEVCENTER_ENDPOINT"] except KeyError: @@ -58,37 +58,39 @@ def main(): # Build a client through AAD client = DevCenterClient(endpoint, credential=DefaultAzureCredential()) - # Fetch control plane resource dependencies - target_project_name = list(client.list_projects(top=1))[0]["name"] - target_catalog_name = list(client.list_catalogs(target_project_name, top=1))[0]["name"] - target_environment_definition_name = list( - client.list_environment_definitions_by_catalog( - target_project_name, target_catalog_name, top=1 - ) - )[0]["name"] - target_environment_type_name = list( - client.list_environment_types(target_project_name, top=1) - )[0]["name"] - - # Stand up a new environment - environment = { - "catalogName": target_catalog_name, - "environmentDefinitionName": target_environment_definition_name, - "environmentType": target_environment_type_name, - } - - create_response = client.begin_create_or_update_environment( - target_project_name, "me", "DevTestEnv", environment - ) - environment_result = create_response.result() - - print(f"Provisioned environment with status {environment_result['provisioningState']}.") - - # Tear down the environment when finished - delete_response = client.begin_delete_environment(target_project_name, "me", "DevTestEnv") - delete_result = delete_response.result() - print(f"Completed deletion for the environment with status {delete_result['status']}") + # List Dev Boxes + dev_boxes = client.list_all_dev_boxes_by_user("me") + if dev_boxes: + print("List of dev boxes: ") + for dev_box in dev_boxes: + print(f"{dev_box.name}") + + # Select first dev box in the list + target_dev_box = list(dev_boxes)[0] + else: + raise ValueError("Missing Dev Box - please create one before running the example.") + + # Get the target dev box properties + project_name = target_dev_box.project_name + user = target_dev_box.user + dev_box_name = target_dev_box.name + + # Stop dev box if it's running + if target_dev_box.power_state == PowerState.Running: + stop_poller = client.begin_stop_dev_box(project_name, user, dev_box_name) + stop_result = stop_poller.result() + print(f"Stopping dev box completed with status {stop_result.status}") + + # At this point we should have a stopped dev box . Let's start it + start_poller = client.begin_start_dev_box(project_name, user, dev_box_name) + start_result = start_poller.result() + print(f"Starting dev box completed with status {start_result.status}") + + # Restart the dev box + restart_poller = client.begin_restart_dev_box(project_name, user, dev_box_name) + restart_result = restart_poller.result() + print(f"Done restarting the dev box with status {start_result.status}") if __name__ == "__main__": - main() + dev_box_restart_stop_start() diff --git a/sdk/devcenter/azure-developer-devcenter/sdk-generation.ps1 b/sdk/devcenter/azure-developer-devcenter/sdk-generation.ps1 new file mode 100644 index 000000000000..ab73b47aa557 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/sdk-generation.ps1 @@ -0,0 +1,8 @@ +Write-Host "TypeSpec Sync files" +ECHO 'y' | tsp-client sync + +Write-Host "Update python client" +Move-item -Path 'TempTypeSpecFiles\DevCenter\python-client.tsp' -destination 'TempTypeSpecFiles\DevCenter\client.tsp' -Force + +Write-Host "TypeSpec Generate" +ECHO 'y' | tsp-client generate \ No newline at end of file diff --git a/sdk/devcenter/azure-developer-devcenter/setup.py b/sdk/devcenter/azure-developer-devcenter/setup.py index 709fbcfd99ed..2be63bfc3c86 100644 --- a/sdk/devcenter/azure-developer-devcenter/setup.py +++ b/sdk/devcenter/azure-developer-devcenter/setup.py @@ -38,15 +38,15 @@ url="https://github.com/Azure/azure-sdk-for-python/tree/main/sdk", keywords="azure, azure sdk", classifiers=[ - "Development Status :: 4 - Beta", + "Development Status :: 5 - Production/Stable", "Programming Language :: Python", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", "License :: OSI Approved :: MIT License", ], zip_safe=False, @@ -63,9 +63,9 @@ "azure.developer.devcenter": ["py.typed"], }, install_requires=[ - "isodate<1.0.0,>=0.6.1", - "azure-core<2.0.0,>=1.28.0", - "typing-extensions>=4.3.0; python_version<'3.8.0'", + "isodate>=0.6.1", + "azure-core>=1.30.0", + "typing-extensions>=4.6.0", ], - python_requires=">=3.7", + python_requires=">=3.8", ) diff --git a/sdk/devcenter/azure-developer-devcenter/tests/conftest.py b/sdk/devcenter/azure-developer-devcenter/tests/conftest.py index 327a835048c1..07e19a00eff0 100644 --- a/sdk/devcenter/azure-developer-devcenter/tests/conftest.py +++ b/sdk/devcenter/azure-developer-devcenter/tests/conftest.py @@ -4,7 +4,15 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- -from devtools_testutils import test_proxy, add_body_key_sanitizer, add_oauth_response_sanitizer, remove_batch_sanitizers +from unittest import mock +from devtools_testutils import ( + test_proxy, + add_body_key_sanitizer, + add_oauth_response_sanitizer, + remove_batch_sanitizers, + add_uri_regex_sanitizer, + is_live, +) import pytest # autouse=True will trigger this fixture on each pytest run, even if it's not explicitly used by a test method @@ -13,8 +21,34 @@ def start_proxy(test_proxy): add_body_key_sanitizer(json_path="$..id_token", value="Sanitized") add_body_key_sanitizer(json_path="$..client_info", value="Sanitized") add_oauth_response_sanitizer() + add_uri_regex_sanitizer(regex="\\.(?.*)\\.devcenter\\.azure\\.com", group_for_replace="location", value="location") # Remove the following sanitizers since certain fields are needed in tests and are non-sensitive: # - AZSDK2003: Location # - AZSDK3493: $..name remove_batch_sanitizers(["AZSDK2003", "AZSDK3493"]) return + +@pytest.fixture(scope="session", autouse=True) +def patch_async_sleep(): + async def immediate_return(_): + return + + if not is_live(): + with mock.patch("asyncio.sleep", immediate_return): + yield + + else: + yield + + +@pytest.fixture(scope="session", autouse=True) +def patch_sleep(): + def immediate_return(_): + return + + if not is_live(): + with mock.patch("time.sleep", immediate_return): + yield + + else: + yield diff --git a/sdk/devcenter/azure-developer-devcenter/tests/test_devcenter_operations.py b/sdk/devcenter/azure-developer-devcenter/tests/test_devcenter_operations.py index 6ecb69357abf..6482d8d291fb 100644 --- a/sdk/devcenter/azure-developer-devcenter/tests/test_devcenter_operations.py +++ b/sdk/devcenter/azure-developer-devcenter/tests/test_devcenter_operations.py @@ -10,221 +10,413 @@ import logging from devtools_testutils import AzureRecordedTestCase, PowerShellPreparer, recorded_by_proxy from azure.identity import InteractiveBrowserCredential +from azure.identity import DefaultAzureCredential from azure.developer.devcenter import DevCenterClient -from azure.core.exceptions import HttpResponseError +from azure.developer.devcenter.models import DevBoxProvisioningState +from azure.developer.devcenter.models import OperationStatus from testcase import DevcenterPowerShellPreparer -from datetime import datetime, timedelta, timezone +from datetime import timedelta class TestDevcenter(AzureRecordedTestCase): def create_client(self, endpoint): credential = self.get_credential(DevCenterClient) return DevCenterClient(endpoint, credential=credential) - + + @DevcenterPowerShellPreparer() + @recorded_by_proxy + def test_get_project(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + + client = self.create_client(endpoint) + + project = client.get_project(project_name) + assert project is not None + assert project.name == project_name + + @DevcenterPowerShellPreparer() + @recorded_by_proxy + def test_list_projects(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + + client = self.create_client(endpoint) + + projects = list(client.list_projects()) + assert projects is not None + assert len(projects) == 1 + assert projects[0].name == project_name + @DevcenterPowerShellPreparer() @recorded_by_proxy - def test_devbox_operations(self, **kwargs): + def test_get_pool(self, **kwargs): self.logger = logging.getLogger(__name__) endpoint = kwargs.pop("devcenter_endpoint") project_name = kwargs.pop("devcenter_project_name") pool_name = kwargs.pop("devcenter_pool_name") - user = kwargs.pop("devcenter_test_user_id") - devbox_name = kwargs.pop("devcenter_devbox_name") - time_format = "%Y-%m-%dT%H:%M:%S.%fZ" - default_user = "me" client = self.create_client(endpoint) - # Pools pool_response = client.get_pool(project_name, pool_name) - assert pool_response["name"] == pool_name + assert pool_response is not None + assert pool_response.name == pool_name + + @DevcenterPowerShellPreparer() + @recorded_by_proxy + def test_get_pools(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + pool_name = kwargs.pop("devcenter_pool_name") + + client = self.create_client(endpoint) - pools_response = client.list_pools(project_name) - assert pools_response.next()["name"] == pool_response["name"] + pools_response = list(client.list_pools(project_name)) + assert pools_response is not None + assert len(pools_response) == 1 + assert pools_response[0].name == pool_name - # Schedules + @DevcenterPowerShellPreparer() + @recorded_by_proxy + def test_get_schedule(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + pool_name = kwargs.pop("devcenter_pool_name") + + client = self.create_client(endpoint) + + # Schedule schedule_response = client.get_schedule(project_name, pool_name, "default") - assert schedule_response["name"] == "default" + assert schedule_response is not None + assert schedule_response.name == "default" + + @DevcenterPowerShellPreparer() + @recorded_by_proxy + def test_get_schedules(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + pool_name = kwargs.pop("devcenter_pool_name") + + client = self.create_client(endpoint) - schedules_response = client.list_schedules(project_name, pool_name) - assert schedules_response.next()["name"] == schedule_response["name"] + # Schedules + schedules_response = list(client.list_schedules(project_name, pool_name)) + assert schedules_response is not None + assert len(schedules_response) == 1 + assert schedules_response[0].name == "default" + + @DevcenterPowerShellPreparer() + @recorded_by_proxy + def test_create_dev_box(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + pool_name = kwargs.pop("devcenter_pool_name") + user = kwargs.pop("devcenter_test_user_id") + devbox_name = kwargs.pop("devcenter_devbox_name") + + client = self.create_client(endpoint) # Create DevBox - create_devbox_response = client.begin_create_dev_box( - project_name, user, devbox_name, {"poolName": pool_name} - ) + create_devbox_response = client.begin_create_dev_box(project_name, user, devbox_name, {"poolName": pool_name}) devbox_result = create_devbox_response.result() - assert devbox_result["provisioningState"] in ["Succeeded", "ProvisionedWithWarning"] + assert devbox_result is not None + assert devbox_result.provisioning_state in [ + DevBoxProvisioningState.SUCCEEDED, + DevBoxProvisioningState.PROVISIONED_WITH_WARNING, + ] + + @DevcenterPowerShellPreparer() + @recorded_by_proxy + def test_dev_box_action(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + devbox_name = kwargs.pop("devcenter_devbox_name") + default_user = "me" + + client = self.create_client(endpoint) # Actions - action_response = client.get_dev_box_action( - project_name, default_user, devbox_name, "schedule-default" - ) - next_time_str = action_response["next"]["scheduledTime"] - next_time_date = datetime.strptime(next_time_str, time_format) - assert action_response["name"] == "schedule-default" + action_response = client.get_dev_box_action(project_name, default_user, devbox_name, "schedule-default") + next_time_date = action_response.next.scheduled_time + assert next_time_date is not None + assert action_response.name == "schedule-default" - actions_response = client.list_dev_box_actions(project_name, user, devbox_name) - assert actions_response.next()["name"] == action_response["name"] + actions_response = list(client.list_dev_box_actions(project_name, default_user, devbox_name)) + assert actions_response[0].name == action_response.name next_time_date = next_time_date + timedelta(hours=1) - delay_all_response = client.delay_all_dev_box_actions( - project_name, default_user, devbox_name, delay_until=next_time_date + delay_all_response = list( + client.delay_all_dev_box_actions(project_name, default_user, devbox_name, delay_until=next_time_date) ) - assert delay_all_response.next()["action"]["next"]["scheduledTime"] == next_time_date.strftime(time_format) + assert delay_all_response[0].action.next.scheduled_time == next_time_date # Failing with a 400 saying the date range isn't valid, even though the delay_all works just fine. next_time_date = next_time_date + timedelta(hours=1) delay_response = client.delay_dev_box_action( project_name, default_user, devbox_name, "schedule-default", delay_until=next_time_date ) - assert delay_response["next"]["scheduledTime"] == next_time_date.strftime(time_format) + assert delay_response.next.scheduled_time == next_time_date client.skip_dev_box_action(project_name, default_user, devbox_name, "schedule-default") - # Dev Box: - # list_all_dev_boxes, get_dev_box, list_dev_boxes, list_all_dev_boxes_by_user + @DevcenterPowerShellPreparer() + @recorded_by_proxy + def test_get_dev_box(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + devbox_name = kwargs.pop("devcenter_devbox_name") + default_user = "me" + + client = self.create_client(endpoint) devbox_response = client.get_dev_box(project_name, default_user, devbox_name) - assert devbox_response["name"] == devbox_name + assert devbox_response.name == devbox_name + + @DevcenterPowerShellPreparer() + @recorded_by_proxy + def test_list_dev_boxes(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + devbox_name = kwargs.pop("devcenter_devbox_name") + default_user = "me" + + client = self.create_client(endpoint) devboxes_response = client.list_dev_boxes(project_name, default_user) - filtered_devbox_response = filter(lambda x: x["name"] == devbox_name, devboxes_response) + filtered_devbox_response = filter(lambda x: x.name == devbox_name, devboxes_response) assert len(list(filtered_devbox_response)) == 1 + @DevcenterPowerShellPreparer() + @recorded_by_proxy + def test_list_all_dev_boxes(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + devbox_name = kwargs.pop("devcenter_devbox_name") + default_user = "me" + + client = self.create_client(endpoint) + devboxes_response = client.list_all_dev_boxes() filtered_devbox_response = filter( - lambda x: x["name"] == devbox_name and x["projectName"] == project_name, devboxes_response + lambda x: x.name == devbox_name and x.project_name == project_name, devboxes_response ) assert len(list(filtered_devbox_response)) == 1 + @DevcenterPowerShellPreparer() + @recorded_by_proxy + def test_list_all_dev_boxes_by_user(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + devbox_name = kwargs.pop("devcenter_devbox_name") + default_user = "me" + + client = self.create_client(endpoint) + devboxes_response = client.list_all_dev_boxes_by_user(default_user) filtered_devbox_response = filter( - lambda x: x["name"] == devbox_name and x["projectName"] == project_name, devboxes_response + lambda x: x.name == devbox_name and x.project_name == project_name, devboxes_response ) assert len(list(filtered_devbox_response)) == 1 - # get_remote_connection + @DevcenterPowerShellPreparer() + @recorded_by_proxy + def test_get_remote_connection(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + devbox_name = kwargs.pop("devcenter_devbox_name") + default_user = "me" + + client = self.create_client(endpoint) + connection_response = client.get_remote_connection(project_name, default_user, devbox_name) - assert connection_response["webUrl"] != None + assert connection_response.web_url is not None + + @DevcenterPowerShellPreparer() + @recorded_by_proxy + def test_restart_dev_box(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + devbox_name = kwargs.pop("devcenter_devbox_name") + default_user = "me" + + client = self.create_client(endpoint) - # begin_stop_dev_box, begin_start_dev_box, begin_delete_dev_box, begin_restart_dev_box restart_response = client.begin_restart_dev_box(project_name, default_user, devbox_name) restart_result = restart_response.result() - assert restart_result["status"] == "Succeeded" + assert restart_result.status == OperationStatus.SUCCEEDED + + @DevcenterPowerShellPreparer() + @recorded_by_proxy + def test_stop_start_delete_dev_box(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + devbox_name = kwargs.pop("devcenter_devbox_name") + default_user = "me" + + client = self.create_client(endpoint) stop_response = client.begin_stop_dev_box(project_name, default_user, devbox_name) stop_result = stop_response.result() - assert stop_result["status"] == "Succeeded" + assert stop_result.status == OperationStatus.SUCCEEDED start_response = client.begin_start_dev_box(project_name, default_user, devbox_name) start_result = start_response.result() - assert start_result["status"] == "Succeeded" + assert start_result.status == OperationStatus.SUCCEEDED delete_response = client.begin_delete_dev_box(project_name, default_user, devbox_name) delete_result = delete_response.result() - assert delete_result["status"] == "Succeeded" + assert delete_result.status == OperationStatus.SUCCEEDED @DevcenterPowerShellPreparer() @recorded_by_proxy - def test_environment_operations(self, **kwargs): + def test_get_catalog(self, **kwargs): self.logger = logging.getLogger(__name__) endpoint = kwargs.pop("devcenter_endpoint") project_name = kwargs.pop("devcenter_project_name") - environment_type_name = kwargs.pop("devcenter_environment_type_name") catalog_name = kwargs.pop("devcenter_catalog_name") - env_definition_name = kwargs.pop("devcenter_environment_definition_name") - env_name = kwargs.pop("devcenter_environment_name") - default_user = "me" client = self.create_client(endpoint) - # Catalogs catalog_response = client.get_catalog(project_name, catalog_name) - assert catalog_response["name"] == catalog_name + assert catalog_response.name == catalog_name + + @DevcenterPowerShellPreparer() + @recorded_by_proxy + def test_list_catalogs(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + catalog_name = kwargs.pop("devcenter_catalog_name") + + client = self.create_client(endpoint) catalogs_response = client.list_catalogs(project_name) catalogs_response = list(catalogs_response) - filtered_catalog_response = filter(lambda x: x["name"] == catalog_name, catalogs_response) + filtered_catalog_response = filter(lambda x: x.name == catalog_name, catalogs_response) filtered_catalog_response = list(filtered_catalog_response) assert len(filtered_catalog_response) == 1 - assert filtered_catalog_response[0]["name"] == catalog_response["name"] + assert filtered_catalog_response[0].name == catalog_name - # Environment Definitions - env_definition_response = client.get_environment_definition( - project_name, catalog_name, env_definition_name - ) - assert env_definition_response["name"] == env_definition_name + @DevcenterPowerShellPreparer() + @recorded_by_proxy + def test_get_environment_definition(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + catalog_name = kwargs.pop("devcenter_catalog_name") + env_definition_name = kwargs.pop("devcenter_environment_definition_name") + + client = self.create_client(endpoint) + + env_definition_response = client.get_environment_definition(project_name, catalog_name, env_definition_name) + assert env_definition_response.name == env_definition_name + + @DevcenterPowerShellPreparer() + @recorded_by_proxy + def test_list_environment_definitions(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + env_definition_name = kwargs.pop("devcenter_environment_definition_name") + + client = self.create_client(endpoint) all_env_definition_response = client.list_environment_definitions(project_name) filtered_all_env_definition_response = filter( - lambda x: x["name"] == env_definition_name, all_env_definition_response + lambda x: x.name == env_definition_name, all_env_definition_response ) filtered_all_env_definition_response = list(filtered_all_env_definition_response) assert ( len(filtered_all_env_definition_response) == 1 - and filtered_all_env_definition_response[0]["name"] == env_definition_response["name"] + and filtered_all_env_definition_response[0].name == env_definition_name ) - env_definitions_response = client.list_environment_definitions_by_catalog( - project_name, catalog_name - ) - filtered_env_definitions_response = filter(lambda x: x["name"] == env_definition_name, env_definitions_response) + @DevcenterPowerShellPreparer() + @recorded_by_proxy + def test_list_environment_definitions_by_catalog(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + catalog_name = kwargs.pop("devcenter_catalog_name") + env_definition_name = kwargs.pop("devcenter_environment_definition_name") + + client = self.create_client(endpoint) + + env_definitions_response = client.list_environment_definitions_by_catalog(project_name, catalog_name) + filtered_env_definitions_response = filter(lambda x: x.name == env_definition_name, env_definitions_response) filtered_env_definitions_response = list(filtered_env_definitions_response) assert ( len(filtered_env_definitions_response) == 1 - and filtered_env_definitions_response[0]["name"] == env_definition_response["name"] + and filtered_env_definitions_response[0].name == env_definition_name ) - # Environment Types + @DevcenterPowerShellPreparer() + @recorded_by_proxy + def test_list_environment_types(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + environment_type_name = kwargs.pop("devcenter_environment_type_name") + + client = self.create_client(endpoint) + env_types_response = client.list_environment_types(project_name) - filtered_env_types_response = filter(lambda x: x["name"] == environment_type_name, env_types_response) + filtered_env_types_response = filter(lambda x: x.name == environment_type_name, env_types_response) filtered_env_types_response = list(filtered_env_types_response) - assert len(filtered_env_types_response) == 1 and filtered_env_types_response[0]["name"] == environment_type_name + assert len(filtered_env_types_response) == 1 and filtered_env_types_response[0].name == environment_type_name + + @DevcenterPowerShellPreparer() + @recorded_by_proxy + def test_environments(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + environment_type_name = kwargs.pop("devcenter_environment_type_name") + catalog_name = kwargs.pop("devcenter_catalog_name") + env_definition_name = kwargs.pop("devcenter_environment_definition_name") + env_name = kwargs.pop("devcenter_environment_name") + default_user = "me" + + client = self.create_client(endpoint) - # Environments environment = { + "environmentType": environment_type_name, "catalogName": catalog_name, "environmentDefinitionName": env_definition_name, - "environmentType": environment_type_name, } create_env_response = client.begin_create_or_update_environment( project_name, default_user, env_name, environment ) create_env_result = create_env_response.result() - assert create_env_result["provisioningState"] == "Succeeded" + assert create_env_result.provisioning_state == DevBoxProvisioningState.SUCCEEDED env_response = client.get_environment(project_name, default_user, env_name) - assert env_response["name"] == env_name + assert env_response.name == env_name envs_response = client.list_environments(project_name, default_user) - envs_response = filter(lambda x: x["name"] == env_name, envs_response) + envs_response = filter(lambda x: x.name == env_name, envs_response) envs_response = list(envs_response) - assert len(envs_response) == 1 and envs_response[0]["name"] == env_response["name"] + assert len(envs_response) == 1 and envs_response[0].name == env_response.name all_envs_response = client.list_all_environments(project_name) - all_envs_response = filter(lambda x: x["name"] == env_name, all_envs_response) + all_envs_response = filter(lambda x: x.name == env_name, all_envs_response) all_envs_response = list(all_envs_response) - assert len(all_envs_response) == 1 and all_envs_response[0]["name"] == env_response["name"] + assert len(all_envs_response) == 1 and all_envs_response[0].name == env_response.name delete_response = client.begin_delete_environment(project_name, default_user, env_name) delete_result = delete_response.result() - assert delete_result["status"] == "Succeeded" - - @DevcenterPowerShellPreparer() - @recorded_by_proxy - def test_devcenter_operations(self, **kwargs): - self.logger = logging.getLogger(__name__) - endpoint = kwargs.pop("devcenter_endpoint") - project_name = kwargs.pop("devcenter_project_name") - - client = self.create_client(endpoint) - - # Projects - project_response = client.get_project(project_name) - assert project_response["name"] == project_name - - projects_response = client.list_projects() - projects_response = filter(lambda x: x["name"] == project_name, projects_response) - projects_response = list(projects_response) - assert len(projects_response) == 1 and projects_response[0]["name"] == project_response["name"] + assert delete_result.status == OperationStatus.SUCCEEDED diff --git a/sdk/devcenter/azure-developer-devcenter/tests/test_devcenter_operations_async.py b/sdk/devcenter/azure-developer-devcenter/tests/test_devcenter_operations_async.py new file mode 100644 index 000000000000..d5023a07a7e0 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/tests/test_devcenter_operations_async.py @@ -0,0 +1,468 @@ +# 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. +# -------------------------------------------------------------------------- +import functools +import os +import pytest +import logging +from devtools_testutils import AzureRecordedTestCase +from devtools_testutils.aio import recorded_by_proxy_async +from azure.developer.devcenter.aio import DevCenterClient +from azure.developer.devcenter.models import DevBoxProvisioningState +from azure.developer.devcenter.models import OperationStatus +from testcase import DevcenterPowerShellPreparer +from datetime import timedelta + + +class TestDevcenterAsync(AzureRecordedTestCase): + def create_client(self, endpoint): + credential = self.get_credential(DevCenterClient) + return DevCenterClient(endpoint, credential=credential) + + @DevcenterPowerShellPreparer() + @recorded_by_proxy_async + async def test_get_project_async(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + + client = self.create_client(endpoint) + + async with client: + project = await client.get_project(project_name) + assert project is not None + assert project.name == project_name + + @DevcenterPowerShellPreparer() + @recorded_by_proxy_async + async def test_list_projects_async(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + + client = self.create_client(endpoint) + + async with client: + projects = [] + + async for project in client.list_projects(): + projects.append(project) + + assert projects is not None + assert len(projects) == 1 + assert projects[0].name == project_name + + @DevcenterPowerShellPreparer() + @recorded_by_proxy_async + async def test_get_pool_async(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + pool_name = kwargs.pop("devcenter_pool_name") + + client = self.create_client(endpoint) + + async with client: + pool_response = await client.get_pool(project_name, pool_name) + assert pool_response is not None + assert pool_response.name == pool_name + + @DevcenterPowerShellPreparer() + @recorded_by_proxy_async + async def test_get_pools_async(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + pool_name = kwargs.pop("devcenter_pool_name") + + client = self.create_client(endpoint) + + async with client: + pools_response = [] + async for pool in client.list_pools(project_name): + pools_response.append(pool) + + assert pools_response is not None + assert len(pools_response) == 1 + assert pools_response[0].name == pool_name + + @DevcenterPowerShellPreparer() + @recorded_by_proxy_async + async def test_get_schedule_async(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + pool_name = kwargs.pop("devcenter_pool_name") + + client = self.create_client(endpoint) + + async with client: + # Schedule + schedule_response = await client.get_schedule(project_name, pool_name, "default") + assert schedule_response is not None + assert schedule_response.name == "default" + + @DevcenterPowerShellPreparer() + @recorded_by_proxy_async + async def test_get_schedules_async(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + pool_name = kwargs.pop("devcenter_pool_name") + + client = self.create_client(endpoint) + + async with client: + # Schedules + schedules_response = [] + async for schedule in client.list_schedules(project_name, pool_name): + schedules_response.append(schedule) + + assert schedules_response is not None + assert len(schedules_response) == 1 + assert schedules_response[0].name == "default" + + @DevcenterPowerShellPreparer() + @recorded_by_proxy_async + async def test_create_dev_box_async(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + pool_name = kwargs.pop("devcenter_pool_name") + user = kwargs.pop("devcenter_test_user_id") + devbox_name = kwargs.pop("devcenter_devbox_name") + + client = self.create_client(endpoint) + + async with client: + # Create DevBox + create_devbox_response = await client.begin_create_dev_box(project_name, user, devbox_name, {"poolName": pool_name}) + devbox_result = await create_devbox_response.result() + assert devbox_result is not None + assert devbox_result.provisioning_state in [ + DevBoxProvisioningState.SUCCEEDED, + DevBoxProvisioningState.PROVISIONED_WITH_WARNING, + ] + + @DevcenterPowerShellPreparer() + @recorded_by_proxy_async + async def test_dev_box_action_async(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + devbox_name = kwargs.pop("devcenter_devbox_name") + default_user = "me" + + client = self.create_client(endpoint) + + async with client: + # Actions + action_response = await client.get_dev_box_action(project_name, default_user, devbox_name, "schedule-default") + next_time_date = action_response.next.scheduled_time + assert next_time_date is not None + assert action_response.name == "schedule-default" + + actions_response = [] + async for action in client.list_dev_box_actions(project_name, default_user, devbox_name): + actions_response.append(action) + assert actions_response[0].name == action_response.name + + next_time_date = next_time_date + timedelta(hours=1) + delay_all_response = [] + async for action in client.delay_all_dev_box_actions(project_name, default_user, devbox_name, delay_until=next_time_date): + delay_all_response.append(action) + assert delay_all_response[0].action.next.scheduled_time == next_time_date + + # Failing with a 400 saying the date range isn't valid, even though the delay_all works just fine. + next_time_date = next_time_date + timedelta(hours=1) + delay_response = await client.delay_dev_box_action( + project_name, default_user, devbox_name, "schedule-default", delay_until=next_time_date + ) + assert delay_response.next.scheduled_time == next_time_date + + await client.skip_dev_box_action(project_name, default_user, devbox_name, "schedule-default") + + @DevcenterPowerShellPreparer() + @recorded_by_proxy_async + async def test_get_dev_box_async(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + devbox_name = kwargs.pop("devcenter_devbox_name") + default_user = "me" + + client = self.create_client(endpoint) + + async with client: + devbox_response = await client.get_dev_box(project_name, default_user, devbox_name) + assert devbox_response.name == devbox_name + + @DevcenterPowerShellPreparer() + @recorded_by_proxy_async + async def test_list_dev_boxes_async(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + devbox_name = kwargs.pop("devcenter_devbox_name") + default_user = "me" + + client = self.create_client(endpoint) + + async with client: + devboxes = [] + async for devbox in client.list_dev_boxes(project_name, default_user): + if devbox.name == devbox_name: + devboxes.append(devbox) + + assert len(devboxes) == 1 + + @DevcenterPowerShellPreparer() + @recorded_by_proxy_async + async def test_list_all_dev_boxes_async(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + devbox_name = kwargs.pop("devcenter_devbox_name") + + client = self.create_client(endpoint) + + async with client: + devboxes = [] + async for devbox in client.list_all_dev_boxes(): + if devbox.name == devbox_name and devbox.project_name == project_name: + devboxes.append(devbox) + + assert len(devboxes) == 1 + + @DevcenterPowerShellPreparer() + @recorded_by_proxy_async + async def test_list_all_dev_boxes_by_user_async(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + devbox_name = kwargs.pop("devcenter_devbox_name") + default_user = "me" + + client = self.create_client(endpoint) + + async with client: + devboxes = [] + async for devbox in client.list_all_dev_boxes_by_user(default_user): + if devbox.name == devbox_name and devbox.project_name == project_name: + devboxes.append(devbox) + + assert len(devboxes) == 1 + + @DevcenterPowerShellPreparer() + @recorded_by_proxy_async + async def test_get_remote_connection_async(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + devbox_name = kwargs.pop("devcenter_devbox_name") + default_user = "me" + + client = self.create_client(endpoint) + + async with client: + connection_response = await client.get_remote_connection(project_name, default_user, devbox_name) + assert connection_response.web_url is not None + + @DevcenterPowerShellPreparer() + @recorded_by_proxy_async + async def test_restart_dev_box_async(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + devbox_name = kwargs.pop("devcenter_devbox_name") + default_user = "me" + + client = self.create_client(endpoint) + + async with client: + restart_response = await client.begin_restart_dev_box(project_name, default_user, devbox_name) + restart_result = await restart_response.result() + assert restart_result.status == OperationStatus.SUCCEEDED + + @DevcenterPowerShellPreparer() + @recorded_by_proxy_async + async def test_stop_start_delete_dev_box_async(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + devbox_name = kwargs.pop("devcenter_devbox_name") + default_user = "me" + + client = self.create_client(endpoint) + + async with client: + stop_response = await client.begin_stop_dev_box(project_name, default_user, devbox_name) + stop_result = await stop_response.result() + assert stop_result.status == OperationStatus.SUCCEEDED + + start_response = await client.begin_start_dev_box(project_name, default_user, devbox_name) + start_result = await start_response.result() + assert start_result.status == OperationStatus.SUCCEEDED + + delete_response = await client.begin_delete_dev_box(project_name, default_user, devbox_name) + delete_result = await delete_response.result() + assert delete_result.status == OperationStatus.SUCCEEDED + + @DevcenterPowerShellPreparer() + @recorded_by_proxy_async + async def test_get_catalog_async(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + catalog_name = kwargs.pop("devcenter_catalog_name") + + client = self.create_client(endpoint) + + async with client: + catalog_response = await client.get_catalog(project_name, catalog_name) + assert catalog_response.name == catalog_name + + @DevcenterPowerShellPreparer() + @recorded_by_proxy_async + async def test_list_catalogs_async(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + catalog_name = kwargs.pop("devcenter_catalog_name") + + client = self.create_client(endpoint) + + async with client: + catalogs = [] + async for catalog in client.list_catalogs(project_name): + if catalog.name == catalog_name: + catalogs.append(catalog) + + assert len(catalogs) == 1 + assert catalogs[0].name == catalog_name + + @DevcenterPowerShellPreparer() + @recorded_by_proxy_async + async def test_get_environment_definition_async(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + catalog_name = kwargs.pop("devcenter_catalog_name") + env_definition_name = kwargs.pop("devcenter_environment_definition_name") + + client = self.create_client(endpoint) + + async with client: + env_definition_response = await client.get_environment_definition(project_name, catalog_name, env_definition_name) + assert env_definition_response.name == env_definition_name + + @DevcenterPowerShellPreparer() + @recorded_by_proxy_async + async def test_list_environment_definitions_async(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + env_definition_name = kwargs.pop("devcenter_environment_definition_name") + + client = self.create_client(endpoint) + + async with client: + env_definitions = [] + async for env_definition in client.list_environment_definitions(project_name): + if env_definition.name == env_definition_name: + env_definitions.append(env_definition) + + assert len(env_definitions) == 1 + assert env_definitions[0].name == env_definition_name + + @DevcenterPowerShellPreparer() + @recorded_by_proxy_async + async def test_list_environment_definitions_by_catalog_async(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + catalog_name = kwargs.pop("devcenter_catalog_name") + env_definition_name = kwargs.pop("devcenter_environment_definition_name") + + client = self.create_client(endpoint) + + async with client: + env_definitions = [] + async for env_definition in client.list_environment_definitions_by_catalog(project_name, catalog_name): + if env_definition.name == env_definition_name: + env_definitions.append(env_definition) + + assert len(env_definitions) == 1 + assert env_definitions[0].name == env_definition_name + + @DevcenterPowerShellPreparer() + @recorded_by_proxy_async + async def test_list_environment_types_async(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + environment_type_name = kwargs.pop("devcenter_environment_type_name") + + client = self.create_client(endpoint) + + async with client: + env_types = [] + async for env_type in client.list_environment_types(project_name): + if env_type.name == environment_type_name: + env_types.append(env_type) + + assert len(env_types) == 1 + assert env_types[0].name == environment_type_name + + @DevcenterPowerShellPreparer() + @recorded_by_proxy_async + async def test_environments_async(self, **kwargs): + self.logger = logging.getLogger(__name__) + endpoint = kwargs.pop("devcenter_endpoint") + project_name = kwargs.pop("devcenter_project_name") + environment_type_name = kwargs.pop("devcenter_environment_type_name") + catalog_name = kwargs.pop("devcenter_catalog_name") + env_definition_name = kwargs.pop("devcenter_environment_definition_name") + env_name = kwargs.pop("devcenter_environment_name") + default_user = "me" + + client = self.create_client(endpoint) + + environment = { + "environmentType": environment_type_name, + "catalogName": catalog_name, + "environmentDefinitionName": env_definition_name, + } + + async with client: + create_env_response = await client.begin_create_or_update_environment( + project_name, default_user, env_name, environment + ) + create_env_result = await create_env_response.result() + assert create_env_result.provisioning_state == DevBoxProvisioningState.SUCCEEDED + + env_response = await client.get_environment(project_name, default_user, env_name) + assert env_response.name == env_name + + envs = [] + async for env in client.list_environments(project_name, default_user): + if env.name == env_name: + envs.append(env) + + assert len(envs) == 1 + assert envs[0].name == env_name + + all_envs = [] + async for env in client.list_all_environments(project_name): + if env.name == env_name: + all_envs.append(env) + + assert len(all_envs) == 1 + assert all_envs[0].name == env_name + + delete_response = await client.begin_delete_environment(project_name, default_user, env_name) + delete_result = await delete_response.result() + assert delete_result.status == OperationStatus.SUCCEEDED \ No newline at end of file diff --git a/sdk/devcenter/azure-developer-devcenter/tests/testcase.py b/sdk/devcenter/azure-developer-devcenter/tests/testcase.py index 40018f426313..188bafb0696f 100644 --- a/sdk/devcenter/azure-developer-devcenter/tests/testcase.py +++ b/sdk/devcenter/azure-developer-devcenter/tests/testcase.py @@ -17,7 +17,7 @@ def create_client(self, endpoint): DevcenterPowerShellPreparer = functools.partial( - PowerShellPreparer, + EnvironmentVariableLoader, "devcenter", devcenter_endpoint="https://dddd3333-d3d3-3333-d3d3-dddddd333333-fake-dev-center.location.devcenter.azure.com", devcenter_project_name="fake-proj", diff --git a/sdk/devcenter/azure-developer-devcenter/tsp-location.yaml b/sdk/devcenter/azure-developer-devcenter/tsp-location.yaml index 4417efbdd44c..c0db4e4e25d4 100644 --- a/sdk/devcenter/azure-developer-devcenter/tsp-location.yaml +++ b/sdk/devcenter/azure-developer-devcenter/tsp-location.yaml @@ -1,4 +1,4 @@ directory: specification/devcenter/DevCenter -commit: 74e93fc9fb00380250110fba78dadfebeb93cbf1 +commit: d17b385b2e840c541b50f1d415dab6fd408d0814 repo: Azure/azure-rest-api-specs cleanup: true