diff --git a/sdk/devcenter/azure-developer-devcenter/_meta.json b/sdk/devcenter/azure-developer-devcenter/_meta.json new file mode 100644 index 00000000000..6a52790c86f --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/_meta.json @@ -0,0 +1,6 @@ +{ + "commit": "3b3adcf656a508f2806ab4c2596d50b3db7dcfaf", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "typespec_src": "specification/devcenter/DevCenter", + "@azure-tools/typespec-python": "0.38.3" +} \ No newline at end of file diff --git a/sdk/devcenter/azure-developer-devcenter/apiview-properties.json b/sdk/devcenter/azure-developer-devcenter/apiview-properties.json new file mode 100644 index 00000000000..349d5a9c442 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/apiview-properties.json @@ -0,0 +1,70 @@ +{ + "CrossLanguagePackageId": "DevCenterService", + "CrossLanguageDefinitionId": { + "azure.developer.devcenter.models.Catalog": "DevCenterService.Catalog", + "azure.developer.devcenter.models.DevBox": "DevCenterService.DevBox", + "azure.developer.devcenter.models.DevBoxAction": "DevCenterService.DevBoxAction", + "azure.developer.devcenter.models.DevBoxActionDelayResult": "DevCenterService.DevBoxActionDelayResult", + "azure.developer.devcenter.models.DevBoxNextAction": "DevCenterService.DevBoxNextAction", + "azure.developer.devcenter.models.Environment": "DevCenterService.Environment", + "azure.developer.devcenter.models.EnvironmentDefinition": "DevCenterService.EnvironmentDefinition", + "azure.developer.devcenter.models.EnvironmentDefinitionParameter": "DevCenterService.EnvironmentDefinitionParameter", + "azure.developer.devcenter.models.EnvironmentType": "DevCenterService.EnvironmentType", + "azure.developer.devcenter.models.HardwareProfile": "DevCenterService.HardwareProfile", + "azure.developer.devcenter.models.ImageReference": "DevCenterService.ImageReference", + "azure.developer.devcenter.models.OsDisk": "DevCenterService.OsDisk", + "azure.developer.devcenter.models.Pool": "DevCenterService.Pool", + "azure.developer.devcenter.models.Project": "DevCenterService.Project", + "azure.developer.devcenter.models.RemoteConnection": "DevCenterService.RemoteConnection", + "azure.developer.devcenter.models.Schedule": "DevCenterService.Schedule", + "azure.developer.devcenter.models.StopOnDisconnectConfiguration": "DevCenterService.StopOnDisconnectConfiguration", + "azure.developer.devcenter.models.StorageProfile": "DevCenterService.StorageProfile", + "azure.developer.devcenter.models.OsType": "DevCenterService.OsType", + "azure.developer.devcenter.models.SkuName": "DevCenterService.SkuName", + "azure.developer.devcenter.models.HibernateSupport": "DevCenterService.HibernateSupport", + "azure.developer.devcenter.models.LocalAdministratorStatus": "DevCenterService.LocalAdminStatus", + "azure.developer.devcenter.models.StopOnDisconnectStatus": "DevCenterService.StopOnDisconnectEnableStatus", + "azure.developer.devcenter.models.PoolHealthStatus": "DevCenterService.PoolHealthStatus", + "azure.developer.devcenter.models.ScheduledType": "DevCenterService.ScheduledType", + "azure.developer.devcenter.models.ScheduledFrequency": "DevCenterService.ScheduledFrequency", + "azure.developer.devcenter.models.DevBoxProvisioningState": "DevCenterService.DevBoxProvisioningState", + "azure.developer.devcenter.models.PowerState": "DevCenterService.PowerState", + "azure.developer.devcenter.models.DevBoxActionType": "DevCenterService.DevBoxActionType", + "azure.developer.devcenter.models.DevBoxActionDelayStatus": "DevCenterService.DevBoxActionDelayResultStatus", + "azure.developer.devcenter.models.EnvironmentProvisioningState": "DevCenterService.EnvironmentProvisioningState", + "azure.developer.devcenter.models.ParameterType": "DevCenterService.ParameterType", + "azure.developer.devcenter.models.EnvironmentTypeStatus": "DevCenterService.EnvironmentTypeEnableStatus", + "azure.developer.devcenter.DevCenterClient.list_projects": "SdkCustomizations.DevCenterClientOperations.listProjects", + "azure.developer.devcenter.DevCenterClient.get_project": "SdkCustomizations.DevCenterClientOperations.getProject", + "azure.developer.devcenter.DevBoxesClient.list_pools": "SdkCustomizations.DevBoxesClientOperations.listPools", + "azure.developer.devcenter.DevBoxesClient.get_pool": "SdkCustomizations.DevBoxesClientOperations.getPool", + "azure.developer.devcenter.DevBoxesClient.list_schedules": "SdkCustomizations.DevBoxesClientOperations.listSchedules", + "azure.developer.devcenter.DevBoxesClient.get_schedule": "SdkCustomizations.DevBoxesClientOperations.getSchedule", + "azure.developer.devcenter.DevBoxesClient.list_all_dev_boxes": "SdkCustomizations.DevBoxesClientOperations.listAllDevBoxes", + "azure.developer.devcenter.DevBoxesClient.list_all_dev_boxes_by_user": "SdkCustomizations.DevBoxesClientOperations.listAllDevBoxesByUser", + "azure.developer.devcenter.DevBoxesClient.list_dev_boxes": "SdkCustomizations.DevBoxesClientOperations.listDevBoxes", + "azure.developer.devcenter.DevBoxesClient.get_dev_box": "SdkCustomizations.DevBoxesClientOperations.getDevBox", + "azure.developer.devcenter.DevBoxesClient.begin_create_dev_box": "SdkCustomizations.DevBoxesClientOperations.createDevBox", + "azure.developer.devcenter.DevBoxesClient.begin_delete_dev_box": "SdkCustomizations.DevBoxesClientOperations.deleteDevBox", + "azure.developer.devcenter.DevBoxesClient.begin_start_dev_box": "SdkCustomizations.DevBoxesClientOperations.startDevBox", + "azure.developer.devcenter.DevBoxesClient.begin_stop_dev_box": "SdkCustomizations.DevBoxesClientOperations.stopDevBox", + "azure.developer.devcenter.DevBoxesClient.begin_restart_dev_box": "SdkCustomizations.DevBoxesClientOperations.restartDevBox", + "azure.developer.devcenter.DevBoxesClient.get_remote_connection": "SdkCustomizations.DevBoxesClientOperations.getRemoteConnection", + "azure.developer.devcenter.DevBoxesClient.list_dev_box_actions": "SdkCustomizations.DevBoxesClientOperations.listDevBoxActions", + "azure.developer.devcenter.DevBoxesClient.get_dev_box_action": "SdkCustomizations.DevBoxesClientOperations.getDevBoxAction", + "azure.developer.devcenter.DevBoxesClient.skip_action": "SdkCustomizations.DevBoxesClientOperations.skipAction", + "azure.developer.devcenter.DevBoxesClient.delay_action": "SdkCustomizations.DevBoxesClientOperations.delayAction", + "azure.developer.devcenter.DevBoxesClient.delay_all_actions": "SdkCustomizations.DevBoxesClientOperations.delayAllActions", + "azure.developer.devcenter.DeploymentEnvironmentsClient.list_all_environments": "SdkCustomizations.EnvironmentClientOperations.listAllEnvironments", + "azure.developer.devcenter.DeploymentEnvironmentsClient.list_environments": "SdkCustomizations.EnvironmentClientOperations.listEnvironments", + "azure.developer.devcenter.DeploymentEnvironmentsClient.get_environment": "SdkCustomizations.EnvironmentClientOperations.getEnvironment", + "azure.developer.devcenter.DeploymentEnvironmentsClient.begin_create_or_update_environment": "SdkCustomizations.EnvironmentClientOperations.createOrUpdateEnvironment", + "azure.developer.devcenter.DeploymentEnvironmentsClient.begin_delete_environment": "SdkCustomizations.EnvironmentClientOperations.deleteEnvironment", + "azure.developer.devcenter.DeploymentEnvironmentsClient.list_catalogs": "SdkCustomizations.EnvironmentClientOperations.listCatalogs", + "azure.developer.devcenter.DeploymentEnvironmentsClient.get_catalog": "SdkCustomizations.EnvironmentClientOperations.getCatalog", + "azure.developer.devcenter.DeploymentEnvironmentsClient.list_environment_definitions": "SdkCustomizations.EnvironmentClientOperations.listEnvironmentDefinitions", + "azure.developer.devcenter.DeploymentEnvironmentsClient.list_environment_definitions_by_catalog": "SdkCustomizations.EnvironmentClientOperations.listEnvironmentDefinitionsByCatalog", + "azure.developer.devcenter.DeploymentEnvironmentsClient.get_environment_definition": "SdkCustomizations.EnvironmentClientOperations.getEnvironmentDefinition", + "azure.developer.devcenter.DeploymentEnvironmentsClient.list_environment_types": "SdkCustomizations.EnvironmentClientOperations.listEnvironmentTypes" + } +} \ No newline at end of file diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/__init__.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/__init__.py index 7590310c9bd..6e828f9acd2 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/__init__.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/__init__.py @@ -5,22 +5,32 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._client import DevCenterClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import DevCenterClient # type: ignore +from ._client import DevBoxesClient # type: ignore +from ._client import DeploymentEnvironmentsClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # pylint: disable=unused-wildcard-import + from ._patch import * except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk __all__ = [ "DevCenterClient", + "DevBoxesClient", + "DeploymentEnvironmentsClient", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() 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 df902c7477b..0f20e874d04 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_client.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_client.py @@ -8,23 +8,106 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self from azure.core import PipelineClient from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse -from ._configuration import DevCenterClientConfiguration -from ._operations import DevCenterClientOperationsMixin +from ._configuration import ( + DeploymentEnvironmentsClientConfiguration, + DevBoxesClientConfiguration, + DevCenterClientConfiguration, +) +from ._operations import ( + DeploymentEnvironmentsClientOperationsMixin, + DevBoxesClientOperationsMixin, + DevCenterClientOperationsMixin, +) from ._serialization import Deserializer, Serializer if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class DevCenterClient(DevCenterClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword +class DevCenterClient(DevCenterClientOperationsMixin): """DevCenterClient. + :param endpoint: The DevCenter-specific URI to operate on. Required. + :type endpoint: str + :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. + :paramtype api_version: str + """ + + def __init__(self, endpoint: str, credential: "TokenCredential", **kwargs: Any) -> None: + _endpoint = "{endpoint}" + self._config = DevCenterClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) + + +class DevBoxesClient(DevBoxesClientOperationsMixin): + """DevBoxesClient. + :param endpoint: The DevCenter-specific URI to operate on. Required. :type endpoint: str :param credential: Credential used to authenticate requests to the service. Required. @@ -38,7 +121,84 @@ class DevCenterClient(DevCenterClientOperationsMixin): # pylint: disable=client def __init__(self, endpoint: str, credential: "TokenCredential", **kwargs: Any) -> None: _endpoint = "{endpoint}" - self._config = DevCenterClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + self._config = DevBoxesClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) + + +class DeploymentEnvironmentsClient(DeploymentEnvironmentsClientOperationsMixin): + """DeploymentEnvironmentsClient. + + :param endpoint: The DevCenter-specific URI to operate on. Required. + :type endpoint: str + :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. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__(self, endpoint: str, credential: "TokenCredential", **kwargs: Any) -> None: + _endpoint = "{endpoint}" + self._config = DeploymentEnvironmentsClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) _policies = kwargs.pop("policies", None) if _policies is None: _policies = [ @@ -91,7 +251,7 @@ def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: def close(self) -> None: self._client.close() - def __enter__(self) -> "DevCenterClient": + def __enter__(self) -> Self: self._client.__enter__() return self 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 e37ae956cc2..5779f304265 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_configuration.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_configuration.py @@ -13,11 +13,10 @@ from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class DevCenterClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long +class DevCenterClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for DevCenterClient. Note that all parameters used to create this instance are saved as instance @@ -62,3 +61,97 @@ def _configure(self, **kwargs: Any) -> None: self.authentication_policy = policies.BearerTokenCredentialPolicy( self.credential, *self.credential_scopes, **kwargs ) + + +class DevBoxesClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for DevBoxesClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: The DevCenter-specific URI to operate on. Required. + :type endpoint: str + :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. + :paramtype api_version: str + """ + + def __init__(self, endpoint: str, credential: "TokenCredential", **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2023-04-01") + + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.endpoint = endpoint + self.credential = credential + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://devcenter.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "developer-devcenter/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.BearerTokenCredentialPolicy( + self.credential, *self.credential_scopes, **kwargs + ) + + +class DeploymentEnvironmentsClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long + """Configuration for DeploymentEnvironmentsClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: The DevCenter-specific URI to operate on. Required. + :type endpoint: str + :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. + :paramtype api_version: str + """ + + def __init__(self, endpoint: str, credential: "TokenCredential", **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2023-04-01") + + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.endpoint = endpoint + self.credential = credential + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://devcenter.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "developer-devcenter/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.BearerTokenCredentialPolicy( + self.credential, *self.credential_scopes, **kwargs + ) 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 index 4b0f59f73e4..3072ee252ed 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_model_base.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_model_base.py @@ -1,11 +1,13 @@ +# pylint: disable=too-many-lines # 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 +# pylint: disable=protected-access, broad-except +import copy import calendar import decimal import functools @@ -18,6 +20,7 @@ import email.utils from datetime import datetime, date, time, timedelta, timezone from json import JSONEncoder +import xml.etree.ElementTree as ET from typing_extensions import Self import isodate from azure.core.exceptions import DeserializationError @@ -122,7 +125,7 @@ def _serialize_datetime(o, format: typing.Optional[str] = None): def _is_readonly(p): try: - return p._visibility == ["read"] # pylint: disable=protected-access + return p._visibility == ["read"] except AttributeError: return False @@ -285,6 +288,12 @@ def _deserialize_decimal(attr): return decimal.Decimal(str(attr)) +def _deserialize_int_as_str(attr): + if isinstance(attr, int): + return attr + return int(attr) + + _DESERIALIZE_MAPPING = { datetime: _deserialize_datetime, date: _deserialize_date, @@ -306,9 +315,11 @@ def _deserialize_decimal(attr): def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): + if annotation is int and rf and rf._format == "str": + return _deserialize_int_as_str if rf and rf._format: return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) - return _DESERIALIZE_MAPPING.get(annotation) + return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore def _get_type_alias_type(module_name: str, alias_name: str): @@ -362,15 +373,34 @@ def __ne__(self, other: typing.Any) -> bool: return not self.__eq__(other) def keys(self) -> typing.KeysView[str]: + """ + :returns: a set-like object providing a view on D's keys + :rtype: ~typing.KeysView + """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: + """ + :returns: an object providing a view on D's values + :rtype: ~typing.ValuesView + """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: + """ + :returns: set-like object providing a view on D's items + :rtype: ~typing.ItemsView + """ return self._data.items() def get(self, key: str, default: typing.Any = None) -> typing.Any: + """ + Get the value for key if key is in the dictionary, else default. + :param str key: The key to look up. + :param any default: The value to return if key is not in the dictionary. Defaults to None + :returns: D[k] if k in D, else d. + :rtype: any + """ try: return self[key] except KeyError: @@ -386,17 +416,38 @@ def pop(self, key: str, default: _T) -> _T: ... def pop(self, key: str, default: typing.Any) -> typing.Any: ... def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Removes specified key and return the corresponding value. + :param str key: The key to pop. + :param any default: The value to return if key is not in the dictionary + :returns: The value corresponding to the key. + :rtype: any + :raises KeyError: If key is not found and default is not given. + """ if default is _UNSET: return self._data.pop(key) return self._data.pop(key, default) def popitem(self) -> typing.Tuple[str, typing.Any]: + """ + Removes and returns some (key, value) pair + :returns: The (key, value) pair. + :rtype: tuple + :raises KeyError: if D is empty. + """ return self._data.popitem() def clear(self) -> None: + """ + Remove all items from D. + """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: + """ + Updates D from mapping/iterable E and F. + :param any args: Either a mapping object or an iterable of key-value pairs. + """ self._data.update(*args, **kwargs) @typing.overload @@ -406,6 +457,13 @@ def setdefault(self, key: str, default: None = None) -> None: ... def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Same as calling D.get(k, d), and setting D[k]=d if k not found + :param str key: The key to look up. + :param any default: The value to set if key is not in the dictionary + :returns: D[k] if k in D, else d. + :rtype: any + """ if default is _UNSET: return self._data.setdefault(key) return self._data.setdefault(key, default) @@ -440,6 +498,10 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m return float(o) if isinstance(o, enum.Enum): return o.value + if isinstance(o, int): + if format == "str": + return str(o) + return o try: # First try datetime.datetime return _serialize_datetime(o, format) @@ -470,11 +532,16 @@ def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typin return value if rf._is_model: return _deserialize(rf._type, value) + if isinstance(value, ET.Element): + value = _deserialize(rf._type, value) return _serialize(value, rf._format) class Model(_MyMutableMapping): _is_model = True + # label whether current class's _attr_to_rest_field has been calculated + # could not see _attr_to_rest_field directly because subclass inherits it from parent class + _calculated: typing.Set[str] = set() def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: class_name = self.__class__.__name__ @@ -485,10 +552,58 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: 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()} - ) + if args: # pylint: disable=too-many-nested-blocks + if isinstance(args[0], ET.Element): + existed_attr_keys = [] + model_meta = getattr(self, "_xml", {}) + + for rf in self._attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + # attribute + if prop_meta.get("attribute", False) and args[0].get(xml_name) is not None: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].get(xml_name)) + continue + + # unwrapped element is array + if prop_meta.get("unwrapped", False): + # unwrapped array could either use prop items meta/prop meta + if prop_meta.get("itemsName"): + xml_name = prop_meta.get("itemsName") + xml_ns = prop_meta.get("itemNs") + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + items = args[0].findall(xml_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, items) + continue + + # text element is primitive type + if prop_meta.get("text", False): + if args[0].text is not None: + dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].text) + continue + + # wrapped element could be normal property or array, it should only have one element + item = args[0].find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, item) + + # rest thing is additional properties + for e in args[0]: + if e.tag not in existed_attr_keys: + dict_to_pass[e.tag] = _convert_element(e) + else: + 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: @@ -506,55 +621,70 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: 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()) + def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: + if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: + # we know the last nine classes in mro are going to be 'Model', '_MyMutableMapping', 'MutableMapping', + # 'Mapping', 'Collection', 'Sized', 'Iterable', 'Container' and 'object' + mros = cls.__mro__[:-9][::-1] # ignore 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__") + for k, v in mro_class.__annotations__.items() + } + 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()) + cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") 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 + if hasattr(base, "__mapping__"): + base.__mapping__[discriminator or cls.__name__] = cls # type: ignore @classmethod - def _get_discriminator(cls, exist_discriminators) -> typing.Optional[str]: + def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: 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 + if isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators: + return v return None @classmethod def _deserialize(cls, data, exist_discriminators): - if not hasattr(cls, "__mapping__"): # pylint: disable=no-member + if not hasattr(cls, "__mapping__"): 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: + if discriminator is None: return cls(data) - return mapped_cls._deserialize(data, exist_discriminators) # pylint: disable=protected-access + exist_discriminators.append(discriminator._rest_name) + if isinstance(data, ET.Element): + model_meta = getattr(cls, "_xml", {}) + prop_meta = getattr(discriminator, "_xml", {}) + xml_name = prop_meta.get("name", discriminator._rest_name) + xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + if data.get(xml_name) is not None: + discriminator_value = data.get(xml_name) + else: + discriminator_value = data.find(xml_name).text # pyright: ignore + else: + discriminator_value = data.get(discriminator._rest_name) + mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore + return mapped_cls._deserialize(data, exist_discriminators) def as_dict(self, *, exclude_readonly: bool = False) -> typing.Dict[str, typing.Any]: - """Return a dict that can be JSONify using json.dump. + """Return a dict that can be turned into json using json.dump. :keyword bool exclude_readonly: Whether to remove the readonly properties. :returns: A dict JSON compatible object @@ -562,6 +692,7 @@ def as_dict(self, *, exclude_readonly: bool = False) -> typing.Dict[str, typing. """ result = {} + readonly_props = [] 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(): @@ -616,6 +747,8 @@ def _deserialize_dict( ): if obj is None: return obj + if isinstance(obj, ET.Element): + obj = {child.tag: child for child in obj} return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} @@ -636,15 +769,24 @@ def _deserialize_sequence( ): if obj is None: return obj + if isinstance(obj, ET.Element): + obj = list(obj) return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) -def _get_deserialize_callable_from_annotation( # pylint: disable=R0911, R0915, R0912 +def _sorted_annotations(types: typing.List[typing.Any]) -> typing.List[typing.Any]: + return sorted( + types, + key=lambda x: hasattr(x, "__name__") and x.__name__.lower() in ("str", "float", "int", "bool"), + ) + + +def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-branches 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]: + if not annotation: return None # is it a type alias? @@ -659,7 +801,7 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=R0911, R0915, except AttributeError: model_name = annotation if module is not None: - annotation = _get_model(module, model_name) + annotation = _get_model(module, model_name) # type: ignore try: if module and _is_model(annotation): @@ -680,21 +822,25 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=R0911, R0915, # 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) + if len(annotation.__args__) <= 2: # 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) + # the type is Optional[Union[...]], we need to remove the None type from the Union + annotation_copy = copy.copy(annotation) + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a != type(None)] # pyright: ignore + return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) except AttributeError: pass + # is it union? 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 - ) + for arg in _sorted_annotations(annotation.__args__) # pyright: ignore ] return functools.partial(_deserialize_with_union, deserializers) @@ -715,7 +861,6 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=R0911, R0915, 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 @@ -750,12 +895,23 @@ def _deserialize_default( def _deserialize_with_callable( deserializer: typing.Optional[typing.Callable[[typing.Any], typing.Any]], value: typing.Any, -): +): # pylint: disable=too-many-return-statements try: if value is None or isinstance(value, _Null): return None + if isinstance(value, ET.Element): + if deserializer is str: + return value.text or "" + if deserializer is int: + return int(value.text) if value.text else None + if deserializer is float: + return float(value.text) if value.text else None + if deserializer is bool: + return value.text == "true" if value.text else None if deserializer is None: return value + if deserializer in [int, float, bool]: + return deserializer(value) if isinstance(deserializer, CaseInsensitiveEnumMeta): try: return deserializer(value) @@ -785,6 +941,35 @@ def _deserialize( return _deserialize_with_callable(deserializer, value) +def _failsafe_deserialize( + deserializer: typing.Any, + value: typing.Any, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + try: + return _deserialize(deserializer, value, module, rf, format) + except DeserializationError: + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +def _failsafe_deserialize_xml( + deserializer: typing.Any, + value: typing.Any, +) -> typing.Any: + try: + return _deserialize_xml(deserializer, value) + except DeserializationError: + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + class _RestField: def __init__( self, @@ -796,6 +981,7 @@ def __init__( default: typing.Any = _UNSET, format: typing.Optional[str] = None, is_multipart_file_input: bool = False, + xml: typing.Optional[typing.Dict[str, typing.Any]] = None, ): self._type = type self._rest_name_input = name @@ -806,6 +992,7 @@ def __init__( self._default = default self._format = format self._is_multipart_file_input = is_multipart_file_input + self._xml = xml if xml is not None else {} @property def _class_type(self) -> typing.Any: @@ -856,6 +1043,7 @@ def rest_field( default: typing.Any = _UNSET, format: typing.Optional[str] = None, is_multipart_file_input: bool = False, + xml: typing.Optional[typing.Dict[str, typing.Any]] = None, ) -> typing.Any: return _RestField( name=name, @@ -864,6 +1052,7 @@ def rest_field( default=default, format=format, is_multipart_file_input=is_multipart_file_input, + xml=xml, ) @@ -871,5 +1060,176 @@ def rest_discriminator( *, name: typing.Optional[str] = None, type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[typing.List[str]] = None, + xml: typing.Optional[typing.Dict[str, typing.Any]] = None, ) -> typing.Any: - return _RestField(name=name, type=type, is_discriminator=True) + return _RestField(name=name, type=type, is_discriminator=True, visibility=visibility, xml=xml) + + +def serialize_xml(model: Model, exclude_readonly: bool = False) -> str: + """Serialize a model to XML. + + :param Model model: The model to serialize. + :param bool exclude_readonly: Whether to exclude readonly properties. + :returns: The XML representation of the model. + :rtype: str + """ + return ET.tostring(_get_element(model, exclude_readonly), encoding="unicode") # type: ignore + + +def _get_element( + o: typing.Any, + exclude_readonly: bool = False, + parent_meta: typing.Optional[typing.Dict[str, typing.Any]] = None, + wrapped_element: typing.Optional[ET.Element] = None, +) -> typing.Union[ET.Element, typing.List[ET.Element]]: + if _is_model(o): + model_meta = getattr(o, "_xml", {}) + + # if prop is a model, then use the prop element directly, else generate a wrapper of model + if wrapped_element is None: + wrapped_element = _create_xml_element( + model_meta.get("name", o.__class__.__name__), + model_meta.get("prefix"), + model_meta.get("ns"), + ) + + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + + for k, v in o.items(): + # do not serialize readonly properties + if exclude_readonly and k in readonly_props: + continue + + prop_rest_field = _get_rest_field(o._attr_to_rest_field, k) + if prop_rest_field: + prop_meta = getattr(prop_rest_field, "_xml").copy() + # use the wire name as xml name if no specific name is set + if prop_meta.get("name") is None: + prop_meta["name"] = k + else: + # additional properties will not have rest field, use the wire name as xml name + prop_meta = {"name": k} + + # if no ns for prop, use model's + if prop_meta.get("ns") is None and model_meta.get("ns"): + prop_meta["ns"] = model_meta.get("ns") + prop_meta["prefix"] = model_meta.get("prefix") + + if prop_meta.get("unwrapped", False): + # unwrapped could only set on array + wrapped_element.extend(_get_element(v, exclude_readonly, prop_meta)) + elif prop_meta.get("text", False): + # text could only set on primitive type + wrapped_element.text = _get_primitive_type_value(v) + elif prop_meta.get("attribute", False): + xml_name = prop_meta.get("name", k) + if prop_meta.get("ns"): + ET.register_namespace(prop_meta.get("prefix"), prop_meta.get("ns")) # pyright: ignore + xml_name = "{" + prop_meta.get("ns") + "}" + xml_name # pyright: ignore + # attribute should be primitive type + wrapped_element.set(xml_name, _get_primitive_type_value(v)) + else: + # other wrapped prop element + wrapped_element.append(_get_wrapped_element(v, exclude_readonly, prop_meta)) + return wrapped_element + if isinstance(o, list): + return [_get_element(x, exclude_readonly, parent_meta) for x in o] # type: ignore + if isinstance(o, dict): + result = [] + for k, v in o.items(): + result.append( + _get_wrapped_element( + v, + exclude_readonly, + { + "name": k, + "ns": parent_meta.get("ns") if parent_meta else None, + "prefix": parent_meta.get("prefix") if parent_meta else None, + }, + ) + ) + return result + + # primitive case need to create element based on parent_meta + if parent_meta: + return _get_wrapped_element( + o, + exclude_readonly, + { + "name": parent_meta.get("itemsName", parent_meta.get("name")), + "prefix": parent_meta.get("itemsPrefix", parent_meta.get("prefix")), + "ns": parent_meta.get("itemsNs", parent_meta.get("ns")), + }, + ) + + raise ValueError("Could not serialize value into xml: " + o) + + +def _get_wrapped_element( + v: typing.Any, + exclude_readonly: bool, + meta: typing.Optional[typing.Dict[str, typing.Any]], +) -> ET.Element: + wrapped_element = _create_xml_element( + meta.get("name") if meta else None, meta.get("prefix") if meta else None, meta.get("ns") if meta else None + ) + if isinstance(v, (dict, list)): + wrapped_element.extend(_get_element(v, exclude_readonly, meta)) + elif _is_model(v): + _get_element(v, exclude_readonly, meta, wrapped_element) + else: + wrapped_element.text = _get_primitive_type_value(v) + return wrapped_element + + +def _get_primitive_type_value(v) -> str: + if v is True: + return "true" + if v is False: + return "false" + if isinstance(v, _Null): + return "" + return str(v) + + +def _create_xml_element(tag, prefix=None, ns=None): + if prefix and ns: + ET.register_namespace(prefix, ns) + if ns: + return ET.Element("{" + ns + "}" + tag) + return ET.Element(tag) + + +def _deserialize_xml( + deserializer: typing.Any, + value: str, +) -> typing.Any: + element = ET.fromstring(value) # nosec + return _deserialize(deserializer, element) + + +def _convert_element(e: ET.Element): + # dict case + if len(e.attrib) > 0 or len({child.tag for child in e}) > 1: + dict_result: typing.Dict[str, typing.Any] = {} + for child in e: + if dict_result.get(child.tag) is not None: + if isinstance(dict_result[child.tag], list): + dict_result[child.tag].append(_convert_element(child)) + else: + dict_result[child.tag] = [dict_result[child.tag], _convert_element(child)] + else: + dict_result[child.tag] = _convert_element(child) + dict_result.update(e.attrib) + return dict_result + # array case + if len(e) > 0: + array_result: typing.List[typing.Any] = [] + for child in e: + array_result.append(_convert_element(child)) + return array_result + # primitive case + return e.text diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_operations/__init__.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_operations/__init__.py index 32322330a2b..bb0ba294788 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_operations/__init__.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_operations/__init__.py @@ -5,15 +5,25 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._operations import DevCenterClientOperationsMixin +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import DevCenterClientOperationsMixin # type: ignore +from ._operations import DevBoxesClientOperationsMixin # type: ignore +from ._operations import DeploymentEnvironmentsClientOperationsMixin # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "DevCenterClientOperationsMixin", + "DevBoxesClientOperationsMixin", + "DeploymentEnvironmentsClientOperationsMixin", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() 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 825ae666ecf..7dadd3dd67e 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,too-many-statements +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -10,7 +10,7 @@ from io import IOBase import json import sys -from typing import Any, Callable, Dict, IO, Iterable, List, Optional, Type, TypeVar, Union, cast, overload +from typing import Any, Callable, Dict, IO, Iterable, Iterator, List, Optional, TypeVar, Union, cast, overload import urllib.parse from azure.core.exceptions import ( @@ -19,6 +19,8 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.paging import ItemPaged @@ -32,15 +34,15 @@ from .. import models as _models from .._model_base import SdkJSONEncoder, _deserialize from .._serialization import Serializer -from .._vendor import DevCenterClientMixinABC +from .._vendor import DeploymentEnvironmentsClientMixinABC, DevBoxesClientMixinABC, DevCenterClientMixinABC if sys.version_info >= (3, 9): from collections.abc import MutableMapping else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False @@ -89,7 +91,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, **kwargs: Any) -> HttpRequest: +def build_dev_boxes_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 {}) @@ -113,7 +115,7 @@ def build_dev_center_list_pools_request(project_name: str, **kwargs: Any) -> Htt return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_dev_center_get_pool_request(project_name: str, pool_name: str, **kwargs: Any) -> HttpRequest: +def build_dev_boxes_get_pool_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 {}) @@ -138,7 +140,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, **kwargs: Any) -> HttpRequest: +def build_dev_boxes_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 {}) @@ -163,7 +165,7 @@ def build_dev_center_list_schedules_request(project_name: str, pool_name: str, * return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_dev_center_get_schedule_request( +def build_dev_boxes_get_schedule_request( project_name: str, pool_name: str, schedule_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -191,7 +193,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(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long +def build_dev_boxes_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 {}) @@ -210,7 +212,7 @@ def build_dev_center_list_all_dev_boxes_request(**kwargs: Any) -> HttpRequest: return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_dev_center_list_all_dev_boxes_by_user_request( # pylint: disable=name-too-long +def build_dev_boxes_list_all_dev_boxes_by_user_request( # pylint: disable=name-too-long user_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -236,7 +238,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, **kwargs: Any) -> HttpRequest: +def build_dev_boxes_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 {}) @@ -261,7 +263,7 @@ def build_dev_center_list_dev_boxes_request(project_name: str, user_id: str, **k return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_dev_center_get_dev_box_request( +def build_dev_boxes_get_dev_box_request( project_name: str, user_id: str, dev_box_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -289,7 +291,7 @@ def build_dev_center_get_dev_box_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_dev_center_create_dev_box_request( +def build_dev_boxes_create_dev_box_request( project_name: str, user_id: str, dev_box_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -320,7 +322,7 @@ def build_dev_center_create_dev_box_request( return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_dev_center_delete_dev_box_request( +def build_dev_boxes_delete_dev_box_request( project_name: str, user_id: str, dev_box_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -348,7 +350,7 @@ def build_dev_center_delete_dev_box_request( return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_dev_center_start_dev_box_request( +def build_dev_boxes_start_dev_box_request( project_name: str, user_id: str, dev_box_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -376,7 +378,7 @@ def build_dev_center_start_dev_box_request( return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_dev_center_stop_dev_box_request( +def build_dev_boxes_stop_dev_box_request( project_name: str, user_id: str, dev_box_name: str, *, hibernate: Optional[bool] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -406,7 +408,7 @@ def build_dev_center_stop_dev_box_request( return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_dev_center_restart_dev_box_request( +def build_dev_boxes_restart_dev_box_request( project_name: str, user_id: str, dev_box_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -434,7 +436,7 @@ def build_dev_center_restart_dev_box_request( return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_dev_center_get_remote_connection_request( # pylint: disable=name-too-long +def build_dev_boxes_get_remote_connection_request( # pylint: disable=name-too-long project_name: str, user_id: str, dev_box_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -462,7 +464,7 @@ def build_dev_center_get_remote_connection_request( # pylint: disable=name-too- return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_dev_center_list_dev_box_actions_request( # pylint: disable=name-too-long +def build_dev_boxes_list_dev_box_actions_request( # pylint: disable=name-too-long project_name: str, user_id: str, dev_box_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -490,7 +492,7 @@ def build_dev_center_list_dev_box_actions_request( # pylint: disable=name-too-l return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_dev_center_get_dev_box_action_request( # pylint: disable=name-too-long +def build_dev_boxes_get_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 {}) @@ -519,7 +521,7 @@ def build_dev_center_get_dev_box_action_request( # pylint: disable=name-too-lon return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_dev_center_skip_dev_box_action_request( # pylint: disable=name-too-long +def build_dev_boxes_skip_action_request( project_name: str, user_id: str, dev_box_name: str, action_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -548,7 +550,7 @@ def build_dev_center_skip_dev_box_action_request( # pylint: disable=name-too-lo 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 +def build_dev_boxes_delay_action_request( project_name: str, user_id: str, dev_box_name: str, @@ -584,7 +586,7 @@ def build_dev_center_delay_dev_box_action_request( # pylint: disable=name-too-l return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_dev_center_delay_all_dev_box_actions_request( # pylint: disable=name-too-long +def build_dev_boxes_delay_all_actions_request( # pylint: disable=name-too-long project_name: str, user_id: str, dev_box_name: str, *, delay_until: datetime.datetime, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -613,7 +615,7 @@ def build_dev_center_delay_all_dev_box_actions_request( # pylint: disable=name- return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_dev_center_list_all_environments_request( # pylint: disable=name-too-long +def build_deployment_environments_list_all_environments_request( # pylint: disable=name-too-long project_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -639,7 +641,7 @@ def build_dev_center_list_all_environments_request( # pylint: disable=name-too- return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_dev_center_list_environments_request( # pylint: disable=name-too-long +def build_deployment_environments_list_environments_request( # pylint: disable=name-too-long project_name: str, user_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -666,7 +668,7 @@ def build_dev_center_list_environments_request( # pylint: disable=name-too-long return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_dev_center_get_environment_request( +def build_deployment_environments_get_environment_request( # pylint: disable=name-too-long project_name: str, user_id: str, environment_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -694,7 +696,7 @@ def build_dev_center_get_environment_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_dev_center_create_or_update_environment_request( # pylint: disable=name-too-long +def build_deployment_environments_create_or_update_environment_request( # pylint: disable=name-too-long project_name: str, user_id: str, environment_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -725,7 +727,7 @@ def build_dev_center_create_or_update_environment_request( # pylint: disable=na return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_dev_center_delete_environment_request( # pylint: disable=name-too-long +def build_deployment_environments_delete_environment_request( # pylint: disable=name-too-long project_name: str, user_id: str, environment_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -753,7 +755,9 @@ 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, **kwargs: Any) -> HttpRequest: +def build_deployment_environments_list_catalogs_request( # pylint: disable=name-too-long + project_name: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -777,7 +781,9 @@ def build_dev_center_list_catalogs_request(project_name: str, **kwargs: Any) -> return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_dev_center_get_catalog_request(project_name: str, catalog_name: str, **kwargs: Any) -> HttpRequest: +def build_deployment_environments_get_catalog_request( # pylint: disable=name-too-long + 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 {}) @@ -802,7 +808,7 @@ def build_dev_center_get_catalog_request(project_name: str, catalog_name: str, * return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_dev_center_list_environment_definitions_request( # pylint: disable=name-too-long +def build_deployment_environments_list_environment_definitions_request( # pylint: disable=name-too-long project_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -828,7 +834,7 @@ def build_dev_center_list_environment_definitions_request( # pylint: disable=na return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_dev_center_list_environment_definitions_by_catalog_request( # pylint: disable=name-too-long +def build_deployment_environments_list_environment_definitions_by_catalog_request( # pylint: disable=name-too-long project_name: str, catalog_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -855,7 +861,7 @@ def build_dev_center_list_environment_definitions_by_catalog_request( # pylint: return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_dev_center_get_environment_definition_request( # pylint: disable=name-too-long +def build_deployment_environments_get_environment_definition_request( # pylint: disable=name-too-long project_name: str, catalog_name: str, definition_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -883,7 +889,7 @@ def build_dev_center_get_environment_definition_request( # pylint: disable=name return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_dev_center_list_environment_types_request( # pylint: disable=name-too-long +def build_deployment_environments_list_environment_types_request( # pylint: disable=name-too-long project_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -909,34 +915,22 @@ def build_dev_center_list_environment_types_request( # pylint: disable=name-too return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -class DevCenterClientOperationsMixin(DevCenterClientMixinABC): # pylint: disable=too-many-public-methods +class DevCenterClientOperationsMixin(DevCenterClientMixinABC): @distributed_trace def list_projects(self, **kwargs: Any) -> Iterable["_models.Project"]: - # pylint: disable=line-too-long """Lists all projects. :return: An iterator like instance of Project :rtype: ~azure.core.paging.ItemPaged[~azure.developer.devcenter.models.Project] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "name": "str", # Name of the project. Required. - "description": "str", # Optional. Description of the project. - "maxDevBoxesPerUser": 0 # Optional. When specified, indicates the maximum - number of Dev Boxes a single user can create across all pools in the project. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} cls: ClsType[List[_models.Project]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -998,8 +992,6 @@ def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -1009,7 +1001,6 @@ def get_next(next_link=None): @distributed_trace def get_project(self, project_name: str, **kwargs: Any) -> _models.Project: - # pylint: disable=line-too-long """Gets a project. :param project_name: Name of the project. Required. @@ -1017,19 +1008,8 @@ def get_project(self, project_name: str, **kwargs: Any) -> _models.Project: :return: Project. The Project is compatible with MutableMapping :rtype: ~azure.developer.devcenter.models.Project :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "name": "str", # Name of the project. Required. - "description": "str", # Optional. Description of the project. - "maxDevBoxesPerUser": 0 # Optional. When specified, indicates the maximum - number of Dev Boxes a single user can create across all pools in the project. - } """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1062,7 +1042,10 @@ def get_project(self, project_name: str, **kwargs: Any) -> _models.Project: if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -1076,9 +1059,11 @@ def get_project(self, project_name: str, **kwargs: Any) -> _models.Project: return deserialized # type: ignore + +class DevBoxesClientOperationsMixin(DevBoxesClientMixinABC): # pylint: disable=too-many-public-methods + @distributed_trace def list_pools(self, project_name: str, **kwargs: Any) -> Iterable["_models.Pool"]: - # pylint: disable=line-too-long """Lists available pools. :param project_name: Name of the project. Required. @@ -1086,75 +1071,13 @@ def list_pools(self, project_name: str, **kwargs: Any) -> Iterable["_models.Pool :return: An iterator like instance of Pool :rtype: ~azure.core.paging.ItemPaged[~azure.developer.devcenter.models.Pool] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "healthStatus": "str", # 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". - "location": "str", # Azure region where Dev Boxes in the pool are located. - Required. - "name": "str", # Pool name. Required. - "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 owners of Dev - Boxes in this pool are local administrators on the Dev Boxes. Known values are: - "Enabled" and "Disabled". - "osType": "str", # Optional. The operating system type of Dev Boxes in this - pool. "Windows" - "stopOnDisconnect": { - "status": "str", # 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". - "gracePeriodMinutes": 0 # Optional. The specified time in minutes to - wait before stopping a Dev Box once disconnect is detected. - }, - "storageProfile": { - "osDisk": { - "diskSizeGB": 0 # Optional. The size of the OS Disk in - gigabytes. - } - } - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} cls: ClsType[List[_models.Pool]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1165,7 +1088,7 @@ def list_pools(self, project_name: str, **kwargs: Any) -> Iterable["_models.Pool def prepare_request(next_link=None): if not next_link: - _request = build_dev_center_list_pools_request( + _request = build_dev_boxes_list_pools_request( project_name=project_name, api_version=self._config.api_version, headers=_headers, @@ -1217,8 +1140,6 @@ def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -1228,7 +1149,6 @@ def get_next(next_link=None): @distributed_trace 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: Name of the project. Required. @@ -1238,70 +1158,8 @@ def get_pool(self, project_name: str, pool_name: str, **kwargs: Any) -> _models. :return: Pool. The Pool is compatible with MutableMapping :rtype: ~azure.developer.devcenter.models.Pool :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "healthStatus": "str", # 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". - "location": "str", # Azure region where Dev Boxes in the pool are located. - Required. - "name": "str", # Pool name. Required. - "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 owners of Dev - Boxes in this pool are local administrators on the Dev Boxes. Known values are: - "Enabled" and "Disabled". - "osType": "str", # Optional. The operating system type of Dev Boxes in this - pool. "Windows" - "stopOnDisconnect": { - "status": "str", # 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". - "gracePeriodMinutes": 0 # Optional. The specified time in minutes to - wait before stopping a Dev Box once disconnect is detected. - }, - "storageProfile": { - "osDisk": { - "diskSizeGB": 0 # Optional. The size of the OS Disk in - gigabytes. - } - } - } """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1314,7 +1172,7 @@ def get_pool(self, project_name: str, pool_name: str, **kwargs: Any) -> _models. cls: ClsType[_models.Pool] = kwargs.pop("cls", None) - _request = build_dev_center_get_pool_request( + _request = build_dev_boxes_get_pool_request( project_name=project_name, pool_name=pool_name, api_version=self._config.api_version, @@ -1335,7 +1193,10 @@ def get_pool(self, project_name: str, pool_name: str, **kwargs: Any) -> _models. if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -1360,29 +1221,13 @@ def list_schedules(self, project_name: str, pool_name: str, **kwargs: Any) -> It :return: An iterator like instance of Schedule :rtype: ~azure.core.paging.ItemPaged[~azure.developer.devcenter.models.Schedule] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "frequency": "str", # The frequency of this scheduled task. Required. - "Daily" - "name": "str", # Display name for the Schedule. Required. - "time": "str", # The target time to trigger the action. The format is HH:MM. - Required. - "timeZone": "str", # The IANA timezone id at which the schedule should - execute. Required. - "type": "str" # Supported type this scheduled task represents. Required. - "StopDevBox" - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} cls: ClsType[List[_models.Schedule]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1393,7 +1238,7 @@ def list_schedules(self, project_name: str, pool_name: str, **kwargs: Any) -> It def prepare_request(next_link=None): if not next_link: - _request = build_dev_center_list_schedules_request( + _request = build_dev_boxes_list_schedules_request( project_name=project_name, pool_name=pool_name, api_version=self._config.api_version, @@ -1446,8 +1291,6 @@ def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -1468,24 +1311,8 @@ def get_schedule(self, project_name: str, pool_name: str, schedule_name: str, ** :return: Schedule. The Schedule is compatible with MutableMapping :rtype: ~azure.developer.devcenter.models.Schedule :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "frequency": "str", # The frequency of this scheduled task. Required. - "Daily" - "name": "str", # Display name for the Schedule. Required. - "time": "str", # The target time to trigger the action. The format is HH:MM. - Required. - "timeZone": "str", # The IANA timezone id at which the schedule should - execute. Required. - "type": "str" # Supported type this scheduled task represents. Required. - "StopDevBox" - } """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1498,7 +1325,7 @@ def get_schedule(self, project_name: str, pool_name: str, schedule_name: str, ** cls: ClsType[_models.Schedule] = kwargs.pop("cls", None) - _request = build_dev_center_get_schedule_request( + _request = build_dev_boxes_get_schedule_request( project_name=project_name, pool_name=pool_name, schedule_name=schedule_name, @@ -1520,7 +1347,10 @@ def get_schedule(self, project_name: str, pool_name: str, schedule_name: str, ** if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -1536,104 +1366,18 @@ def get_schedule(self, project_name: str, pool_name: str, schedule_name: str, ** @distributed_trace 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. :return: An iterator like instance of DevBox :rtype: ~azure.core.paging.ItemPaged[~azure.developer.devcenter.models.DevBox] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - 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. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} cls: ClsType[List[_models.DevBox]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1644,7 +1388,7 @@ def list_all_dev_boxes(self, **kwargs: Any) -> Iterable["_models.DevBox"]: def prepare_request(next_link=None): if not next_link: - _request = build_dev_center_list_all_dev_boxes_request( + _request = build_dev_boxes_list_all_dev_boxes_request( api_version=self._config.api_version, headers=_headers, params=_params, @@ -1695,8 +1439,6 @@ def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -1706,7 +1448,6 @@ def get_next(next_link=None): @distributed_trace 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 @@ -1715,98 +1456,13 @@ def list_all_dev_boxes_by_user(self, user_id: str, **kwargs: Any) -> Iterable["_ :return: An iterator like instance of DevBox :rtype: ~azure.core.paging.ItemPaged[~azure.developer.devcenter.models.DevBox] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - 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. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} cls: ClsType[List[_models.DevBox]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1817,7 +1473,7 @@ def list_all_dev_boxes_by_user(self, user_id: str, **kwargs: Any) -> Iterable["_ def prepare_request(next_link=None): if not next_link: - _request = build_dev_center_list_all_dev_boxes_by_user_request( + _request = build_dev_boxes_list_all_dev_boxes_by_user_request( user_id=user_id, api_version=self._config.api_version, headers=_headers, @@ -1869,8 +1525,6 @@ def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -1880,7 +1534,6 @@ def get_next(next_link=None): @distributed_trace 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. @@ -1891,98 +1544,13 @@ def list_dev_boxes(self, project_name: str, user_id: str, **kwargs: Any) -> Iter :return: An iterator like instance of DevBox :rtype: ~azure.core.paging.ItemPaged[~azure.developer.devcenter.models.DevBox] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - 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. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} cls: ClsType[List[_models.DevBox]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1993,7 +1561,7 @@ def list_dev_boxes(self, project_name: str, user_id: str, **kwargs: Any) -> Iter def prepare_request(next_link=None): if not next_link: - _request = build_dev_center_list_dev_boxes_request( + _request = build_dev_boxes_list_dev_boxes_request( project_name=project_name, user_id=user_id, api_version=self._config.api_version, @@ -2046,8 +1614,6 @@ def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -2057,7 +1623,6 @@ def get_next(next_link=None): @distributed_trace 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: Name of the project. Required. @@ -2070,93 +1635,8 @@ def get_dev_box(self, project_name: str, user_id: str, dev_box_name: str, **kwar :return: DevBox. The DevBox is compatible with MutableMapping :rtype: ~azure.developer.devcenter.models.DevBox :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - 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. - } """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2169,7 +1649,7 @@ def get_dev_box(self, project_name: str, user_id: str, dev_box_name: str, **kwar cls: ClsType[_models.DevBox] = kwargs.pop("cls", None) - _request = build_dev_center_get_dev_box_request( + _request = build_dev_boxes_get_dev_box_request( project_name=project_name, user_id=user_id, dev_box_name=dev_box_name, @@ -2191,7 +1671,10 @@ def get_dev_box(self, project_name: str, user_id: str, dev_box_name: str, **kwar if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -2212,8 +1695,8 @@ def _create_dev_box_initial( dev_box_name: str, body: Union[_models.DevBox, JSON, IO[bytes]], **kwargs: Any - ) -> JSON: - error_map: MutableMapping[int, Type[HttpResponseError]] = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2225,7 +1708,7 @@ def _create_dev_box_initial( _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[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None @@ -2234,7 +1717,7 @@ def _create_dev_box_initial( else: _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_dev_center_create_dev_box_request( + _request = build_dev_boxes_create_dev_box_request( project_name=project_name, user_id=user_id, dev_box_name=dev_box_name, @@ -2249,7 +1732,7 @@ def _create_dev_box_initial( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -2257,22 +1740,21 @@ def _create_dev_box_initial( response = pipeline_response.http_response if response.status_code not in [200, 201]: - if _stream: + try: response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) response_headers = {} - if response.status_code == 200: - deserialized = _deserialize(JSON, response.json()) - if response.status_code == 201: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Operation-Location"] = self._deserialize( "str", response.headers.get("Operation-Location") ) - deserialized = _deserialize(JSON, response.json()) + deserialized = response.iter_bytes() if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -2290,10 +1772,9 @@ def begin_create_dev_box( 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. + :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. @@ -2310,173 +1791,6 @@ def begin_create_dev_box( MutableMapping :rtype: ~azure.core.polling.LROPoller[~azure.developer.devcenter.models.DevBox] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = { - "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. - } - - # 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 @@ -2490,10 +1804,9 @@ def begin_create_dev_box( 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. + :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. @@ -2510,91 +1823,6 @@ def begin_create_dev_box( 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 @@ -2608,10 +1836,9 @@ def begin_create_dev_box( 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. + :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. @@ -2628,91 +1855,6 @@ def begin_create_dev_box( 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. - } """ @distributed_trace @@ -2724,10 +1866,9 @@ def begin_create_dev_box( 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 the operation. Required. + :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. @@ -2742,173 +1883,6 @@ def begin_create_dev_box( MutableMapping :rtype: ~azure.core.polling.LROPoller[~azure.developer.devcenter.models.DevBox] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = { - "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. - } - - # 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. - } """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} @@ -2930,6 +1904,7 @@ def begin_create_dev_box( params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): @@ -2964,8 +1939,8 @@ def get_long_running_output(pipeline_response): def _delete_dev_box_initial( self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any - ) -> Optional[JSON]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2976,9 +1951,9 @@ def _delete_dev_box_initial( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[Optional[JSON]] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - _request = build_dev_center_delete_dev_box_request( + _request = build_dev_boxes_delete_dev_box_request( project_name=project_name, user_id=user_id, dev_box_name=dev_box_name, @@ -2991,7 +1966,7 @@ def _delete_dev_box_initial( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -2999,12 +1974,13 @@ def _delete_dev_box_initial( response = pipeline_response.http_response if response.status_code not in [202, 204]: - if _stream: + try: response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) - deserialized = None response_headers = {} if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) @@ -3012,7 +1988,7 @@ def _delete_dev_box_initial( "str", response.headers.get("Operation-Location") ) - deserialized = _deserialize(JSON, response.json()) + deserialized = response.iter_bytes() if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -3022,8 +1998,7 @@ 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[_models.OperationDetails]: - # pylint: disable=line-too-long + ) -> LROPoller[None]: """Deletes a Dev Box. :param project_name: The DevCenter Project upon which to execute operations. Required. @@ -3033,49 +2008,14 @@ 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 - :return: An instance of LROPoller that returns OperationDetails. The OperationDetails is - compatible with MutableMapping - :rtype: ~azure.core.polling.LROPoller[~azure.developer.devcenter.models.OperationDetails] + :return: An instance of LROPoller that returns None + :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # 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: "NotStarted", "Running", "Succeeded", "Failed", and "Canceled". - "endTime": "2020-02-20 00:00:00", # Optional. The end time of the operation. - "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. - }, - "percentComplete": 0.0, # Optional. Percent of the operation that is - complete. - "properties": {}, # Optional. Custom operation properties, populated only - for a successful operation. - "resourceId": "str", # Optional. The id of the resource. - "startTime": "2020-02-20 00:00:00" # Optional. The start time of the - operation. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.OperationDetails] = kwargs.pop("cls", None) + cls: ClsType[None] = 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) @@ -3089,20 +2029,12 @@ def begin_delete_dev_box( params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): - response_headers = {} - response = pipeline_response.http_response - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - response_headers["Operation-Location"] = self._deserialize( - "str", response.headers.get("Operation-Location") - ) - - deserialized = _deserialize(_models.OperationDetails, response.json()) + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized + return cls(pipeline_response, None, {}) # type: ignore path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), @@ -3117,18 +2049,18 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller[_models.OperationDetails].from_continuation_token( + return LROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller[_models.OperationDetails]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) + return LROPoller[None](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: MutableMapping[int, Type[HttpResponseError]] = { + def _start_dev_box_initial( + self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3139,9 +2071,9 @@ def _start_dev_box_initial(self, project_name: str, user_id: str, dev_box_name: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - _request = build_dev_center_start_dev_box_request( + _request = build_dev_boxes_start_dev_box_request( project_name=project_name, user_id=user_id, dev_box_name=dev_box_name, @@ -3154,7 +2086,7 @@ def _start_dev_box_initial(self, project_name: str, user_id: str, dev_box_name: } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -3162,15 +2094,17 @@ def _start_dev_box_initial(self, project_name: str, user_id: str, dev_box_name: response = pipeline_response.http_response if response.status_code not in [202]: - if _stream: + try: response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) response_headers = {} response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) - deserialized = _deserialize(JSON, response.json()) + deserialized = response.iter_bytes() if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -3178,10 +2112,7 @@ def _start_dev_box_initial(self, project_name: str, user_id: str, dev_box_name: 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[_models.OperationDetails]: - # pylint: disable=line-too-long + def begin_start_dev_box(self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any) -> LROPoller[None]: """Starts a Dev Box. :param project_name: Name of the project. Required. @@ -3191,49 +2122,14 @@ def begin_start_dev_box( :type user_id: str :param dev_box_name: Display name for the Dev Box. Required. :type dev_box_name: str - :return: An instance of LROPoller that returns OperationDetails. The OperationDetails is - compatible with MutableMapping - :rtype: ~azure.core.polling.LROPoller[~azure.developer.devcenter.models.OperationDetails] + :return: An instance of LROPoller that returns None + :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # 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: "NotStarted", "Running", "Succeeded", "Failed", and "Canceled". - "endTime": "2020-02-20 00:00:00", # Optional. The end time of the operation. - "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. - }, - "percentComplete": 0.0, # Optional. Percent of the operation that is - complete. - "properties": {}, # Optional. Custom operation properties, populated only - for a successful operation. - "resourceId": "str", # Optional. The id of the resource. - "startTime": "2020-02-20 00:00:00" # Optional. The start time of the - operation. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.OperationDetails] = kwargs.pop("cls", None) + cls: ClsType[None] = 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) @@ -3247,19 +2143,12 @@ def begin_start_dev_box( params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): - response_headers = {} - response = pipeline_response.http_response - response_headers["Operation-Location"] = self._deserialize( - "str", response.headers.get("Operation-Location") - ) - - deserialized = _deserialize(_models.OperationDetails, response.json()) + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized + return cls(pipeline_response, None, {}) # type: ignore path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), @@ -3274,20 +2163,18 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller[_models.OperationDetails].from_continuation_token( + return LROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller[_models.OperationDetails]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) + return LROPoller[None](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: MutableMapping[int, Type[HttpResponseError]] = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3298,9 +2185,9 @@ def _stop_dev_box_initial( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - _request = build_dev_center_stop_dev_box_request( + _request = build_dev_boxes_stop_dev_box_request( project_name=project_name, user_id=user_id, dev_box_name=dev_box_name, @@ -3314,7 +2201,7 @@ def _stop_dev_box_initial( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -3322,15 +2209,17 @@ def _stop_dev_box_initial( response = pipeline_response.http_response if response.status_code not in [202]: - if _stream: + try: response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) response_headers = {} response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) - deserialized = _deserialize(JSON, response.json()) + deserialized = response.iter_bytes() if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -3340,8 +2229,7 @@ def _stop_dev_box_initial( @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[_models.OperationDetails]: - # pylint: disable=line-too-long + ) -> LROPoller[None]: """Stops a Dev Box. :param project_name: Name of the project. Required. @@ -3353,49 +2241,14 @@ def begin_stop_dev_box( :type dev_box_name: str :keyword hibernate: Optional parameter to hibernate the dev box. Default value is None. :paramtype hibernate: bool - :return: An instance of LROPoller that returns OperationDetails. The OperationDetails is - compatible with MutableMapping - :rtype: ~azure.core.polling.LROPoller[~azure.developer.devcenter.models.OperationDetails] + :return: An instance of LROPoller that returns None + :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # 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: "NotStarted", "Running", "Succeeded", "Failed", and "Canceled". - "endTime": "2020-02-20 00:00:00", # Optional. The end time of the operation. - "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. - }, - "percentComplete": 0.0, # Optional. Percent of the operation that is - complete. - "properties": {}, # Optional. Custom operation properties, populated only - for a successful operation. - "resourceId": "str", # Optional. The id of the resource. - "startTime": "2020-02-20 00:00:00" # Optional. The start time of the - operation. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.OperationDetails] = kwargs.pop("cls", None) + cls: ClsType[None] = 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) @@ -3410,19 +2263,12 @@ def begin_stop_dev_box( params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): - response_headers = {} - response = pipeline_response.http_response - response_headers["Operation-Location"] = self._deserialize( - "str", response.headers.get("Operation-Location") - ) - - deserialized = _deserialize(_models.OperationDetails, response.json()) + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized + return cls(pipeline_response, None, {}) # type: ignore path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), @@ -3437,18 +2283,18 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller[_models.OperationDetails].from_continuation_token( + return LROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller[_models.OperationDetails]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) + return LROPoller[None](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: MutableMapping[int, Type[HttpResponseError]] = { + def _restart_dev_box_initial( + self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3459,9 +2305,9 @@ def _restart_dev_box_initial(self, project_name: str, user_id: str, dev_box_name _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - _request = build_dev_center_restart_dev_box_request( + _request = build_dev_boxes_restart_dev_box_request( project_name=project_name, user_id=user_id, dev_box_name=dev_box_name, @@ -3474,7 +2320,7 @@ def _restart_dev_box_initial(self, project_name: str, user_id: str, dev_box_name } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -3482,15 +2328,17 @@ def _restart_dev_box_initial(self, project_name: str, user_id: str, dev_box_name response = pipeline_response.http_response if response.status_code not in [202]: - if _stream: + try: response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) response_headers = {} response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) - deserialized = _deserialize(JSON, response.json()) + deserialized = response.iter_bytes() if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -3500,8 +2348,7 @@ def _restart_dev_box_initial(self, project_name: str, user_id: str, dev_box_name @distributed_trace def begin_restart_dev_box( self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any - ) -> LROPoller[_models.OperationDetails]: - # pylint: disable=line-too-long + ) -> LROPoller[None]: """Restarts a Dev Box. :param project_name: Name of the project. Required. @@ -3511,49 +2358,14 @@ def begin_restart_dev_box( :type user_id: str :param dev_box_name: Display name for the Dev Box. Required. :type dev_box_name: str - :return: An instance of LROPoller that returns OperationDetails. The OperationDetails is - compatible with MutableMapping - :rtype: ~azure.core.polling.LROPoller[~azure.developer.devcenter.models.OperationDetails] + :return: An instance of LROPoller that returns None + :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # 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: "NotStarted", "Running", "Succeeded", "Failed", and "Canceled". - "endTime": "2020-02-20 00:00:00", # Optional. The end time of the operation. - "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. - }, - "percentComplete": 0.0, # Optional. Percent of the operation that is - complete. - "properties": {}, # Optional. Custom operation properties, populated only - for a successful operation. - "resourceId": "str", # Optional. The id of the resource. - "startTime": "2020-02-20 00:00:00" # Optional. The start time of the - operation. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.OperationDetails] = kwargs.pop("cls", None) + cls: ClsType[None] = 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) @@ -3567,19 +2379,12 @@ def begin_restart_dev_box( params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): - response_headers = {} - response = pipeline_response.http_response - response_headers["Operation-Location"] = self._deserialize( - "str", response.headers.get("Operation-Location") - ) - - deserialized = _deserialize(_models.OperationDetails, response.json()) + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized + return cls(pipeline_response, None, {}) # type: ignore path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), @@ -3594,15 +2399,13 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller[_models.OperationDetails].from_continuation_token( + return LROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller[_models.OperationDetails]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore @distributed_trace def get_remote_connection( @@ -3620,18 +2423,8 @@ def get_remote_connection( :return: RemoteConnection. The RemoteConnection is compatible with MutableMapping :rtype: ~azure.developer.devcenter.models.RemoteConnection :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "rdpConnectionUrl": "str", # Optional. Link to open a Remote Desktop - session. - "webUrl": "str" # Optional. URL to open a browser based RDP session. - } """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3644,7 +2437,7 @@ def get_remote_connection( cls: ClsType[_models.RemoteConnection] = kwargs.pop("cls", None) - _request = build_dev_center_get_remote_connection_request( + _request = build_dev_boxes_get_remote_connection_request( project_name=project_name, user_id=user_id, dev_box_name=dev_box_name, @@ -3666,7 +2459,10 @@ def get_remote_connection( if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -3696,30 +2492,13 @@ def list_dev_box_actions( :return: An iterator like instance of DevBoxAction :rtype: ~azure.core.paging.ItemPaged[~azure.developer.devcenter.models.DevBoxAction] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "actionType": "str", # The action that will be taken. Required. "Stop" - "name": "str", # The name of the action. Required. - "sourceId": "str", # The id of the resource which triggered this action. - Required. - "next": { - "scheduledTime": "2020-02-20 00:00:00" # The time the action will be - triggered (UTC). Required. - }, - "suspendedUntil": "2020-02-20 00:00:00" # Optional. The earliest time that - the action could occur (UTC). - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} cls: ClsType[List[_models.DevBoxAction]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3730,7 +2509,7 @@ def list_dev_box_actions( def prepare_request(next_link=None): if not next_link: - _request = build_dev_center_list_dev_box_actions_request( + _request = build_dev_boxes_list_dev_box_actions_request( project_name=project_name, user_id=user_id, dev_box_name=dev_box_name, @@ -3784,8 +2563,6 @@ def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -3811,25 +2588,8 @@ def get_dev_box_action( :return: DevBoxAction. The DevBoxAction is compatible with MutableMapping :rtype: ~azure.developer.devcenter.models.DevBoxAction :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "actionType": "str", # The action that will be taken. Required. "Stop" - "name": "str", # The name of the action. Required. - "sourceId": "str", # The id of the resource which triggered this action. - Required. - "next": { - "scheduledTime": "2020-02-20 00:00:00" # The time the action will be - triggered (UTC). Required. - }, - "suspendedUntil": "2020-02-20 00:00:00" # Optional. The earliest time that - the action could occur (UTC). - } """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3842,7 +2602,7 @@ def get_dev_box_action( cls: ClsType[_models.DevBoxAction] = kwargs.pop("cls", None) - _request = build_dev_center_get_dev_box_action_request( + _request = build_dev_boxes_get_dev_box_action_request( project_name=project_name, user_id=user_id, dev_box_name=dev_box_name, @@ -3865,7 +2625,10 @@ def get_dev_box_action( if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -3880,7 +2643,7 @@ def get_dev_box_action( return deserialized # type: ignore @distributed_trace - def skip_dev_box_action( # pylint: disable=inconsistent-return-statements + def skip_action( # pylint: disable=inconsistent-return-statements self, project_name: str, user_id: str, dev_box_name: str, action_name: str, **kwargs: Any ) -> None: """Skips an occurrence of an action. @@ -3898,7 +2661,7 @@ def skip_dev_box_action( # pylint: disable=inconsistent-return-statements :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3911,7 +2674,7 @@ def skip_dev_box_action( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_dev_center_skip_dev_box_action_request( + _request = build_dev_boxes_skip_action_request( project_name=project_name, user_id=user_id, dev_box_name=dev_box_name, @@ -3933,8 +2696,6 @@ def skip_dev_box_action( # pylint: disable=inconsistent-return-statements response = pipeline_response.http_response if response.status_code not in [204]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -3942,7 +2703,7 @@ def skip_dev_box_action( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - def delay_dev_box_action( + def delay_action( self, project_name: str, user_id: str, @@ -3963,30 +2724,14 @@ def delay_dev_box_action( :type dev_box_name: str :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. + :keyword delay_until: The time to delay the Dev Box action or actions until, in RFC3339 format. + Required. :paramtype delay_until: ~datetime.datetime :return: DevBoxAction. The DevBoxAction is compatible with MutableMapping :rtype: ~azure.developer.devcenter.models.DevBoxAction :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "actionType": "str", # The action that will be taken. Required. "Stop" - "name": "str", # The name of the action. Required. - "sourceId": "str", # The id of the resource which triggered this action. - Required. - "next": { - "scheduledTime": "2020-02-20 00:00:00" # The time the action will be - triggered (UTC). Required. - }, - "suspendedUntil": "2020-02-20 00:00:00" # Optional. The earliest time that - the action could occur (UTC). - } """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3999,7 +2744,7 @@ def delay_dev_box_action( cls: ClsType[_models.DevBoxAction] = kwargs.pop("cls", None) - _request = build_dev_center_delay_dev_box_action_request( + _request = build_dev_boxes_delay_action_request( project_name=project_name, user_id=user_id, dev_box_name=dev_box_name, @@ -4023,7 +2768,10 @@ def delay_dev_box_action( if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -4038,10 +2786,9 @@ def delay_dev_box_action( return deserialized # type: ignore @distributed_trace - def delay_all_dev_box_actions( + def delay_all_actions( self, project_name: str, user_id: str, dev_box_name: str, *, delay_until: datetime.datetime, **kwargs: Any ) -> Iterable["_models.DevBoxActionDelayResult"]: - # pylint: disable=line-too-long """Delays all actions. :param project_name: Name of the project. Required. @@ -4051,56 +2798,19 @@ def delay_all_dev_box_actions( :type user_id: str :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. + :keyword delay_until: The time to delay the Dev Box action or actions until, in RFC3339 format. + Required. :paramtype delay_until: ~datetime.datetime :return: An iterator like instance of DevBoxActionDelayResult :rtype: ~azure.core.paging.ItemPaged[~azure.developer.devcenter.models.DevBoxActionDelayResult] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "name": "str", # The name of the action. Required. - "result": "str", # The result of the delay operation on this action. - Required. Known values are: "Succeeded" and "Failed". - "action": { - "actionType": "str", # The action that will be taken. Required. - "Stop" - "name": "str", # The name of the action. Required. - "sourceId": "str", # The id of the resource which triggered this - action. Required. - "next": { - "scheduledTime": "2020-02-20 00:00:00" # The time the action - will be triggered (UTC). Required. - }, - "suspendedUntil": "2020-02-20 00:00:00" # Optional. The earliest - time that the action could occur (UTC). - }, - "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. - } - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} cls: ClsType[List[_models.DevBoxActionDelayResult]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4111,7 +2821,7 @@ def delay_all_dev_box_actions( def prepare_request(next_link=None): if not next_link: - _request = build_dev_center_delay_all_dev_box_actions_request( + _request = build_dev_boxes_delay_all_actions_request( project_name=project_name, user_id=user_id, dev_box_name=dev_box_name, @@ -4166,8 +2876,6 @@ def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -4175,9 +2883,13 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) + +class DeploymentEnvironmentsClientOperationsMixin( # pylint: disable=name-too-long + DeploymentEnvironmentsClientMixinABC +): + @distributed_trace 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. @@ -4185,51 +2897,13 @@ def list_all_environments(self, project_name: str, **kwargs: Any) -> Iterable["_ :return: An iterator like instance of Environment :rtype: ~azure.core.paging.ItemPaged[~azure.developer.devcenter.models.Environment] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - 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. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} cls: ClsType[List[_models.Environment]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4240,7 +2914,7 @@ def list_all_environments(self, project_name: str, **kwargs: Any) -> Iterable["_ def prepare_request(next_link=None): if not next_link: - _request = build_dev_center_list_all_environments_request( + _request = build_deployment_environments_list_all_environments_request( project_name=project_name, api_version=self._config.api_version, headers=_headers, @@ -4292,8 +2966,6 @@ def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -4303,7 +2975,6 @@ def get_next(next_link=None): @distributed_trace 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. @@ -4314,51 +2985,13 @@ def list_environments(self, project_name: str, user_id: str, **kwargs: Any) -> I :return: An iterator like instance of Environment :rtype: ~azure.core.paging.ItemPaged[~azure.developer.devcenter.models.Environment] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - 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. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} cls: ClsType[List[_models.Environment]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4369,7 +3002,7 @@ def list_environments(self, project_name: str, user_id: str, **kwargs: Any) -> I def prepare_request(next_link=None): if not next_link: - _request = build_dev_center_list_environments_request( + _request = build_deployment_environments_list_environments_request( project_name=project_name, user_id=user_id, api_version=self._config.api_version, @@ -4422,8 +3055,6 @@ def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -4435,7 +3066,6 @@ def get_next(next_link=None): 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: Name of the project. Required. @@ -4448,46 +3078,8 @@ def get_environment( :return: Environment. The Environment is compatible with MutableMapping :rtype: ~azure.developer.devcenter.models.Environment :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - 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. - } """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4500,7 +3092,7 @@ def get_environment( cls: ClsType[_models.Environment] = kwargs.pop("cls", None) - _request = build_dev_center_get_environment_request( + _request = build_deployment_environments_get_environment_request( project_name=project_name, user_id=user_id, environment_name=environment_name, @@ -4522,7 +3114,10 @@ def get_environment( if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -4543,8 +3138,8 @@ def _create_or_update_environment_initial( environment_name: str, body: Union[_models.Environment, JSON, IO[bytes]], **kwargs: Any - ) -> JSON: - error_map: MutableMapping[int, Type[HttpResponseError]] = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4556,7 +3151,7 @@ def _create_or_update_environment_initial( _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[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None @@ -4565,7 +3160,7 @@ def _create_or_update_environment_initial( else: _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_dev_center_create_or_update_environment_request( + _request = build_deployment_environments_create_or_update_environment_request( project_name=project_name, user_id=user_id, environment_name=environment_name, @@ -4580,7 +3175,7 @@ def _create_or_update_environment_initial( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -4588,15 +3183,17 @@ def _create_or_update_environment_initial( response = pipeline_response.http_response if response.status_code not in [201]: - if _stream: + try: response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) response_headers = {} response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) - deserialized = _deserialize(JSON, response.json()) + deserialized = response.iter_bytes() if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -4614,7 +3211,6 @@ def begin_create_or_update_environment( 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. @@ -4633,79 +3229,6 @@ def begin_create_or_update_environment( MutableMapping :rtype: ~azure.core.polling.LROPoller[~azure.developer.devcenter.models.Environment] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = { - "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. - } - - # 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 @@ -4719,7 +3242,6 @@ def begin_create_or_update_environment( 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. @@ -4738,44 +3260,6 @@ def begin_create_or_update_environment( 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 @@ -4789,7 +3273,6 @@ def begin_create_or_update_environment( 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. @@ -4808,44 +3291,6 @@ def begin_create_or_update_environment( 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. - } """ @distributed_trace @@ -4857,7 +3302,6 @@ def begin_create_or_update_environment( 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. @@ -4874,79 +3318,6 @@ def begin_create_or_update_environment( MutableMapping :rtype: ~azure.core.polling.LROPoller[~azure.developer.devcenter.models.Environment] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = { - "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. - } - - # 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. - } """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} @@ -4968,6 +3339,7 @@ def begin_create_or_update_environment( params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): @@ -5007,8 +3379,8 @@ def get_long_running_output(pipeline_response): def _delete_environment_initial( self, project_name: str, user_id: str, environment_name: str, **kwargs: Any - ) -> Optional[JSON]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -5019,9 +3391,9 @@ def _delete_environment_initial( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[Optional[JSON]] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - _request = build_dev_center_delete_environment_request( + _request = build_deployment_environments_delete_environment_request( project_name=project_name, user_id=user_id, environment_name=environment_name, @@ -5034,7 +3406,7 @@ def _delete_environment_initial( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -5042,12 +3414,13 @@ def _delete_environment_initial( response = pipeline_response.http_response if response.status_code not in [202, 204]: - if _stream: + try: response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) - deserialized = None response_headers = {} if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) @@ -5055,7 +3428,7 @@ def _delete_environment_initial( "str", response.headers.get("Operation-Location") ) - deserialized = _deserialize(JSON, response.json()) + deserialized = response.iter_bytes() if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -5065,8 +3438,7 @@ def _delete_environment_initial( @distributed_trace def begin_delete_environment( self, project_name: str, user_id: str, environment_name: str, **kwargs: Any - ) -> LROPoller[_models.OperationDetails]: - # pylint: disable=line-too-long + ) -> LROPoller[None]: """Deletes an environment and all its associated resources. :param project_name: The DevCenter Project upon which to execute operations. Required. @@ -5076,49 +3448,14 @@ def begin_delete_environment( :type user_id: str :param environment_name: The name of the environment. Required. :type environment_name: str - :return: An instance of LROPoller that returns OperationDetails. The OperationDetails is - compatible with MutableMapping - :rtype: ~azure.core.polling.LROPoller[~azure.developer.devcenter.models.OperationDetails] + :return: An instance of LROPoller that returns None + :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # 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: "NotStarted", "Running", "Succeeded", "Failed", and "Canceled". - "endTime": "2020-02-20 00:00:00", # Optional. The end time of the operation. - "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. - }, - "percentComplete": 0.0, # Optional. Percent of the operation that is - complete. - "properties": {}, # Optional. Custom operation properties, populated only - for a successful operation. - "resourceId": "str", # Optional. The id of the resource. - "startTime": "2020-02-20 00:00:00" # Optional. The start time of the - operation. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.OperationDetails] = kwargs.pop("cls", None) + cls: ClsType[None] = 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) @@ -5132,20 +3469,12 @@ def begin_delete_environment( params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): - response_headers = {} - response = pipeline_response.http_response - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - response_headers["Operation-Location"] = self._deserialize( - "str", response.headers.get("Operation-Location") - ) - - deserialized = _deserialize(_models.OperationDetails, response.json()) + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized + return cls(pipeline_response, None, {}) # type: ignore path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), @@ -5160,15 +3489,13 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller[_models.OperationDetails].from_continuation_token( + return LROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller[_models.OperationDetails]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore @distributed_trace def list_catalogs(self, project_name: str, **kwargs: Any) -> Iterable["_models.Catalog"]: @@ -5179,21 +3506,13 @@ def list_catalogs(self, project_name: str, **kwargs: Any) -> Iterable["_models.C :return: An iterator like instance of Catalog :rtype: ~azure.core.paging.ItemPaged[~azure.developer.devcenter.models.Catalog] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "name": "str" # Name of the catalog. Required. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} cls: ClsType[List[_models.Catalog]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -5204,7 +3523,7 @@ def list_catalogs(self, project_name: str, **kwargs: Any) -> Iterable["_models.C def prepare_request(next_link=None): if not next_link: - _request = build_dev_center_list_catalogs_request( + _request = build_deployment_environments_list_catalogs_request( project_name=project_name, api_version=self._config.api_version, headers=_headers, @@ -5256,8 +3575,6 @@ def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -5276,16 +3593,8 @@ def get_catalog(self, project_name: str, catalog_name: str, **kwargs: Any) -> _m :return: Catalog. The Catalog is compatible with MutableMapping :rtype: ~azure.developer.devcenter.models.Catalog :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "name": "str" # Name of the catalog. Required. - } """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -5298,7 +3607,7 @@ def get_catalog(self, project_name: str, catalog_name: str, **kwargs: Any) -> _m cls: ClsType[_models.Catalog] = kwargs.pop("cls", None) - _request = build_dev_center_get_catalog_request( + _request = build_deployment_environments_get_catalog_request( project_name=project_name, catalog_name=catalog_name, api_version=self._config.api_version, @@ -5319,7 +3628,10 @@ def get_catalog(self, project_name: str, catalog_name: str, **kwargs: Any) -> _m if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -5337,7 +3649,6 @@ def get_catalog(self, project_name: str, catalog_name: str, **kwargs: Any) -> _m def list_environment_definitions( 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. @@ -5345,49 +3656,13 @@ def list_environment_definitions( :return: An iterator like instance of EnvironmentDefinition :rtype: ~azure.core.paging.ItemPaged[~azure.developer.devcenter.models.EnvironmentDefinition] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "catalogName": "str", # Name of the catalog. Required. - "id": "str", # The ID of the environment definition. Required. - "name": "str", # Name of the environment definition. Required. - "description": "str", # Optional. A short description of the environment - definition. - "parameters": [ - { - "id": "str", # Unique ID of the parameter. Required. - "required": bool, # Whether or not this parameter is - required. Required. - "type": "str", # 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". - "allowed": [ - "str" # Optional. An array of allowed values. - ], - "default": "str", # Optional. Default value of the - parameter. - "description": "str", # Optional. Description of the - parameter. - "name": "str", # Optional. Display name of the parameter. - "readOnly": bool # Optional. Whether or not this parameter - is read-only. If true, default should have a value. - } - ], - "parametersSchema": "str", # Optional. JSON schema defining the parameters - object passed to an environment. - "templatePath": "str" # Optional. Path to the Environment Definition - entrypoint file. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} cls: ClsType[List[_models.EnvironmentDefinition]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -5398,7 +3673,7 @@ def list_environment_definitions( def prepare_request(next_link=None): if not next_link: - _request = build_dev_center_list_environment_definitions_request( + _request = build_deployment_environments_list_environment_definitions_request( project_name=project_name, api_version=self._config.api_version, headers=_headers, @@ -5450,8 +3725,6 @@ def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -5463,7 +3736,6 @@ def get_next(next_link=None): def list_environment_definitions_by_catalog( 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. @@ -5473,49 +3745,13 @@ def list_environment_definitions_by_catalog( :return: An iterator like instance of EnvironmentDefinition :rtype: ~azure.core.paging.ItemPaged[~azure.developer.devcenter.models.EnvironmentDefinition] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "catalogName": "str", # Name of the catalog. Required. - "id": "str", # The ID of the environment definition. Required. - "name": "str", # Name of the environment definition. Required. - "description": "str", # Optional. A short description of the environment - definition. - "parameters": [ - { - "id": "str", # Unique ID of the parameter. Required. - "required": bool, # Whether or not this parameter is - required. Required. - "type": "str", # 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". - "allowed": [ - "str" # Optional. An array of allowed values. - ], - "default": "str", # Optional. Default value of the - parameter. - "description": "str", # Optional. Description of the - parameter. - "name": "str", # Optional. Display name of the parameter. - "readOnly": bool # Optional. Whether or not this parameter - is read-only. If true, default should have a value. - } - ], - "parametersSchema": "str", # Optional. JSON schema defining the parameters - object passed to an environment. - "templatePath": "str" # Optional. Path to the Environment Definition - entrypoint file. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} cls: ClsType[List[_models.EnvironmentDefinition]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -5526,7 +3762,7 @@ def list_environment_definitions_by_catalog( def prepare_request(next_link=None): if not next_link: - _request = build_dev_center_list_environment_definitions_by_catalog_request( + _request = build_deployment_environments_list_environment_definitions_by_catalog_request( project_name=project_name, catalog_name=catalog_name, api_version=self._config.api_version, @@ -5579,8 +3815,6 @@ def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -5592,7 +3826,6 @@ def get_next(next_link=None): def get_environment_definition( self, project_name: str, catalog_name: str, definition_name: str, **kwargs: Any ) -> _models.EnvironmentDefinition: - # pylint: disable=line-too-long """Get an environment definition from a catalog. :param project_name: Name of the project. Required. @@ -5604,44 +3837,8 @@ def get_environment_definition( :return: EnvironmentDefinition. The EnvironmentDefinition is compatible with MutableMapping :rtype: ~azure.developer.devcenter.models.EnvironmentDefinition :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "catalogName": "str", # Name of the catalog. Required. - "id": "str", # The ID of the environment definition. Required. - "name": "str", # Name of the environment definition. Required. - "description": "str", # Optional. A short description of the environment - definition. - "parameters": [ - { - "id": "str", # Unique ID of the parameter. Required. - "required": bool, # Whether or not this parameter is - required. Required. - "type": "str", # 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". - "allowed": [ - "str" # Optional. An array of allowed values. - ], - "default": "str", # Optional. Default value of the - parameter. - "description": "str", # Optional. Description of the - parameter. - "name": "str", # Optional. Display name of the parameter. - "readOnly": bool # Optional. Whether or not this parameter - is read-only. If true, default should have a value. - } - ], - "parametersSchema": "str", # Optional. JSON schema defining the parameters - object passed to an environment. - "templatePath": "str" # Optional. Path to the Environment Definition - entrypoint file. - } """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -5654,7 +3851,7 @@ def get_environment_definition( cls: ClsType[_models.EnvironmentDefinition] = kwargs.pop("cls", None) - _request = build_dev_center_get_environment_definition_request( + _request = build_deployment_environments_get_environment_definition_request( project_name=project_name, catalog_name=catalog_name, definition_name=definition_name, @@ -5676,7 +3873,10 @@ def get_environment_definition( if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -5692,34 +3892,20 @@ def get_environment_definition( @distributed_trace 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. + :param project_name: Name of the project. Required. :type project_name: str :return: An iterator like instance of EnvironmentType :rtype: ~azure.core.paging.ItemPaged[~azure.developer.devcenter.models.EnvironmentType] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "deploymentTargetId": "str", # 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. - "name": "str", # Name of the environment type. Required. - "status": "str" # Indicates whether this environment type is enabled for use - in this project. Required. Known values are: "Enabled" and "Disabled". - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} cls: ClsType[List[_models.EnvironmentType]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -5730,7 +3916,7 @@ def list_environment_types(self, project_name: str, **kwargs: Any) -> Iterable[" def prepare_request(next_link=None): if not next_link: - _request = build_dev_center_list_environment_types_request( + _request = build_deployment_environments_list_environment_types_request( project_name=project_name, api_version=self._config.api_version, headers=_headers, @@ -5782,8 +3968,6 @@ def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) 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 2f781d74082..a066e16a64d 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_serialization.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_serialization.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # # Copyright (c) Microsoft Corporation. All rights reserved. @@ -24,7 +25,6 @@ # # -------------------------------------------------------------------------- -# pylint: skip-file # pyright: reportUnnecessaryTypeIgnoreComment=false from base64 import b64decode, b64encode @@ -48,11 +48,8 @@ IO, Mapping, Callable, - TypeVar, MutableMapping, - Type, List, - Mapping, ) try: @@ -62,13 +59,13 @@ import xml.etree.ElementTree as ET import isodate # type: ignore +from typing_extensions import Self from azure.core.exceptions import DeserializationError, SerializationError from azure.core.serialization import NULL as CoreNull _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") -ModelType = TypeVar("ModelType", bound="Model") JSON = MutableMapping[str, Any] @@ -91,6 +88,8 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: :param data: Input, could be bytes or stream (will be decoded with UTF8) or text :type data: str or bytes or IO :param str content_type: The content type. + :return: The deserialized data. + :rtype: object """ if hasattr(data, "read"): # Assume a stream @@ -112,7 +111,7 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: try: return json.loads(data_as_str) except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) + raise DeserializationError("JSON is invalid: {}".format(err), err) from err elif "xml" in (content_type or []): try: @@ -144,6 +143,8 @@ def _json_attemp(data): # context otherwise. _LOGGER.critical("Wasn't XML not JSON, failing") raise DeserializationError("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) @classmethod @@ -153,6 +154,11 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], Use bytes and headers to NOT use any requests/aiohttp or whatever specific implementation. Headers will tested for "content-type" + + :param bytes body_bytes: The body of the response. + :param dict headers: The headers of the response. + :returns: The deserialized data. + :rtype: object """ # Try to use content-type from headers if available content_type = None @@ -177,80 +183,31 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], except NameError: _long_type = int - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -try: - from datetime import timezone as _FixedOffset # type: ignore -except ImportError: # Python 2.7 - - class _FixedOffset(datetime.tzinfo): # type: ignore - """Fixed offset in minutes east from UTC. - Copy/pasted from Python doc - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc -except ImportError: - TZ_UTC = UTC() # type: ignore +TZ_UTC = datetime.timezone.utc _FLATTEN = re.compile(r"(? None: self.additional_properties: Optional[Dict[str, Any]] = {} - for k in kwargs: + for k in kwargs: # pylint: disable=consider-using-dict-items if k not in self._attribute_map: _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) elif k in self._validation and self._validation[k].get("readonly", False): @@ -298,13 +262,23 @@ def __init__(self, **kwargs: Any) -> None: setattr(self, k, kwargs[k]) def __eq__(self, other: Any) -> bool: - """Compare objects by comparing all attributes.""" + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ return False def __ne__(self, other: Any) -> bool: - """Compare objects by comparing all attributes.""" + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ return not self.__eq__(other) def __str__(self) -> str: @@ -324,7 +298,11 @@ def is_xml_model(cls) -> bool: @classmethod def _create_xml_node(cls): - """Create XML node.""" + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ try: xml_map = cls._xml_map # type: ignore except AttributeError: @@ -344,7 +322,9 @@ def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) # type: ignore + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) def as_dict( self, @@ -378,12 +358,15 @@ def my_key_transformer(key, attr_desc, value): If you want XML serialization, you can pass the kwargs is_xml=True. + :param bool keep_readonly: If you want to serialize the readonly attributes :param function key_transformer: A key transformer function. :returns: A dict JSON compatible object :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) # type: ignore + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs + ) @classmethod def _infer_class_models(cls): @@ -393,30 +376,31 @@ def _infer_class_models(cls): client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} if cls.__name__ not in client_models: raise ValueError("Not Autorest generated code") - except Exception: + except Exception: # pylint: disable=broad-exception-caught # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. client_models = {cls.__name__: cls} return client_models @classmethod - def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = None) -> ModelType: + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: """Parse a str using the RestAPI syntax and return a model. :param str data: A str using RestAPI structure. JSON by default. :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model - :raises: DeserializationError if something went wrong + :raises DeserializationError: if something went wrong + :rtype: Self """ deserializer = Deserializer(cls._infer_class_models()) return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod def from_dict( - cls: Type[ModelType], + cls, data: Any, key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, content_type: Optional[str] = None, - ) -> ModelType: + ) -> Self: """Parse a dict using given key extractor return a model. By default consider key @@ -424,9 +408,11 @@ def from_dict( and last_rest_key_case_insensitive_extractor) :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model :raises: DeserializationError if something went wrong + :rtype: Self """ deserializer = Deserializer(cls._infer_class_models()) deserializer.key_extractors = ( # type: ignore @@ -446,21 +432,25 @@ def _flatten_subtype(cls, key, objects): return {} result = dict(cls._subtype_map[key]) for valuetype in cls._subtype_map[key].values(): - result.update(objects[valuetype]._flatten_subtype(key, objects)) + result.update(objects[valuetype]._flatten_subtype(key, objects)) # pylint: disable=protected-access return result @classmethod def _classify(cls, response, objects): """Check the class _subtype_map for any child classes. We want to ignore any inherited _subtype_maps. - Remove the polymorphic key from the initial data. + + :param dict response: The initial data + :param dict objects: The class objects + :returns: The class to be used + :rtype: class """ for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): subtype_value = None if not isinstance(response, ET.Element): rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] - subtype_value = response.pop(rest_api_response_key, None) or response.pop(subtype_key, None) + subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) else: subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) if subtype_value: @@ -499,11 +489,13 @@ def _decode_attribute_map_key(key): inside the received data. :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str """ return key.replace("\\.", ".") -class Serializer(object): +class Serializer: # pylint: disable=too-many-public-methods """Request object model serializer.""" basic_types = {str: "str", int: "int", bool: "bool", float: "float"} @@ -538,7 +530,7 @@ class Serializer(object): "multiple": lambda x, y: x % y != 0, } - def __init__(self, classes: Optional[Mapping[str, type]] = None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.serialize_type = { "iso-8601": Serializer.serialize_iso, "rfc-1123": Serializer.serialize_rfc, @@ -558,13 +550,16 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None): self.key_transformer = full_restapi_key_transformer self.client_side_validation = True - def _serialize(self, target_obj, data_type=None, **kwargs): + def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals + self, target_obj, data_type=None, **kwargs + ): """Serialize data into a string according to type. - :param target_obj: The data to be serialized. + :param object target_obj: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str, dict - :raises: SerializationError if serialization fails. + :raises SerializationError: if serialization fails. + :returns: The serialized data. """ key_transformer = kwargs.get("key_transformer", self.key_transformer) keep_readonly = kwargs.get("keep_readonly", False) @@ -590,12 +585,14 @@ def _serialize(self, target_obj, data_type=None, **kwargs): serialized = {} if is_xml_model_serialization: - serialized = target_obj._create_xml_node() + serialized = target_obj._create_xml_node() # pylint: disable=protected-access try: - attributes = target_obj._attribute_map + attributes = target_obj._attribute_map # pylint: disable=protected-access for attr, attr_desc in attributes.items(): attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + attr_name, {} + ).get("readonly", False): continue if attr_name == "additional_properties" and attr_desc["key"] == "": @@ -631,7 +628,8 @@ def _serialize(self, target_obj, data_type=None, **kwargs): if isinstance(new_attr, list): serialized.extend(new_attr) # type: ignore elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. + # If the down XML has no XML/Name, + # we MUST replace the tag with the local tag. But keeping the namespaces. if "name" not in getattr(orig_attr, "_xml_map", {}): splitted_tag = new_attr.tag.split("}") if len(splitted_tag) == 2: # Namespace @@ -662,17 +660,17 @@ def _serialize(self, target_obj, data_type=None, **kwargs): except (AttributeError, KeyError, TypeError) as err: msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) raise SerializationError(msg) from err - else: - return serialized + return serialized def body(self, data, data_type, **kwargs): """Serialize data intended for a request body. - :param data: The data to be serialized. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None + :raises SerializationError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized request body """ # Just in case this is a dict @@ -701,7 +699,7 @@ def body(self, data, data_type, **kwargs): attribute_key_case_insensitive_extractor, last_rest_key_case_insensitive_extractor, ] - data = deserializer._deserialize(data_type, data) + data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access except DeserializationError as err: raise SerializationError("Unable to build a model: " + str(err)) from err @@ -710,11 +708,13 @@ def body(self, data, data_type, **kwargs): def url(self, name, data, data_type, **kwargs): """Serialize data intended for a URL path. - :param data: The data to be serialized. + :param str name: The name of the URL path parameter. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None + :returns: The serialized URL path + :raises TypeError: if serialization fails. + :raises ValueError: if data is None """ try: output = self.serialize_data(data, data_type, **kwargs) @@ -726,21 +726,20 @@ def url(self, name, data, data_type, **kwargs): output = output.replace("{", quote("{")).replace("}", quote("}")) else: output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return output def query(self, name, data, data_type, **kwargs): """Serialize data intended for a URL query. - :param data: The data to be serialized. + :param str name: The name of the query parameter. + :param object data: The data to be serialized. :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, list - :raises: TypeError if serialization fails. - :raises: ValueError if data is None + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized query parameter """ try: # Treat the list aside, since we don't want to encode the div separator @@ -757,19 +756,20 @@ def query(self, name, data, data_type, **kwargs): output = str(output) else: output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) def header(self, name, data, data_type, **kwargs): """Serialize data intended for a request header. - :param data: The data to be serialized. + :param str name: The name of the header. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized header """ try: if data_type in ["[str]"]: @@ -778,21 +778,20 @@ def header(self, name, data, data_type, **kwargs): output = self.serialize_data(data, data_type, **kwargs) if data_type == "bool": output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) def serialize_data(self, data, data_type, **kwargs): """Serialize generic data according to supplied data type. - :param data: The data to be serialized. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. + :raises AttributeError: if required data is None. + :raises ValueError: if data is None + :raises SerializationError: if serialization fails. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list """ if data is None: raise ValueError("No value for given attribute") @@ -803,7 +802,7 @@ def serialize_data(self, data, data_type, **kwargs): if data_type in self.basic_types.values(): return self.serialize_basic(data, data_type, **kwargs) - elif data_type in self.serialize_type: + if data_type in self.serialize_type: return self.serialize_type[data_type](data, **kwargs) # If dependencies is empty, try with current data class @@ -819,11 +818,10 @@ def serialize_data(self, data, data_type, **kwargs): except (ValueError, TypeError) as err: msg = "Unable to serialize value: {!r} as type: {!r}." raise SerializationError(msg.format(data, data_type)) from err - else: - return self._serialize(data, **kwargs) + return self._serialize(data, **kwargs) @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): + def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) if custom_serializer: return custom_serializer @@ -839,23 +837,26 @@ def serialize_basic(cls, data, data_type, **kwargs): - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - is_xml bool : If set, use xml_basic_types_serializers - :param data: Object to be serialized. + :param obj data: Object to be serialized. :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object """ custom_serializer = cls._get_custom_serializers(data_type, **kwargs) if custom_serializer: return custom_serializer(data) if data_type == "str": return cls.serialize_unicode(data) - return eval(data_type)(data) # nosec + return eval(data_type)(data) # nosec # pylint: disable=eval-used @classmethod def serialize_unicode(cls, data): """Special handling for serializing unicode strings in Py2. Encode to UTF-8 if unicode, otherwise handle as a str. - :param data: Object to be serialized. + :param str data: Object to be serialized. :rtype: str + :return: serialized object """ try: # If I received an enum, return its value return data.value @@ -869,8 +870,7 @@ def serialize_unicode(cls, data): return data except NameError: return str(data) - else: - return str(data) + return str(data) def serialize_iter(self, data, iter_type, div=None, **kwargs): """Serialize iterable. @@ -880,15 +880,13 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): serialization_ctxt['type'] should be same as data_type. - is_xml bool : If set, serialize as XML - :param list attr: Object to be serialized. + :param list data: Object to be serialized. :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. :param str div: If set, this str will be used to combine the elements in the iterable into a combined string. Default is 'None'. - :keyword bool do_quote: Whether to quote the serialized result of each iterable element. Defaults to False. :rtype: list, str + :return: serialized iterable """ if isinstance(data, str): raise SerializationError("Refuse str type as a valid iter type.") @@ -943,9 +941,8 @@ def serialize_dict(self, attr, dict_type, **kwargs): :param dict attr: Object to be serialized. :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. :rtype: dict + :return: serialized dictionary """ serialization_ctxt = kwargs.get("serialization_ctxt", {}) serialized = {} @@ -969,7 +966,7 @@ def serialize_dict(self, attr, dict_type, **kwargs): return serialized - def serialize_object(self, attr, **kwargs): + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements """Serialize a generic object. This will be handled as a dictionary. If object passed in is not a basic type (str, int, float, dict, list) it will simply be @@ -977,6 +974,7 @@ def serialize_object(self, attr, **kwargs): :param dict attr: Object to be serialized. :rtype: dict or str + :return: serialized object """ if attr is None: return None @@ -1001,7 +999,7 @@ def serialize_object(self, attr, **kwargs): return self.serialize_decimal(attr) # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): + if obj_type in self.dependencies.values() or isinstance(attr, Model): return self._serialize(attr) if obj_type == dict: @@ -1032,56 +1030,61 @@ def serialize_enum(attr, enum_obj=None): try: enum_obj(result) # type: ignore return result - except ValueError: + except ValueError as exc: for enum_value in enum_obj: # type: ignore if enum_value.value.lower() == str(attr).lower(): return enum_value.value error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) + raise SerializationError(error.format(attr, enum_obj)) from exc @staticmethod - def serialize_bytearray(attr, **kwargs): + def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument """Serialize bytearray into base-64 string. - :param attr: Object to be serialized. + :param str attr: Object to be serialized. :rtype: str + :return: serialized base64 """ return b64encode(attr).decode() @staticmethod - def serialize_base64(attr, **kwargs): + def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument """Serialize str into base-64 string. - :param attr: Object to be serialized. + :param str attr: Object to be serialized. :rtype: str + :return: serialized base64 """ encoded = b64encode(attr).decode("ascii") return encoded.strip("=").replace("+", "-").replace("/", "_") @staticmethod - def serialize_decimal(attr, **kwargs): + def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument """Serialize Decimal object to float. - :param attr: Object to be serialized. + :param decimal attr: Object to be serialized. :rtype: float + :return: serialized decimal """ return float(attr) @staticmethod - def serialize_long(attr, **kwargs): + def serialize_long(attr, **kwargs): # pylint: disable=unused-argument """Serialize long (Py2) or int (Py3). - :param attr: Object to be serialized. + :param int attr: Object to be serialized. :rtype: int/long + :return: serialized long """ return _long_type(attr) @staticmethod - def serialize_date(attr, **kwargs): + def serialize_date(attr, **kwargs): # pylint: disable=unused-argument """Serialize Date object into ISO-8601 formatted string. :param Date attr: Object to be serialized. :rtype: str + :return: serialized date """ if isinstance(attr, str): attr = isodate.parse_date(attr) @@ -1089,11 +1092,12 @@ def serialize_date(attr, **kwargs): return t @staticmethod - def serialize_time(attr, **kwargs): + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument """Serialize Time object into ISO-8601 formatted string. :param datetime.time attr: Object to be serialized. :rtype: str + :return: serialized time """ if isinstance(attr, str): attr = isodate.parse_time(attr) @@ -1103,30 +1107,32 @@ def serialize_time(attr, **kwargs): return t @staticmethod - def serialize_duration(attr, **kwargs): + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument """Serialize TimeDelta object into ISO-8601 formatted string. :param TimeDelta attr: Object to be serialized. :rtype: str + :return: serialized duration """ if isinstance(attr, str): attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) @staticmethod - def serialize_rfc(attr, **kwargs): + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. :param Datetime attr: Object to be serialized. :rtype: str - :raises: TypeError if format invalid. + :raises TypeError: if format invalid. + :return: serialized rfc """ try: if not attr.tzinfo: _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( Serializer.days[utc.tm_wday], @@ -1139,12 +1145,13 @@ def serialize_rfc(attr, **kwargs): ) @staticmethod - def serialize_iso(attr, **kwargs): + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into ISO-8601 formatted string. :param Datetime attr: Object to be serialized. :rtype: str - :raises: SerializationError if format invalid. + :raises SerializationError: if format invalid. + :return: serialized iso """ if isinstance(attr, str): attr = isodate.parse_datetime(attr) @@ -1170,13 +1177,14 @@ def serialize_iso(attr, **kwargs): raise TypeError(msg) from err @staticmethod - def serialize_unix(attr, **kwargs): + def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into IntTime format. This is represented as seconds. :param Datetime attr: Object to be serialized. :rtype: int - :raises: SerializationError if format invalid + :raises SerializationError: if format invalid + :return: serialied unix """ if isinstance(attr, int): return attr @@ -1184,11 +1192,11 @@ def serialize_unix(attr, **kwargs): if not attr.tzinfo: _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc -def rest_key_extractor(attr, attr_desc, data): +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument key = attr_desc["key"] working_data = data @@ -1209,7 +1217,9 @@ def rest_key_extractor(attr, attr_desc, data): return working_data.get(key) -def rest_key_case_insensitive_extractor(attr, attr_desc, data): +def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements + attr, attr_desc, data +): key = attr_desc["key"] working_data = data @@ -1230,17 +1240,29 @@ def rest_key_case_insensitive_extractor(attr, attr_desc, data): return attribute_key_case_insensitive_extractor(key, None, working_data) -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ key = attr_desc["key"] dict_keys = _FLATTEN.split(key) return attribute_key_extractor(dict_keys[-1], None, data) -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument """Extract the attribute in "data" based on the last part of the JSON path key. This is the case insensitive version of "last_rest_key_extractor" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute """ key = attr_desc["key"] dict_keys = _FLATTEN.split(key) @@ -1277,7 +1299,7 @@ def _extract_name_from_internal_type(internal_type): return xml_name -def xml_key_extractor(attr, attr_desc, data): +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements if isinstance(data, dict): return None @@ -1329,22 +1351,21 @@ def xml_key_extractor(attr, attr_desc, data): if is_iter_type: if is_wrapped: return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list + return [] # not wrapped, assume empty list return None # Assume it's not there, maybe an optional node. # If is_iter_type and not wrapped, return all found children if is_iter_type: if not is_wrapped: return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) + # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( # pylint: disable=line-too-long + xml_name ) - return list(children[0]) # Might be empty list and that's ok. + ) + return list(children[0]) # Might be empty list and that's ok. # Here it's not a itertype, we should have found one element only or empty if len(children) > 1: @@ -1352,7 +1373,7 @@ def xml_key_extractor(attr, attr_desc, data): return children[0] -class Deserializer(object): +class Deserializer: """Response object model deserializer. :param dict classes: Class type dictionary for deserializing complex types. @@ -1361,9 +1382,9 @@ class Deserializer(object): basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - 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_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - def __init__(self, classes: Optional[Mapping[str, type]] = None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.deserialize_type = { "iso-8601": Deserializer.deserialize_iso, "rfc-1123": Deserializer.deserialize_rfc, @@ -1399,27 +1420,29 @@ def __call__(self, target_obj, response_data, content_type=None): :param str target_obj: Target data type to deserialize to. :param requests.Response response_data: REST response object. :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. + :rtype: object """ data = self._unpack_content(response_data, content_type) return self._deserialize(target_obj, data) - def _deserialize(self, target_obj, data): + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements """Call the deserializer on a model. Data needs to be already deserialized as JSON or XML ElementTree :param str target_obj: Target data type to deserialize to. :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. + :rtype: object """ # This is already a model, go recursive just in case if hasattr(data, "_attribute_map"): constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] try: - for attr, mapconfig in data._attribute_map.items(): + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access if attr in constants: continue value = getattr(data, attr) @@ -1438,13 +1461,13 @@ def _deserialize(self, target_obj, data): if isinstance(response, str): return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): + if isinstance(response, type) and issubclass(response, Enum): return self.deserialize_enum(data, response) - if data is None: + if data is None or data is CoreNull: return data try: - attributes = response._attribute_map # type: ignore + attributes = response._attribute_map # type: ignore # pylint: disable=protected-access d_attrs = {} for attr, attr_desc in attributes.items(): # Check empty string. If it's not empty, someone has a real "additionalProperties"... @@ -1474,9 +1497,8 @@ def _deserialize(self, target_obj, data): except (AttributeError, TypeError, KeyError) as err: msg = "Unable to deserialize to object: " + class_name # type: ignore raise DeserializationError(msg) from err - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) def _build_additional_properties(self, attribute_map, data): if not self.additional_properties_detection: @@ -1503,6 +1525,8 @@ def _classify_target(self, target, data): :param str target: The target object type to deserialize to. :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple """ if target is None: return None, None @@ -1514,7 +1538,7 @@ def _classify_target(self, target, data): return target, target try: - target = target._classify(data, self.dependencies) # type: ignore + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access except AttributeError: pass # Target is not a Model, no classify return target, target.__class__.__name__ # type: ignore @@ -1529,10 +1553,12 @@ def failsafe_deserialize(self, target_obj, data, content_type=None): :param str target_obj: The target object type to deserialize to. :param str/dict data: The response data to deserialize. :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object """ try: return self(target_obj, data, content_type=content_type) - except: + except: # pylint: disable=bare-except _LOGGER.debug( "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True ) @@ -1550,10 +1576,12 @@ def _unpack_content(raw_data, content_type=None): If raw_data is something else, bypass all logic and return it directly. - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. + :param obj raw_data: Data to be processed. + :param str content_type: How to parse if raw_data is a string/bytes. :raises JSONDecodeError: If JSON is requested and parsing is impossible. :raises UnicodeDecodeError: If bytes is not UTF8 + :rtype: object + :return: Unpacked content. """ # Assume this is enough to detect a Pipeline Response without importing it context = getattr(raw_data, "context", {}) @@ -1577,24 +1605,35 @@ def _unpack_content(raw_data, content_type=None): def _instantiate_model(self, response, attrs, additional_properties=None): """Instantiate a response model passing in deserialized args. - :param response: The response model class. - :param d_attrs: The deserialized response attributes. + :param Response response: The response model class. + :param dict attrs: The deserialized response attributes. + :param dict additional_properties: Additional properties to be set. + :rtype: Response + :return: The instantiated response model. """ if callable(response): subtype = getattr(response, "_subtype_map", {}) try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] + readonly = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("readonly") + ] + const = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("constant") + ] kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} response_obj = response(**kwargs) for attr in readonly: setattr(response_obj, attr, attrs.get(attr)) if additional_properties: - response_obj.additional_properties = additional_properties + response_obj.additional_properties = additional_properties # type: ignore return response_obj except TypeError as err: msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore - raise DeserializationError(msg + str(err)) + raise DeserializationError(msg + str(err)) from err else: try: for attr, value in attrs.items(): @@ -1603,15 +1642,16 @@ def _instantiate_model(self, response, attrs, additional_properties=None): except Exception as exp: msg = "Unable to populate response model. " msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) + raise DeserializationError(msg) from exp - def deserialize_data(self, data, data_type): + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements """Process data for deserialization according to data type. :param str data: The response string to be deserialized. :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. + :rtype: object """ if data is None: return data @@ -1625,7 +1665,11 @@ def deserialize_data(self, data, data_type): if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): return data - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "object", + "[]", + r"{}", + ] if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: return None data_val = self.deserialize_type[data_type](data) @@ -1645,14 +1689,14 @@ def deserialize_data(self, data, data_type): msg = "Unable to deserialize response data." msg += " Data: {}, {}".format(data, data_type) raise DeserializationError(msg) from err - else: - return self._deserialize(obj_type, data) + return self._deserialize(obj_type, data) def deserialize_iter(self, attr, iter_type): """Deserialize an iterable. :param list attr: Iterable to be deserialized. :param str iter_type: The type of object in the iterable. + :return: Deserialized iterable. :rtype: list """ if attr is None: @@ -1669,6 +1713,7 @@ def deserialize_dict(self, attr, dict_type): :param dict/list attr: Dictionary to be deserialized. Also accepts a list of key, value pairs. :param str dict_type: The object type of the items in the dictionary. + :return: Deserialized dictionary. :rtype: dict """ if isinstance(attr, list): @@ -1679,13 +1724,14 @@ def deserialize_dict(self, attr, dict_type): attr = {el.tag: el.text for el in attr} return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - def deserialize_object(self, attr, **kwargs): + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements """Deserialize a generic object. This will be handled as a dictionary. :param dict attr: Dictionary to be deserialized. + :return: Deserialized object. :rtype: dict - :raises: TypeError if non-builtin datatype encountered. + :raises TypeError: if non-builtin datatype encountered. """ if attr is None: return None @@ -1718,11 +1764,10 @@ def deserialize_object(self, attr, **kwargs): pass return deserialized - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) - def deserialize_basic(self, attr, data_type): + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements """Deserialize basic builtin data type from string. Will attempt to convert to str, int, float and bool. This function will also accept '1', '0', 'true' and 'false' as @@ -1730,8 +1775,9 @@ def deserialize_basic(self, attr, data_type): :param str attr: response string to be deserialized. :param str data_type: deserialization data type. + :return: Deserialized basic type. :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. + :raises TypeError: if string format is not valid. """ # If we're here, data is supposed to be a basic type. # If it's still an XML node, take the text @@ -1741,24 +1787,23 @@ def deserialize_basic(self, attr, data_type): if data_type == "str": # None or '', node is empty string. return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None if data_type == "bool": if attr in [True, False, 1, 0]: return bool(attr) - elif isinstance(attr, str): + if isinstance(attr, str): if attr.lower() in ["true", "1"]: return True - elif attr.lower() in ["false", "0"]: + if attr.lower() in ["false", "0"]: return False raise TypeError("Invalid boolean value: {}".format(attr)) if data_type == "str": return self.deserialize_unicode(attr) - return eval(data_type)(attr) # nosec + return eval(data_type)(attr) # nosec # pylint: disable=eval-used @staticmethod def deserialize_unicode(data): @@ -1766,6 +1811,7 @@ def deserialize_unicode(data): as a string. :param str data: response string to be deserialized. + :return: Deserialized string. :rtype: str or unicode """ # We might be here because we have an enum modeled as string, @@ -1779,8 +1825,7 @@ def deserialize_unicode(data): return data except NameError: return str(data) - else: - return str(data) + return str(data) @staticmethod def deserialize_enum(data, enum_obj): @@ -1792,6 +1837,7 @@ def deserialize_enum(data, enum_obj): :param str data: Response string to be deserialized. If this value is None or invalid it will be returned as-is. :param Enum enum_obj: Enum object to deserialize to. + :return: Deserialized enum object. :rtype: Enum """ if isinstance(data, enum_obj) or data is None: @@ -1802,9 +1848,9 @@ def deserialize_enum(data, enum_obj): # Workaround. We might consider remove it in the future. try: return list(enum_obj.__members__.values())[data] - except IndexError: + except IndexError as exc: error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) + raise DeserializationError(error.format(data, enum_obj)) from exc try: return enum_obj(str(data)) except ValueError: @@ -1820,8 +1866,9 @@ def deserialize_bytearray(attr): """Deserialize string into bytearray. :param str attr: response string to be deserialized. + :return: Deserialized bytearray :rtype: bytearray - :raises: TypeError if string format invalid. + :raises TypeError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1832,8 +1879,9 @@ def deserialize_base64(attr): """Deserialize base64 encoded string into string. :param str attr: response string to be deserialized. + :return: Deserialized base64 string :rtype: bytearray - :raises: TypeError if string format invalid. + :raises TypeError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1847,8 +1895,9 @@ def deserialize_decimal(attr): """Deserialize string into Decimal object. :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. + :return: Deserialized decimal + :raises DeserializationError: if string format invalid. + :rtype: decimal """ if isinstance(attr, ET.Element): attr = attr.text @@ -1863,8 +1912,9 @@ def deserialize_long(attr): """Deserialize string into long (Py2) or int (Py3). :param str attr: response string to be deserialized. + :return: Deserialized int :rtype: long or int - :raises: ValueError if string format invalid. + :raises ValueError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1875,8 +1925,9 @@ def deserialize_duration(attr): """Deserialize ISO-8601 formatted string into TimeDelta object. :param str attr: response string to be deserialized. + :return: Deserialized duration :rtype: TimeDelta - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1885,16 +1936,16 @@ def deserialize_duration(attr): except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize duration object." raise DeserializationError(msg) from err - else: - return duration + return duration @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. :param str attr: response string to be deserialized. + :return: Deserialized date :rtype: Date - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1908,8 +1959,9 @@ def deserialize_time(attr): """Deserialize ISO-8601 formatted string into time object. :param str attr: response string to be deserialized. + :return: Deserialized time :rtype: datetime.time - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1922,31 +1974,32 @@ def deserialize_rfc(attr): """Deserialize RFC-1123 formatted string into Datetime object. :param str attr: response string to be deserialized. + :return: Deserialized RFC datetime :rtype: Datetime - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text try: parsed_date = email.utils.parsedate_tz(attr) # type: ignore date_obj = datetime.datetime( - *parsed_date[:6], tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) ) if not date_obj.tzinfo: date_obj = date_obj.astimezone(tz=TZ_UTC) except ValueError as err: msg = "Cannot deserialize to rfc datetime object." raise DeserializationError(msg) from err - else: - return date_obj + return date_obj @staticmethod def deserialize_iso(attr): """Deserialize ISO-8601 formatted string into Datetime object. :param str attr: response string to be deserialized. + :return: Deserialized ISO datetime :rtype: Datetime - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1974,8 +2027,7 @@ def deserialize_iso(attr): except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize datetime object." raise DeserializationError(msg) from err - else: - return date_obj + return date_obj @staticmethod def deserialize_unix(attr): @@ -1983,8 +2035,9 @@ def deserialize_unix(attr): This is represented as seconds. :param int attr: Object to be serialized. + :return: Deserialized datetime :rtype: Datetime - :raises: DeserializationError if format invalid + :raises DeserializationError: if format invalid """ if isinstance(attr, ET.Element): attr = int(attr.text) # type: ignore @@ -1994,5 +2047,4 @@ def deserialize_unix(attr): except ValueError as err: msg = "Cannot deserialize to unix datetime object." raise DeserializationError(msg) from err - else: - return date_obj + return date_obj diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_vendor.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_vendor.py index f8a0e715e8f..2b5f59d9af7 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_vendor.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_vendor.py @@ -8,10 +8,13 @@ from abc import ABC from typing import TYPE_CHECKING -from ._configuration import DevCenterClientConfiguration +from ._configuration import ( + DeploymentEnvironmentsClientConfiguration, + DevBoxesClientConfiguration, + DevCenterClientConfiguration, +) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core import PipelineClient from ._serialization import Deserializer, Serializer @@ -24,3 +27,21 @@ class DevCenterClientMixinABC(ABC): _config: DevCenterClientConfiguration _serialize: "Serializer" _deserialize: "Deserializer" + + +class DevBoxesClientMixinABC(ABC): + """DO NOT use this class. It is for internal typing use only.""" + + _client: "PipelineClient" + _config: DevBoxesClientConfiguration + _serialize: "Serializer" + _deserialize: "Deserializer" + + +class DeploymentEnvironmentsClientMixinABC(ABC): + """DO NOT use this class. It is for internal typing use only.""" + + _client: "PipelineClient" + _config: DeploymentEnvironmentsClientConfiguration + _serialize: "Serializer" + _deserialize: "Deserializer" 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 83602e6274b..0ec13ea52bb 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.1" +VERSION = "1.0.0" diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/__init__.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/__init__.py index dc5f6ca493e..e1efc66ed20 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/__init__.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/__init__.py @@ -5,19 +5,29 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._client import DevCenterClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import DevCenterClient # type: ignore +from ._client import DevBoxesClient # type: ignore +from ._client import DeploymentEnvironmentsClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # pylint: disable=unused-wildcard-import + from ._patch import * except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk __all__ = [ "DevCenterClient", + "DevBoxesClient", + "DeploymentEnvironmentsClient", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() 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 e94fae1092d..66bd4a3f64a 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 @@ -8,23 +8,108 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self from azure.core import AsyncPipelineClient from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from .._serialization import Deserializer, Serializer -from ._configuration import DevCenterClientConfiguration -from ._operations import DevCenterClientOperationsMixin +from ._configuration import ( + DeploymentEnvironmentsClientConfiguration, + DevBoxesClientConfiguration, + DevCenterClientConfiguration, +) +from ._operations import ( + DeploymentEnvironmentsClientOperationsMixin, + DevBoxesClientOperationsMixin, + DevCenterClientOperationsMixin, +) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class DevCenterClient(DevCenterClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword +class DevCenterClient(DevCenterClientOperationsMixin): """DevCenterClient. + :param endpoint: The DevCenter-specific URI to operate on. Required. + :type endpoint: str + :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. + :paramtype api_version: str + """ + + def __init__(self, endpoint: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: + _endpoint = "{endpoint}" + self._config = DevCenterClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + + def send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) + + +class DevBoxesClient(DevBoxesClientOperationsMixin): + """DevBoxesClient. + :param endpoint: The DevCenter-specific URI to operate on. Required. :type endpoint: str :param credential: Credential used to authenticate requests to the service. Required. @@ -38,7 +123,86 @@ class DevCenterClient(DevCenterClientOperationsMixin): # pylint: disable=client def __init__(self, endpoint: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: _endpoint = "{endpoint}" - self._config = DevCenterClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + self._config = DevBoxesClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + + def send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) + + +class DeploymentEnvironmentsClient(DeploymentEnvironmentsClientOperationsMixin): + """DeploymentEnvironmentsClient. + + :param endpoint: The DevCenter-specific URI to operate on. Required. + :type endpoint: str + :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. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__(self, endpoint: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: + _endpoint = "{endpoint}" + self._config = DeploymentEnvironmentsClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) _policies = kwargs.pop("policies", None) if _policies is None: _policies = [ @@ -93,7 +257,7 @@ def send_request( async def close(self) -> None: await self._client.close() - async def __aenter__(self) -> "DevCenterClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self 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 7f1449d13d5..e1d46cf18e2 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 @@ -13,11 +13,10 @@ from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class DevCenterClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long +class DevCenterClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for DevCenterClient. Note that all parameters used to create this instance are saved as instance @@ -62,3 +61,97 @@ def _configure(self, **kwargs: Any) -> None: self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy( self.credential, *self.credential_scopes, **kwargs ) + + +class DevBoxesClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for DevBoxesClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: The DevCenter-specific URI to operate on. Required. + :type endpoint: str + :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. + :paramtype api_version: str + """ + + def __init__(self, endpoint: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2023-04-01") + + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.endpoint = endpoint + self.credential = credential + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://devcenter.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "developer-devcenter/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy( + self.credential, *self.credential_scopes, **kwargs + ) + + +class DeploymentEnvironmentsClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long + """Configuration for DeploymentEnvironmentsClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: The DevCenter-specific URI to operate on. Required. + :type endpoint: str + :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. + :paramtype api_version: str + """ + + def __init__(self, endpoint: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2023-04-01") + + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.endpoint = endpoint + self.credential = credential + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://devcenter.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "developer-devcenter/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_operations/__init__.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_operations/__init__.py index 32322330a2b..bb0ba294788 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_operations/__init__.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_operations/__init__.py @@ -5,15 +5,25 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._operations import DevCenterClientOperationsMixin +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import DevCenterClientOperationsMixin # type: ignore +from ._operations import DevBoxesClientOperationsMixin # type: ignore +from ._operations import DeploymentEnvironmentsClientOperationsMixin # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "DevCenterClientOperationsMixin", + "DevBoxesClientOperationsMixin", + "DeploymentEnvironmentsClientOperationsMixin", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() 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 d265d51dfc7..bfa2dcde89d 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,too-many-statements +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -10,7 +10,7 @@ from io import IOBase import json import sys -from typing import Any, AsyncIterable, Callable, Dict, IO, List, Optional, Type, TypeVar, Union, cast, overload +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, List, Optional, TypeVar, Union, cast, overload import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList @@ -20,6 +20,8 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse @@ -33,78 +35,66 @@ 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, - build_dev_center_delay_all_dev_box_actions_request, - build_dev_center_delay_dev_box_action_request, - build_dev_center_delete_dev_box_request, - build_dev_center_delete_environment_request, - build_dev_center_get_catalog_request, - build_dev_center_get_dev_box_action_request, - build_dev_center_get_dev_box_request, - build_dev_center_get_environment_definition_request, - build_dev_center_get_environment_request, - build_dev_center_get_pool_request, + build_deployment_environments_create_or_update_environment_request, + build_deployment_environments_delete_environment_request, + build_deployment_environments_get_catalog_request, + build_deployment_environments_get_environment_definition_request, + build_deployment_environments_get_environment_request, + build_deployment_environments_list_all_environments_request, + build_deployment_environments_list_catalogs_request, + build_deployment_environments_list_environment_definitions_by_catalog_request, + build_deployment_environments_list_environment_definitions_request, + build_deployment_environments_list_environment_types_request, + build_deployment_environments_list_environments_request, + build_dev_boxes_create_dev_box_request, + build_dev_boxes_delay_action_request, + build_dev_boxes_delay_all_actions_request, + build_dev_boxes_delete_dev_box_request, + build_dev_boxes_get_dev_box_action_request, + build_dev_boxes_get_dev_box_request, + build_dev_boxes_get_pool_request, + build_dev_boxes_get_remote_connection_request, + build_dev_boxes_get_schedule_request, + build_dev_boxes_list_all_dev_boxes_by_user_request, + build_dev_boxes_list_all_dev_boxes_request, + build_dev_boxes_list_dev_box_actions_request, + build_dev_boxes_list_dev_boxes_request, + build_dev_boxes_list_pools_request, + build_dev_boxes_list_schedules_request, + build_dev_boxes_restart_dev_box_request, + build_dev_boxes_skip_action_request, + build_dev_boxes_start_dev_box_request, + build_dev_boxes_stop_dev_box_request, build_dev_center_get_project_request, - build_dev_center_get_remote_connection_request, - build_dev_center_get_schedule_request, - build_dev_center_list_all_dev_boxes_by_user_request, - build_dev_center_list_all_dev_boxes_request, - build_dev_center_list_all_environments_request, - build_dev_center_list_catalogs_request, - build_dev_center_list_dev_box_actions_request, - build_dev_center_list_dev_boxes_request, - build_dev_center_list_environment_definitions_by_catalog_request, - build_dev_center_list_environment_definitions_request, - build_dev_center_list_environment_types_request, - build_dev_center_list_environments_request, - build_dev_center_list_pools_request, build_dev_center_list_projects_request, - build_dev_center_list_schedules_request, - build_dev_center_restart_dev_box_request, - build_dev_center_skip_dev_box_action_request, - build_dev_center_start_dev_box_request, - build_dev_center_stop_dev_box_request, ) -from .._vendor import DevCenterClientMixinABC +from .._vendor import DeploymentEnvironmentsClientMixinABC, DevBoxesClientMixinABC, DevCenterClientMixinABC if sys.version_info >= (3, 9): from collections.abc import MutableMapping else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] +JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object -class DevCenterClientOperationsMixin(DevCenterClientMixinABC): # pylint: disable=too-many-public-methods +class DevCenterClientOperationsMixin(DevCenterClientMixinABC): @distributed_trace def list_projects(self, **kwargs: Any) -> AsyncIterable["_models.Project"]: - # pylint: disable=line-too-long """Lists all projects. :return: An iterator like instance of Project :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.developer.devcenter.models.Project] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "name": "str", # Name of the project. Required. - "description": "str", # Optional. Description of the project. - "maxDevBoxesPerUser": 0 # Optional. When specified, indicates the maximum - number of Dev Boxes a single user can create across all pools in the project. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} cls: ClsType[List[_models.Project]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -166,8 +156,6 @@ async def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -177,7 +165,6 @@ async def get_next(next_link=None): @distributed_trace_async async def get_project(self, project_name: str, **kwargs: Any) -> _models.Project: - # pylint: disable=line-too-long """Gets a project. :param project_name: Name of the project. Required. @@ -185,19 +172,8 @@ async def get_project(self, project_name: str, **kwargs: Any) -> _models.Project :return: Project. The Project is compatible with MutableMapping :rtype: ~azure.developer.devcenter.models.Project :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "name": "str", # Name of the project. Required. - "description": "str", # Optional. Description of the project. - "maxDevBoxesPerUser": 0 # Optional. When specified, indicates the maximum - number of Dev Boxes a single user can create across all pools in the project. - } """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -230,7 +206,10 @@ async def get_project(self, project_name: str, **kwargs: Any) -> _models.Project if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -244,9 +223,11 @@ async def get_project(self, project_name: str, **kwargs: Any) -> _models.Project return deserialized # type: ignore + +class DevBoxesClientOperationsMixin(DevBoxesClientMixinABC): # pylint: disable=too-many-public-methods + @distributed_trace def list_pools(self, project_name: str, **kwargs: Any) -> AsyncIterable["_models.Pool"]: - # pylint: disable=line-too-long """Lists available pools. :param project_name: Name of the project. Required. @@ -254,75 +235,13 @@ def list_pools(self, project_name: str, **kwargs: Any) -> AsyncIterable["_models :return: An iterator like instance of Pool :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.developer.devcenter.models.Pool] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "healthStatus": "str", # 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". - "location": "str", # Azure region where Dev Boxes in the pool are located. - Required. - "name": "str", # Pool name. Required. - "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 owners of Dev - Boxes in this pool are local administrators on the Dev Boxes. Known values are: - "Enabled" and "Disabled". - "osType": "str", # Optional. The operating system type of Dev Boxes in this - pool. "Windows" - "stopOnDisconnect": { - "status": "str", # 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". - "gracePeriodMinutes": 0 # Optional. The specified time in minutes to - wait before stopping a Dev Box once disconnect is detected. - }, - "storageProfile": { - "osDisk": { - "diskSizeGB": 0 # Optional. The size of the OS Disk in - gigabytes. - } - } - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} cls: ClsType[List[_models.Pool]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -333,7 +252,7 @@ def list_pools(self, project_name: str, **kwargs: Any) -> AsyncIterable["_models def prepare_request(next_link=None): if not next_link: - _request = build_dev_center_list_pools_request( + _request = build_dev_boxes_list_pools_request( project_name=project_name, api_version=self._config.api_version, headers=_headers, @@ -385,8 +304,6 @@ async def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -396,7 +313,6 @@ async def get_next(next_link=None): @distributed_trace_async 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: Name of the project. Required. @@ -406,70 +322,8 @@ async def get_pool(self, project_name: str, pool_name: str, **kwargs: Any) -> _m :return: Pool. The Pool is compatible with MutableMapping :rtype: ~azure.developer.devcenter.models.Pool :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "healthStatus": "str", # 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". - "location": "str", # Azure region where Dev Boxes in the pool are located. - Required. - "name": "str", # Pool name. Required. - "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 owners of Dev - Boxes in this pool are local administrators on the Dev Boxes. Known values are: - "Enabled" and "Disabled". - "osType": "str", # Optional. The operating system type of Dev Boxes in this - pool. "Windows" - "stopOnDisconnect": { - "status": "str", # 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". - "gracePeriodMinutes": 0 # Optional. The specified time in minutes to - wait before stopping a Dev Box once disconnect is detected. - }, - "storageProfile": { - "osDisk": { - "diskSizeGB": 0 # Optional. The size of the OS Disk in - gigabytes. - } - } - } """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -482,7 +336,7 @@ async def get_pool(self, project_name: str, pool_name: str, **kwargs: Any) -> _m cls: ClsType[_models.Pool] = kwargs.pop("cls", None) - _request = build_dev_center_get_pool_request( + _request = build_dev_boxes_get_pool_request( project_name=project_name, pool_name=pool_name, api_version=self._config.api_version, @@ -503,7 +357,10 @@ async def get_pool(self, project_name: str, pool_name: str, **kwargs: Any) -> _m if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -528,29 +385,13 @@ def list_schedules(self, project_name: str, pool_name: str, **kwargs: Any) -> As :return: An iterator like instance of Schedule :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.developer.devcenter.models.Schedule] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "frequency": "str", # The frequency of this scheduled task. Required. - "Daily" - "name": "str", # Display name for the Schedule. Required. - "time": "str", # The target time to trigger the action. The format is HH:MM. - Required. - "timeZone": "str", # The IANA timezone id at which the schedule should - execute. Required. - "type": "str" # Supported type this scheduled task represents. Required. - "StopDevBox" - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} cls: ClsType[List[_models.Schedule]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -561,7 +402,7 @@ def list_schedules(self, project_name: str, pool_name: str, **kwargs: Any) -> As def prepare_request(next_link=None): if not next_link: - _request = build_dev_center_list_schedules_request( + _request = build_dev_boxes_list_schedules_request( project_name=project_name, pool_name=pool_name, api_version=self._config.api_version, @@ -614,8 +455,6 @@ async def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -638,24 +477,8 @@ async def get_schedule( :return: Schedule. The Schedule is compatible with MutableMapping :rtype: ~azure.developer.devcenter.models.Schedule :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "frequency": "str", # The frequency of this scheduled task. Required. - "Daily" - "name": "str", # Display name for the Schedule. Required. - "time": "str", # The target time to trigger the action. The format is HH:MM. - Required. - "timeZone": "str", # The IANA timezone id at which the schedule should - execute. Required. - "type": "str" # Supported type this scheduled task represents. Required. - "StopDevBox" - } """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -668,7 +491,7 @@ async def get_schedule( cls: ClsType[_models.Schedule] = kwargs.pop("cls", None) - _request = build_dev_center_get_schedule_request( + _request = build_dev_boxes_get_schedule_request( project_name=project_name, pool_name=pool_name, schedule_name=schedule_name, @@ -690,7 +513,10 @@ async def get_schedule( if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -706,104 +532,18 @@ async def get_schedule( @distributed_trace 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. :return: An iterator like instance of DevBox :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.developer.devcenter.models.DevBox] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - 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. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} cls: ClsType[List[_models.DevBox]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -814,7 +554,7 @@ def list_all_dev_boxes(self, **kwargs: Any) -> AsyncIterable["_models.DevBox"]: def prepare_request(next_link=None): if not next_link: - _request = build_dev_center_list_all_dev_boxes_request( + _request = build_dev_boxes_list_all_dev_boxes_request( api_version=self._config.api_version, headers=_headers, params=_params, @@ -865,8 +605,6 @@ async def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -876,7 +614,6 @@ async def get_next(next_link=None): @distributed_trace 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 @@ -885,98 +622,13 @@ def list_all_dev_boxes_by_user(self, user_id: str, **kwargs: Any) -> AsyncIterab :return: An iterator like instance of DevBox :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.developer.devcenter.models.DevBox] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - 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. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} cls: ClsType[List[_models.DevBox]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -987,7 +639,7 @@ def list_all_dev_boxes_by_user(self, user_id: str, **kwargs: Any) -> AsyncIterab def prepare_request(next_link=None): if not next_link: - _request = build_dev_center_list_all_dev_boxes_by_user_request( + _request = build_dev_boxes_list_all_dev_boxes_by_user_request( user_id=user_id, api_version=self._config.api_version, headers=_headers, @@ -1039,8 +691,6 @@ async def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -1050,7 +700,6 @@ async def get_next(next_link=None): @distributed_trace 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. @@ -1061,98 +710,13 @@ def list_dev_boxes(self, project_name: str, user_id: str, **kwargs: Any) -> Asyn :return: An iterator like instance of DevBox :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.developer.devcenter.models.DevBox] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - 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. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} cls: ClsType[List[_models.DevBox]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1163,7 +727,7 @@ def list_dev_boxes(self, project_name: str, user_id: str, **kwargs: Any) -> Asyn def prepare_request(next_link=None): if not next_link: - _request = build_dev_center_list_dev_boxes_request( + _request = build_dev_boxes_list_dev_boxes_request( project_name=project_name, user_id=user_id, api_version=self._config.api_version, @@ -1216,8 +780,6 @@ async def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -1227,7 +789,6 @@ async def get_next(next_link=None): @distributed_trace_async 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: Name of the project. Required. @@ -1240,93 +801,8 @@ async def get_dev_box(self, project_name: str, user_id: str, dev_box_name: str, :return: DevBox. The DevBox is compatible with MutableMapping :rtype: ~azure.developer.devcenter.models.DevBox :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - 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. - } """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1339,7 +815,7 @@ async def get_dev_box(self, project_name: str, user_id: str, dev_box_name: str, cls: ClsType[_models.DevBox] = kwargs.pop("cls", None) - _request = build_dev_center_get_dev_box_request( + _request = build_dev_boxes_get_dev_box_request( project_name=project_name, user_id=user_id, dev_box_name=dev_box_name, @@ -1361,7 +837,10 @@ async def get_dev_box(self, project_name: str, user_id: str, dev_box_name: str, if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -1382,8 +861,8 @@ async def _create_dev_box_initial( dev_box_name: str, body: Union[_models.DevBox, JSON, IO[bytes]], **kwargs: Any - ) -> JSON: - error_map: MutableMapping[int, Type[HttpResponseError]] = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1395,7 +874,7 @@ async def _create_dev_box_initial( _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[AsyncIterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None @@ -1404,7 +883,7 @@ async def _create_dev_box_initial( else: _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_dev_center_create_dev_box_request( + _request = build_dev_boxes_create_dev_box_request( project_name=project_name, user_id=user_id, dev_box_name=dev_box_name, @@ -1419,7 +898,7 @@ async def _create_dev_box_initial( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -1427,22 +906,21 @@ async def _create_dev_box_initial( response = pipeline_response.http_response if response.status_code not in [200, 201]: - if _stream: + try: await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) response_headers = {} - if response.status_code == 200: - deserialized = _deserialize(JSON, response.json()) - if response.status_code == 201: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Operation-Location"] = self._deserialize( "str", response.headers.get("Operation-Location") ) - deserialized = _deserialize(JSON, response.json()) + deserialized = response.iter_bytes() if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -1460,10 +938,9 @@ async def begin_create_dev_box( 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. + :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. @@ -1480,173 +957,6 @@ async def begin_create_dev_box( MutableMapping :rtype: ~azure.core.polling.AsyncLROPoller[~azure.developer.devcenter.models.DevBox] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = { - "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. - } - - # 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 @@ -1660,10 +970,9 @@ async def begin_create_dev_box( 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. + :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. @@ -1680,91 +989,6 @@ async def begin_create_dev_box( 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 @@ -1778,10 +1002,9 @@ async def begin_create_dev_box( 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. + :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. @@ -1798,91 +1021,6 @@ async def begin_create_dev_box( 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. - } """ @distributed_trace_async @@ -1894,10 +1032,9 @@ async def begin_create_dev_box( 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 the operation. Required. + :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. @@ -1912,173 +1049,6 @@ async def begin_create_dev_box( MutableMapping :rtype: ~azure.core.polling.AsyncLROPoller[~azure.developer.devcenter.models.DevBox] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = { - "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. - } - - # 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. - } """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} @@ -2100,6 +1070,7 @@ async def begin_create_dev_box( params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): @@ -2135,8 +1106,8 @@ def get_long_running_output(pipeline_response): async def _delete_dev_box_initial( self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any - ) -> Optional[JSON]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2147,9 +1118,9 @@ async def _delete_dev_box_initial( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[Optional[JSON]] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - _request = build_dev_center_delete_dev_box_request( + _request = build_dev_boxes_delete_dev_box_request( project_name=project_name, user_id=user_id, dev_box_name=dev_box_name, @@ -2162,7 +1133,7 @@ async def _delete_dev_box_initial( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -2170,12 +1141,13 @@ async def _delete_dev_box_initial( response = pipeline_response.http_response if response.status_code not in [202, 204]: - if _stream: + try: await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) - deserialized = None response_headers = {} if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) @@ -2183,7 +1155,7 @@ async def _delete_dev_box_initial( "str", response.headers.get("Operation-Location") ) - deserialized = _deserialize(JSON, response.json()) + deserialized = response.iter_bytes() if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -2193,8 +1165,7 @@ 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[_models.OperationDetails]: - # pylint: disable=line-too-long + ) -> AsyncLROPoller[None]: """Deletes a Dev Box. :param project_name: The DevCenter Project upon which to execute operations. Required. @@ -2204,49 +1175,14 @@ 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 - :return: An instance of AsyncLROPoller that returns OperationDetails. The OperationDetails is - compatible with MutableMapping - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.developer.devcenter.models.OperationDetails] + :return: An instance of AsyncLROPoller that returns None + :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # 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: "NotStarted", "Running", "Succeeded", "Failed", and "Canceled". - "endTime": "2020-02-20 00:00:00", # Optional. The end time of the operation. - "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. - }, - "percentComplete": 0.0, # Optional. Percent of the operation that is - complete. - "properties": {}, # Optional. Custom operation properties, populated only - for a successful operation. - "resourceId": "str", # Optional. The id of the resource. - "startTime": "2020-02-20 00:00:00" # Optional. The start time of the - operation. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.OperationDetails] = kwargs.pop("cls", None) + cls: ClsType[None] = 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) @@ -2260,20 +1196,12 @@ async def begin_delete_dev_box( params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): - response_headers = {} - response = pipeline_response.http_response - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - response_headers["Operation-Location"] = self._deserialize( - "str", response.headers.get("Operation-Location") - ) - - deserialized = _deserialize(_models.OperationDetails, response.json()) + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized + return cls(pipeline_response, None, {}) # type: ignore path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), @@ -2289,18 +1217,18 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller[_models.OperationDetails].from_continuation_token( + return AsyncLROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller[_models.OperationDetails]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) + return AsyncLROPoller[None](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: MutableMapping[int, Type[HttpResponseError]] = { + async def _start_dev_box_initial( + self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2311,9 +1239,9 @@ async def _start_dev_box_initial(self, project_name: str, user_id: str, dev_box_ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - _request = build_dev_center_start_dev_box_request( + _request = build_dev_boxes_start_dev_box_request( project_name=project_name, user_id=user_id, dev_box_name=dev_box_name, @@ -2326,7 +1254,7 @@ async def _start_dev_box_initial(self, project_name: str, user_id: str, dev_box_ } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -2334,15 +1262,17 @@ async def _start_dev_box_initial(self, project_name: str, user_id: str, dev_box_ response = pipeline_response.http_response if response.status_code not in [202]: - if _stream: + try: await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) response_headers = {} response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) - deserialized = _deserialize(JSON, response.json()) + deserialized = response.iter_bytes() if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -2352,8 +1282,7 @@ async def _start_dev_box_initial(self, project_name: str, user_id: str, dev_box_ @distributed_trace_async async def begin_start_dev_box( self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any - ) -> AsyncLROPoller[_models.OperationDetails]: - # pylint: disable=line-too-long + ) -> AsyncLROPoller[None]: """Starts a Dev Box. :param project_name: Name of the project. Required. @@ -2363,49 +1292,14 @@ async def begin_start_dev_box( :type user_id: str :param dev_box_name: Display name for the Dev Box. Required. :type dev_box_name: str - :return: An instance of AsyncLROPoller that returns OperationDetails. The OperationDetails is - compatible with MutableMapping - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.developer.devcenter.models.OperationDetails] + :return: An instance of AsyncLROPoller that returns None + :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # 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: "NotStarted", "Running", "Succeeded", "Failed", and "Canceled". - "endTime": "2020-02-20 00:00:00", # Optional. The end time of the operation. - "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. - }, - "percentComplete": 0.0, # Optional. Percent of the operation that is - complete. - "properties": {}, # Optional. Custom operation properties, populated only - for a successful operation. - "resourceId": "str", # Optional. The id of the resource. - "startTime": "2020-02-20 00:00:00" # Optional. The start time of the - operation. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.OperationDetails] = kwargs.pop("cls", None) + cls: ClsType[None] = 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) @@ -2419,19 +1313,12 @@ async def begin_start_dev_box( params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): - response_headers = {} - response = pipeline_response.http_response - response_headers["Operation-Location"] = self._deserialize( - "str", response.headers.get("Operation-Location") - ) - - deserialized = _deserialize(_models.OperationDetails, response.json()) + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized + return cls(pipeline_response, None, {}) # type: ignore path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), @@ -2447,20 +1334,18 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller[_models.OperationDetails].from_continuation_token( + return AsyncLROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller[_models.OperationDetails]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) + return AsyncLROPoller[None](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: MutableMapping[int, Type[HttpResponseError]] = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2471,9 +1356,9 @@ async def _stop_dev_box_initial( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - _request = build_dev_center_stop_dev_box_request( + _request = build_dev_boxes_stop_dev_box_request( project_name=project_name, user_id=user_id, dev_box_name=dev_box_name, @@ -2487,7 +1372,7 @@ async def _stop_dev_box_initial( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -2495,15 +1380,17 @@ async def _stop_dev_box_initial( response = pipeline_response.http_response if response.status_code not in [202]: - if _stream: + try: await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) response_headers = {} response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) - deserialized = _deserialize(JSON, response.json()) + deserialized = response.iter_bytes() if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -2513,8 +1400,7 @@ async def _stop_dev_box_initial( @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[_models.OperationDetails]: - # pylint: disable=line-too-long + ) -> AsyncLROPoller[None]: """Stops a Dev Box. :param project_name: Name of the project. Required. @@ -2526,49 +1412,14 @@ async def begin_stop_dev_box( :type dev_box_name: str :keyword hibernate: Optional parameter to hibernate the dev box. Default value is None. :paramtype hibernate: bool - :return: An instance of AsyncLROPoller that returns OperationDetails. The OperationDetails is - compatible with MutableMapping - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.developer.devcenter.models.OperationDetails] + :return: An instance of AsyncLROPoller that returns None + :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # 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: "NotStarted", "Running", "Succeeded", "Failed", and "Canceled". - "endTime": "2020-02-20 00:00:00", # Optional. The end time of the operation. - "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. - }, - "percentComplete": 0.0, # Optional. Percent of the operation that is - complete. - "properties": {}, # Optional. Custom operation properties, populated only - for a successful operation. - "resourceId": "str", # Optional. The id of the resource. - "startTime": "2020-02-20 00:00:00" # Optional. The start time of the - operation. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.OperationDetails] = kwargs.pop("cls", None) + cls: ClsType[None] = 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) @@ -2583,19 +1434,12 @@ async def begin_stop_dev_box( params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): - response_headers = {} - response = pipeline_response.http_response - response_headers["Operation-Location"] = self._deserialize( - "str", response.headers.get("Operation-Location") - ) - - deserialized = _deserialize(_models.OperationDetails, response.json()) + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized + return cls(pipeline_response, None, {}) # type: ignore path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), @@ -2611,18 +1455,18 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller[_models.OperationDetails].from_continuation_token( + return AsyncLROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller[_models.OperationDetails]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) + return AsyncLROPoller[None](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: MutableMapping[int, Type[HttpResponseError]] = { + async def _restart_dev_box_initial( + self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2633,9 +1477,9 @@ async def _restart_dev_box_initial(self, project_name: str, user_id: str, dev_bo _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[JSON] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - _request = build_dev_center_restart_dev_box_request( + _request = build_dev_boxes_restart_dev_box_request( project_name=project_name, user_id=user_id, dev_box_name=dev_box_name, @@ -2648,7 +1492,7 @@ async def _restart_dev_box_initial(self, project_name: str, user_id: str, dev_bo } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -2656,15 +1500,17 @@ async def _restart_dev_box_initial(self, project_name: str, user_id: str, dev_bo response = pipeline_response.http_response if response.status_code not in [202]: - if _stream: + try: await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) response_headers = {} response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) - deserialized = _deserialize(JSON, response.json()) + deserialized = response.iter_bytes() if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -2674,8 +1520,7 @@ async def _restart_dev_box_initial(self, project_name: str, user_id: str, dev_bo @distributed_trace_async async def begin_restart_dev_box( self, project_name: str, user_id: str, dev_box_name: str, **kwargs: Any - ) -> AsyncLROPoller[_models.OperationDetails]: - # pylint: disable=line-too-long + ) -> AsyncLROPoller[None]: """Restarts a Dev Box. :param project_name: Name of the project. Required. @@ -2685,49 +1530,14 @@ async def begin_restart_dev_box( :type user_id: str :param dev_box_name: Display name for the Dev Box. Required. :type dev_box_name: str - :return: An instance of AsyncLROPoller that returns OperationDetails. The OperationDetails is - compatible with MutableMapping - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.developer.devcenter.models.OperationDetails] + :return: An instance of AsyncLROPoller that returns None + :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # 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: "NotStarted", "Running", "Succeeded", "Failed", and "Canceled". - "endTime": "2020-02-20 00:00:00", # Optional. The end time of the operation. - "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. - }, - "percentComplete": 0.0, # Optional. Percent of the operation that is - complete. - "properties": {}, # Optional. Custom operation properties, populated only - for a successful operation. - "resourceId": "str", # Optional. The id of the resource. - "startTime": "2020-02-20 00:00:00" # Optional. The start time of the - operation. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.OperationDetails] = kwargs.pop("cls", None) + cls: ClsType[None] = 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) @@ -2741,19 +1551,12 @@ async def begin_restart_dev_box( params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): - response_headers = {} - response = pipeline_response.http_response - response_headers["Operation-Location"] = self._deserialize( - "str", response.headers.get("Operation-Location") - ) - - deserialized = _deserialize(_models.OperationDetails, response.json()) + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized + return cls(pipeline_response, None, {}) # type: ignore path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), @@ -2769,15 +1572,13 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller[_models.OperationDetails].from_continuation_token( + return AsyncLROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller[_models.OperationDetails]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore @distributed_trace_async async def get_remote_connection( @@ -2795,18 +1596,8 @@ async def get_remote_connection( :return: RemoteConnection. The RemoteConnection is compatible with MutableMapping :rtype: ~azure.developer.devcenter.models.RemoteConnection :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "rdpConnectionUrl": "str", # Optional. Link to open a Remote Desktop - session. - "webUrl": "str" # Optional. URL to open a browser based RDP session. - } """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2819,7 +1610,7 @@ async def get_remote_connection( cls: ClsType[_models.RemoteConnection] = kwargs.pop("cls", None) - _request = build_dev_center_get_remote_connection_request( + _request = build_dev_boxes_get_remote_connection_request( project_name=project_name, user_id=user_id, dev_box_name=dev_box_name, @@ -2841,7 +1632,10 @@ async def get_remote_connection( if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -2871,30 +1665,13 @@ def list_dev_box_actions( :return: An iterator like instance of DevBoxAction :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.developer.devcenter.models.DevBoxAction] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "actionType": "str", # The action that will be taken. Required. "Stop" - "name": "str", # The name of the action. Required. - "sourceId": "str", # The id of the resource which triggered this action. - Required. - "next": { - "scheduledTime": "2020-02-20 00:00:00" # The time the action will be - triggered (UTC). Required. - }, - "suspendedUntil": "2020-02-20 00:00:00" # Optional. The earliest time that - the action could occur (UTC). - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} cls: ClsType[List[_models.DevBoxAction]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2905,7 +1682,7 @@ def list_dev_box_actions( def prepare_request(next_link=None): if not next_link: - _request = build_dev_center_list_dev_box_actions_request( + _request = build_dev_boxes_list_dev_box_actions_request( project_name=project_name, user_id=user_id, dev_box_name=dev_box_name, @@ -2959,8 +1736,6 @@ async def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -2986,25 +1761,8 @@ async def get_dev_box_action( :return: DevBoxAction. The DevBoxAction is compatible with MutableMapping :rtype: ~azure.developer.devcenter.models.DevBoxAction :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "actionType": "str", # The action that will be taken. Required. "Stop" - "name": "str", # The name of the action. Required. - "sourceId": "str", # The id of the resource which triggered this action. - Required. - "next": { - "scheduledTime": "2020-02-20 00:00:00" # The time the action will be - triggered (UTC). Required. - }, - "suspendedUntil": "2020-02-20 00:00:00" # Optional. The earliest time that - the action could occur (UTC). - } """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3017,7 +1775,7 @@ async def get_dev_box_action( cls: ClsType[_models.DevBoxAction] = kwargs.pop("cls", None) - _request = build_dev_center_get_dev_box_action_request( + _request = build_dev_boxes_get_dev_box_action_request( project_name=project_name, user_id=user_id, dev_box_name=dev_box_name, @@ -3040,7 +1798,10 @@ async def get_dev_box_action( if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -3055,7 +1816,7 @@ async def get_dev_box_action( return deserialized # type: ignore @distributed_trace_async - async def skip_dev_box_action( # pylint: disable=inconsistent-return-statements + async def skip_action( self, project_name: str, user_id: str, dev_box_name: str, action_name: str, **kwargs: Any ) -> None: """Skips an occurrence of an action. @@ -3073,7 +1834,7 @@ async def skip_dev_box_action( # pylint: disable=inconsistent-return-statements :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3086,7 +1847,7 @@ async def skip_dev_box_action( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_dev_center_skip_dev_box_action_request( + _request = build_dev_boxes_skip_action_request( project_name=project_name, user_id=user_id, dev_box_name=dev_box_name, @@ -3108,8 +1869,6 @@ async def skip_dev_box_action( # pylint: disable=inconsistent-return-statements response = pipeline_response.http_response if response.status_code not in [204]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -3117,7 +1876,7 @@ async def skip_dev_box_action( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def delay_dev_box_action( + async def delay_action( self, project_name: str, user_id: str, @@ -3138,30 +1897,14 @@ async def delay_dev_box_action( :type dev_box_name: str :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. + :keyword delay_until: The time to delay the Dev Box action or actions until, in RFC3339 format. + Required. :paramtype delay_until: ~datetime.datetime :return: DevBoxAction. The DevBoxAction is compatible with MutableMapping :rtype: ~azure.developer.devcenter.models.DevBoxAction :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "actionType": "str", # The action that will be taken. Required. "Stop" - "name": "str", # The name of the action. Required. - "sourceId": "str", # The id of the resource which triggered this action. - Required. - "next": { - "scheduledTime": "2020-02-20 00:00:00" # The time the action will be - triggered (UTC). Required. - }, - "suspendedUntil": "2020-02-20 00:00:00" # Optional. The earliest time that - the action could occur (UTC). - } """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3174,7 +1917,7 @@ async def delay_dev_box_action( cls: ClsType[_models.DevBoxAction] = kwargs.pop("cls", None) - _request = build_dev_center_delay_dev_box_action_request( + _request = build_dev_boxes_delay_action_request( project_name=project_name, user_id=user_id, dev_box_name=dev_box_name, @@ -3198,7 +1941,10 @@ async def delay_dev_box_action( if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -3213,10 +1959,9 @@ async def delay_dev_box_action( return deserialized # type: ignore @distributed_trace - def delay_all_dev_box_actions( + def delay_all_actions( self, project_name: str, user_id: str, dev_box_name: str, *, delay_until: datetime.datetime, **kwargs: Any ) -> AsyncIterable["_models.DevBoxActionDelayResult"]: - # pylint: disable=line-too-long """Delays all actions. :param project_name: Name of the project. Required. @@ -3226,57 +1971,20 @@ def delay_all_dev_box_actions( :type user_id: str :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. + :keyword delay_until: The time to delay the Dev Box action or actions until, in RFC3339 format. + Required. :paramtype delay_until: ~datetime.datetime :return: An iterator like instance of DevBoxActionDelayResult :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.developer.devcenter.models.DevBoxActionDelayResult] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "name": "str", # The name of the action. Required. - "result": "str", # The result of the delay operation on this action. - Required. Known values are: "Succeeded" and "Failed". - "action": { - "actionType": "str", # The action that will be taken. Required. - "Stop" - "name": "str", # The name of the action. Required. - "sourceId": "str", # The id of the resource which triggered this - action. Required. - "next": { - "scheduledTime": "2020-02-20 00:00:00" # The time the action - will be triggered (UTC). Required. - }, - "suspendedUntil": "2020-02-20 00:00:00" # Optional. The earliest - time that the action could occur (UTC). - }, - "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. - } - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} cls: ClsType[List[_models.DevBoxActionDelayResult]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3287,7 +1995,7 @@ def delay_all_dev_box_actions( def prepare_request(next_link=None): if not next_link: - _request = build_dev_center_delay_all_dev_box_actions_request( + _request = build_dev_boxes_delay_all_actions_request( project_name=project_name, user_id=user_id, dev_box_name=dev_box_name, @@ -3342,8 +2050,6 @@ async def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -3351,9 +2057,13 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) + +class DeploymentEnvironmentsClientOperationsMixin( # pylint: disable=name-too-long + DeploymentEnvironmentsClientMixinABC +): + @distributed_trace 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. @@ -3361,51 +2071,13 @@ def list_all_environments(self, project_name: str, **kwargs: Any) -> AsyncIterab :return: An iterator like instance of Environment :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.developer.devcenter.models.Environment] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - 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. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} cls: ClsType[List[_models.Environment]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3416,7 +2088,7 @@ def list_all_environments(self, project_name: str, **kwargs: Any) -> AsyncIterab def prepare_request(next_link=None): if not next_link: - _request = build_dev_center_list_all_environments_request( + _request = build_deployment_environments_list_all_environments_request( project_name=project_name, api_version=self._config.api_version, headers=_headers, @@ -3468,8 +2140,6 @@ async def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -3479,7 +2149,6 @@ async def get_next(next_link=None): @distributed_trace 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. @@ -3490,51 +2159,13 @@ def list_environments(self, project_name: str, user_id: str, **kwargs: Any) -> A :return: An iterator like instance of Environment :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.developer.devcenter.models.Environment] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - 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. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} cls: ClsType[List[_models.Environment]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3545,7 +2176,7 @@ def list_environments(self, project_name: str, user_id: str, **kwargs: Any) -> A def prepare_request(next_link=None): if not next_link: - _request = build_dev_center_list_environments_request( + _request = build_deployment_environments_list_environments_request( project_name=project_name, user_id=user_id, api_version=self._config.api_version, @@ -3598,8 +2229,6 @@ async def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -3611,7 +2240,6 @@ async def get_next(next_link=None): 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: Name of the project. Required. @@ -3624,46 +2252,8 @@ async def get_environment( :return: Environment. The Environment is compatible with MutableMapping :rtype: ~azure.developer.devcenter.models.Environment :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - 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. - } """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3676,7 +2266,7 @@ async def get_environment( cls: ClsType[_models.Environment] = kwargs.pop("cls", None) - _request = build_dev_center_get_environment_request( + _request = build_deployment_environments_get_environment_request( project_name=project_name, user_id=user_id, environment_name=environment_name, @@ -3698,7 +2288,10 @@ async def get_environment( if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -3719,8 +2312,8 @@ async def _create_or_update_environment_initial( environment_name: str, body: Union[_models.Environment, JSON, IO[bytes]], **kwargs: Any - ) -> JSON: - error_map: MutableMapping[int, Type[HttpResponseError]] = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3732,7 +2325,7 @@ async def _create_or_update_environment_initial( _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[AsyncIterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None @@ -3741,7 +2334,7 @@ async def _create_or_update_environment_initial( else: _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_dev_center_create_or_update_environment_request( + _request = build_deployment_environments_create_or_update_environment_request( project_name=project_name, user_id=user_id, environment_name=environment_name, @@ -3756,7 +2349,7 @@ async def _create_or_update_environment_initial( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -3764,15 +2357,17 @@ async def _create_or_update_environment_initial( response = pipeline_response.http_response if response.status_code not in [201]: - if _stream: + try: await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) response_headers = {} response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) - deserialized = _deserialize(JSON, response.json()) + deserialized = response.iter_bytes() if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -3790,7 +2385,6 @@ async def begin_create_or_update_environment( 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. @@ -3809,79 +2403,6 @@ async def begin_create_or_update_environment( with MutableMapping :rtype: ~azure.core.polling.AsyncLROPoller[~azure.developer.devcenter.models.Environment] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = { - "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. - } - - # 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 @@ -3895,7 +2416,6 @@ async def begin_create_or_update_environment( 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. @@ -3914,44 +2434,6 @@ async def begin_create_or_update_environment( 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 == { - "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 @@ -3965,7 +2447,6 @@ async def begin_create_or_update_environment( 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. @@ -3984,44 +2465,6 @@ async def begin_create_or_update_environment( 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 == { - "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. - } """ @distributed_trace_async @@ -4033,7 +2476,6 @@ async def begin_create_or_update_environment( 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. @@ -4050,79 +2492,6 @@ async def begin_create_or_update_environment( with MutableMapping :rtype: ~azure.core.polling.AsyncLROPoller[~azure.developer.devcenter.models.Environment] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = { - "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. - } - - # 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. - } """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} @@ -4144,6 +2513,7 @@ async def begin_create_or_update_environment( params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): @@ -4184,8 +2554,8 @@ def get_long_running_output(pipeline_response): async def _delete_environment_initial( self, project_name: str, user_id: str, environment_name: str, **kwargs: Any - ) -> Optional[JSON]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4196,9 +2566,9 @@ async def _delete_environment_initial( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[Optional[JSON]] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - _request = build_dev_center_delete_environment_request( + _request = build_deployment_environments_delete_environment_request( project_name=project_name, user_id=user_id, environment_name=environment_name, @@ -4211,7 +2581,7 @@ async def _delete_environment_initial( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -4219,12 +2589,13 @@ async def _delete_environment_initial( response = pipeline_response.http_response if response.status_code not in [202, 204]: - if _stream: + try: await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) - deserialized = None response_headers = {} if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) @@ -4232,7 +2603,7 @@ async def _delete_environment_initial( "str", response.headers.get("Operation-Location") ) - deserialized = _deserialize(JSON, response.json()) + deserialized = response.iter_bytes() if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -4242,8 +2613,7 @@ 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[_models.OperationDetails]: - # pylint: disable=line-too-long + ) -> AsyncLROPoller[None]: """Deletes an environment and all its associated resources. :param project_name: The DevCenter Project upon which to execute operations. Required. @@ -4253,49 +2623,14 @@ async def begin_delete_environment( :type user_id: str :param environment_name: The name of the environment. Required. :type environment_name: str - :return: An instance of AsyncLROPoller that returns OperationDetails. The OperationDetails is - compatible with MutableMapping - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.developer.devcenter.models.OperationDetails] + :return: An instance of AsyncLROPoller that returns None + :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # 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: "NotStarted", "Running", "Succeeded", "Failed", and "Canceled". - "endTime": "2020-02-20 00:00:00", # Optional. The end time of the operation. - "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. - }, - "percentComplete": 0.0, # Optional. Percent of the operation that is - complete. - "properties": {}, # Optional. Custom operation properties, populated only - for a successful operation. - "resourceId": "str", # Optional. The id of the resource. - "startTime": "2020-02-20 00:00:00" # Optional. The start time of the - operation. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.OperationDetails] = kwargs.pop("cls", None) + cls: ClsType[None] = 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) @@ -4309,20 +2644,12 @@ async def begin_delete_environment( params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): - response_headers = {} - response = pipeline_response.http_response - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - response_headers["Operation-Location"] = self._deserialize( - "str", response.headers.get("Operation-Location") - ) - - deserialized = _deserialize(_models.OperationDetails, response.json()) + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized + return cls(pipeline_response, None, {}) # type: ignore path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), @@ -4338,15 +2665,13 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller[_models.OperationDetails].from_continuation_token( + return AsyncLROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller[_models.OperationDetails]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore @distributed_trace def list_catalogs(self, project_name: str, **kwargs: Any) -> AsyncIterable["_models.Catalog"]: @@ -4357,21 +2682,13 @@ def list_catalogs(self, project_name: str, **kwargs: Any) -> AsyncIterable["_mod :return: An iterator like instance of Catalog :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.developer.devcenter.models.Catalog] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "name": "str" # Name of the catalog. Required. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} cls: ClsType[List[_models.Catalog]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4382,7 +2699,7 @@ def list_catalogs(self, project_name: str, **kwargs: Any) -> AsyncIterable["_mod def prepare_request(next_link=None): if not next_link: - _request = build_dev_center_list_catalogs_request( + _request = build_deployment_environments_list_catalogs_request( project_name=project_name, api_version=self._config.api_version, headers=_headers, @@ -4434,8 +2751,6 @@ async def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -4454,16 +2769,8 @@ async def get_catalog(self, project_name: str, catalog_name: str, **kwargs: Any) :return: Catalog. The Catalog is compatible with MutableMapping :rtype: ~azure.developer.devcenter.models.Catalog :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "name": "str" # Name of the catalog. Required. - } """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4476,7 +2783,7 @@ async def get_catalog(self, project_name: str, catalog_name: str, **kwargs: Any) cls: ClsType[_models.Catalog] = kwargs.pop("cls", None) - _request = build_dev_center_get_catalog_request( + _request = build_deployment_environments_get_catalog_request( project_name=project_name, catalog_name=catalog_name, api_version=self._config.api_version, @@ -4497,7 +2804,10 @@ async def get_catalog(self, project_name: str, catalog_name: str, **kwargs: Any) if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -4515,7 +2825,6 @@ async def get_catalog(self, project_name: str, catalog_name: str, **kwargs: Any) def list_environment_definitions( 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. @@ -4524,49 +2833,13 @@ def list_environment_definitions( :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.developer.devcenter.models.EnvironmentDefinition] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "catalogName": "str", # Name of the catalog. Required. - "id": "str", # The ID of the environment definition. Required. - "name": "str", # Name of the environment definition. Required. - "description": "str", # Optional. A short description of the environment - definition. - "parameters": [ - { - "id": "str", # Unique ID of the parameter. Required. - "required": bool, # Whether or not this parameter is - required. Required. - "type": "str", # 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". - "allowed": [ - "str" # Optional. An array of allowed values. - ], - "default": "str", # Optional. Default value of the - parameter. - "description": "str", # Optional. Description of the - parameter. - "name": "str", # Optional. Display name of the parameter. - "readOnly": bool # Optional. Whether or not this parameter - is read-only. If true, default should have a value. - } - ], - "parametersSchema": "str", # Optional. JSON schema defining the parameters - object passed to an environment. - "templatePath": "str" # Optional. Path to the Environment Definition - entrypoint file. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} cls: ClsType[List[_models.EnvironmentDefinition]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4577,7 +2850,7 @@ def list_environment_definitions( def prepare_request(next_link=None): if not next_link: - _request = build_dev_center_list_environment_definitions_request( + _request = build_deployment_environments_list_environment_definitions_request( project_name=project_name, api_version=self._config.api_version, headers=_headers, @@ -4629,8 +2902,6 @@ async def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -4642,7 +2913,6 @@ async def get_next(next_link=None): def list_environment_definitions_by_catalog( 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. @@ -4653,49 +2923,13 @@ def list_environment_definitions_by_catalog( :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.developer.devcenter.models.EnvironmentDefinition] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "catalogName": "str", # Name of the catalog. Required. - "id": "str", # The ID of the environment definition. Required. - "name": "str", # Name of the environment definition. Required. - "description": "str", # Optional. A short description of the environment - definition. - "parameters": [ - { - "id": "str", # Unique ID of the parameter. Required. - "required": bool, # Whether or not this parameter is - required. Required. - "type": "str", # 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". - "allowed": [ - "str" # Optional. An array of allowed values. - ], - "default": "str", # Optional. Default value of the - parameter. - "description": "str", # Optional. Description of the - parameter. - "name": "str", # Optional. Display name of the parameter. - "readOnly": bool # Optional. Whether or not this parameter - is read-only. If true, default should have a value. - } - ], - "parametersSchema": "str", # Optional. JSON schema defining the parameters - object passed to an environment. - "templatePath": "str" # Optional. Path to the Environment Definition - entrypoint file. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} cls: ClsType[List[_models.EnvironmentDefinition]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4706,7 +2940,7 @@ def list_environment_definitions_by_catalog( def prepare_request(next_link=None): if not next_link: - _request = build_dev_center_list_environment_definitions_by_catalog_request( + _request = build_deployment_environments_list_environment_definitions_by_catalog_request( project_name=project_name, catalog_name=catalog_name, api_version=self._config.api_version, @@ -4759,8 +2993,6 @@ async def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -4772,7 +3004,6 @@ async def get_next(next_link=None): async def get_environment_definition( self, project_name: str, catalog_name: str, definition_name: str, **kwargs: Any ) -> _models.EnvironmentDefinition: - # pylint: disable=line-too-long """Get an environment definition from a catalog. :param project_name: Name of the project. Required. @@ -4784,44 +3015,8 @@ async def get_environment_definition( :return: EnvironmentDefinition. The EnvironmentDefinition is compatible with MutableMapping :rtype: ~azure.developer.devcenter.models.EnvironmentDefinition :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "catalogName": "str", # Name of the catalog. Required. - "id": "str", # The ID of the environment definition. Required. - "name": "str", # Name of the environment definition. Required. - "description": "str", # Optional. A short description of the environment - definition. - "parameters": [ - { - "id": "str", # Unique ID of the parameter. Required. - "required": bool, # Whether or not this parameter is - required. Required. - "type": "str", # 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". - "allowed": [ - "str" # Optional. An array of allowed values. - ], - "default": "str", # Optional. Default value of the - parameter. - "description": "str", # Optional. Description of the - parameter. - "name": "str", # Optional. Display name of the parameter. - "readOnly": bool # Optional. Whether or not this parameter - is read-only. If true, default should have a value. - } - ], - "parametersSchema": "str", # Optional. JSON schema defining the parameters - object passed to an environment. - "templatePath": "str" # Optional. Path to the Environment Definition - entrypoint file. - } """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4834,7 +3029,7 @@ async def get_environment_definition( cls: ClsType[_models.EnvironmentDefinition] = kwargs.pop("cls", None) - _request = build_dev_center_get_environment_definition_request( + _request = build_deployment_environments_get_environment_definition_request( project_name=project_name, catalog_name=catalog_name, definition_name=definition_name, @@ -4856,7 +3051,10 @@ async def get_environment_definition( if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -4872,35 +3070,21 @@ async def get_environment_definition( @distributed_trace 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. + :param project_name: Name of the project. Required. :type project_name: str :return: An iterator like instance of EnvironmentType :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.developer.devcenter.models.EnvironmentType] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "deploymentTargetId": "str", # 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. - "name": "str", # Name of the environment type. Required. - "status": "str" # Indicates whether this environment type is enabled for use - in this project. Required. Known values are: "Enabled" and "Disabled". - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} cls: ClsType[List[_models.EnvironmentType]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4911,7 +3095,7 @@ def list_environment_types(self, project_name: str, **kwargs: Any) -> AsyncItera def prepare_request(next_link=None): if not next_link: - _request = build_dev_center_list_environment_types_request( + _request = build_deployment_environments_list_environment_types_request( project_name=project_name, api_version=self._config.api_version, headers=_headers, @@ -4963,8 +3147,6 @@ async def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_vendor.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_vendor.py index a6ebf787154..e561794aac8 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_vendor.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_vendor.py @@ -8,10 +8,13 @@ from abc import ABC from typing import TYPE_CHECKING -from ._configuration import DevCenterClientConfiguration +from ._configuration import ( + DeploymentEnvironmentsClientConfiguration, + DevBoxesClientConfiguration, + DevCenterClientConfiguration, +) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core import AsyncPipelineClient from .._serialization import Deserializer, Serializer @@ -24,3 +27,21 @@ class DevCenterClientMixinABC(ABC): _config: DevCenterClientConfiguration _serialize: "Serializer" _deserialize: "Deserializer" + + +class DevBoxesClientMixinABC(ABC): + """DO NOT use this class. It is for internal typing use only.""" + + _client: "AsyncPipelineClient" + _config: DevBoxesClientConfiguration + _serialize: "Serializer" + _deserialize: "Deserializer" + + +class DeploymentEnvironmentsClientMixinABC(ABC): + """DO NOT use this class. It is for internal typing use only.""" + + _client: "AsyncPipelineClient" + _config: DeploymentEnvironmentsClientConfiguration + _serialize: "Serializer" + _deserialize: "Deserializer" 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 index 89f8c60752c..e07b12f52ff 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/models/__init__.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/models/__init__.py @@ -5,47 +5,54 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -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 typing import TYPE_CHECKING -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 +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models import ( # type: ignore + Catalog, + DevBox, + DevBoxAction, + DevBoxActionDelayResult, + DevBoxNextAction, + Environment, + EnvironmentDefinition, + EnvironmentDefinitionParameter, + EnvironmentType, + HardwareProfile, + ImageReference, + OsDisk, + Pool, + Project, + RemoteConnection, + Schedule, + StopOnDisconnectConfiguration, + StorageProfile, +) + +from ._enums import ( # type: ignore + DevBoxActionDelayStatus, + DevBoxActionType, + DevBoxProvisioningState, + EnvironmentProvisioningState, + EnvironmentTypeStatus, + HibernateSupport, + LocalAdministratorStatus, + OsType, + ParameterType, + PoolHealthStatus, + PowerState, + ScheduledFrequency, + ScheduledType, + SkuName, + StopOnDisconnectStatus, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -58,12 +65,9 @@ "EnvironmentDefinition", "EnvironmentDefinitionParameter", "EnvironmentType", - "Error", "HardwareProfile", "ImageReference", - "InnerError", - "OSDisk", - "OperationDetails", + "OsDisk", "Pool", "Project", "RemoteConnection", @@ -77,8 +81,7 @@ "EnvironmentTypeStatus", "HibernateSupport", "LocalAdministratorStatus", - "OSType", - "OperationStatus", + "OsType", "ParameterType", "PoolHealthStatus", "PowerState", @@ -87,5 +90,5 @@ "SkuName", "StopOnDisconnectStatus", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _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 index ca1fa886982..ed3aa403542 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/models/_enums.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/models/_enums.py @@ -117,22 +117,7 @@ class LocalAdministratorStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): """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): +class OsType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The operating system type.""" WINDOWS = "Windows" @@ -203,49 +188,49 @@ class ScheduledType(str, Enum, metaclass=CaseInsensitiveEnumMeta): class SkuName(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Indicates the Dev Box compute.""" - GENERAL_I_8C32GB256SSD_V2 = "general_i_8c32gb256ssd_v2" + GENERAL_I8_C32_GB256_SSD_V2 = "general_i_8c32gb256ssd_v2" """Intel, 8 vCPU, 32 GB RAM, 256 GB Storage.""" - GENERAL_I_8C32GB512SSD_V2 = "general_i_8c32gb512ssd_v2" + GENERAL_I8_C32_GB512_SSD_V2 = "general_i_8c32gb512ssd_v2" """Intel, 8 vCPU, 32 GB RAM, 512 GB Storage.""" - GENERAL_I_8C32GB1024SSD_V2 = "general_i_8c32gb1024ssd_v2" + GENERAL_I8_C32_GB1024_SSD_V2 = "general_i_8c32gb1024ssd_v2" """Intel, 8 vCPU, 32 GB RAM, 1024 GB Storage.""" - GENERAL_I_8C32GB2048SSD_V2 = "general_i_8c32gb2048ssd_v2" + GENERAL_I8_C32_GB2048_SSD_V2 = "general_i_8c32gb2048ssd_v2" """Intel, 8 vCPU, 32 GB RAM, 2048 GB Storage.""" - GENERAL_I_16C64GB256SSD_V2 = "general_i_16c64gb256ssd_v2" + GENERAL_I16_C64_GB256_SSD_V2 = "general_i_16c64gb256ssd_v2" """Intel, 16 vCPU, 64 GB RAM, 256 GB Storage.""" - GENERAL_I_16C64GB512SSD_V2 = "general_i_16c64gb512ssd_v2" + GENERAL_I16_C64_GB512_SSD_V2 = "general_i_16c64gb512ssd_v2" """Intel, 16 vCPU, 64 GB RAM, 512 GB Storage.""" - GENERAL_I_16C64GB1024SSD_V2 = "general_i_16c64gb1024ssd_v2" + GENERAL_I16_C64_GB1024_SSD_V2 = "general_i_16c64gb1024ssd_v2" """Intel, 16 vCPU, 64 GB RAM, 1024 GB Storage.""" - GENERAL_I_16C64GB2048SSD_V2 = "general_i_16c64gb2048ssd_v2" + GENERAL_I16_C64_GB2048_SSD_V2 = "general_i_16c64gb2048ssd_v2" """Intel, 16 vCPU, 64 GB RAM, 2048 GB Storage.""" - GENERAL_I_32C128GB512SSD_V2 = "general_i_32c128gb512ssd_v2" + GENERAL_I32_C128_GB512_SSD_V2 = "general_i_32c128gb512ssd_v2" """Intel, 32 vCPU, 128 GB RAM, 512 GB Storage.""" - GENERAL_I_32C128GB1024SSD_V2 = "general_i_32c128gb1024ssd_v2" + GENERAL_I32_C128_GB1024_SSD_V2 = "general_i_32c128gb1024ssd_v2" """Intel, 32 vCPU, 128 GB RAM, 1024 GB Storage.""" - GENERAL_I_32C128GB2048SSD_V2 = "general_i_32c128gb2048ssd_v2" + GENERAL_I32_C128_GB2048_SSD_V2 = "general_i_32c128gb2048ssd_v2" """Intel, 32 vCPU, 128 GB RAM, 2048 GB Storage.""" - GENERAL_A_8C32GB256SSD_V2 = "general_a_8c32gb256ssd_v2" + GENERAL_A8_C32_GB256_SSD_V2 = "general_a_8c32gb256ssd_v2" """AMD, 8 vCPU, 32 GB RAM, 256 GB Storage.""" - GENERAL_A_8C32GB512SSD_V2 = "general_a_8c32gb512ssd_v2" + GENERAL_A8_C32_GB512_SSD_V2 = "general_a_8c32gb512ssd_v2" """AMD, 8 vCPU, 32 GB RAM, 512 GB Storage.""" - GENERAL_A_8C32GB1024SSD_V2 = "general_a_8c32gb1024ssd_v2" + GENERAL_A8_C32_GB1024_SSD_V2 = "general_a_8c32gb1024ssd_v2" """AMD, 8 vCPU, 32 GB RAM, 1024 GB Storage.""" - GENERAL_A_8C32GB2048SSD_V2 = "general_a_8c32gb2048ssd_v2" + GENERAL_A8_C32_GB2048_SSD_V2 = "general_a_8c32gb2048ssd_v2" """AMD, 8 vCPU, 32 GB RAM, 2048 GB Storage.""" - GENERAL_A_16C64GB256SSD_V2 = "general_a_16c64gb256ssd_v2" + GENERAL_A16_C64_GB256_SSD_V2 = "general_a_16c64gb256ssd_v2" """AMD, 16 vCPU, 64 GB RAM, 256 GB Storage.""" - GENERAL_A_16C64GB512SSD_V2 = "general_a_16c64gb512ssd_v2" + GENERAL_A16_C64_GB512_SSD_V2 = "general_a_16c64gb512ssd_v2" """AMD, 16 vCPU, 64 GB RAM, 512 GB Storage.""" - GENERAL_A_16C64GB1024SSD_V2 = "general_a_16c64gb1024ssd_v2" + GENERAL_A16_C64_GB1024_SSD_V2 = "general_a_16c64gb1024ssd_v2" """AMD, 16 vCPU, 64 GB RAM, 1024 GB Storage.""" - GENERAL_A_16C64GB2048SSD_V2 = "general_a_16c64gb2048ssd_v2" + GENERAL_A16_C64_GB2048_SSD_V2 = "general_a_16c64gb2048ssd_v2" """AMD, 16 vCPU, 64 GB RAM, 2048 GB Storage.""" - GENERAL_A_32C128GB512SSD_V2 = "general_a_32c128gb512ssd_v2" + GENERAL_A32_C128_GB512_SSD_V2 = "general_a_32c128gb512ssd_v2" """AMD, 32 vCPU, 128 GB RAM, 512 GB Storage.""" - GENERAL_A_32C128GB1024SSD_V2 = "general_a_32c128gb1024ssd_v2" + GENERAL_A32_C128_GB1024_SSD_V2 = "general_a_32c128gb1024ssd_v2" """AMD, 32 vCPU, 128 GB RAM, 1024 GB Storage.""" - GENERAL_A_32C128GB2048SSD_V2 = "general_a_32c128gb2048ssd_v2" + GENERAL_A32_C128_GB2048_SSD_V2 = "general_a_32c128gb2048ssd_v2" """AMD, 32 vCPU, 128 GB RAM, 2048 GB Storage.""" 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 index 9154decbf8f..fae02af3c1a 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/models/_models.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/models/_models.py @@ -1,20 +1,21 @@ # 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. # -------------------------------------------------------------------------- +# pylint: disable=useless-super-delegation import datetime from typing import Any, Dict, List, Mapping, Optional, TYPE_CHECKING, Union, overload +from azure.core.exceptions import ODataV4Format + from .. import _model_base from .._model_base import rest_field if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models @@ -23,7 +24,6 @@ class Catalog(_model_base.Model): 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 @@ -33,12 +33,11 @@ class Catalog(_model_base.Model): """Name of the catalog. Required.""" -class DevBox(_model_base.Model): # pylint: disable=too-many-instance-attributes +class DevBox(_model_base.Model): """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 @@ -63,12 +62,12 @@ class DevBox(_model_base.Model): # pylint: disable=too-many-instance-attributes 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 + :vartype error: ~azure.core.ODataV4Format :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 + :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. @@ -77,7 +76,7 @@ class DevBox(_model_base.Model): # pylint: disable=too-many-instance-attributes :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. + :ivar created_time: Creation time of this Dev Box, in RFC3339 format. :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". @@ -110,12 +109,12 @@ class DevBox(_model_base.Model): # pylint: disable=too-many-instance-attributes 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"]) + error: Optional[ODataV4Format] = 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"]) + 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.""" @@ -126,9 +125,9 @@ class DevBox(_model_base.Model): # pylint: disable=too-many-instance-attributes 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.""" + """Creation time of this Dev Box, in RFC3339 format.""" local_administrator: Optional[Union[str, "_models.LocalAdministratorStatus"]] = rest_field( - name="localAdministrator", visibility=["read", "create"] + name="localAdministrator", visibility=["read"] ) """Indicates whether the owner of the Dev Box is a local administrator. Known values are: \"Enabled\" and \"Disabled\".""" @@ -138,17 +137,16 @@ def __init__( self, *, pool_name: str, - local_administrator: Optional[Union[str, "_models.LocalAdministratorStatus"]] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :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 + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) @@ -157,7 +155,6 @@ class DevBoxAction(_model_base.Model): 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 @@ -165,7 +162,7 @@ class DevBoxAction(_model_base.Model): :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). + :ivar suspended_until: The earliest time that the action could occur (UTC), in RFC3339 format. :vartype suspended_until: ~datetime.datetime :ivar next: Details about the next run of this action. :vartype next: ~azure.developer.devcenter.models.DevBoxNextAction @@ -178,7 +175,7 @@ class DevBoxAction(_model_base.Model): 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).""" + """The earliest time that the action could occur (UTC), in RFC3339 format.""" next: Optional["_models.DevBoxNextAction"] = rest_field() """Details about the next run of this action.""" @@ -190,43 +187,42 @@ def __init__( source_id: str, suspended_until: Optional[datetime.datetime] = None, next: Optional["_models.DevBoxNextAction"] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :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 + def __init__(self, *args: Any, **kwargs: Any) -> None: 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 delay_status: The result of the delay operation on this action. Required. Known values + are: "Succeeded" and "Failed". + :vartype delay_status: 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 + :vartype error: ~azure.core.ODataV4Format """ name: str = rest_field() """The name of the action. Required.""" - result: Union[str, "_models.DevBoxActionDelayStatus"] = rest_field() + delay_status: Union[str, "_models.DevBoxActionDelayStatus"] = rest_field(name="result") """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() + error: Optional[ODataV4Format] = rest_field() """Information about the error that occurred. Only populated on error.""" @overload @@ -234,49 +230,48 @@ def __init__( self, *, name: str, - result: Union[str, "_models.DevBoxActionDelayStatus"], + delay_status: Union[str, "_models.DevBoxActionDelayStatus"], action: Optional["_models.DevBoxAction"] = None, - error: Optional["_models.Error"] = None, - ): ... + error: Optional[ODataV4Format] = None, + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :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 + def __init__(self, *args: Any, **kwargs: Any) -> None: 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. + :ivar scheduled_time: The time the action will be triggered (UTC), in RFC3339 format. 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.""" + """The time the action will be triggered (UTC), in RFC3339 format. Required.""" @overload def __init__( self, *, scheduled_time: datetime.datetime, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :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 + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) @@ -285,7 +280,6 @@ class Environment(_model_base.Model): 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] @@ -308,7 +302,7 @@ class Environment(_model_base.Model): :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 + :vartype error: ~azure.core.ODataV4Format """ parameters: Optional[Dict[str, Any]] = rest_field() @@ -332,7 +326,7 @@ class Environment(_model_base.Model): """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"]) + error: Optional[ODataV4Format] = rest_field(visibility=["read"]) """Provisioning error details. Populated only for error states.""" @overload @@ -343,16 +337,16 @@ def __init__( catalog_name: str, environment_definition_name: str, parameters: Optional[Dict[str, Any]] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :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 + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) @@ -361,7 +355,6 @@ class EnvironmentDefinition(_model_base.Model): 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 @@ -404,23 +397,22 @@ def __init__( parameters: Optional[List["_models.EnvironmentDefinitionParameter"]] = None, parameters_schema: Optional[str] = None, template_path: Optional[str] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :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 + def __init__(self, *args: Any, **kwargs: Any) -> None: 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 @@ -475,23 +467,24 @@ def __init__( default: Optional[str] = None, read_only: Optional[bool] = None, allowed: Optional[List[str]] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :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 + def __init__(self, *args: Any, **kwargs: Any) -> None: 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. + Readonly variables are only populated by the server, and will be ignored when sending a request. + :ivar name: Name of the environment type. Required. :vartype name: str @@ -505,7 +498,7 @@ class EnvironmentType(_model_base.Model): :vartype status: str or ~azure.developer.devcenter.models.EnvironmentTypeStatus """ - name: str = rest_field() + name: str = rest_field(visibility=["read"]) """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 @@ -519,70 +512,18 @@ class EnvironmentType(_model_base.Model): 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, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :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 + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) @@ -601,8 +542,8 @@ class HardwareProfile(_model_base.Model): "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 v_cp_us: The number of vCPUs available for the Dev Box. + :vartype v_cp_us: int :ivar memory_gb: The amount of memory available for the Dev Box. :vartype memory_gb: int """ @@ -618,7 +559,7 @@ class HardwareProfile(_model_base.Model): \"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"]) + v_cp_us: 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.""" @@ -637,7 +578,8 @@ class ImageReference(_model_base.Model): :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. + :ivar published_date: The datetime that the backing image version was published, in RFC3339 + format. :vartype published_date: ~datetime.datetime """ @@ -652,117 +594,10 @@ class ImageReference(_model_base.Model): 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) + """The datetime that the backing image version was published, in RFC3339 format.""" -class OSDisk(_model_base.Model): +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. @@ -780,14 +615,13 @@ class Pool(_model_base.Model): 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 + :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 @@ -814,7 +648,7 @@ class Pool(_model_base.Model): """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") + 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.""" @@ -843,23 +677,23 @@ def __init__( *, location: str, health_status: Union[str, "_models.PoolHealthStatus"], - os_type: Optional[Union[str, "_models.OSType"]] = None, + 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, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :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 + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) @@ -868,7 +702,6 @@ class Project(_model_base.Model): 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 @@ -894,16 +727,16 @@ def __init__( *, description: Optional[str] = None, max_dev_boxes_per_user: Optional[int] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :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 + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) @@ -927,16 +760,16 @@ def __init__( *, web_url: Optional[str] = None, rdp_connection_url: Optional[str] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :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 + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) @@ -945,7 +778,6 @@ class Schedule(_model_base.Model): 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 @@ -978,23 +810,22 @@ def __init__( frequency: Union[str, "_models.ScheduledFrequency"], time: str, time_zone: str, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :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 + def __init__(self, *args: Any, **kwargs: Any) -> None: 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". @@ -1018,16 +849,16 @@ def __init__( *, status: Union[str, "_models.StopOnDisconnectStatus"], grace_period_minutes: Optional[int] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :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 + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) @@ -1035,25 +866,25 @@ 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 + :vartype os_disk: ~azure.developer.devcenter.models.OsDisk """ - os_disk: Optional["_models.OSDisk"] = rest_field(name="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, - ): ... + os_disk: Optional["_models.OsDisk"] = None, + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :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 + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_create_dev_box.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_create_dev_box.py new file mode 100644 index 00000000000..f076d5f62f4 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_create_dev_box.py @@ -0,0 +1,44 @@ +# 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 azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DevBoxesClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python dev_boxes_create_dev_box.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.begin_create_dev_box( + project_name="myProject", + user_id="me", + dev_box_name="MyDevBox", + body={"poolName": "LargeDevWorkStationPool"}, + ).result() + print(response) + + +# x-ms-original-file: 2023-04-01/DevBoxes_CreateDevBox.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_delay_action.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_delay_action.py new file mode 100644 index 00000000000..53cbd0ddd7e --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_delay_action.py @@ -0,0 +1,47 @@ +# 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. +# -------------------------------------------------------------------------- + +import isodate + +from azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DevBoxesClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python dev_boxes_delay_action.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.delay_action( + project_name="myProject", + user_id="me", + dev_box_name="myDevBox", + action_name="schedule-default", + delay_until=isodate.parse_datetime("2022-09-30T17:00:00Z"), + ) + print(response) + + +# x-ms-original-file: 2023-04-01/DevBoxes_DelayAction.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_delay_actions.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_delay_actions.py new file mode 100644 index 00000000000..e756be183b6 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_delay_actions.py @@ -0,0 +1,47 @@ +# 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. +# -------------------------------------------------------------------------- + +import isodate + +from azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DevBoxesClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python dev_boxes_delay_actions.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.delay_all_actions( + project_name="myProject", + user_id="me", + dev_box_name="myDevBox", + delay_until=isodate.parse_datetime("2022-09-30T17:00:00Z"), + ) + for item in response: + print(item) + + +# x-ms-original-file: 2023-04-01/DevBoxes_DelayActions.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_delete_dev_box.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_delete_dev_box.py new file mode 100644 index 00000000000..4faf3730d04 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_delete_dev_box.py @@ -0,0 +1,42 @@ +# 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 azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DevBoxesClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python dev_boxes_delete_dev_box.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + client.begin_delete_dev_box( + project_name="myProject", + user_id="me", + dev_box_name="MyDevBox", + ).result() + + +# x-ms-original-file: 2023-04-01/DevBoxes_DeleteDevBox.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_get_action.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_get_action.py new file mode 100644 index 00000000000..8e63e82aafb --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_get_action.py @@ -0,0 +1,44 @@ +# 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 azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DevBoxesClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python dev_boxes_get_action.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.get_dev_box_action( + project_name="myProject", + user_id="me", + dev_box_name="myDevBox", + action_name="schedule-default", + ) + print(response) + + +# x-ms-original-file: 2023-04-01/DevBoxes_GetAction.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_get_dev_box_by_user.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_get_dev_box_by_user.py new file mode 100644 index 00000000000..ca8825cddb1 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_get_dev_box_by_user.py @@ -0,0 +1,43 @@ +# 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 azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DevBoxesClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python dev_boxes_get_dev_box_by_user.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.get_dev_box( + project_name="myProject", + user_id="me", + dev_box_name="MyDevBox", + ) + print(response) + + +# x-ms-original-file: 2023-04-01/DevBoxes_GetDevBoxByUser.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_get_pool.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_get_pool.py new file mode 100644 index 00000000000..e08698a0711 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_get_pool.py @@ -0,0 +1,42 @@ +# 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 azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DevBoxesClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python dev_boxes_get_pool.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.get_pool( + project_name="myProject", + pool_name="DevPool", + ) + print(response) + + +# x-ms-original-file: 2023-04-01/DevBoxes_GetPool.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_get_remote_connection.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_get_remote_connection.py new file mode 100644 index 00000000000..a3029b01fe8 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_get_remote_connection.py @@ -0,0 +1,43 @@ +# 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 azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DevBoxesClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python dev_boxes_get_remote_connection.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.get_remote_connection( + project_name="myProject", + user_id="me", + dev_box_name="MyDevBox", + ) + print(response) + + +# x-ms-original-file: 2023-04-01/DevBoxes_GetRemoteConnection.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_get_schedule_by_pool.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_get_schedule_by_pool.py new file mode 100644 index 00000000000..dd2f91b9e6f --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_get_schedule_by_pool.py @@ -0,0 +1,43 @@ +# 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 azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DevBoxesClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python dev_boxes_get_schedule_by_pool.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.get_schedule( + project_name="myProject", + pool_name="DevPool", + schedule_name="default", + ) + print(response) + + +# x-ms-original-file: 2023-04-01/DevBoxes_GetScheduleByPool.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_list_actions.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_list_actions.py new file mode 100644 index 00000000000..63d012c0855 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_list_actions.py @@ -0,0 +1,44 @@ +# 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 azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DevBoxesClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python dev_boxes_list_actions.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.list_dev_box_actions( + project_name="myProject", + user_id="me", + dev_box_name="myDevBox", + ) + for item in response: + print(item) + + +# x-ms-original-file: 2023-04-01/DevBoxes_ListActions.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_list_all_dev_boxes.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_list_all_dev_boxes.py new file mode 100644 index 00000000000..1a64ac78fb8 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_list_all_dev_boxes.py @@ -0,0 +1,40 @@ +# 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 azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DevBoxesClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python dev_boxes_list_all_dev_boxes.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.list_all_dev_boxes() + for item in response: + print(item) + + +# x-ms-original-file: 2023-04-01/DevBoxes_ListAllDevBoxes.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_list_all_dev_boxes_by_user.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_list_all_dev_boxes_by_user.py new file mode 100644 index 00000000000..e744e0c9a56 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_list_all_dev_boxes_by_user.py @@ -0,0 +1,42 @@ +# 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 azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DevBoxesClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python dev_boxes_list_all_dev_boxes_by_user.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.list_all_dev_boxes_by_user( + user_id="me", + ) + for item in response: + print(item) + + +# x-ms-original-file: 2023-04-01/DevBoxes_ListAllDevBoxesByUser.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_list_dev_boxes_by_user.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_list_dev_boxes_by_user.py new file mode 100644 index 00000000000..0d0918e36fe --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_list_dev_boxes_by_user.py @@ -0,0 +1,43 @@ +# 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 azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DevBoxesClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python dev_boxes_list_dev_boxes_by_user.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.list_dev_boxes( + project_name="myProject", + user_id="me", + ) + for item in response: + print(item) + + +# x-ms-original-file: 2023-04-01/DevBoxes_ListDevBoxesByUser.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_list_pools.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_list_pools.py new file mode 100644 index 00000000000..c6b26d47f47 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_list_pools.py @@ -0,0 +1,42 @@ +# 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 azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DevBoxesClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python dev_boxes_list_pools.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.list_pools( + project_name="myProject", + ) + for item in response: + print(item) + + +# x-ms-original-file: 2023-04-01/DevBoxes_ListPools.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_list_schedules_by_pool.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_list_schedules_by_pool.py new file mode 100644 index 00000000000..34878bf934e --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_list_schedules_by_pool.py @@ -0,0 +1,43 @@ +# 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 azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DevBoxesClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python dev_boxes_list_schedules_by_pool.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.list_schedules( + project_name="myProject", + pool_name="DevPool", + ) + for item in response: + print(item) + + +# x-ms-original-file: 2023-04-01/DevBoxes_ListSchedulesByPool.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_restart_dev_box.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_restart_dev_box.py new file mode 100644 index 00000000000..6d1cc96004d --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_restart_dev_box.py @@ -0,0 +1,42 @@ +# 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 azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DevBoxesClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python dev_boxes_restart_dev_box.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + client.begin_restart_dev_box( + project_name="myProject", + user_id="me", + dev_box_name="MyDevBox", + ).result() + + +# x-ms-original-file: 2023-04-01/DevBoxes_RestartDevBox.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_skip_action.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_skip_action.py new file mode 100644 index 00000000000..9be65420721 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_skip_action.py @@ -0,0 +1,43 @@ +# 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 azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DevBoxesClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python dev_boxes_skip_action.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + client.skip_action( + project_name="myProject", + user_id="me", + dev_box_name="myDevBox", + action_name="schedule-default", + ) + + +# x-ms-original-file: 2023-04-01/DevBoxes_SkipAction.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_start_dev_box.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_start_dev_box.py new file mode 100644 index 00000000000..05b1b7a5926 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_start_dev_box.py @@ -0,0 +1,42 @@ +# 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 azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DevBoxesClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python dev_boxes_start_dev_box.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + client.begin_start_dev_box( + project_name="myProject", + user_id="me", + dev_box_name="MyDevBox", + ).result() + + +# x-ms-original-file: 2023-04-01/DevBoxes_StartDevBox.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_stop_dev_box.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_stop_dev_box.py new file mode 100644 index 00000000000..7037dd33c24 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_boxes_stop_dev_box.py @@ -0,0 +1,42 @@ +# 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 azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DevBoxesClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python dev_boxes_stop_dev_box.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + client.begin_stop_dev_box( + project_name="myProject", + user_id="me", + dev_box_name="MyDevBox", + ).result() + + +# x-ms-original-file: 2023-04-01/DevBoxes_StopDevBox.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_center_get_project.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_center_get_project.py new file mode 100644 index 00000000000..f3220929a79 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_center_get_project.py @@ -0,0 +1,41 @@ +# 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 azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DevCenterClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python dev_center_get_project.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.get_project( + project_name="myProject", + ) + print(response) + + +# x-ms-original-file: 2023-04-01/DevCenter_GetProject.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_center_list_projects.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_center_list_projects.py new file mode 100644 index 00000000000..d7cb162c041 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/dev_center_list_projects.py @@ -0,0 +1,40 @@ +# 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 azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DevCenterClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python dev_center_list_projects.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.list_projects() + for item in response: + print(item) + + +# x-ms-original-file: 2023-04-01/DevCenter_ListProjects.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_create_or_replace_environment.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_create_or_replace_environment.py new file mode 100644 index 00000000000..7ca26b4dc6a --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_create_or_replace_environment.py @@ -0,0 +1,49 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DeploymentEnvironmentsClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python environments_create_or_replace_environment.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.begin_create_or_update_environment( + project_name="myProject", + user_id="me", + environment_name="mydevenv", + body={ + "catalogName": "main", + "environmentDefinitionName": "helloworld", + "environmentType": "DevTest", + "parameters": {"functionAppRuntime": "node", "storageAccountType": "Standard_LRS"}, + }, + ).result() + print(response) + + +# x-ms-original-file: 2023-04-01/Environments_CreateOrReplaceEnvironment.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_delete_environment.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_delete_environment.py new file mode 100644 index 00000000000..e4dc1d3ecc2 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_delete_environment.py @@ -0,0 +1,42 @@ +# 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 azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DeploymentEnvironmentsClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python environments_delete_environment.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + client.begin_delete_environment( + project_name="myProject", + user_id="me", + environment_name="mydevenv", + ).result() + + +# x-ms-original-file: 2023-04-01/Environments_DeleteEnvironment.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_get_catalog.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_get_catalog.py new file mode 100644 index 00000000000..c4459f02c9e --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_get_catalog.py @@ -0,0 +1,42 @@ +# 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 azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DeploymentEnvironmentsClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python environments_get_catalog.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.get_catalog( + project_name="myProject", + catalog_name="foo", + ) + print(response) + + +# x-ms-original-file: 2023-04-01/Environments_GetCatalog.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_get_environment_by_user.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_get_environment_by_user.py new file mode 100644 index 00000000000..c10b33b6687 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_get_environment_by_user.py @@ -0,0 +1,43 @@ +# 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 azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DeploymentEnvironmentsClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python environments_get_environment_by_user.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.get_environment( + project_name="myProject", + user_id="me", + environment_name="mydevenv", + ) + print(response) + + +# x-ms-original-file: 2023-04-01/Environments_GetEnvironmentByUser.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_get_environment_definition.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_get_environment_definition.py new file mode 100644 index 00000000000..72a06c01a61 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_get_environment_definition.py @@ -0,0 +1,43 @@ +# 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 azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DeploymentEnvironmentsClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python environments_get_environment_definition.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.get_environment_definition( + project_name="myProject", + catalog_name="myCatalog", + definition_name="foo", + ) + print(response) + + +# x-ms-original-file: 2023-04-01/Environments_GetEnvironmentDefinition.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_list_catalogs_by_project.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_list_catalogs_by_project.py new file mode 100644 index 00000000000..8ab6e5c4012 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_list_catalogs_by_project.py @@ -0,0 +1,42 @@ +# 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 azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DeploymentEnvironmentsClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python environments_list_catalogs_by_project.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.list_catalogs( + project_name="myProject", + ) + for item in response: + print(item) + + +# x-ms-original-file: 2023-04-01/Environments_ListCatalogsByProject.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_list_environment_definitions_by_catalog.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_list_environment_definitions_by_catalog.py new file mode 100644 index 00000000000..5c49a9bfe97 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_list_environment_definitions_by_catalog.py @@ -0,0 +1,43 @@ +# 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 azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DeploymentEnvironmentsClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python environments_list_environment_definitions_by_catalog.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.list_environment_definitions_by_catalog( + project_name="myProject", + catalog_name="myCatalog", + ) + for item in response: + print(item) + + +# x-ms-original-file: 2023-04-01/Environments_ListEnvironmentDefinitionsByCatalog.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_list_environment_definitions_by_project.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_list_environment_definitions_by_project.py new file mode 100644 index 00000000000..90b600a9d2b --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_list_environment_definitions_by_project.py @@ -0,0 +1,42 @@ +# 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 azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DeploymentEnvironmentsClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python environments_list_environment_definitions_by_project.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.list_environment_definitions( + project_name="myProject", + ) + for item in response: + print(item) + + +# x-ms-original-file: 2023-04-01/Environments_ListEnvironmentDefinitionsByProject.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_list_environment_types.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_list_environment_types.py new file mode 100644 index 00000000000..ebc43b0a7dc --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_list_environment_types.py @@ -0,0 +1,42 @@ +# 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 azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DeploymentEnvironmentsClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python environments_list_environment_types.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.list_environment_types( + project_name="myProject", + ) + for item in response: + print(item) + + +# x-ms-original-file: 2023-04-01/Environments_ListEnvironmentTypes.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_list_environments.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_list_environments.py new file mode 100644 index 00000000000..7d4e964110f --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_list_environments.py @@ -0,0 +1,42 @@ +# 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 azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DeploymentEnvironmentsClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python environments_list_environments.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.list_all_environments( + project_name="myProject", + ) + for item in response: + print(item) + + +# x-ms-original-file: 2023-04-01/Environments_ListEnvironments.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_list_environments_by_user.py b/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_list_environments_by_user.py new file mode 100644 index 00000000000..d98727add90 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_list_environments_by_user.py @@ -0,0 +1,43 @@ +# 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 azure.identity import DefaultAzureCredential + +from azure.developer.devcenter import DeploymentEnvironmentsClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-developer-devcenter +# USAGE + python environments_list_environments_by_user.py + + Before run the sample, please 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. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = DevCenterClient( + endpoint="https://8a40af38-3b4c-4672-a6a4-5e964b1870ed-contosodevcenter.centralus.devcenter.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.list_environments( + project_name="myProject", + user_id="me", + ) + for item in response: + print(item) + + +# x-ms-original-file: 2023-04-01/Environments_ListEnvironmentsByUser.json +if __name__ == "__main__": + main() diff --git a/sdk/devcenter/azure-developer-devcenter/generated_tests/conftest.py b/sdk/devcenter/azure-developer-devcenter/generated_tests/conftest.py new file mode 100644 index 00000000000..53905c7949d --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_tests/conftest.py @@ -0,0 +1,65 @@ +# 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. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + devcenter_subscription_id = os.environ.get("DEVCENTER_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + devcenter_tenant_id = os.environ.get("DEVCENTER_TENANT_ID", "00000000-0000-0000-0000-000000000000") + devcenter_client_id = os.environ.get("DEVCENTER_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + devcenter_client_secret = os.environ.get("DEVCENTER_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=devcenter_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=devcenter_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=devcenter_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=devcenter_client_secret, value="00000000-0000-0000-0000-000000000000") + + devboxes_subscription_id = os.environ.get("DEVBOXES_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + devboxes_tenant_id = os.environ.get("DEVBOXES_TENANT_ID", "00000000-0000-0000-0000-000000000000") + devboxes_client_id = os.environ.get("DEVBOXES_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + devboxes_client_secret = os.environ.get("DEVBOXES_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=devboxes_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=devboxes_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=devboxes_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=devboxes_client_secret, value="00000000-0000-0000-0000-000000000000") + + deploymentenvironments_subscription_id = os.environ.get( + "DEPLOYMENTENVIRONMENTS_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000" + ) + deploymentenvironments_tenant_id = os.environ.get( + "DEPLOYMENTENVIRONMENTS_TENANT_ID", "00000000-0000-0000-0000-000000000000" + ) + deploymentenvironments_client_id = os.environ.get( + "DEPLOYMENTENVIRONMENTS_CLIENT_ID", "00000000-0000-0000-0000-000000000000" + ) + deploymentenvironments_client_secret = os.environ.get( + "DEPLOYMENTENVIRONMENTS_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000" + ) + add_general_regex_sanitizer( + regex=deploymentenvironments_subscription_id, value="00000000-0000-0000-0000-000000000000" + ) + add_general_regex_sanitizer(regex=deploymentenvironments_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=deploymentenvironments_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer( + regex=deploymentenvironments_client_secret, value="00000000-0000-0000-0000-000000000000" + ) + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/devcenter/azure-developer-devcenter/generated_tests/test_deployment_environments.py b/sdk/devcenter/azure-developer-devcenter/generated_tests/test_deployment_environments.py new file mode 100644 index 00000000000..3af71ad1365 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_tests/test_deployment_environments.py @@ -0,0 +1,156 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils import recorded_by_proxy +from testpreparer import DeploymentEnvironmentsClientTestBase, DeploymentEnvironmentsPreparer + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestDeploymentEnvironments(DeploymentEnvironmentsClientTestBase): + @DeploymentEnvironmentsPreparer() + @recorded_by_proxy + def test_list_all_environments(self, deploymentenvironments_endpoint): + client = self.create_client(endpoint=deploymentenvironments_endpoint) + response = client.list_all_environments( + project_name="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @DeploymentEnvironmentsPreparer() + @recorded_by_proxy + def test_list_environments(self, deploymentenvironments_endpoint): + client = self.create_client(endpoint=deploymentenvironments_endpoint) + response = client.list_environments( + project_name="str", + user_id="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @DeploymentEnvironmentsPreparer() + @recorded_by_proxy + def test_get_environment(self, deploymentenvironments_endpoint): + client = self.create_client(endpoint=deploymentenvironments_endpoint) + response = client.get_environment( + project_name="str", + user_id="str", + environment_name="str", + ) + + # please add some check logic here by yourself + # ... + + @DeploymentEnvironmentsPreparer() + @recorded_by_proxy + def test_begin_create_or_update_environment(self, deploymentenvironments_endpoint): + client = self.create_client(endpoint=deploymentenvironments_endpoint) + response = client.begin_create_or_update_environment( + project_name="str", + user_id="str", + environment_name="str", + body={ + "catalogName": "str", + "environmentDefinitionName": "str", + "environmentType": "str", + "name": "str", + "error": ~azure.core.ODataV4Format, + "parameters": {"str": {}}, + "provisioningState": "str", + "resourceGroupId": "str", + "user": "str", + }, + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @DeploymentEnvironmentsPreparer() + @recorded_by_proxy + def test_begin_delete_environment(self, deploymentenvironments_endpoint): + client = self.create_client(endpoint=deploymentenvironments_endpoint) + response = client.begin_delete_environment( + project_name="str", + user_id="str", + environment_name="str", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @DeploymentEnvironmentsPreparer() + @recorded_by_proxy + def test_list_catalogs(self, deploymentenvironments_endpoint): + client = self.create_client(endpoint=deploymentenvironments_endpoint) + response = client.list_catalogs( + project_name="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @DeploymentEnvironmentsPreparer() + @recorded_by_proxy + def test_get_catalog(self, deploymentenvironments_endpoint): + client = self.create_client(endpoint=deploymentenvironments_endpoint) + response = client.get_catalog( + project_name="str", + catalog_name="str", + ) + + # please add some check logic here by yourself + # ... + + @DeploymentEnvironmentsPreparer() + @recorded_by_proxy + def test_list_environment_definitions(self, deploymentenvironments_endpoint): + client = self.create_client(endpoint=deploymentenvironments_endpoint) + response = client.list_environment_definitions( + project_name="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @DeploymentEnvironmentsPreparer() + @recorded_by_proxy + def test_list_environment_definitions_by_catalog(self, deploymentenvironments_endpoint): + client = self.create_client(endpoint=deploymentenvironments_endpoint) + response = client.list_environment_definitions_by_catalog( + project_name="str", + catalog_name="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @DeploymentEnvironmentsPreparer() + @recorded_by_proxy + def test_get_environment_definition(self, deploymentenvironments_endpoint): + client = self.create_client(endpoint=deploymentenvironments_endpoint) + response = client.get_environment_definition( + project_name="str", + catalog_name="str", + definition_name="str", + ) + + # please add some check logic here by yourself + # ... + + @DeploymentEnvironmentsPreparer() + @recorded_by_proxy + def test_list_environment_types(self, deploymentenvironments_endpoint): + client = self.create_client(endpoint=deploymentenvironments_endpoint) + response = client.list_environment_types( + project_name="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/devcenter/azure-developer-devcenter/generated_tests/test_deployment_environments_async.py b/sdk/devcenter/azure-developer-devcenter/generated_tests/test_deployment_environments_async.py new file mode 100644 index 00000000000..72e06ce9a28 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_tests/test_deployment_environments_async.py @@ -0,0 +1,161 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils.aio import recorded_by_proxy_async +from testpreparer import DeploymentEnvironmentsPreparer +from testpreparer_async import DeploymentEnvironmentsClientTestBaseAsync + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestDeploymentEnvironmentsAsync(DeploymentEnvironmentsClientTestBaseAsync): + @DeploymentEnvironmentsPreparer() + @recorded_by_proxy_async + async def test_list_all_environments(self, deploymentenvironments_endpoint): + client = self.create_async_client(endpoint=deploymentenvironments_endpoint) + response = client.list_all_environments( + project_name="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @DeploymentEnvironmentsPreparer() + @recorded_by_proxy_async + async def test_list_environments(self, deploymentenvironments_endpoint): + client = self.create_async_client(endpoint=deploymentenvironments_endpoint) + response = client.list_environments( + project_name="str", + user_id="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @DeploymentEnvironmentsPreparer() + @recorded_by_proxy_async + async def test_get_environment(self, deploymentenvironments_endpoint): + client = self.create_async_client(endpoint=deploymentenvironments_endpoint) + response = await client.get_environment( + project_name="str", + user_id="str", + environment_name="str", + ) + + # please add some check logic here by yourself + # ... + + @DeploymentEnvironmentsPreparer() + @recorded_by_proxy_async + async def test_begin_create_or_update_environment(self, deploymentenvironments_endpoint): + client = self.create_async_client(endpoint=deploymentenvironments_endpoint) + response = await ( + await client.begin_create_or_update_environment( + project_name="str", + user_id="str", + environment_name="str", + body={ + "catalogName": "str", + "environmentDefinitionName": "str", + "environmentType": "str", + "name": "str", + "error": ~azure.core.ODataV4Format, + "parameters": {"str": {}}, + "provisioningState": "str", + "resourceGroupId": "str", + "user": "str", + }, + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @DeploymentEnvironmentsPreparer() + @recorded_by_proxy_async + async def test_begin_delete_environment(self, deploymentenvironments_endpoint): + client = self.create_async_client(endpoint=deploymentenvironments_endpoint) + response = await ( + await client.begin_delete_environment( + project_name="str", + user_id="str", + environment_name="str", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @DeploymentEnvironmentsPreparer() + @recorded_by_proxy_async + async def test_list_catalogs(self, deploymentenvironments_endpoint): + client = self.create_async_client(endpoint=deploymentenvironments_endpoint) + response = client.list_catalogs( + project_name="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @DeploymentEnvironmentsPreparer() + @recorded_by_proxy_async + async def test_get_catalog(self, deploymentenvironments_endpoint): + client = self.create_async_client(endpoint=deploymentenvironments_endpoint) + response = await client.get_catalog( + project_name="str", + catalog_name="str", + ) + + # please add some check logic here by yourself + # ... + + @DeploymentEnvironmentsPreparer() + @recorded_by_proxy_async + async def test_list_environment_definitions(self, deploymentenvironments_endpoint): + client = self.create_async_client(endpoint=deploymentenvironments_endpoint) + response = client.list_environment_definitions( + project_name="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @DeploymentEnvironmentsPreparer() + @recorded_by_proxy_async + async def test_list_environment_definitions_by_catalog(self, deploymentenvironments_endpoint): + client = self.create_async_client(endpoint=deploymentenvironments_endpoint) + response = client.list_environment_definitions_by_catalog( + project_name="str", + catalog_name="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @DeploymentEnvironmentsPreparer() + @recorded_by_proxy_async + async def test_get_environment_definition(self, deploymentenvironments_endpoint): + client = self.create_async_client(endpoint=deploymentenvironments_endpoint) + response = await client.get_environment_definition( + project_name="str", + catalog_name="str", + definition_name="str", + ) + + # please add some check logic here by yourself + # ... + + @DeploymentEnvironmentsPreparer() + @recorded_by_proxy_async + async def test_list_environment_types(self, deploymentenvironments_endpoint): + client = self.create_async_client(endpoint=deploymentenvironments_endpoint) + response = client.list_environment_types( + project_name="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/devcenter/azure-developer-devcenter/generated_tests/test_dev_boxes.py b/sdk/devcenter/azure-developer-devcenter/generated_tests/test_dev_boxes.py new file mode 100644 index 00000000000..c0392abb538 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_tests/test_dev_boxes.py @@ -0,0 +1,279 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils import recorded_by_proxy +from testpreparer import DevBoxesClientTestBase, DevBoxesPreparer + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestDevBoxes(DevBoxesClientTestBase): + @DevBoxesPreparer() + @recorded_by_proxy + def test_list_pools(self, devboxes_endpoint): + client = self.create_client(endpoint=devboxes_endpoint) + response = client.list_pools( + project_name="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy + def test_get_pool(self, devboxes_endpoint): + client = self.create_client(endpoint=devboxes_endpoint) + response = client.get_pool( + project_name="str", + pool_name="str", + ) + + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy + def test_list_schedules(self, devboxes_endpoint): + client = self.create_client(endpoint=devboxes_endpoint) + response = client.list_schedules( + project_name="str", + pool_name="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy + def test_get_schedule(self, devboxes_endpoint): + client = self.create_client(endpoint=devboxes_endpoint) + response = client.get_schedule( + project_name="str", + pool_name="str", + schedule_name="str", + ) + + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy + def test_list_all_dev_boxes(self, devboxes_endpoint): + client = self.create_client(endpoint=devboxes_endpoint) + response = client.list_all_dev_boxes() + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy + def test_list_all_dev_boxes_by_user(self, devboxes_endpoint): + client = self.create_client(endpoint=devboxes_endpoint) + response = client.list_all_dev_boxes_by_user( + user_id="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy + def test_list_dev_boxes(self, devboxes_endpoint): + client = self.create_client(endpoint=devboxes_endpoint) + response = client.list_dev_boxes( + project_name="str", + user_id="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy + def test_get_dev_box(self, devboxes_endpoint): + client = self.create_client(endpoint=devboxes_endpoint) + response = client.get_dev_box( + project_name="str", + user_id="str", + dev_box_name="str", + ) + + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy + def test_begin_create_dev_box(self, devboxes_endpoint): + client = self.create_client(endpoint=devboxes_endpoint) + response = client.begin_create_dev_box( + project_name="str", + user_id="str", + dev_box_name="str", + body={ + "name": "str", + "poolName": "str", + "actionState": "str", + "createdTime": "2020-02-20 00:00:00", + "error": ~azure.core.ODataV4Format, + "hardwareProfile": {"memoryGB": 0, "skuName": "str", "vCPUs": 0}, + "hibernateSupport": "str", + "imageReference": { + "name": "str", + "operatingSystem": "str", + "osBuildNumber": "str", + "publishedDate": "2020-02-20 00:00:00", + "version": "str", + }, + "localAdministrator": "str", + "location": "str", + "osType": "str", + "powerState": "str", + "projectName": "str", + "provisioningState": "str", + "storageProfile": {"osDisk": {"diskSizeGB": 0}}, + "uniqueId": "str", + "user": "str", + }, + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy + def test_begin_delete_dev_box(self, devboxes_endpoint): + client = self.create_client(endpoint=devboxes_endpoint) + response = client.begin_delete_dev_box( + project_name="str", + user_id="str", + dev_box_name="str", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy + def test_begin_start_dev_box(self, devboxes_endpoint): + client = self.create_client(endpoint=devboxes_endpoint) + response = client.begin_start_dev_box( + project_name="str", + user_id="str", + dev_box_name="str", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy + def test_begin_stop_dev_box(self, devboxes_endpoint): + client = self.create_client(endpoint=devboxes_endpoint) + response = client.begin_stop_dev_box( + project_name="str", + user_id="str", + dev_box_name="str", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy + def test_begin_restart_dev_box(self, devboxes_endpoint): + client = self.create_client(endpoint=devboxes_endpoint) + response = client.begin_restart_dev_box( + project_name="str", + user_id="str", + dev_box_name="str", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy + def test_get_remote_connection(self, devboxes_endpoint): + client = self.create_client(endpoint=devboxes_endpoint) + response = client.get_remote_connection( + project_name="str", + user_id="str", + dev_box_name="str", + ) + + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy + def test_list_dev_box_actions(self, devboxes_endpoint): + client = self.create_client(endpoint=devboxes_endpoint) + response = client.list_dev_box_actions( + project_name="str", + user_id="str", + dev_box_name="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy + def test_get_dev_box_action(self, devboxes_endpoint): + client = self.create_client(endpoint=devboxes_endpoint) + response = client.get_dev_box_action( + project_name="str", + user_id="str", + dev_box_name="str", + action_name="str", + ) + + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy + def test_skip_action(self, devboxes_endpoint): + client = self.create_client(endpoint=devboxes_endpoint) + response = client.skip_action( + project_name="str", + user_id="str", + dev_box_name="str", + action_name="str", + ) + + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy + def test_delay_action(self, devboxes_endpoint): + client = self.create_client(endpoint=devboxes_endpoint) + response = client.delay_action( + project_name="str", + user_id="str", + dev_box_name="str", + action_name="str", + delay_until="2020-02-20 00:00:00", + ) + + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy + def test_delay_all_actions(self, devboxes_endpoint): + client = self.create_client(endpoint=devboxes_endpoint) + response = client.delay_all_actions( + project_name="str", + user_id="str", + dev_box_name="str", + delay_until="2020-02-20 00:00:00", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/devcenter/azure-developer-devcenter/generated_tests/test_dev_boxes_async.py b/sdk/devcenter/azure-developer-devcenter/generated_tests/test_dev_boxes_async.py new file mode 100644 index 00000000000..03bec3816b0 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_tests/test_dev_boxes_async.py @@ -0,0 +1,290 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils.aio import recorded_by_proxy_async +from testpreparer import DevBoxesPreparer +from testpreparer_async import DevBoxesClientTestBaseAsync + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestDevBoxesAsync(DevBoxesClientTestBaseAsync): + @DevBoxesPreparer() + @recorded_by_proxy_async + async def test_list_pools(self, devboxes_endpoint): + client = self.create_async_client(endpoint=devboxes_endpoint) + response = client.list_pools( + project_name="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy_async + async def test_get_pool(self, devboxes_endpoint): + client = self.create_async_client(endpoint=devboxes_endpoint) + response = await client.get_pool( + project_name="str", + pool_name="str", + ) + + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy_async + async def test_list_schedules(self, devboxes_endpoint): + client = self.create_async_client(endpoint=devboxes_endpoint) + response = client.list_schedules( + project_name="str", + pool_name="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy_async + async def test_get_schedule(self, devboxes_endpoint): + client = self.create_async_client(endpoint=devboxes_endpoint) + response = await client.get_schedule( + project_name="str", + pool_name="str", + schedule_name="str", + ) + + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy_async + async def test_list_all_dev_boxes(self, devboxes_endpoint): + client = self.create_async_client(endpoint=devboxes_endpoint) + response = client.list_all_dev_boxes() + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy_async + async def test_list_all_dev_boxes_by_user(self, devboxes_endpoint): + client = self.create_async_client(endpoint=devboxes_endpoint) + response = client.list_all_dev_boxes_by_user( + user_id="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy_async + async def test_list_dev_boxes(self, devboxes_endpoint): + client = self.create_async_client(endpoint=devboxes_endpoint) + response = client.list_dev_boxes( + project_name="str", + user_id="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy_async + async def test_get_dev_box(self, devboxes_endpoint): + client = self.create_async_client(endpoint=devboxes_endpoint) + response = await client.get_dev_box( + project_name="str", + user_id="str", + dev_box_name="str", + ) + + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy_async + async def test_begin_create_dev_box(self, devboxes_endpoint): + client = self.create_async_client(endpoint=devboxes_endpoint) + response = await ( + await client.begin_create_dev_box( + project_name="str", + user_id="str", + dev_box_name="str", + body={ + "name": "str", + "poolName": "str", + "actionState": "str", + "createdTime": "2020-02-20 00:00:00", + "error": ~azure.core.ODataV4Format, + "hardwareProfile": {"memoryGB": 0, "skuName": "str", "vCPUs": 0}, + "hibernateSupport": "str", + "imageReference": { + "name": "str", + "operatingSystem": "str", + "osBuildNumber": "str", + "publishedDate": "2020-02-20 00:00:00", + "version": "str", + }, + "localAdministrator": "str", + "location": "str", + "osType": "str", + "powerState": "str", + "projectName": "str", + "provisioningState": "str", + "storageProfile": {"osDisk": {"diskSizeGB": 0}}, + "uniqueId": "str", + "user": "str", + }, + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy_async + async def test_begin_delete_dev_box(self, devboxes_endpoint): + client = self.create_async_client(endpoint=devboxes_endpoint) + response = await ( + await client.begin_delete_dev_box( + project_name="str", + user_id="str", + dev_box_name="str", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy_async + async def test_begin_start_dev_box(self, devboxes_endpoint): + client = self.create_async_client(endpoint=devboxes_endpoint) + response = await ( + await client.begin_start_dev_box( + project_name="str", + user_id="str", + dev_box_name="str", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy_async + async def test_begin_stop_dev_box(self, devboxes_endpoint): + client = self.create_async_client(endpoint=devboxes_endpoint) + response = await ( + await client.begin_stop_dev_box( + project_name="str", + user_id="str", + dev_box_name="str", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy_async + async def test_begin_restart_dev_box(self, devboxes_endpoint): + client = self.create_async_client(endpoint=devboxes_endpoint) + response = await ( + await client.begin_restart_dev_box( + project_name="str", + user_id="str", + dev_box_name="str", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy_async + async def test_get_remote_connection(self, devboxes_endpoint): + client = self.create_async_client(endpoint=devboxes_endpoint) + response = await client.get_remote_connection( + project_name="str", + user_id="str", + dev_box_name="str", + ) + + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy_async + async def test_list_dev_box_actions(self, devboxes_endpoint): + client = self.create_async_client(endpoint=devboxes_endpoint) + response = client.list_dev_box_actions( + project_name="str", + user_id="str", + dev_box_name="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy_async + async def test_get_dev_box_action(self, devboxes_endpoint): + client = self.create_async_client(endpoint=devboxes_endpoint) + response = await client.get_dev_box_action( + project_name="str", + user_id="str", + dev_box_name="str", + action_name="str", + ) + + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy_async + async def test_skip_action(self, devboxes_endpoint): + client = self.create_async_client(endpoint=devboxes_endpoint) + response = await client.skip_action( + project_name="str", + user_id="str", + dev_box_name="str", + action_name="str", + ) + + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy_async + async def test_delay_action(self, devboxes_endpoint): + client = self.create_async_client(endpoint=devboxes_endpoint) + response = await client.delay_action( + project_name="str", + user_id="str", + dev_box_name="str", + action_name="str", + delay_until="2020-02-20 00:00:00", + ) + + # please add some check logic here by yourself + # ... + + @DevBoxesPreparer() + @recorded_by_proxy_async + async def test_delay_all_actions(self, devboxes_endpoint): + client = self.create_async_client(endpoint=devboxes_endpoint) + response = client.delay_all_actions( + project_name="str", + user_id="str", + dev_box_name="str", + delay_until="2020-02-20 00:00:00", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/devcenter/azure-developer-devcenter/generated_tests/test_dev_center.py b/sdk/devcenter/azure-developer-devcenter/generated_tests/test_dev_center.py new file mode 100644 index 00000000000..91c08fcd665 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_tests/test_dev_center.py @@ -0,0 +1,33 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils import recorded_by_proxy +from testpreparer import DevCenterClientTestBase, DevCenterPreparer + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestDevCenter(DevCenterClientTestBase): + @DevCenterPreparer() + @recorded_by_proxy + def test_list_projects(self, devcenter_endpoint): + client = self.create_client(endpoint=devcenter_endpoint) + response = client.list_projects() + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @DevCenterPreparer() + @recorded_by_proxy + def test_get_project(self, devcenter_endpoint): + client = self.create_client(endpoint=devcenter_endpoint) + response = client.get_project( + project_name="str", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/devcenter/azure-developer-devcenter/generated_tests/test_dev_center_async.py b/sdk/devcenter/azure-developer-devcenter/generated_tests/test_dev_center_async.py new file mode 100644 index 00000000000..e066609a5be --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_tests/test_dev_center_async.py @@ -0,0 +1,34 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils.aio import recorded_by_proxy_async +from testpreparer import DevCenterPreparer +from testpreparer_async import DevCenterClientTestBaseAsync + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestDevCenterAsync(DevCenterClientTestBaseAsync): + @DevCenterPreparer() + @recorded_by_proxy_async + async def test_list_projects(self, devcenter_endpoint): + client = self.create_async_client(endpoint=devcenter_endpoint) + response = client.list_projects() + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @DevCenterPreparer() + @recorded_by_proxy_async + async def test_get_project(self, devcenter_endpoint): + client = self.create_async_client(endpoint=devcenter_endpoint) + response = await client.get_project( + project_name="str", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/devcenter/azure-developer-devcenter/generated_tests/testpreparer.py b/sdk/devcenter/azure-developer-devcenter/generated_tests/testpreparer.py new file mode 100644 index 00000000000..adccf2afca0 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_tests/testpreparer.py @@ -0,0 +1,60 @@ +# 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 azure.developer.devcenter import DeploymentEnvironmentsClient, DevBoxesClient, DevCenterClient +from devtools_testutils import AzureRecordedTestCase, PowerShellPreparer +import functools + + +class DevCenterClientTestBase(AzureRecordedTestCase): + + def create_client(self, endpoint): + credential = self.get_credential(DevCenterClient) + return self.create_client_from_credential( + DevCenterClient, + credential=credential, + endpoint=endpoint, + ) + + +DevCenterPreparer = functools.partial( + PowerShellPreparer, "devcenter", devcenter_endpoint="https://fake_devcenter_endpoint.com" +) + + +class DevBoxesClientTestBase(AzureRecordedTestCase): + + def create_client(self, endpoint): + credential = self.get_credential(DevBoxesClient) + return self.create_client_from_credential( + DevBoxesClient, + credential=credential, + endpoint=endpoint, + ) + + +DevBoxesPreparer = functools.partial( + PowerShellPreparer, "devboxes", devboxes_endpoint="https://fake_devboxes_endpoint.com" +) + + +class DeploymentEnvironmentsClientTestBase(AzureRecordedTestCase): + + def create_client(self, endpoint): + credential = self.get_credential(DeploymentEnvironmentsClient) + return self.create_client_from_credential( + DeploymentEnvironmentsClient, + credential=credential, + endpoint=endpoint, + ) + + +DeploymentEnvironmentsPreparer = functools.partial( + PowerShellPreparer, + "deploymentenvironments", + deploymentenvironments_endpoint="https://fake_deploymentenvironments_endpoint.com", +) diff --git a/sdk/devcenter/azure-developer-devcenter/generated_tests/testpreparer_async.py b/sdk/devcenter/azure-developer-devcenter/generated_tests/testpreparer_async.py new file mode 100644 index 00000000000..8adeb8ade37 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_tests/testpreparer_async.py @@ -0,0 +1,42 @@ +# 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 azure.developer.devcenter.aio import DeploymentEnvironmentsClient, DevBoxesClient, DevCenterClient +from devtools_testutils import AzureRecordedTestCase + + +class DevCenterClientTestBaseAsync(AzureRecordedTestCase): + + def create_async_client(self, endpoint): + credential = self.get_credential(DevCenterClient, is_async=True) + return self.create_client_from_credential( + DevCenterClient, + credential=credential, + endpoint=endpoint, + ) + + +class DevBoxesClientTestBaseAsync(AzureRecordedTestCase): + + def create_async_client(self, endpoint): + credential = self.get_credential(DevBoxesClient, is_async=True) + return self.create_client_from_credential( + DevBoxesClient, + credential=credential, + endpoint=endpoint, + ) + + +class DeploymentEnvironmentsClientTestBaseAsync(AzureRecordedTestCase): + + def create_async_client(self, endpoint): + credential = self.get_credential(DeploymentEnvironmentsClient, is_async=True) + return self.create_client_from_credential( + DeploymentEnvironmentsClient, + credential=credential, + endpoint=endpoint, + ) 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 index c09e6cd0889..76f7fd09939 100644 --- 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 @@ -90,7 +90,9 @@ async def environment_create_and_delete_async(): # List available Environment Definitions environment_definitions = [] - async for environment_definition in client.list_environment_definitions_by_catalog(target_project_name, target_catalog_name): + 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: ") @@ -141,8 +143,10 @@ async def environment_create_and_delete_async(): 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__': + +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 index f07a385725d..3c22d6be12b 100644 --- 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 @@ -47,6 +47,7 @@ 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: @@ -75,7 +76,9 @@ async def dev_box_action_async(): 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") + 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}.") @@ -92,8 +95,10 @@ async def dev_box_action_async(): 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__': + +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 index a2335ad58a1..5c2dd1b02fd 100644 --- 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 @@ -45,6 +45,7 @@ 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: @@ -66,12 +67,12 @@ async def dev_box_create_connect_delete_async(): 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): @@ -80,35 +81,37 @@ async def dev_box_create_connect_delete_async(): 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__': + +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 index 8cff68746ac..dad191d28b5 100644 --- 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 @@ -46,6 +46,7 @@ 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: @@ -67,35 +68,37 @@ async def dev_box_restart_stop_start_async(): 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__': + +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 index 70836ae439c..49d102565fb 100644 --- a/sdk/devcenter/azure-developer-devcenter/samples/create_client_sample.py +++ b/sdk/devcenter/azure-developer-devcenter/samples/create_client_sample.py @@ -39,6 +39,7 @@ 1) DEVCENTER_ENDPOINT - the endpoint for your devcenter """ + def create_dev_center_client(): # [START create_dev_center_client] import os @@ -57,5 +58,6 @@ def create_dev_center_client(): 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 index 4ffaf5d1260..7e0fef55b9e 100644 --- a/sdk/devcenter/azure-developer-devcenter/samples/deployment_environments_sample.py +++ b/sdk/devcenter/azure-developer-devcenter/samples/deployment_environments_sample.py @@ -40,6 +40,7 @@ 1) DEVCENTER_ENDPOINT - the endpoint for your devcenter """ + def environment_create_and_delete(): # [START environment_create_and_delete] import os diff --git a/sdk/devcenter/azure-developer-devcenter/samples/dev_box_create_sample.py b/sdk/devcenter/azure-developer-devcenter/samples/dev_box_create_sample.py index c8cefb4c41c..3a181bbfca5 100644 --- a/sdk/devcenter/azure-developer-devcenter/samples/dev_box_create_sample.py +++ b/sdk/devcenter/azure-developer-devcenter/samples/dev_box_create_sample.py @@ -40,6 +40,7 @@ 1) DEVCENTER_ENDPOINT - the endpoint for your devcenter """ + def dev_box_create_connect_delete(): # [START dev_box_create_connect_delete] import os @@ -102,5 +103,6 @@ def dev_box_create_connect_delete(): print(f"Completed deletion for the dev box with status {delete_result.status}") # [END dev_box_create_connect_delete] + if __name__ == "__main__": dev_box_create_connect_delete() diff --git a/sdk/devcenter/azure-developer-devcenter/tests/conftest.py b/sdk/devcenter/azure-developer-devcenter/tests/conftest.py index 07e19a00eff..a759437b05a 100644 --- a/sdk/devcenter/azure-developer-devcenter/tests/conftest.py +++ b/sdk/devcenter/azure-developer-devcenter/tests/conftest.py @@ -15,19 +15,23 @@ ) import pytest + # autouse=True will trigger this fixture on each pytest run, even if it's not explicitly used by a test method @pytest.fixture(scope="session", autouse=True) 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") + 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(_): 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 index d5023a07a7e..5eed70e20e0 100644 --- a/sdk/devcenter/azure-developer-devcenter/tests/test_devcenter_operations_async.py +++ b/sdk/devcenter/azure-developer-devcenter/tests/test_devcenter_operations_async.py @@ -139,13 +139,15 @@ async def test_create_dev_box_async(self, **kwargs): async with client: # Create DevBox - create_devbox_response = await client.begin_create_dev_box(project_name, user, devbox_name, {"poolName": pool_name}) + 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 @@ -160,7 +162,9 @@ async def test_dev_box_action_async(self, **kwargs): async with client: # Actions - action_response = await client.get_dev_box_action(project_name, default_user, devbox_name, "schedule-default") + 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" @@ -172,7 +176,9 @@ async def test_dev_box_action_async(self, **kwargs): 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): + 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 @@ -247,7 +253,7 @@ async def test_list_all_dev_boxes_by_user_async(self, **kwargs): 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): @@ -320,7 +326,7 @@ async def test_get_catalog_async(self, **kwargs): 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 @@ -340,7 +346,7 @@ async def test_list_catalogs_async(self, **kwargs): 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 @@ -356,7 +362,9 @@ async def test_get_environment_definition_async(self, **kwargs): client = self.create_client(endpoint) async with client: - env_definition_response = await client.get_environment_definition(project_name, catalog_name, env_definition_name) + env_definition_response = await client.get_environment_definition( + project_name, catalog_name, env_definition_name + ) assert env_definition_response.name == env_definition_name @DevcenterPowerShellPreparer() @@ -368,13 +376,13 @@ async def test_list_environment_definitions_async(self, **kwargs): 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 @@ -443,26 +451,26 @@ async def test_environments_async(self, **kwargs): ) 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 + assert delete_result.status == OperationStatus.SUCCEEDED diff --git a/sdk/devcenter/azure-developer-devcenter/tsp-location.yaml b/sdk/devcenter/azure-developer-devcenter/tsp-location.yaml index c0db4e4e25d..43ca67f8eba 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: d17b385b2e840c541b50f1d415dab6fd408d0814 +commit: 3b3adcf656a508f2806ab4c2596d50b3db7dcfaf repo: Azure/azure-rest-api-specs -cleanup: true +additionalDirectories: