diff --git a/sdk/devcenter/azure-developer-devcenter/MANIFEST.in b/sdk/devcenter/azure-developer-devcenter/MANIFEST.in index 2ff00927e078..9b28a6779610 100644 --- a/sdk/devcenter/azure-developer-devcenter/MANIFEST.in +++ b/sdk/devcenter/azure-developer-devcenter/MANIFEST.in @@ -4,4 +4,4 @@ include azure/developer/devcenter/py.typed recursive-include tests *.py recursive-include samples *.py *.md include azure/__init__.py -include azure/developer/__init__.py \ No newline at end of file +include azure/developer/__init__.py diff --git a/sdk/devcenter/azure-developer-devcenter/_meta.json b/sdk/devcenter/azure-developer-devcenter/_meta.json new file mode 100644 index 000000000000..c5db093f3634 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/_meta.json @@ -0,0 +1,6 @@ +{ + "commit": "0660a73ea14775552af66f95d92e1a0446a04b54", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "typespec_src": "specification/devcenter/DevCenter", + "@azure-tools/typespec-python": "0.44.1" +} \ 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 000000000000..d9f11e2d9998 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/apiview-properties.json @@ -0,0 +1,102 @@ +{ + "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.aio.DevCenterClient.list_projects": "SdkCustomizations.DevCenterClientOperations.listProjects", + "azure.developer.devcenter.DevCenterClient.get_project": "SdkCustomizations.DevCenterClientOperations.getProject", + "azure.developer.devcenter.aio.DevCenterClient.get_project": "SdkCustomizations.DevCenterClientOperations.getProject", + "azure.developer.devcenter.DevBoxesClient.list_pools": "SdkCustomizations.DevBoxesClientOperations.listPools", + "azure.developer.devcenter.aio.DevBoxesClient.list_pools": "SdkCustomizations.DevBoxesClientOperations.listPools", + "azure.developer.devcenter.DevBoxesClient.get_pool": "SdkCustomizations.DevBoxesClientOperations.getPool", + "azure.developer.devcenter.aio.DevBoxesClient.get_pool": "SdkCustomizations.DevBoxesClientOperations.getPool", + "azure.developer.devcenter.DevBoxesClient.list_schedules": "SdkCustomizations.DevBoxesClientOperations.listSchedules", + "azure.developer.devcenter.aio.DevBoxesClient.list_schedules": "SdkCustomizations.DevBoxesClientOperations.listSchedules", + "azure.developer.devcenter.DevBoxesClient.get_schedule": "SdkCustomizations.DevBoxesClientOperations.getSchedule", + "azure.developer.devcenter.aio.DevBoxesClient.get_schedule": "SdkCustomizations.DevBoxesClientOperations.getSchedule", + "azure.developer.devcenter.DevBoxesClient.list_all_dev_boxes": "SdkCustomizations.DevBoxesClientOperations.listAllDevBoxes", + "azure.developer.devcenter.aio.DevBoxesClient.list_all_dev_boxes": "SdkCustomizations.DevBoxesClientOperations.listAllDevBoxes", + "azure.developer.devcenter.DevBoxesClient.list_all_dev_boxes_by_user": "SdkCustomizations.DevBoxesClientOperations.listAllDevBoxesByUser", + "azure.developer.devcenter.aio.DevBoxesClient.list_all_dev_boxes_by_user": "SdkCustomizations.DevBoxesClientOperations.listAllDevBoxesByUser", + "azure.developer.devcenter.DevBoxesClient.list_dev_boxes": "SdkCustomizations.DevBoxesClientOperations.listDevBoxes", + "azure.developer.devcenter.aio.DevBoxesClient.list_dev_boxes": "SdkCustomizations.DevBoxesClientOperations.listDevBoxes", + "azure.developer.devcenter.DevBoxesClient.get_dev_box": "SdkCustomizations.DevBoxesClientOperations.getDevBox", + "azure.developer.devcenter.aio.DevBoxesClient.get_dev_box": "SdkCustomizations.DevBoxesClientOperations.getDevBox", + "azure.developer.devcenter.DevBoxesClient.begin_create_dev_box": "SdkCustomizations.DevBoxesClientOperations.createDevBox", + "azure.developer.devcenter.aio.DevBoxesClient.begin_create_dev_box": "SdkCustomizations.DevBoxesClientOperations.createDevBox", + "azure.developer.devcenter.DevBoxesClient.begin_delete_dev_box": "SdkCustomizations.DevBoxesClientOperations.deleteDevBox", + "azure.developer.devcenter.aio.DevBoxesClient.begin_delete_dev_box": "SdkCustomizations.DevBoxesClientOperations.deleteDevBox", + "azure.developer.devcenter.DevBoxesClient.begin_start_dev_box": "SdkCustomizations.DevBoxesClientOperations.startDevBox", + "azure.developer.devcenter.aio.DevBoxesClient.begin_start_dev_box": "SdkCustomizations.DevBoxesClientOperations.startDevBox", + "azure.developer.devcenter.DevBoxesClient.begin_stop_dev_box": "SdkCustomizations.DevBoxesClientOperations.stopDevBox", + "azure.developer.devcenter.aio.DevBoxesClient.begin_stop_dev_box": "SdkCustomizations.DevBoxesClientOperations.stopDevBox", + "azure.developer.devcenter.DevBoxesClient.begin_restart_dev_box": "SdkCustomizations.DevBoxesClientOperations.restartDevBox", + "azure.developer.devcenter.aio.DevBoxesClient.begin_restart_dev_box": "SdkCustomizations.DevBoxesClientOperations.restartDevBox", + "azure.developer.devcenter.DevBoxesClient.get_remote_connection": "SdkCustomizations.DevBoxesClientOperations.getRemoteConnection", + "azure.developer.devcenter.aio.DevBoxesClient.get_remote_connection": "SdkCustomizations.DevBoxesClientOperations.getRemoteConnection", + "azure.developer.devcenter.DevBoxesClient.list_dev_box_actions": "SdkCustomizations.DevBoxesClientOperations.listDevBoxActions", + "azure.developer.devcenter.aio.DevBoxesClient.list_dev_box_actions": "SdkCustomizations.DevBoxesClientOperations.listDevBoxActions", + "azure.developer.devcenter.DevBoxesClient.get_dev_box_action": "SdkCustomizations.DevBoxesClientOperations.getDevBoxAction", + "azure.developer.devcenter.aio.DevBoxesClient.get_dev_box_action": "SdkCustomizations.DevBoxesClientOperations.getDevBoxAction", + "azure.developer.devcenter.DevBoxesClient.skip_action": "SdkCustomizations.DevBoxesClientOperations.skipAction", + "azure.developer.devcenter.aio.DevBoxesClient.skip_action": "SdkCustomizations.DevBoxesClientOperations.skipAction", + "azure.developer.devcenter.DevBoxesClient.delay_action": "SdkCustomizations.DevBoxesClientOperations.delayAction", + "azure.developer.devcenter.aio.DevBoxesClient.delay_action": "SdkCustomizations.DevBoxesClientOperations.delayAction", + "azure.developer.devcenter.DevBoxesClient.delay_all_actions": "SdkCustomizations.DevBoxesClientOperations.delayAllActions", + "azure.developer.devcenter.aio.DevBoxesClient.delay_all_actions": "SdkCustomizations.DevBoxesClientOperations.delayAllActions", + "azure.developer.devcenter.DeploymentEnvironmentsClient.list_all_environments": "SdkCustomizations.EnvironmentClientOperations.listAllEnvironments", + "azure.developer.devcenter.aio.DeploymentEnvironmentsClient.list_all_environments": "SdkCustomizations.EnvironmentClientOperations.listAllEnvironments", + "azure.developer.devcenter.DeploymentEnvironmentsClient.list_environments": "SdkCustomizations.EnvironmentClientOperations.listEnvironments", + "azure.developer.devcenter.aio.DeploymentEnvironmentsClient.list_environments": "SdkCustomizations.EnvironmentClientOperations.listEnvironments", + "azure.developer.devcenter.DeploymentEnvironmentsClient.get_environment": "SdkCustomizations.EnvironmentClientOperations.getEnvironment", + "azure.developer.devcenter.aio.DeploymentEnvironmentsClient.get_environment": "SdkCustomizations.EnvironmentClientOperations.getEnvironment", + "azure.developer.devcenter.DeploymentEnvironmentsClient.begin_create_or_update_environment": "SdkCustomizations.EnvironmentClientOperations.createOrUpdateEnvironment", + "azure.developer.devcenter.aio.DeploymentEnvironmentsClient.begin_create_or_update_environment": "SdkCustomizations.EnvironmentClientOperations.createOrUpdateEnvironment", + "azure.developer.devcenter.DeploymentEnvironmentsClient.begin_delete_environment": "SdkCustomizations.EnvironmentClientOperations.deleteEnvironment", + "azure.developer.devcenter.aio.DeploymentEnvironmentsClient.begin_delete_environment": "SdkCustomizations.EnvironmentClientOperations.deleteEnvironment", + "azure.developer.devcenter.DeploymentEnvironmentsClient.list_catalogs": "SdkCustomizations.EnvironmentClientOperations.listCatalogs", + "azure.developer.devcenter.aio.DeploymentEnvironmentsClient.list_catalogs": "SdkCustomizations.EnvironmentClientOperations.listCatalogs", + "azure.developer.devcenter.DeploymentEnvironmentsClient.get_catalog": "SdkCustomizations.EnvironmentClientOperations.getCatalog", + "azure.developer.devcenter.aio.DeploymentEnvironmentsClient.get_catalog": "SdkCustomizations.EnvironmentClientOperations.getCatalog", + "azure.developer.devcenter.DeploymentEnvironmentsClient.list_environment_definitions": "SdkCustomizations.EnvironmentClientOperations.listEnvironmentDefinitions", + "azure.developer.devcenter.aio.DeploymentEnvironmentsClient.list_environment_definitions": "SdkCustomizations.EnvironmentClientOperations.listEnvironmentDefinitions", + "azure.developer.devcenter.DeploymentEnvironmentsClient.list_environment_definitions_by_catalog": "SdkCustomizations.EnvironmentClientOperations.listEnvironmentDefinitionsByCatalog", + "azure.developer.devcenter.aio.DeploymentEnvironmentsClient.list_environment_definitions_by_catalog": "SdkCustomizations.EnvironmentClientOperations.listEnvironmentDefinitionsByCatalog", + "azure.developer.devcenter.DeploymentEnvironmentsClient.get_environment_definition": "SdkCustomizations.EnvironmentClientOperations.getEnvironmentDefinition", + "azure.developer.devcenter.aio.DeploymentEnvironmentsClient.get_environment_definition": "SdkCustomizations.EnvironmentClientOperations.getEnvironmentDefinition", + "azure.developer.devcenter.DeploymentEnvironmentsClient.list_environment_types": "SdkCustomizations.EnvironmentClientOperations.listEnvironmentTypes", + "azure.developer.devcenter.aio.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 7590310c9bda..6e828f9acd22 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 df902c7477b9..d6c95a87dd9c 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,107 @@ 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 ._serialization import Deserializer, Serializer +from ._configuration import ( + DeploymentEnvironmentsClientConfiguration, + DevBoxesClientConfiguration, + DevCenterClientConfiguration, +) +from ._operations import ( + DeploymentEnvironmentsClientOperationsMixin, + DevBoxesClientOperationsMixin, + DevCenterClientOperationsMixin, +) +from ._utils.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 +122,86 @@ 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 +254,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 e37ae956cc25..5779f3042654 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/_operations/__init__.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_operations/__init__.py index 32322330a2b5..bb0ba294788e 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 825ae666ecff..896eb6b85d29 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. @@ -6,19 +6,22 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from collections.abc import MutableMapping import datetime 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 import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.paging import ItemPaged @@ -30,17 +33,18 @@ from azure.core.utils import case_insensitive_dict from .. import models as _models -from .._model_base import SdkJSONEncoder, _deserialize -from .._serialization import Serializer -from .._vendor import DevCenterClientMixinABC - -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 .._configuration import ( + DeploymentEnvironmentsClientConfiguration, + DevBoxesClientConfiguration, + DevCenterClientConfiguration, +) +from .._utils.model_base import SdkJSONEncoder, _deserialize +from .._utils.serialization import Serializer +from .._utils.utils import ClientMixinABC + T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +JSON = MutableMapping[str, Any] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False @@ -89,7 +93,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 +117,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 +142,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 +167,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 +195,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 +214,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 +240,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 +265,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 +293,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 +324,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 +352,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 +380,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 +410,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 +438,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 +466,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 +494,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 +523,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 +552,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 +588,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 +617,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 +643,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 +670,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 +698,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 +729,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 +757,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 +783,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 +810,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 +836,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 +863,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 +891,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 +917,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(ClientMixinABC[PipelineClient, DevCenterClientConfiguration]): @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, @@ -983,7 +979,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.Project], deserialized["value"]) + list_of_elem = _deserialize(List[_models.Project], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -998,8 +994,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 +1003,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 +1010,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 +1044,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 +1061,13 @@ def get_project(self, project_name: str, **kwargs: Any) -> _models.Project: return deserialized # type: ignore + +class DevBoxesClientOperationsMixin( # pylint: disable=too-many-public-methods + ClientMixinABC[PipelineClient, DevBoxesClientConfiguration] +): + @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 +1075,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 +1092,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, @@ -1202,7 +1129,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.Pool], deserialized["value"]) + list_of_elem = _deserialize(List[_models.Pool], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -1217,8 +1144,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 +1153,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 +1162,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 +1176,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 +1197,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 +1225,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 +1242,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, @@ -1431,7 +1280,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.Schedule], deserialized["value"]) + list_of_elem = _deserialize(List[_models.Schedule], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -1446,8 +1295,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 +1315,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 +1329,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 +1351,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 +1370,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 +1392,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, @@ -1680,7 +1428,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.DevBox], deserialized["value"]) + list_of_elem = _deserialize(List[_models.DevBox], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -1695,8 +1443,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 +1452,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 +1460,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 +1477,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, @@ -1854,7 +1514,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.DevBox], deserialized["value"]) + list_of_elem = _deserialize(List[_models.DevBox], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -1869,8 +1529,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 +1538,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 +1548,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 +1565,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, @@ -2031,7 +1603,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.DevBox], deserialized["value"]) + list_of_elem = _deserialize(List[_models.DevBox], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -2046,8 +1618,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 +1627,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 +1639,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 +1653,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 +1675,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 +1699,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 +1712,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 +1721,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 +1736,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 +1744,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 +1776,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 +1795,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 +1808,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 +1827,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 +1840,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 +1859,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 +1870,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 +1887,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 +1908,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 +1943,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 +1955,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 +1970,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 +1978,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 +1992,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 +2002,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 +2012,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 +2033,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 +2053,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 +2075,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 +2090,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 +2098,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 +2116,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 +2126,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 +2147,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 +2167,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 +2189,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 +2205,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 +2213,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 +2233,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 +2245,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 +2267,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 +2287,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 +2309,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 +2324,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 +2332,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 +2352,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 +2362,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 +2383,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 +2403,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 +2427,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 +2441,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 +2463,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 +2496,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 +2513,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, @@ -3769,7 +2552,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.DevBoxAction], deserialized["value"]) + list_of_elem = _deserialize(List[_models.DevBoxAction], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -3784,8 +2567,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 +2592,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 +2606,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 +2629,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 +2647,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 +2665,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 +2678,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 +2700,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 +2707,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 +2728,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 +2748,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 +2772,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 +2790,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 +2802,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 +2825,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, @@ -4151,7 +2865,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.DevBoxActionDelayResult], deserialized["value"]) + list_of_elem = _deserialize(List[_models.DevBoxActionDelayResult], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -4166,8 +2880,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 +2887,13 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) + +class DeploymentEnvironmentsClientOperationsMixin( # pylint: disable=name-too-long + ClientMixinABC[PipelineClient, DeploymentEnvironmentsClientConfiguration] +): + @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 +2901,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 +2918,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, @@ -4277,7 +2955,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.Environment], deserialized["value"]) + list_of_elem = _deserialize(List[_models.Environment], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -4292,8 +2970,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 +2979,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 +2989,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 +3006,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, @@ -4407,7 +3044,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.Environment], deserialized["value"]) + list_of_elem = _deserialize(List[_models.Environment], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -4422,8 +3059,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 +3070,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 +3082,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 +3096,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 +3118,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 +3142,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 +3155,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 +3164,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 +3179,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 +3187,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 +3215,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 +3233,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 +3246,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 +3264,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 +3277,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 +3295,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 +3306,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 +3322,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 +3343,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 +3383,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 +3395,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 +3410,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 +3418,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 +3432,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 +3442,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 +3452,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 +3473,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 +3493,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 +3510,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 +3527,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, @@ -5241,7 +3564,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.Catalog], deserialized["value"]) + list_of_elem = _deserialize(List[_models.Catalog], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -5256,8 +3579,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 +3597,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 +3611,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 +3632,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 +3653,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 +3660,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 +3677,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, @@ -5435,7 +3714,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.EnvironmentDefinition], deserialized["value"]) + list_of_elem = _deserialize(List[_models.EnvironmentDefinition], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -5450,8 +3729,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 +3740,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 +3749,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 +3766,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, @@ -5564,7 +3804,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.EnvironmentDefinition], deserialized["value"]) + list_of_elem = _deserialize(List[_models.EnvironmentDefinition], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -5579,8 +3819,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 +3830,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 +3841,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 +3855,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 +3877,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 +3896,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 +3920,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, @@ -5767,7 +3957,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.EnvironmentType], deserialized["value"]) + list_of_elem = _deserialize(List[_models.EnvironmentType], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -5782,8 +3972,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/_operations/_patch.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_operations/_patch.py index f7dd32510333..8bcb627aa475 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_operations/_patch.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_operations/_patch.py @@ -1,7 +1,8 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# 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. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_patch.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_patch.py index f7dd32510333..8bcb627aa475 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_patch.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_patch.py @@ -1,7 +1,8 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# 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. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_utils/__init__.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_utils/__init__.py new file mode 100644 index 000000000000..8026245c2abc --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_utils/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------- +# 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. +# -------------------------------------------------------------------------- diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_model_base.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_utils/model_base.py similarity index 60% rename from sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_model_base.py rename to sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_utils/model_base.py index 4b0f59f73e4c..49d5c7259389 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_model_base.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_utils/model_base.py @@ -1,11 +1,14 @@ +# 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. +# 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=protected-access, arguments-differ, signature-differs, broad-except +# pylint: disable=protected-access, broad-except +import copy import calendar import decimal import functools @@ -18,6 +21,8 @@ import email.utils from datetime import datetime, date, time, timedelta, timezone from json import JSONEncoder +import xml.etree.ElementTree as ET +from collections.abc import MutableMapping from typing_extensions import Self import isodate from azure.core.exceptions import DeserializationError @@ -25,11 +30,6 @@ from azure.core.pipeline import PipelineResponse from azure.core.serialization import _Null -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping - _LOGGER = logging.getLogger(__name__) __all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] @@ -122,7 +122,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 +285,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 +312,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): @@ -336,7 +344,7 @@ def _get_model(module_name: str, model_name: str): _UNSET = object() -class _MyMutableMapping(MutableMapping[str, typing.Any]): # pylint: disable=unsubscriptable-object +class _MyMutableMapping(MutableMapping[str, typing.Any]): def __init__(self, data: typing.Dict[str, typing.Any]) -> None: self._data = data @@ -362,50 +370,97 @@ 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: return default @typing.overload - def pop(self, key: str) -> typing.Any: ... + def pop(self, key: str) -> typing.Any: ... # pylint: disable=arguments-differ @typing.overload - def pop(self, key: str, default: _T) -> _T: ... + def pop(self, key: str, default: _T) -> _T: ... # pylint: disable=signature-differs @typing.overload - def pop(self, key: str, default: typing.Any) -> typing.Any: ... + def pop(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs 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: + def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ + """ + 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 def setdefault(self, key: str, default: None = None) -> None: ... @typing.overload - def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... + def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs 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 +495,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 +529,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 +549,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 +618,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()) - - return super().__new__(cls) # pylint: disable=no-value-for-parameter + 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) 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 # pylint: disable=no-member + 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 +689,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 +744,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 +766,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 +798,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 +819,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 +858,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 +892,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 +938,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 +978,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 +989,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 +1040,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 +1049,7 @@ def rest_field( default=default, format=format, is_multipart_file_input=is_multipart_file_input, + xml=xml, ) @@ -871,5 +1057,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, 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: - return _RestField(name=name, type=type, is_discriminator=True) + 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/_serialization.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_utils/serialization.py similarity index 82% rename from sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_serialization.py rename to sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_utils/serialization.py index 2f781d740827..eb86ea23c965 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_serialization.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_utils/serialization.py @@ -1,30 +1,12 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 # -------------------------------------------------------------------------- -# # Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# +# 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: skip-file # pyright: reportUnnecessaryTypeIgnoreComment=false from base64 import b64decode, b64encode @@ -48,11 +30,8 @@ IO, Mapping, Callable, - TypeVar, MutableMapping, - Type, List, - Mapping, ) try: @@ -62,13 +41,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 +70,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 +93,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 +125,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 +136,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 +165,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 +244,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 +280,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 +304,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 +340,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 +358,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 +390,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 + :raises DeserializationError: if something went wrong + :rtype: Self """ deserializer = Deserializer(cls._infer_class_models()) deserializer.key_extractors = ( # type: ignore @@ -446,21 +414,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 +471,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 +512,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 +532,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 +567,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 +610,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 +642,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 +681,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 +690,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 +708,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 +738,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 +760,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 +784,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 +800,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 +819,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 +852,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 +862,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 +923,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 +948,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 +956,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 +981,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 +1012,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 +1074,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 +1089,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 +1127,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 +1159,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 +1174,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 +1199,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 +1222,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 +1281,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 +1333,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( + 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 +1355,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 +1364,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 +1402,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 +1443,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 +1479,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 +1507,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 +1520,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 +1535,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 +1558,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 +1587,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 +1624,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 +1647,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 +1671,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 +1695,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 +1706,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 +1746,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 +1757,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 +1769,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 +1793,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 +1807,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 +1819,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 +1830,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 +1848,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 +1861,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 +1877,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 +1894,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 +1907,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 +1918,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 +1941,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 +1956,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 +2009,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 +2017,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 +2029,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/_utils/utils.py similarity index 64% rename from sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_vendor.py rename to sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_utils/utils.py index f8a0e715e8f5..35c9c836f85f 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_vendor.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_utils/utils.py @@ -6,21 +6,20 @@ # -------------------------------------------------------------------------- from abc import ABC -from typing import TYPE_CHECKING - -from ._configuration import DevCenterClientConfiguration +from typing import Generic, TYPE_CHECKING, TypeVar if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core import PipelineClient + from .serialization import Deserializer, Serializer + - from ._serialization import Deserializer, Serializer +TClient = TypeVar("TClient") +TConfig = TypeVar("TConfig") -class DevCenterClientMixinABC(ABC): +class ClientMixinABC(ABC, Generic[TClient, TConfig]): """DO NOT use this class. It is for internal typing use only.""" - _client: "PipelineClient" - _config: DevCenterClientConfiguration + _client: TClient + _config: TConfig _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 83602e6274bc..0ec13ea52bbf 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_version.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "1.0.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 dc5f6ca493ef..e1efc66ed204 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 e94fae1092d9..e027506dd99f 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,109 @@ 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 .._utils.serialization import Deserializer, Serializer +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 +124,88 @@ 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 +260,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 7f1449d13d56..e1d46cf18e22 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 32322330a2b5..bb0ba294788e 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 d265d51dfc79..9eb5a0c0e465 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=line-too-long,useless-suppression,too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,13 +6,14 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from collections.abc import MutableMapping import datetime 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 import AsyncPipelineClient from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, @@ -20,6 +21,8 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse @@ -31,80 +34,69 @@ from azure.core.utils import case_insensitive_dict from ... import models as _models -from ..._model_base import SdkJSONEncoder, _deserialize from ..._operations._operations import ( - build_dev_center_create_dev_box_request, - build_dev_center_create_or_update_environment_request, - 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 ..._utils.model_base import SdkJSONEncoder, _deserialize +from ..._utils.utils import ClientMixinABC +from .._configuration import ( + DeploymentEnvironmentsClientConfiguration, + DevBoxesClientConfiguration, + DevCenterClientConfiguration, +) -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 T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] +JSON = MutableMapping[str, Any] -class DevCenterClientOperationsMixin(DevCenterClientMixinABC): # pylint: disable=too-many-public-methods +class DevCenterClientOperationsMixin(ClientMixinABC[AsyncPipelineClient, DevCenterClientConfiguration]): @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, @@ -151,7 +143,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.Project], deserialized["value"]) + list_of_elem = _deserialize(List[_models.Project], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -166,8 +158,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 +167,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 +174,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 +208,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 +225,13 @@ async def get_project(self, project_name: str, **kwargs: Any) -> _models.Project return deserialized # type: ignore + +class DevBoxesClientOperationsMixin( # pylint: disable=too-many-public-methods + ClientMixinABC[AsyncPipelineClient, DevBoxesClientConfiguration] +): + @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 +239,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 +256,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, @@ -370,7 +293,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.Pool], deserialized["value"]) + list_of_elem = _deserialize(List[_models.Pool], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -385,8 +308,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 +317,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 +326,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 +340,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 +361,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 +389,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 +406,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, @@ -599,7 +444,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.Schedule], deserialized["value"]) + list_of_elem = _deserialize(List[_models.Schedule], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -614,8 +459,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 +481,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 +495,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 +517,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 +536,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 +558,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, @@ -850,7 +594,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.DevBox], deserialized["value"]) + list_of_elem = _deserialize(List[_models.DevBox], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -865,8 +609,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 +618,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 +626,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 +643,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, @@ -1024,7 +680,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.DevBox], deserialized["value"]) + list_of_elem = _deserialize(List[_models.DevBox], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -1039,8 +695,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 +704,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 +714,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 +731,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, @@ -1201,7 +769,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.DevBox], deserialized["value"]) + list_of_elem = _deserialize(List[_models.DevBox], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -1216,8 +784,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 +793,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 +805,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 +819,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 +841,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 +865,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 +878,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 +887,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 +902,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 +910,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 +942,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 +961,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 +974,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 +993,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 +1006,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 +1025,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 +1036,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 +1053,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 +1074,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 +1110,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 +1122,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 +1137,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 +1145,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 +1159,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 +1169,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 +1179,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 +1200,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 +1221,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 +1243,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 +1258,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 +1266,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 +1286,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 +1296,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 +1317,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 +1338,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 +1360,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 +1376,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 +1384,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 +1404,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 +1416,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 +1438,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 +1459,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 +1481,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 +1496,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 +1504,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 +1524,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 +1534,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 +1555,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 +1576,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 +1600,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 +1614,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 +1636,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 +1669,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 +1686,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, @@ -2944,7 +1725,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.DevBoxAction], deserialized["value"]) + list_of_elem = _deserialize(List[_models.DevBoxAction], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -2959,8 +1740,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 +1765,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 +1779,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 +1802,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 +1820,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 +1838,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 +1851,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 +1873,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 +1880,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 +1901,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 +1921,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 +1945,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 +1963,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 +1975,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 +1999,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, @@ -3327,7 +2039,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.DevBoxActionDelayResult], deserialized["value"]) + list_of_elem = _deserialize(List[_models.DevBoxActionDelayResult], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -3342,8 +2054,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 +2061,13 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) + +class DeploymentEnvironmentsClientOperationsMixin( # pylint: disable=name-too-long + ClientMixinABC[AsyncPipelineClient, DeploymentEnvironmentsClientConfiguration] +): + @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 +2075,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 +2092,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, @@ -3453,7 +2129,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.Environment], deserialized["value"]) + list_of_elem = _deserialize(List[_models.Environment], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -3468,8 +2144,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 +2153,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 +2163,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 +2180,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, @@ -3583,7 +2218,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.Environment], deserialized["value"]) + list_of_elem = _deserialize(List[_models.Environment], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -3598,8 +2233,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 +2244,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 +2256,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 +2270,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 +2292,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 +2316,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 +2329,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 +2338,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 +2353,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 +2361,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 +2389,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 +2407,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 +2420,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 +2438,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 +2451,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 +2469,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 +2480,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 +2496,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 +2517,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 +2558,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 +2570,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 +2585,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 +2593,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 +2607,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 +2617,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 +2627,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 +2648,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 +2669,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 +2686,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 +2703,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, @@ -4419,7 +2740,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.Catalog], deserialized["value"]) + list_of_elem = _deserialize(List[_models.Catalog], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -4434,8 +2755,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 +2773,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 +2787,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 +2808,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 +2829,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 +2837,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 +2854,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, @@ -4614,7 +2891,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.EnvironmentDefinition], deserialized["value"]) + list_of_elem = _deserialize(List[_models.EnvironmentDefinition], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -4629,8 +2906,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 +2917,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 +2927,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 +2944,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, @@ -4744,7 +2982,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.EnvironmentDefinition], deserialized["value"]) + list_of_elem = _deserialize(List[_models.EnvironmentDefinition], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -4759,8 +2997,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 +3008,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 +3019,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 +3033,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 +3055,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 +3074,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 +3099,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, @@ -4948,7 +3136,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.EnvironmentType], deserialized["value"]) + list_of_elem = _deserialize(List[_models.EnvironmentType], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -4963,8 +3151,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/_operations/_patch.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_operations/_patch.py index f7dd32510333..8bcb627aa475 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_operations/_patch.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_operations/_patch.py @@ -1,7 +1,8 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# 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. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_patch.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_patch.py index f7dd32510333..8bcb627aa475 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_patch.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_patch.py @@ -1,7 +1,8 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# 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. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize 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 deleted file mode 100644 index a6ebf7871547..000000000000 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_vendor.py +++ /dev/null @@ -1,26 +0,0 @@ -# -------------------------------------------------------------------------- -# 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 abc import ABC -from typing import TYPE_CHECKING - -from ._configuration import DevCenterClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core import AsyncPipelineClient - - from .._serialization import Deserializer, Serializer - - -class DevCenterClientMixinABC(ABC): - """DO NOT use this class. It is for internal typing use only.""" - - _client: "AsyncPipelineClient" - _config: DevCenterClientConfiguration - _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 89f8c60752cf..e07b12f52ff9 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 ca1fa8869828..ed3aa4035428 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 9154decbf8f0..93730d8691d8 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,30 +1,26 @@ # 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 .. import _model_base -from .._model_base import rest_field +from azure.core.exceptions import ODataV4Format + +from .._utils.model_base import Model as _Model, rest_field if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models -class Catalog(_model_base.Model): +class Catalog(_Model): """A catalog. - Readonly variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - :ivar name: Name of the catalog. Required. :vartype name: str """ @@ -33,13 +29,9 @@ class Catalog(_model_base.Model): """Name of the catalog. Required.""" -class DevBox(_model_base.Model): # pylint: disable=too-many-instance-attributes +class DevBox(_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 :ivar project_name: Name of the project this Dev Box belongs to. @@ -63,12 +55,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 +69,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 +102,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 +118,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,34 +130,29 @@ 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) -class DevBoxAction(_model_base.Model): +class DevBoxAction(_Model): """An action which will take place on a Dev Box. - Readonly variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - :ivar name: The name of the action. Required. :vartype name: str :ivar action_type: The action that will be taken. Required. "Stop" :vartype action_type: str or ~azure.developer.devcenter.models.DevBoxActionType :ivar source_id: The id of the resource which triggered this action. Required. :vartype source_id: str - :ivar suspended_until: The earliest time that the action could occur (UTC). + :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 @@ -173,13 +160,17 @@ class DevBoxAction(_model_base.Model): name: str = rest_field(visibility=["read"]) """The name of the action. Required.""" - action_type: Union[str, "_models.DevBoxActionType"] = rest_field(name="actionType") + action_type: Union[str, "_models.DevBoxActionType"] = rest_field( + name="actionType", visibility=["read", "create", "update", "delete", "query"] + ) """The action that will be taken. Required. \"Stop\"""" - source_id: str = rest_field(name="sourceId") + source_id: str = rest_field(name="sourceId", visibility=["read", "create", "update", "delete", "query"]) """The id of the resource which triggered this action. Required.""" - suspended_until: Optional[datetime.datetime] = rest_field(name="suspendedUntil", format="rfc3339") - """The earliest time that the action could occur (UTC).""" - next: Optional["_models.DevBoxNextAction"] = rest_field() + suspended_until: Optional[datetime.datetime] = rest_field( + name="suspendedUntil", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The earliest time that the action could occur (UTC), in RFC3339 format.""" + next: Optional["_models.DevBoxNextAction"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Details about the next run of this action.""" @overload @@ -190,43 +181,43 @@ 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): +class DevBoxActionDelayResult(_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() + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The name of the action. Required.""" - result: Union[str, "_models.DevBoxActionDelayStatus"] = rest_field() + delay_status: Union[str, "_models.DevBoxActionDelayStatus"] = rest_field( + name="result", visibility=["read", "create", "update", "delete", "query"] + ) """The result of the delay operation on this action. Required. Known values are: \"Succeeded\" and \"Failed\".""" - action: Optional["_models.DevBoxAction"] = rest_field() + action: Optional["_models.DevBoxAction"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The delayed action.""" - error: Optional["_models.Error"] = rest_field() + error: Optional[ODataV4Format] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Information about the error that occurred. Only populated on error.""" @overload @@ -234,59 +225,55 @@ 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): +class DevBoxNextAction(_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.""" + scheduled_time: datetime.datetime = rest_field( + name="scheduledTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """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) -class Environment(_model_base.Model): +class Environment(_Model): """Properties of an environment. - Readonly variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - :ivar parameters: Parameters object for the environment. :vartype parameters: dict[str, any] :ivar name: Environment name. Required. @@ -308,10 +295,10 @@ 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() + parameters: Optional[Dict[str, Any]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Parameters object for the environment.""" name: str = rest_field(visibility=["read"]) """Environment name. Required.""" @@ -332,7 +319,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,26 +330,22 @@ 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) -class EnvironmentDefinition(_model_base.Model): +class EnvironmentDefinition(_Model): """An environment definition. - Readonly variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - :ivar id: The ID of the environment definition. Required. :vartype id: str :ivar name: Name of the environment definition. Required. @@ -379,19 +362,25 @@ class EnvironmentDefinition(_model_base.Model): :vartype template_path: str """ - id: str = rest_field() + id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The ID of the environment definition. Required.""" name: str = rest_field(visibility=["read"]) """Name of the environment definition. Required.""" - catalog_name: str = rest_field(name="catalogName") + catalog_name: str = rest_field(name="catalogName", visibility=["read", "create", "update", "delete", "query"]) """Name of the catalog. Required.""" - description: Optional[str] = rest_field() + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """A short description of the environment definition.""" - parameters: Optional[List["_models.EnvironmentDefinitionParameter"]] = rest_field() + parameters: Optional[List["_models.EnvironmentDefinitionParameter"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) """Input parameters passed to an environment.""" - parameters_schema: Optional[str] = rest_field(name="parametersSchema") + parameters_schema: Optional[str] = rest_field( + name="parametersSchema", visibility=["read", "create", "update", "delete", "query"] + ) """JSON schema defining the parameters object passed to an environment.""" - template_path: Optional[str] = rest_field(name="templatePath") + template_path: Optional[str] = rest_field( + name="templatePath", visibility=["read", "create", "update", "delete", "query"] + ) """Path to the Environment Definition entrypoint file.""" @overload @@ -404,24 +393,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): +class EnvironmentDefinitionParameter(_Model): """Properties of an Environment Definition parameter. - All required parameters must be populated in order to send to server. - :ivar id: Unique ID of the parameter. Required. :vartype id: str :ivar name: Display name of the parameter. @@ -443,24 +430,24 @@ class EnvironmentDefinitionParameter(_model_base.Model): :vartype allowed: list[str] """ - id: str = rest_field() + id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Unique ID of the parameter. Required.""" - name: Optional[str] = rest_field() + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Display name of the parameter.""" - description: Optional[str] = rest_field() + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Description of the parameter.""" - default: Optional[str] = rest_field() + default: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Default value of the parameter.""" - type: Union[str, "_models.ParameterType"] = rest_field() + type: Union[str, "_models.ParameterType"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """A string of one of the basic JSON types (number, integer, array, object, boolean, string). Required. Known values are: \"array\", \"boolean\", \"integer\", \"number\", \"object\", and \"string\".""" - read_only: Optional[bool] = rest_field(name="readOnly") + read_only: Optional[bool] = rest_field(name="readOnly", visibility=["read", "create", "update", "delete", "query"]) """Whether or not this parameter is read-only. If true, default should have a value.""" - required: bool = rest_field() + required: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Whether or not this parameter is required. Required.""" - allowed: Optional[List[str]] = rest_field() + allowed: Optional[List[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """An array of allowed values.""" @overload @@ -475,24 +462,22 @@ 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): +class EnvironmentType(_Model): """Properties of an environment type. - All required parameters must be populated in order to send to server. - :ivar name: Name of the environment type. Required. :vartype name: str :ivar deployment_target_id: Id of a subscription or management group that the environment type @@ -505,13 +490,17 @@ 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") + deployment_target_id: str = rest_field( + name="deploymentTargetId", visibility=["read", "create", "update", "delete", "query"] + ) """Id of a subscription or management group that the environment type will be mapped to. The environment's resources will be deployed into this subscription or management group. Required.""" - status: Union[str, "_models.EnvironmentTypeStatus"] = rest_field() + status: Union[str, "_models.EnvironmentTypeStatus"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) """Indicates whether this environment type is enabled for use in this project. Required. Known values are: \"Enabled\" and \"Disabled\".""" @@ -519,78 +508,24 @@ 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) -class HardwareProfile(_model_base.Model): +class HardwareProfile(_Model): """Hardware specifications for the Dev Box. - Readonly variables are only populated by the server, and will be ignored when sending a request. - :ivar sku_name: The name of the SKU. Known values are: "general_i_8c32gb256ssd_v2", "general_i_8c32gb512ssd_v2", "general_i_8c32gb1024ssd_v2", "general_i_8c32gb2048ssd_v2", "general_i_16c64gb256ssd_v2", "general_i_16c64gb512ssd_v2", "general_i_16c64gb1024ssd_v2", @@ -601,8 +536,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,17 +553,15 @@ 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.""" -class ImageReference(_model_base.Model): +class ImageReference(_Model): """Specifies information about the image used. - Readonly variables are only populated by the server, and will be ignored when sending a request. - :ivar name: The name of the image used. :vartype name: str :ivar version: The version of the image. @@ -637,7 +570,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,121 +586,12 @@ 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.""" - + """The datetime that the backing image version was published, in RFC3339 format.""" -class InnerError(_model_base.Model): - """An object containing more specific information about the error. As per Microsoft One API - guidelines - - https://github.com/Microsoft/api-guidelines/blob/vNext/Guidelines.md#7102-error-condition-responses. - :ivar code: One of a server-defined set of error codes. - :vartype code: str - :ivar innererror: Inner error. - :vartype innererror: ~azure.developer.devcenter.models.InnerError - """ - - code: Optional[str] = rest_field() - """One of a server-defined set of error codes.""" - innererror: Optional["_models.InnerError"] = rest_field() - """Inner error.""" - - @overload - def __init__( - self, - *, - code: Optional[str] = None, - innererror: Optional["_models.InnerError"] = None, - ): ... - - @overload - def __init__(self, mapping: Mapping[str, Any]): - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation - super().__init__(*args, **kwargs) - - -class OperationDetails(_model_base.Model): - """The current status of an async operation. - - Readonly variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: Fully qualified ID for the operation status. Required. - :vartype id: str - :ivar name: The operation id name. Required. - :vartype name: str - :ivar status: Provisioning state of the resource. Required. Known values are: "NotStarted", - "Running", "Succeeded", "Failed", and "Canceled". - :vartype status: str or ~azure.developer.devcenter.models.OperationStatus - :ivar resource_id: The id of the resource. - :vartype resource_id: str - :ivar start_time: The start time of the operation. - :vartype start_time: ~datetime.datetime - :ivar end_time: The end time of the operation. - :vartype end_time: ~datetime.datetime - :ivar percent_complete: Percent of the operation that is complete. - :vartype percent_complete: float - :ivar properties: Custom operation properties, populated only for a successful operation. - :vartype properties: any - :ivar error: Operation Error message. - :vartype error: ~azure.developer.devcenter.models.Error - """ - - id: str = rest_field(visibility=["read"]) - """Fully qualified ID for the operation status. Required.""" - name: str = rest_field(visibility=["read"]) - """The operation id name. Required.""" - status: Union[str, "_models.OperationStatus"] = rest_field() - """Provisioning state of the resource. Required. Known values are: \"NotStarted\", \"Running\", - \"Succeeded\", \"Failed\", and \"Canceled\".""" - resource_id: Optional[str] = rest_field(name="resourceId") - """The id of the resource.""" - start_time: Optional[datetime.datetime] = rest_field(name="startTime", format="rfc3339") - """The start time of the operation.""" - end_time: Optional[datetime.datetime] = rest_field(name="endTime", format="rfc3339") - """The end time of the operation.""" - percent_complete: Optional[float] = rest_field(name="percentComplete") - """Percent of the operation that is complete.""" - properties: Optional[Any] = rest_field() - """Custom operation properties, populated only for a successful operation.""" - error: Optional["_models.Error"] = rest_field() - """Operation Error message.""" - - @overload - def __init__( - self, - *, - status: Union[str, "_models.OperationStatus"], - resource_id: Optional[str] = None, - start_time: Optional[datetime.datetime] = None, - end_time: Optional[datetime.datetime] = None, - percent_complete: Optional[float] = None, - properties: Optional[Any] = None, - error: Optional["_models.Error"] = None, - ): ... - - @overload - def __init__(self, mapping: Mapping[str, Any]): - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation - super().__init__(*args, **kwargs) - - -class OSDisk(_model_base.Model): +class OsDisk(_Model): """Settings for the operating system disk. - Readonly variables are only populated by the server, and will be ignored when sending a request. - :ivar disk_size_gb: The size of the OS Disk in gigabytes. :vartype disk_size_gb: int """ @@ -775,19 +600,15 @@ class OSDisk(_model_base.Model): """The size of the OS Disk in gigabytes.""" -class Pool(_model_base.Model): +class Pool(_Model): """A pool of Dev Boxes. - Readonly variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - :ivar name: Pool name. Required. :vartype name: str :ivar location: Azure region where Dev Boxes in the pool are located. Required. :vartype location: str :ivar os_type: The operating system type of Dev Boxes in this pool. "Windows" - :vartype os_type: str or ~azure.developer.devcenter.models.OSType + :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 @@ -812,27 +633,41 @@ class Pool(_model_base.Model): name: str = rest_field(visibility=["read"]) """Pool name. Required.""" - location: str = rest_field() + location: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """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", visibility=["read", "create", "update", "delete", "query"] + ) """The operating system type of Dev Boxes in this pool. \"Windows\"""" - hardware_profile: Optional["_models.HardwareProfile"] = rest_field(name="hardwareProfile") + hardware_profile: Optional["_models.HardwareProfile"] = rest_field( + name="hardwareProfile", visibility=["read", "create", "update", "delete", "query"] + ) """Hardware settings for the Dev Boxes created in this pool.""" - hibernate_support: Optional[Union[str, "_models.HibernateSupport"]] = rest_field(name="hibernateSupport") + hibernate_support: Optional[Union[str, "_models.HibernateSupport"]] = rest_field( + name="hibernateSupport", visibility=["read", "create", "update", "delete", "query"] + ) """Indicates whether hibernate is enabled/disabled or unknown. Known values are: \"Enabled\", \"Disabled\", and \"OsUnsupported\".""" - storage_profile: Optional["_models.StorageProfile"] = rest_field(name="storageProfile") + storage_profile: Optional["_models.StorageProfile"] = rest_field( + name="storageProfile", visibility=["read", "create", "update", "delete", "query"] + ) """Storage settings for Dev Box created in this pool.""" - image_reference: Optional["_models.ImageReference"] = rest_field(name="imageReference") + image_reference: Optional["_models.ImageReference"] = rest_field( + name="imageReference", visibility=["read", "create", "update", "delete", "query"] + ) """Image settings for Dev Boxes create in this pool.""" local_administrator: Optional[Union[str, "_models.LocalAdministratorStatus"]] = rest_field( - name="localAdministrator" + name="localAdministrator", visibility=["read", "create", "update", "delete", "query"] ) """Indicates whether owners of Dev Boxes in this pool are local administrators on the Dev Boxes. Known values are: \"Enabled\" and \"Disabled\".""" - stop_on_disconnect: Optional["_models.StopOnDisconnectConfiguration"] = rest_field(name="stopOnDisconnect") + stop_on_disconnect: Optional["_models.StopOnDisconnectConfiguration"] = rest_field( + name="stopOnDisconnect", visibility=["read", "create", "update", "delete", "query"] + ) """Stop on disconnect configuration settings for Dev Boxes created in this pool.""" - health_status: Union[str, "_models.PoolHealthStatus"] = rest_field(name="healthStatus") + health_status: Union[str, "_models.PoolHealthStatus"] = rest_field( + name="healthStatus", visibility=["read", "create", "update", "delete", "query"] + ) """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\".""" @@ -843,33 +678,29 @@ 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) -class Project(_model_base.Model): +class Project(_Model): """Project details. - Readonly variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - :ivar name: Name of the project. Required. :vartype name: str :ivar description: Description of the project. @@ -882,9 +713,11 @@ class Project(_model_base.Model): name: str = rest_field(visibility=["read"]) """Name of the project. Required.""" - description: Optional[str] = rest_field() + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Description of the project.""" - max_dev_boxes_per_user: Optional[int] = rest_field(name="maxDevBoxesPerUser") + max_dev_boxes_per_user: Optional[int] = rest_field( + name="maxDevBoxesPerUser", visibility=["read", "create", "update", "delete", "query"] + ) """When specified, indicates the maximum number of Dev Boxes a single user can create across all pools in the project.""" @@ -894,20 +727,20 @@ 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) -class RemoteConnection(_model_base.Model): +class RemoteConnection(_Model): """Provides remote connection information for a Dev Box. :ivar web_url: URL to open a browser based RDP session. @@ -916,9 +749,11 @@ class RemoteConnection(_model_base.Model): :vartype rdp_connection_url: str """ - web_url: Optional[str] = rest_field(name="webUrl") + web_url: Optional[str] = rest_field(name="webUrl", visibility=["read", "create", "update", "delete", "query"]) """URL to open a browser based RDP session.""" - rdp_connection_url: Optional[str] = rest_field(name="rdpConnectionUrl") + rdp_connection_url: Optional[str] = rest_field( + name="rdpConnectionUrl", visibility=["read", "create", "update", "delete", "query"] + ) """Link to open a Remote Desktop session.""" @overload @@ -927,26 +762,22 @@ 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) -class Schedule(_model_base.Model): +class Schedule(_Model): """A Schedule to execute action. - Readonly variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - :ivar name: Display name for the Schedule. Required. :vartype name: str :ivar type: Supported type this scheduled task represents. Required. "StopDevBox" @@ -961,13 +792,15 @@ class Schedule(_model_base.Model): name: str = rest_field(visibility=["read"]) """Display name for the Schedule. Required.""" - type: Union[str, "_models.ScheduledType"] = rest_field() + type: Union[str, "_models.ScheduledType"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Supported type this scheduled task represents. Required. \"StopDevBox\"""" - frequency: Union[str, "_models.ScheduledFrequency"] = rest_field() + frequency: Union[str, "_models.ScheduledFrequency"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) """The frequency of this scheduled task. Required. \"Daily\"""" - time: str = rest_field() + time: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The target time to trigger the action. The format is HH:MM. Required.""" - time_zone: str = rest_field(name="timeZone") + time_zone: str = rest_field(name="timeZone", visibility=["read", "create", "update", "delete", "query"]) """The IANA timezone id at which the schedule should execute. Required.""" @overload @@ -978,24 +811,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): +class StopOnDisconnectConfiguration(_Model): """Stop on disconnect configuration settings for Dev Boxes created in this pool. - All required parameters must be populated in order to send to server. - :ivar status: Indicates whether the feature to stop the devbox on disconnect once the grace period has lapsed is enabled. Required. Known values are: "Enabled" and "Disabled". :vartype status: str or ~azure.developer.devcenter.models.StopOnDisconnectStatus @@ -1005,10 +836,14 @@ class StopOnDisconnectConfiguration(_model_base.Model): :vartype grace_period_minutes: int """ - status: Union[str, "_models.StopOnDisconnectStatus"] = rest_field() + status: Union[str, "_models.StopOnDisconnectStatus"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) """Indicates whether the feature to stop the devbox on disconnect once the grace period has lapsed is enabled. Required. Known values are: \"Enabled\" and \"Disabled\".""" - grace_period_minutes: Optional[int] = rest_field(name="gracePeriodMinutes") + grace_period_minutes: Optional[int] = rest_field( + name="gracePeriodMinutes", visibility=["read", "create", "update", "delete", "query"] + ) """The specified time in minutes to wait before stopping a Dev Box once disconnect is detected.""" @@ -1018,42 +853,44 @@ 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) -class StorageProfile(_model_base.Model): +class StorageProfile(_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", visibility=["read", "create", "update", "delete", "query"] + ) """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/azure/developer/devcenter/models/_patch.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/models/_patch.py index f7dd32510333..8bcb627aa475 100644 --- a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/models/_patch.py +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/models/_patch.py @@ -1,7 +1,8 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# 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. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize 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 000000000000..f076d5f62f44 --- /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 000000000000..53cbd0ddd7e6 --- /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 000000000000..e756be183b63 --- /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 000000000000..4faf3730d045 --- /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 000000000000..8e63e82aafb1 --- /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 000000000000..ca8825cddb1b --- /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 000000000000..e08698a07112 --- /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 000000000000..a3029b01fe87 --- /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 000000000000..dd2f91b9e6f4 --- /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 000000000000..63d012c0855e --- /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 000000000000..1a64ac78fb89 --- /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 000000000000..e744e0c9a560 --- /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 000000000000..0d0918e36fe0 --- /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 000000000000..c6b26d47f477 --- /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 000000000000..34878bf934eb --- /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 000000000000..6d1cc96004d2 --- /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 000000000000..9be65420721a --- /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 000000000000..05b1b7a5926b --- /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 000000000000..7037dd33c24e --- /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 000000000000..f3220929a793 --- /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 000000000000..d7cb162c0418 --- /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 000000000000..006261c786bc --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/generated_samples/environments_create_or_replace_environment.py @@ -0,0 +1,50 @@ +# pylint: disable=line-too-long,useless-suppression +# 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 000000000000..e4dc1d3ecc21 --- /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 000000000000..c4459f02c9e5 --- /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 000000000000..c10b33b66879 --- /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 000000000000..72a06c01a61d --- /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 000000000000..8ab6e5c4012f --- /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 000000000000..5c49a9bfe974 --- /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 000000000000..90b600a9d2b0 --- /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 000000000000..ebc43b0a7dc3 --- /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 000000000000..7d4e964110fa --- /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 000000000000..d98727add90c --- /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 000000000000..53905c7949d8 --- /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 000000000000..3af71ad13653 --- /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 000000000000..72e06ce9a284 --- /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 000000000000..c0392abb5385 --- /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 000000000000..03bec3816b0e --- /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 000000000000..91c08fcd6658 --- /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 000000000000..e066609a5be1 --- /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 000000000000..adccf2afca05 --- /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 000000000000..8adeb8ade37d --- /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 c09e6cd08891..60c2b23d94bd 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 @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # 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 f07a385725d8..5cf908d0090e 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 @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # @@ -47,6 +48,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 +77,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 +96,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 a2335ad58a19..30ce0003d804 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 @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # @@ -45,6 +46,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 +68,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 +82,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 8cff68746acd..6310c03b3a58 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 @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # @@ -46,6 +47,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 +69,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 70836ae439c7..805dbe56b2ef 100644 --- a/sdk/devcenter/azure-developer-devcenter/samples/create_client_sample.py +++ b/sdk/devcenter/azure-developer-devcenter/samples/create_client_sample.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # @@ -39,6 +40,7 @@ 1) DEVCENTER_ENDPOINT - the endpoint for your devcenter """ + def create_dev_center_client(): # [START create_dev_center_client] import os @@ -57,5 +59,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 4ffaf5d12603..1bcbba63c1a6 100644 --- a/sdk/devcenter/azure-developer-devcenter/samples/deployment_environments_sample.py +++ b/sdk/devcenter/azure-developer-devcenter/samples/deployment_environments_sample.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # diff --git a/sdk/devcenter/azure-developer-devcenter/samples/dev_box_action_sample.py b/sdk/devcenter/azure-developer-devcenter/samples/dev_box_action_sample.py index c8cebbaa68b5..1290c506e844 100644 --- a/sdk/devcenter/azure-developer-devcenter/samples/dev_box_action_sample.py +++ b/sdk/devcenter/azure-developer-devcenter/samples/dev_box_action_sample.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # 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 c8cefb4c41c8..cb421c1254ec 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 @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # @@ -40,6 +41,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 +104,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/samples/dev_box_restart_sample.py b/sdk/devcenter/azure-developer-devcenter/samples/dev_box_restart_sample.py index 785b3105ef6d..3c4d68564349 100644 --- a/sdk/devcenter/azure-developer-devcenter/samples/dev_box_restart_sample.py +++ b/sdk/devcenter/azure-developer-devcenter/samples/dev_box_restart_sample.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # diff --git a/sdk/devcenter/azure-developer-devcenter/setup.py b/sdk/devcenter/azure-developer-devcenter/setup.py index 2be63bfc3c86..f3c5828c9e6c 100644 --- a/sdk/devcenter/azure-developer-devcenter/setup.py +++ b/sdk/devcenter/azure-developer-devcenter/setup.py @@ -5,7 +5,7 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -# coding: utf-8 + import os import re @@ -29,7 +29,7 @@ setup( name=PACKAGE_NAME, version=version, - description="Microsoft {} Client Library for Python".format(PACKAGE_PPRINT_NAME), + description="Microsoft Corporation {} Client Library for Python".format(PACKAGE_PPRINT_NAME), long_description=open("README.md", "r").read(), long_description_content_type="text/markdown", license="MIT License", @@ -42,7 +42,6 @@ "Programming Language :: Python", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", @@ -67,5 +66,5 @@ "azure-core>=1.30.0", "typing-extensions>=4.6.0", ], - python_requires=">=3.8", + python_requires=">=3.9", ) diff --git a/sdk/devcenter/azure-developer-devcenter/tests/conftest.py b/sdk/devcenter/azure-developer-devcenter/tests/conftest.py index 07e19a00eff0..a759437b05a2 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 d5023a07a7e0..5eed70e20e02 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 c0db4e4e25d4..c06510d00df1 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: 0660a73ea14775552af66f95d92e1a0446a04b54 repo: Azure/azure-rest-api-specs -cleanup: true +additionalDirectories: