diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/CHANGELOG.md b/sdk/managementgroups/azure-mgmt-managementgroups/CHANGELOG.md index 34de25dce2e9..c99df6bfcf70 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/CHANGELOG.md +++ b/sdk/managementgroups/azure-mgmt-managementgroups/CHANGELOG.md @@ -1,5 +1,11 @@ # Release History +## 1.1.0b2 (2024-11-05) + +### Other Changes + + - Update dependencies + ## 1.1.0b1 (2022-11-01) ### Features Added diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/README.md b/sdk/managementgroups/azure-mgmt-managementgroups/README.md index 41fad690551e..fe5e08a6d803 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/README.md +++ b/sdk/managementgroups/azure-mgmt-managementgroups/README.md @@ -1,28 +1,61 @@ # Microsoft Azure SDK for Python This is the Microsoft Azure Management Groups Client Library. -This package has been tested with Python 3.7+. +This package has been tested with Python 3.8+. For a more complete view of Azure libraries, see the [azure sdk python release](https://aka.ms/azsdk/python/all). ## _Disclaimer_ _Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691_ -# Usage +## Getting started +### Prerequisites -To learn how to use this package, see the [quickstart guide](https://aka.ms/azsdk/python/mgmt) - -For docs and references, see [Python SDK References](https://docs.microsoft.com/python/api/overview/azure/) -Code samples for this package can be found at [Management Groups](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com. -Additional code samples for different Azure services are available at [Samples Repo](https://aka.ms/azsdk/python/mgmt/samples) +- Python 3.8+ is required to use this package. +- [Azure subscription](https://azure.microsoft.com/free/) +### Install the package -# Provide Feedback +```bash +pip install azure-mgmt-managementgroups +pip install azure-identity +``` + +### Authentication + +By default, [Azure Active Directory](https://aka.ms/awps/aad) token authentication depends on correct configure of following environment variables. + +- `AZURE_CLIENT_ID` for Azure client ID. +- `AZURE_TENANT_ID` for Azure tenant ID. +- `AZURE_CLIENT_SECRET` for Azure client secret. + +In addition, Azure subscription ID can be configured via environment variable `AZURE_SUBSCRIPTION_ID`. + +With above configuration, client can be authenticated by following code: + +```python +from azure.identity import DefaultAzureCredential +from azure.mgmt.managementgroups import ManagementGroupsAPI +import os + +sub_id = os.getenv("AZURE_SUBSCRIPTION_ID") +client = ManagementGroupsAPI(credential=DefaultAzureCredential(), subscription_id=sub_id) +``` + +## Examples + +Code samples for this package can be found at: +- [Search Management Groups](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com +- [Azure Python Mgmt SDK Samples Repo](https://aka.ms/azsdk/python/mgmt/samples) + + +## Troubleshooting + +## Next steps + +## Provide Feedback If you encounter any bugs or have suggestions, please file an issue in the [Issues](https://github.com/Azure/azure-sdk-for-python/issues) section of the project. - - -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-python%2Fazure-mgmt-managementgroups%2FREADME.png) diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/_meta.json b/sdk/managementgroups/azure-mgmt-managementgroups/_meta.json index 2057fb195769..08ce36824dda 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/_meta.json +++ b/sdk/managementgroups/azure-mgmt-managementgroups/_meta.json @@ -1,11 +1,11 @@ { - "commit": "4522e1d3fb6dcb81bc63e3414d11dd7eaf08264b", + "commit": "690a7656d65a03b134fa44fc7bb8013dc18a15b5", "repository_url": "https://github.com/Azure/azure-rest-api-specs", - "autorest": "3.9.2", + "autorest": "3.10.2", "use": [ - "@autorest/python@6.2.1", - "@autorest/modelerfour@4.24.3" + "@autorest/python@6.19.0", + "@autorest/modelerfour@4.27.0" ], - "autorest_command": "autorest specification/managementgroups/resource-manager/readme.md --generate-sample=True --include-x-ms-examples-original-file=True --python --python-sdks-folder=/home/vsts/work/1/azure-sdk-for-python/sdk --use=@autorest/python@6.2.1 --use=@autorest/modelerfour@4.24.3 --version=3.9.2 --version-tolerant=False", + "autorest_command": "autorest specification/managementgroups/resource-manager/readme.md --generate-sample=True --generate-test=True --include-x-ms-examples-original-file=True --python --python-sdks-folder=/mnt/vss/_work/1/azure-sdk-for-python/sdk --tag=package-2021-04 --use=@autorest/python@6.19.0 --use=@autorest/modelerfour@4.27.0 --version=3.10.2 --version-tolerant=False", "readme": "specification/managementgroups/resource-manager/readme.md" } \ No newline at end of file diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/__init__.py b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/__init__.py index db986cb4f5e1..8e9886cca32f 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/__init__.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/__init__.py @@ -13,7 +13,7 @@ try: from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import + from ._patch import * # pylint: disable=unused-wildcard-import except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/_configuration.py b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/_configuration.py index 4a024e8a9b57..1238dac2312c 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/_configuration.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/_configuration.py @@ -6,26 +6,19 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports - if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class ManagementGroupsAPIConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class ManagementGroupsAPIConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long """Configuration for ManagementGroupsAPI. Note that all parameters used to create this instance are saved as instance @@ -39,8 +32,7 @@ class ManagementGroupsAPIConfiguration(Configuration): # pylint: disable=too-ma """ def __init__(self, credential: "TokenCredential", **kwargs: Any) -> None: - super(ManagementGroupsAPIConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop("api_version", "2021-04-01") # type: Literal["2021-04-01"] + api_version: str = kwargs.pop("api_version", "2021-04-01") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -49,20 +41,18 @@ def __init__(self, credential: "TokenCredential", **kwargs: Any) -> None: self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-managementgroups/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> None + 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 ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**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 = ARMChallengeAuthenticationPolicy( diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/_management_groups_api.py b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/_management_groups_api.py index 8fd919b71a46..1f218f35a823 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/_management_groups_api.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/_management_groups_api.py @@ -8,11 +8,14 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy -from . import models +from . import models as _models from ._configuration import ManagementGroupsAPIConfiguration from ._serialization import Deserializer, Serializer from .operations import ( @@ -60,9 +63,27 @@ def __init__( self, credential: "TokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = ManagementGroupsAPIConfiguration(credential=credential, **kwargs) - self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) - - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + _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), + ARMAutoResourceProviderRegistrationPolicy(), + 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: ARMPipelineClient = ARMPipelineClient(base_url=base_url, policies=_policies, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False @@ -78,7 +99,7 @@ def __init__( self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) self.entities = EntitiesOperations(self._client, self._config, self._serialize, self._deserialize) - def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + 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 @@ -98,17 +119,14 @@ def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: request_copy = deepcopy(request) request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - def close(self): - # type: () -> None + def close(self) -> None: self._client.close() - def __enter__(self): - # type: () -> ManagementGroupsAPI + def __enter__(self) -> Self: self._client.__enter__() return self - def __exit__(self, *exc_details): - # type: (Any) -> None + def __exit__(self, *exc_details: Any) -> None: self._client.__exit__(*exc_details) diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/_serialization.py b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/_serialization.py index 7c1dedb5133d..8139854b97bb 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/_serialization.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/_serialization.py @@ -25,6 +25,7 @@ # -------------------------------------------------------------------------- # pylint: skip-file +# pyright: reportUnnecessaryTypeIgnoreComment=false from base64 import b64decode, b64encode import calendar @@ -37,23 +38,38 @@ import re import sys import codecs +from typing import ( + Dict, + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + TypeVar, + MutableMapping, + Type, + List, + Mapping, +) try: from urllib import quote # type: ignore except ImportError: - from urllib.parse import quote # type: ignore + from urllib.parse import quote import xml.etree.ElementTree as ET -import isodate +import isodate # type: ignore -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping +ModelType = TypeVar("ModelType", bound="Model") +JSON = MutableMapping[str, Any] class RawDeserializer: @@ -65,8 +81,7 @@ class RawDeserializer: CONTEXT_NAME = "deserialized_data" @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any + def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: """Decode data according to content-type. Accept a stream of data as well, but will be load at once in memory for now. @@ -109,7 +124,7 @@ def deserialize_from_text(cls, data, content_type=None): pass return ET.fromstring(data_as_str) # nosec - except ET.ParseError: + except ET.ParseError as err: # It might be because the server has an issue, and returned JSON with # content-type XML.... # So let's try a JSON load, and if it's still broken @@ -128,12 +143,13 @@ def _json_attemp(data): # The function hack is because Py2.7 messes up with exception # context otherwise. _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") + 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 - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any + def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: """Deserialize from HTTP response. Use bytes and headers to NOT use any requests/aiohttp or whatever @@ -156,13 +172,6 @@ def deserialize_from_http_generics(cls, body_bytes, headers): return None -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - _LOGGER = logging.getLogger(__name__) try: @@ -188,7 +197,7 @@ def dst(self, dt): try: - from datetime import timezone as _FixedOffset + from datetime import timezone as _FixedOffset # type: ignore except ImportError: # Python 2.7 class _FixedOffset(datetime.tzinfo): # type: ignore @@ -219,7 +228,7 @@ def __getinitargs__(self): try: from datetime import timezone - TZ_UTC = timezone.utc # type: ignore + TZ_UTC = timezone.utc except ImportError: TZ_UTC = UTC() # type: ignore @@ -276,12 +285,12 @@ class Model(object): serialization and deserialization. """ - _subtype_map = {} # type: Dict[str, Dict[str, Any]] - _attribute_map = {} # type: Dict[str, Dict[str, Any]] - _validation = {} # type: Dict[str, Dict[str, Any]] + _subtype_map: Dict[str, Dict[str, Any]] = {} + _attribute_map: Dict[str, Dict[str, Any]] = {} + _validation: Dict[str, Dict[str, Any]] = {} - def __init__(self, **kwargs): - self.additional_properties = {} + def __init__(self, **kwargs: Any) -> None: + self.additional_properties: Optional[Dict[str, Any]] = {} for k in kwargs: 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__) @@ -290,27 +299,27 @@ def __init__(self, **kwargs): else: setattr(self, k, kwargs[k]) - def __eq__(self, other): + def __eq__(self, other: Any) -> bool: """Compare objects by comparing all attributes.""" if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ return False - def __ne__(self, other): + def __ne__(self, other: Any) -> bool: """Compare objects by comparing all attributes.""" return not self.__eq__(other) - def __str__(self): + def __str__(self) -> str: return str(self.__dict__) @classmethod - def enable_additional_properties_sending(cls): + def enable_additional_properties_sending(cls) -> None: cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} @classmethod - def is_xml_model(cls): + def is_xml_model(cls) -> bool: try: - cls._xml_map + cls._xml_map # type: ignore except AttributeError: return False return True @@ -319,14 +328,14 @@ def is_xml_model(cls): def _create_xml_node(cls): """Create XML node.""" try: - xml_map = cls._xml_map + xml_map = cls._xml_map # type: ignore except AttributeError: xml_map = {} return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) - def serialize(self, keep_readonly=False, **kwargs): - """Return the JSON that would be sent to azure from this model. + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. @@ -337,10 +346,15 @@ def serialize(self, keep_readonly=False, **kwargs): :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) + return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) # type: ignore - def as_dict(self, keep_readonly=True, key_transformer=attribute_transformer, **kwargs): - """Return a dict that can be JSONify using json.dump. + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, Dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. Advanced usage might optionally use a callback as parameter: @@ -371,7 +385,7 @@ def my_key_transformer(key, attr_desc, value): :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) + return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) # type: ignore @classmethod def _infer_class_models(cls): @@ -387,7 +401,7 @@ def _infer_class_models(cls): return client_models @classmethod - def deserialize(cls, data, content_type=None): + def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = None) -> ModelType: """Parse a str using the RestAPI syntax and return a model. :param str data: A str using RestAPI structure. JSON by default. @@ -396,10 +410,15 @@ def deserialize(cls, data, content_type=None): :raises: DeserializationError if something went wrong """ deserializer = Deserializer(cls._infer_class_models()) - return deserializer(cls.__name__, data, content_type=content_type) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod - def from_dict(cls, data, key_extractors=None, content_type=None): + def from_dict( + cls: Type[ModelType], + data: Any, + key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> ModelType: """Parse a dict using given key extractor return a model. By default consider key @@ -412,8 +431,8 @@ def from_dict(cls, data, key_extractors=None, content_type=None): :raises: DeserializationError if something went wrong """ deserializer = Deserializer(cls._infer_class_models()) - deserializer.key_extractors = ( - [ + deserializer.key_extractors = ( # type: ignore + [ # type: ignore attribute_key_case_insensitive_extractor, rest_key_case_insensitive_extractor, last_rest_key_case_insensitive_extractor, @@ -421,7 +440,7 @@ def from_dict(cls, data, key_extractors=None, content_type=None): if key_extractors is None else key_extractors ) - return deserializer(cls.__name__, data, content_type=content_type) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod def _flatten_subtype(cls, key, objects): @@ -453,7 +472,7 @@ def _classify(cls, response, objects): return cls flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) try: - return objects[flatten_mapping_type[subtype_value]] + return objects[flatten_mapping_type[subtype_value]] # type: ignore except KeyError: _LOGGER.warning( "Subtype value %s has no mapping, use base class %s.", @@ -521,7 +540,7 @@ class Serializer(object): "multiple": lambda x, y: x % y != 0, } - def __init__(self, classes=None): + def __init__(self, classes: Optional[Mapping[str, type]] = None): self.serialize_type = { "iso-8601": Serializer.serialize_iso, "rfc-1123": Serializer.serialize_rfc, @@ -537,7 +556,7 @@ def __init__(self, classes=None): "[]": self.serialize_iter, "{}": self.serialize_dict, } - self.dependencies = dict(classes) if classes else {} + self.dependencies: Dict[str, type] = dict(classes) if classes else {} self.key_transformer = full_restapi_key_transformer self.client_side_validation = True @@ -605,14 +624,14 @@ def _serialize(self, target_obj, data_type=None, **kwargs): if xml_desc.get("attr", False): if xml_ns: ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) # type: ignore continue if xml_desc.get("text", False): - serialized.text = new_attr + serialized.text = new_attr # type: ignore continue if isinstance(new_attr, list): - serialized.extend(new_attr) + 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 "name" not in getattr(orig_attr, "_xml_map", {}): @@ -621,30 +640,30 @@ def _serialize(self, target_obj, data_type=None, **kwargs): new_attr.tag = "}".join([splitted_tag[0], xml_name]) else: new_attr.tag = xml_name - serialized.append(new_attr) + serialized.append(new_attr) # type: ignore else: # That's a basic type # Integrate namespace if necessary local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) + local_node.text = str(new_attr) + serialized.append(local_node) # type: ignore else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened + for k in reversed(keys): # type: ignore + new_attr = {k: new_attr} _new_attr = new_attr _serialized = serialized - for k in keys: + for k in keys: # type: ignore if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] + _serialized.update(_new_attr) # type: ignore + _new_attr = _new_attr[k] # type: ignore _serialized = _serialized[k] - except ValueError: - continue + except ValueError as err: + if isinstance(err, SerializationError): + raise except (AttributeError, KeyError, TypeError) as err: msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) + raise SerializationError(msg) from err else: return serialized @@ -659,8 +678,8 @@ def body(self, data, data_type, **kwargs): """ # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) try: is_xml_model_serialization = kwargs["is_xml"] except KeyError: @@ -675,7 +694,7 @@ def body(self, data, data_type, **kwargs): # We're not able to deal with additional properties for now. deserializer.additional_properties_detection = False if is_xml_model_serialization: - deserializer.key_extractors = [ + deserializer.key_extractors = [ # type: ignore attribute_key_case_insensitive_extractor, ] else: @@ -686,7 +705,7 @@ def body(self, data, data_type, **kwargs): ] data = deserializer._deserialize(data_type, data) except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) + raise SerializationError("Unable to build a model: " + str(err)) from err return self._serialize(data, data_type, **kwargs) @@ -706,6 +725,7 @@ def url(self, name, data, data_type, **kwargs): if kwargs.get("skip_quote") is True: output = str(output) + output = output.replace("{", quote("{")).replace("}", quote("}")) else: output = quote(str(output), safe="") except SerializationError: @@ -718,7 +738,9 @@ def query(self, name, data, data_type, **kwargs): :param data: The data to be serialized. :param str data_type: The type to be serialized from. - :rtype: str + :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 """ @@ -726,10 +748,8 @@ def query(self, name, data, data_type, **kwargs): # Treat the list aside, since we don't want to encode the div separator if data_type.startswith("["): internal_data_type = data_type[1:-1] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) # Not a list, regular serialization output = self.serialize_data(data, data_type, **kwargs) @@ -780,6 +800,8 @@ def serialize_data(self, data, data_type, **kwargs): raise ValueError("No value for given attribute") try: + if data is CoreNull: + return None if data_type in self.basic_types.values(): return self.serialize_basic(data, data_type, **kwargs) @@ -798,7 +820,7 @@ def serialize_data(self, data, data_type, **kwargs): except (ValueError, TypeError) as err: msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) + raise SerializationError(msg.format(data, data_type)) from err else: return self._serialize(data, **kwargs) @@ -843,7 +865,7 @@ def serialize_unicode(cls, data): pass try: - if isinstance(data, unicode): + if isinstance(data, unicode): # type: ignore # Don't change it, JSON and XML ElementTree are totally able # to serialize correctly u'' strings return data @@ -866,6 +888,8 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): 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 """ if isinstance(data, str): @@ -878,9 +902,14 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): for d in data: try: serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: + except ValueError as err: + if isinstance(err, SerializationError): + raise serialized.append(None) + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + if div: serialized = ["" if s is None else str(s) for s in serialized] serialized = div.join(serialized) @@ -925,7 +954,9 @@ def serialize_dict(self, attr, dict_type, **kwargs): for key, value in attr.items(): try: serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: + except ValueError as err: + if isinstance(err, SerializationError): + raise serialized[self.serialize_unicode(key)] = None if "xml" in serialization_ctxt: @@ -958,7 +989,7 @@ def serialize_object(self, attr, **kwargs): return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) if obj_type is _long_type: return self.serialize_long(attr) - if obj_type is unicode_str: + if obj_type is str: return self.serialize_unicode(attr) if obj_type is datetime.datetime: return self.serialize_iso(attr) @@ -1001,10 +1032,10 @@ def serialize_enum(attr, enum_obj=None): except AttributeError: result = attr try: - enum_obj(result) + enum_obj(result) # type: ignore return result except ValueError: - for enum_value in enum_obj: + 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}" @@ -1135,10 +1166,10 @@ def serialize_iso(attr, **kwargs): return date + microseconds + "Z" except (ValueError, OverflowError) as err: msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) + raise SerializationError(msg) from err except AttributeError as err: msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) + raise TypeError(msg) from err @staticmethod def serialize_unix(attr, **kwargs): @@ -1164,7 +1195,8 @@ def rest_key_extractor(attr, attr_desc, data): working_data = data while "." in key: - dict_keys = _FLATTEN.split(key) + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(List[str], _FLATTEN.split(key)) if len(dict_keys) == 1: key = _decode_attribute_map_key(dict_keys[0]) break @@ -1173,7 +1205,6 @@ def rest_key_extractor(attr, attr_desc, data): if working_data is None: # If at any point while following flatten JSON path see None, it means # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 return None key = ".".join(dict_keys[1:]) @@ -1194,7 +1225,6 @@ def rest_key_case_insensitive_extractor(attr, attr_desc, data): if working_data is None: # If at any point while following flatten JSON path see None, it means # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 return None key = ".".join(dict_keys[1:]) @@ -1245,7 +1275,7 @@ def _extract_name_from_internal_type(internal_type): xml_name = internal_type_xml_map.get("name", internal_type.__name__) xml_ns = internal_type_xml_map.get("ns", None) if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) return xml_name @@ -1269,7 +1299,7 @@ def xml_key_extractor(attr, attr_desc, data): # Integrate namespace if necessary xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) # If it's an attribute, that's simple if xml_desc.get("attr", False): @@ -1335,7 +1365,7 @@ class Deserializer(object): valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - def __init__(self, classes=None): + def __init__(self, classes: Optional[Mapping[str, type]] = None): self.deserialize_type = { "iso-8601": Deserializer.deserialize_iso, "rfc-1123": Deserializer.deserialize_rfc, @@ -1355,7 +1385,7 @@ def __init__(self, classes=None): "duration": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } - self.dependencies = dict(classes) if classes else {} + self.dependencies: Dict[str, type] = dict(classes) if classes else {} self.key_extractors = [rest_key_extractor, xml_key_extractor] # Additional properties only works if the "rest_key_extractor" is used to # extract the keys. Making it to work whatever the key extractor is too much @@ -1408,15 +1438,15 @@ def _deserialize(self, target_obj, data): response, class_name = self._classify_target(target_obj, data) - if isinstance(response, basestring): + if isinstance(response, str): return self.deserialize_data(data, response) elif isinstance(response, type) and issubclass(response, Enum): return self.deserialize_enum(data, response) - if data is None: + if data is None or data is CoreNull: return data try: - attributes = response._attribute_map + attributes = response._attribute_map # type: ignore d_attrs = {} for attr, attr_desc in attributes.items(): # Check empty string. If it's not empty, someone has a real "additionalProperties"... @@ -1444,8 +1474,8 @@ def _deserialize(self, target_obj, data): value = self.deserialize_data(raw_value, attr_desc["type"]) d_attrs[attr] = value except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, 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) @@ -1474,22 +1504,22 @@ def _classify_target(self, target, data): Once classification has been determined, initialize object. :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. + :param str/dict data: The response data to deserialize. """ if target is None: return None, None - if isinstance(target, basestring): + if isinstance(target, str): try: target = self.dependencies[target] except KeyError: return target, target try: - target = target._classify(data, self.dependencies) + target = target._classify(data, self.dependencies) # type: ignore except AttributeError: pass # Target is not a Model, no classify - return target, target.__class__.__name__ + return target, target.__class__.__name__ # type: ignore def failsafe_deserialize(self, target_obj, data, content_type=None): """Ignores any errors encountered in deserialization, @@ -1499,7 +1529,7 @@ def failsafe_deserialize(self, target_obj, data, content_type=None): a deserialization error. :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. + :param str/dict data: The response data to deserialize. :param str content_type: Swagger "produces" if available. """ try: @@ -1542,8 +1572,8 @@ def _unpack_content(raw_data, content_type=None): if hasattr(raw_data, "_content_consumed"): return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore return raw_data def _instantiate_model(self, response, attrs, additional_properties=None): @@ -1565,7 +1595,7 @@ def _instantiate_model(self, response, attrs, additional_properties=None): response_obj.additional_properties = additional_properties return response_obj except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore raise DeserializationError(msg + str(err)) else: try: @@ -1616,7 +1646,7 @@ def deserialize_data(self, data, data_type): except (ValueError, TypeError, AttributeError) as err: msg = "Unable to deserialize response data." msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err else: return self._deserialize(obj_type, data) @@ -1664,7 +1694,7 @@ def deserialize_object(self, attr, **kwargs): if isinstance(attr, ET.Element): # Do no recurse on XML, just return the tree as-is return attr - if isinstance(attr, basestring): + if isinstance(attr, str): return self.deserialize_basic(attr, "str") obj_type = type(attr) if obj_type in self.basic_types: @@ -1721,7 +1751,7 @@ def deserialize_basic(self, attr, data_type): if data_type == "bool": if attr in [True, False, 1, 0]: return bool(attr) - elif isinstance(attr, basestring): + elif isinstance(attr, str): if attr.lower() in ["true", "1"]: return True elif attr.lower() in ["false", "0"]: @@ -1747,7 +1777,7 @@ def deserialize_unicode(data): # Consider this is real string try: - if isinstance(data, unicode): + if isinstance(data, unicode): # type: ignore return data except NameError: return str(data) @@ -1772,7 +1802,6 @@ def deserialize_enum(data, enum_obj): data = data.value if isinstance(data, int): # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 try: return list(enum_obj.__members__.values())[data] except IndexError: @@ -1798,7 +1827,7 @@ def deserialize_bytearray(attr): """ if isinstance(attr, ET.Element): attr = attr.text - return bytearray(b64decode(attr)) + return bytearray(b64decode(attr)) # type: ignore @staticmethod def deserialize_base64(attr): @@ -1810,8 +1839,8 @@ def deserialize_base64(attr): """ if isinstance(attr, ET.Element): attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore encoded = attr.replace("-", "+").replace("_", "/") return b64decode(encoded) @@ -1826,10 +1855,10 @@ def deserialize_decimal(attr): if isinstance(attr, ET.Element): attr = attr.text try: - return decimal.Decimal(attr) + return decimal.Decimal(str(attr)) # type: ignore except decimal.DecimalException as err: msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err @staticmethod def deserialize_long(attr): @@ -1841,7 +1870,7 @@ def deserialize_long(attr): """ if isinstance(attr, ET.Element): attr = attr.text - return _long_type(attr) + return _long_type(attr) # type: ignore @staticmethod def deserialize_duration(attr): @@ -1857,7 +1886,7 @@ def deserialize_duration(attr): duration = isodate.parse_duration(attr) except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err else: return duration @@ -1871,10 +1900,10 @@ def deserialize_date(attr): """ if isinstance(attr, ET.Element): attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore raise DeserializationError("Date must have only digits and -. Received: %s" % attr) # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) @staticmethod def deserialize_time(attr): @@ -1886,7 +1915,7 @@ def deserialize_time(attr): """ if isinstance(attr, ET.Element): attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore raise DeserializationError("Date must have only digits and -. Received: %s" % attr) return isodate.parse_time(attr) @@ -1901,7 +1930,7 @@ def deserialize_rfc(attr): if isinstance(attr, ET.Element): attr = attr.text try: - parsed_date = email.utils.parsedate_tz(attr) + 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)) ) @@ -1909,7 +1938,7 @@ def deserialize_rfc(attr): date_obj = date_obj.astimezone(tz=TZ_UTC) except ValueError as err: msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err else: return date_obj @@ -1924,7 +1953,7 @@ def deserialize_iso(attr): if isinstance(attr, ET.Element): attr = attr.text try: - attr = attr.upper() + attr = attr.upper() # type: ignore match = Deserializer.valid_date.match(attr) if not match: raise ValueError("Invalid datetime string: " + attr) @@ -1946,7 +1975,7 @@ def deserialize_iso(attr): raise OverflowError("Hit max or min date") except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err else: return date_obj @@ -1960,11 +1989,12 @@ def deserialize_unix(attr): :raises: DeserializationError if format invalid """ if isinstance(attr, ET.Element): - attr = int(attr.text) + attr = int(attr.text) # type: ignore try: + attr = int(attr) date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) except ValueError as err: msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err else: return date_obj diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/_vendor.py b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/_vendor.py index 4ea910bfc12f..59d3f80715a2 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/_vendor.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/_vendor.py @@ -8,8 +8,6 @@ from abc import ABC from typing import TYPE_CHECKING -from azure.core.pipeline.transport import HttpRequest - from ._configuration import ManagementGroupsAPIConfiguration if TYPE_CHECKING: @@ -19,25 +17,6 @@ from ._serialization import Deserializer, Serializer -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - formatted_components = template.split("/") - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) - - class ManagementGroupsAPIMixinABC(ABC): """DO NOT use this class. It is for internal typing use only.""" diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/_version.py b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/_version.py index 653b73a4a199..f1fb63697cf5 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/_version.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "1.1.0b1" +VERSION = "1.1.0b2" diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/__init__.py b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/__init__.py index e87251407abe..311e06c2a36d 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/__init__.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/__init__.py @@ -10,7 +10,7 @@ try: from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import + from ._patch import * # pylint: disable=unused-wildcard-import except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/_configuration.py b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/_configuration.py index d63c043d8829..95eea1ddf7e8 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/_configuration.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/_configuration.py @@ -6,26 +6,19 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports - if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class ManagementGroupsAPIConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class ManagementGroupsAPIConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long """Configuration for ManagementGroupsAPI. Note that all parameters used to create this instance are saved as instance @@ -39,8 +32,7 @@ class ManagementGroupsAPIConfiguration(Configuration): # pylint: disable=too-ma """ def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None: - super(ManagementGroupsAPIConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop("api_version", "2021-04-01") # type: Literal["2021-04-01"] + api_version: str = kwargs.pop("api_version", "2021-04-01") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -49,6 +41,7 @@ def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None: self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-managementgroups/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -57,9 +50,9 @@ def _configure(self, **kwargs: Any) -> None: 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 ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**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 = AsyncARMChallengeAuthenticationPolicy( diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/_management_groups_api.py b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/_management_groups_api.py index ae895d186241..e00daa120c5b 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/_management_groups_api.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/_management_groups_api.py @@ -8,11 +8,14 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy -from .. import models +from .. import models as _models from .._serialization import Deserializer, Serializer from ._configuration import ManagementGroupsAPIConfiguration from .operations import ( @@ -62,9 +65,27 @@ def __init__( self, credential: "AsyncTokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = ManagementGroupsAPIConfiguration(credential=credential, **kwargs) - self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) - - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + _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), + AsyncARMAutoResourceProviderRegistrationPolicy(), + 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: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, policies=_policies, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False @@ -80,7 +101,9 @@ def __init__( self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) self.entities = EntitiesOperations(self._client, self._config, self._serialize, self._deserialize) - def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + 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 @@ -100,14 +123,14 @@ def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncH request_copy = deepcopy(request) request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) + 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) -> "ManagementGroupsAPI": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self - async def __aexit__(self, *exc_details) -> None: + async def __aexit__(self, *exc_details: Any) -> None: await self._client.__aexit__(*exc_details) diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/_vendor.py b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/_vendor.py index 6a2d36ab0576..d4f2a8633b08 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/_vendor.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/_vendor.py @@ -8,8 +8,6 @@ from abc import ABC from typing import TYPE_CHECKING -from azure.core.pipeline.transport import HttpRequest - from ._configuration import ManagementGroupsAPIConfiguration if TYPE_CHECKING: diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/operations/__init__.py b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/operations/__init__.py index 2d20b499bdbe..17da0c8d00e0 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/operations/__init__.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/operations/__init__.py @@ -14,7 +14,7 @@ from ._entities_operations import EntitiesOperations from ._patch import __all__ as _patch_all -from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import * # pylint: disable=unused-wildcard-import from ._patch import patch_sdk as _patch_sdk __all__ = [ diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/operations/_entities_operations.py b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/operations/_entities_operations.py index cba69970343f..cbf581dd3f19 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/operations/_entities_operations.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/operations/_entities_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,7 +7,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar, Union import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList @@ -20,21 +20,18 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request from ...operations._entities_operations import build_list_request -from .._vendor import ManagementGroupsAPIMixinABC -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -125,7 +122,6 @@ def list( :param cache_control: Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. Default value is "no-cache". :type cache_control: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either EntityInfo or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.managementgroups.models.EntityInfo] :raises ~azure.core.exceptions.HttpResponseError: @@ -133,12 +129,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.EntityListResult] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.EntityListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -149,7 +143,7 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( skiptoken=skiptoken, skip=skip, top=top, @@ -160,12 +154,10 @@ def prepare_request(next_link=None): group_name=group_name, cache_control=cache_control, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -177,26 +169,26 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("EntityListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -208,5 +200,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/providers/Microsoft.Management/getEntities"} # type: ignore diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/operations/_hierarchy_settings_operations.py b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/operations/_hierarchy_settings_operations.py index 25161f2aed6a..996a93ab1010 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/operations/_hierarchy_settings_operations.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/operations/_hierarchy_settings_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,8 +6,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase import sys -from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload +from typing import Any, Callable, Dict, IO, Optional, Type, TypeVar, Union, overload from azure.core.exceptions import ( ClientAuthenticationError, @@ -18,14 +19,12 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request from ...operations._hierarchy_settings_operations import ( build_create_or_update_request, build_delete_request, @@ -33,12 +32,11 @@ build_list_request, build_update_request, ) -from .._vendor import ManagementGroupsAPIMixinABC -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -69,12 +67,11 @@ async def list(self, group_id: str, **kwargs: Any) -> _models.HierarchySettingsL :param group_id: Management Group ID. Required. :type group_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: HierarchySettingsList or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.HierarchySettingsList :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -85,23 +82,20 @@ async def list(self, group_id: str, **kwargs: Any) -> _models.HierarchySettingsL _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.HierarchySettingsList] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.HierarchySettingsList] = kwargs.pop("cls", None) - request = build_list_request( + _request = build_list_request( group_id=group_id, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -111,14 +105,12 @@ async def list(self, group_id: str, **kwargs: Any) -> _models.HierarchySettingsL error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("HierarchySettingsList", pipeline_response) + deserialized = self._deserialize("HierarchySettingsList", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - list.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}/settings"} # type: ignore + return deserialized # type: ignore @distributed_trace_async async def get(self, group_id: str, **kwargs: Any) -> _models.HierarchySettings: @@ -127,12 +119,11 @@ async def get(self, group_id: str, **kwargs: Any) -> _models.HierarchySettings: :param group_id: Management Group ID. Required. :type group_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: HierarchySettings or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -143,23 +134,20 @@ async def get(self, group_id: str, **kwargs: Any) -> _models.HierarchySettings: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.HierarchySettings] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.HierarchySettings] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( group_id=group_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -169,14 +157,12 @@ async def get(self, group_id: str, **kwargs: Any) -> _models.HierarchySettings: error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("HierarchySettings", pipeline_response) + deserialized = self._deserialize("HierarchySettings", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}/settings/default"} # type: ignore + return deserialized # type: ignore @overload async def create_or_update( @@ -197,7 +183,6 @@ async def create_or_update( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: HierarchySettings or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings :raises ~azure.core.exceptions.HttpResponseError: @@ -207,7 +192,7 @@ async def create_or_update( async def create_or_update( self, group_id: str, - create_tenant_settings_request: IO, + create_tenant_settings_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -217,11 +202,10 @@ async def create_or_update( :param group_id: Management Group ID. Required. :type group_id: str :param create_tenant_settings_request: Tenant level settings request parameter. Required. - :type create_tenant_settings_request: IO + :type create_tenant_settings_request: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: HierarchySettings or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings :raises ~azure.core.exceptions.HttpResponseError: @@ -231,7 +215,7 @@ async def create_or_update( async def create_or_update( self, group_id: str, - create_tenant_settings_request: Union[_models.CreateOrUpdateSettingsRequest, IO], + create_tenant_settings_request: Union[_models.CreateOrUpdateSettingsRequest, IO[bytes]], **kwargs: Any ) -> _models.HierarchySettings: """Creates or updates the hierarchy settings defined at the Management Group level. @@ -239,18 +223,14 @@ async def create_or_update( :param group_id: Management Group ID. Required. :type group_id: str :param create_tenant_settings_request: Tenant level settings request parameter. Is either a - model type or a IO type. Required. + CreateOrUpdateSettingsRequest type or a IO[bytes] type. Required. :type create_tenant_settings_request: - ~azure.mgmt.managementgroups.models.CreateOrUpdateSettingsRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + ~azure.mgmt.managementgroups.models.CreateOrUpdateSettingsRequest or IO[bytes] :return: HierarchySettings or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -261,35 +241,32 @@ async def create_or_update( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.HierarchySettings] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.HierarchySettings] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(create_tenant_settings_request, (IO, bytes)): + if isinstance(create_tenant_settings_request, (IOBase, bytes)): _content = create_tenant_settings_request else: _json = self._serialize.body(create_tenant_settings_request, "CreateOrUpdateSettingsRequest") - request = build_create_or_update_request( + _request = build_create_or_update_request( group_id=group_id, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.create_or_update.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -299,14 +276,12 @@ async def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("HierarchySettings", pipeline_response) + deserialized = self._deserialize("HierarchySettings", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - create_or_update.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}/settings/default"} # type: ignore + return deserialized # type: ignore @overload async def update( @@ -327,7 +302,6 @@ async def update( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: HierarchySettings or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings :raises ~azure.core.exceptions.HttpResponseError: @@ -337,7 +311,7 @@ async def update( async def update( self, group_id: str, - create_tenant_settings_request: IO, + create_tenant_settings_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -347,11 +321,10 @@ async def update( :param group_id: Management Group ID. Required. :type group_id: str :param create_tenant_settings_request: Tenant level settings request parameter. Required. - :type create_tenant_settings_request: IO + :type create_tenant_settings_request: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: HierarchySettings or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings :raises ~azure.core.exceptions.HttpResponseError: @@ -361,7 +334,7 @@ async def update( async def update( self, group_id: str, - create_tenant_settings_request: Union[_models.CreateOrUpdateSettingsRequest, IO], + create_tenant_settings_request: Union[_models.CreateOrUpdateSettingsRequest, IO[bytes]], **kwargs: Any ) -> _models.HierarchySettings: """Updates the hierarchy settings defined at the Management Group level. @@ -369,18 +342,14 @@ async def update( :param group_id: Management Group ID. Required. :type group_id: str :param create_tenant_settings_request: Tenant level settings request parameter. Is either a - model type or a IO type. Required. + CreateOrUpdateSettingsRequest type or a IO[bytes] type. Required. :type create_tenant_settings_request: - ~azure.mgmt.managementgroups.models.CreateOrUpdateSettingsRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + ~azure.mgmt.managementgroups.models.CreateOrUpdateSettingsRequest or IO[bytes] :return: HierarchySettings or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -391,35 +360,32 @@ async def update( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.HierarchySettings] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.HierarchySettings] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(create_tenant_settings_request, (IO, bytes)): + if isinstance(create_tenant_settings_request, (IOBase, bytes)): _content = create_tenant_settings_request else: _json = self._serialize.body(create_tenant_settings_request, "CreateOrUpdateSettingsRequest") - request = build_update_request( + _request = build_update_request( group_id=group_id, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.update.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -429,14 +395,12 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("HierarchySettings", pipeline_response) + deserialized = self._deserialize("HierarchySettings", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - update.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}/settings/default"} # type: ignore + return deserialized # type: ignore @distributed_trace_async async def delete(self, group_id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements @@ -444,12 +408,11 @@ async def delete(self, group_id: str, **kwargs: Any) -> None: # pylint: disable :param group_id: Management Group ID. Required. :type group_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -460,23 +423,20 @@ async def delete(self, group_id: str, **kwargs: Any) -> None: # pylint: disable _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[None] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( group_id=group_id, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -487,6 +447,4 @@ async def delete(self, group_id: str, **kwargs: Any) -> None: # pylint: disable raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}/settings/default"} # type: ignore + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/operations/_management_group_subscriptions_operations.py b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/operations/_management_group_subscriptions_operations.py index 6d746a95dccf..2b8418c0ee75 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/operations/_management_group_subscriptions_operations.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/operations/_management_group_subscriptions_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,7 +7,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList @@ -20,27 +20,24 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request from ...operations._management_group_subscriptions_operations import ( build_create_request, build_delete_request, build_get_subscription_request, build_get_subscriptions_under_management_group_request, ) -from .._vendor import ManagementGroupsAPIMixinABC -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -77,12 +74,11 @@ async def create( :param cache_control: Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. Default value is "no-cache". :type cache_control: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: SubscriptionUnderManagementGroup or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.SubscriptionUnderManagementGroup :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -93,25 +89,22 @@ async def create( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.SubscriptionUnderManagementGroup] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SubscriptionUnderManagementGroup] = kwargs.pop("cls", None) - request = build_create_request( + _request = build_create_request( group_id=group_id, subscription_id=subscription_id, cache_control=cache_control, api_version=api_version, - template_url=self.create.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -121,14 +114,12 @@ async def create( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("SubscriptionUnderManagementGroup", pipeline_response) + deserialized = self._deserialize("SubscriptionUnderManagementGroup", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - create.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId}"} # type: ignore + return deserialized # type: ignore @distributed_trace_async async def delete( # pylint: disable=inconsistent-return-statements @@ -143,12 +134,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :param cache_control: Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. Default value is "no-cache". :type cache_control: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -159,25 +149,22 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[None] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( group_id=group_id, subscription_id=subscription_id, cache_control=cache_control, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -188,9 +175,7 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId}"} # type: ignore + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async async def get_subscription( @@ -205,12 +190,11 @@ async def get_subscription( :param cache_control: Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. Default value is "no-cache". :type cache_control: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: SubscriptionUnderManagementGroup or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.SubscriptionUnderManagementGroup :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -221,25 +205,22 @@ async def get_subscription( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.SubscriptionUnderManagementGroup] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SubscriptionUnderManagementGroup] = kwargs.pop("cls", None) - request = build_get_subscription_request( + _request = build_get_subscription_request( group_id=group_id, subscription_id=subscription_id, cache_control=cache_control, api_version=api_version, - template_url=self.get_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -249,14 +230,12 @@ async def get_subscription( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("SubscriptionUnderManagementGroup", pipeline_response) + deserialized = self._deserialize("SubscriptionUnderManagementGroup", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - get_subscription.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId}"} # type: ignore + return deserialized # type: ignore @distributed_trace def get_subscriptions_under_management_group( @@ -272,7 +251,6 @@ def get_subscriptions_under_management_group( include a token parameter that specifies a starting point to use for subsequent calls. Default value is None. :type skiptoken: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either SubscriptionUnderManagementGroup or the result of cls(response) :rtype: @@ -282,12 +260,10 @@ def get_subscriptions_under_management_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.ListSubscriptionUnderManagementGroup] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ListSubscriptionUnderManagementGroup] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -298,16 +274,14 @@ def get_subscriptions_under_management_group( def prepare_request(next_link=None): if not next_link: - request = build_get_subscriptions_under_management_group_request( + _request = build_get_subscriptions_under_management_group_request( group_id=group_id, skiptoken=skiptoken, api_version=api_version, - template_url=self.get_subscriptions_under_management_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -319,26 +293,26 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ListSubscriptionUnderManagementGroup", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -350,5 +324,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - get_subscriptions_under_management_group.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}/subscriptions"} # type: ignore diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/operations/_management_groups_api_operations.py b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/operations/_management_groups_api_operations.py index d39a831e3226..8aa8c6eefadb 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/operations/_management_groups_api_operations.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/operations/_management_groups_api_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,8 +6,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase import sys -from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload +from typing import Any, Callable, Dict, IO, Optional, Type, TypeVar, Union, overload from azure.core.exceptions import ( ClientAuthenticationError, @@ -18,14 +19,12 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request from ...operations._management_groups_api_operations import ( build_check_name_availability_request, build_start_tenant_backfill_request, @@ -33,15 +32,16 @@ ) from .._vendor import ManagementGroupsAPIMixinABC -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class ManagementGroupsAPIOperationsMixin(ManagementGroupsAPIMixinABC): + @overload async def check_name_availability( self, @@ -59,7 +59,6 @@ async def check_name_availability( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: CheckNameAvailabilityResult or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.CheckNameAvailabilityResult :raises ~azure.core.exceptions.HttpResponseError: @@ -67,17 +66,16 @@ async def check_name_availability( @overload async def check_name_availability( - self, check_name_availability_request: IO, *, content_type: str = "application/json", **kwargs: Any + self, check_name_availability_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.CheckNameAvailabilityResult: """Checks if the specified management group name is valid and unique. :param check_name_availability_request: Management group name availability check parameters. Required. - :type check_name_availability_request: IO + :type check_name_availability_request: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: CheckNameAvailabilityResult or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.CheckNameAvailabilityResult :raises ~azure.core.exceptions.HttpResponseError: @@ -85,23 +83,19 @@ async def check_name_availability( @distributed_trace_async async def check_name_availability( - self, check_name_availability_request: Union[_models.CheckNameAvailabilityRequest, IO], **kwargs: Any + self, check_name_availability_request: Union[_models.CheckNameAvailabilityRequest, IO[bytes]], **kwargs: Any ) -> _models.CheckNameAvailabilityResult: """Checks if the specified management group name is valid and unique. :param check_name_availability_request: Management group name availability check parameters. Is - either a model type or a IO type. Required. + either a CheckNameAvailabilityRequest type or a IO[bytes] type. Required. :type check_name_availability_request: - ~azure.mgmt.managementgroups.models.CheckNameAvailabilityRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + ~azure.mgmt.managementgroups.models.CheckNameAvailabilityRequest or IO[bytes] :return: CheckNameAvailabilityResult or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.CheckNameAvailabilityResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -112,34 +106,31 @@ async def check_name_availability( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckNameAvailabilityResult] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CheckNameAvailabilityResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(check_name_availability_request, (IO, bytes)): + if isinstance(check_name_availability_request, (IOBase, bytes)): _content = check_name_availability_request else: _json = self._serialize.body(check_name_availability_request, "CheckNameAvailabilityRequest") - request = build_check_name_availability_request( + _request = build_check_name_availability_request( api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.check_name_availability.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -149,25 +140,22 @@ async def check_name_availability( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("CheckNameAvailabilityResult", pipeline_response) + deserialized = self._deserialize("CheckNameAvailabilityResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - check_name_availability.metadata = {"url": "/providers/Microsoft.Management/checkNameAvailability"} # type: ignore + return deserialized # type: ignore @distributed_trace_async async def start_tenant_backfill(self, **kwargs: Any) -> _models.TenantBackfillStatusResult: """Starts backfilling subscriptions for the Tenant. - :keyword callable cls: A custom type or function that will be passed the direct response :return: TenantBackfillStatusResult or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.TenantBackfillStatusResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -178,22 +166,19 @@ async def start_tenant_backfill(self, **kwargs: Any) -> _models.TenantBackfillSt _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.TenantBackfillStatusResult] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.TenantBackfillStatusResult] = kwargs.pop("cls", None) - request = build_start_tenant_backfill_request( + _request = build_start_tenant_backfill_request( api_version=api_version, - template_url=self.start_tenant_backfill.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -203,25 +188,22 @@ async def start_tenant_backfill(self, **kwargs: Any) -> _models.TenantBackfillSt error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("TenantBackfillStatusResult", pipeline_response) + deserialized = self._deserialize("TenantBackfillStatusResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - start_tenant_backfill.metadata = {"url": "/providers/Microsoft.Management/startTenantBackfill"} # type: ignore + return deserialized # type: ignore @distributed_trace_async async def tenant_backfill_status(self, **kwargs: Any) -> _models.TenantBackfillStatusResult: """Gets tenant backfill status. - :keyword callable cls: A custom type or function that will be passed the direct response :return: TenantBackfillStatusResult or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.TenantBackfillStatusResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -232,22 +214,19 @@ async def tenant_backfill_status(self, **kwargs: Any) -> _models.TenantBackfillS _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.TenantBackfillStatusResult] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.TenantBackfillStatusResult] = kwargs.pop("cls", None) - request = build_tenant_backfill_status_request( + _request = build_tenant_backfill_status_request( api_version=api_version, - template_url=self.tenant_backfill_status.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -257,11 +236,9 @@ async def tenant_backfill_status(self, **kwargs: Any) -> _models.TenantBackfillS error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("TenantBackfillStatusResult", pipeline_response) + deserialized = self._deserialize("TenantBackfillStatusResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - tenant_backfill_status.metadata = {"url": "/providers/Microsoft.Management/tenantBackfillStatus"} # type: ignore + return deserialized # type: ignore diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/operations/_management_groups_operations.py b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/operations/_management_groups_operations.py index eb65996b9ec6..df7ca2a82348 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/operations/_management_groups_operations.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/operations/_management_groups_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,8 +6,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase import sys -from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList @@ -17,12 +18,13 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict @@ -30,7 +32,6 @@ from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models -from ..._vendor import _convert_request from ...operations._management_groups_operations import ( build_create_or_update_request, build_delete_request, @@ -39,12 +40,11 @@ build_list_request, build_update_request, ) -from .._vendor import ManagementGroupsAPIMixinABC -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -83,7 +83,6 @@ def list( include a token parameter that specifies a starting point to use for subsequent calls. Default value is None. :type skiptoken: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ManagementGroupInfo or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.managementgroups.models.ManagementGroupInfo] @@ -92,12 +91,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.ManagementGroupListResult] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ManagementGroupListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -108,16 +105,14 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( cache_control=cache_control, skiptoken=skiptoken, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -129,26 +124,26 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ManagementGroupListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -161,8 +156,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list.metadata = {"url": "/providers/Microsoft.Management/managementGroups"} # type: ignore - @distributed_trace_async async def get( self, @@ -192,12 +185,11 @@ async def get( :param cache_control: Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. Default value is "no-cache". :type cache_control: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ManagementGroup or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.ManagementGroup :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -208,27 +200,24 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.ManagementGroup] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ManagementGroup] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( group_id=group_id, expand=expand, recurse=recurse, filter=filter, cache_control=cache_control, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -238,23 +227,21 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ManagementGroup", pipeline_response) + deserialized = self._deserialize("ManagementGroup", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}"} # type: ignore + return deserialized # type: ignore async def _create_or_update_initial( self, group_id: str, - create_management_group_request: Union[_models.CreateManagementGroupRequest, IO], + create_management_group_request: Union[_models.CreateManagementGroupRequest, IO[bytes]], cache_control: str = "no-cache", **kwargs: Any - ) -> Union[_models.ManagementGroup, _models.AzureAsyncOperationResults]: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -265,65 +252,60 @@ async def _create_or_update_initial( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop( - "cls", None - ) # type: ClsType[Union[_models.ManagementGroup, _models.AzureAsyncOperationResults]] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(create_management_group_request, (IO, bytes)): + if isinstance(create_management_group_request, (IOBase, bytes)): _content = create_management_group_request else: _json = self._serialize.body(create_management_group_request, "CreateManagementGroupRequest") - request = build_create_or_update_request( + _request = build_create_or_update_request( group_id=group_id, cache_control=cache_control, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("ManagementGroup", pipeline_response) - if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Azure-AsyncOperation"] = self._deserialize( "str", response.headers.get("Azure-AsyncOperation") ) - deserialized = self._deserialize("AzureAsyncOperationResults", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: - return cls(pipeline_response, deserialized, response_headers) - - return deserialized + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _create_or_update_initial.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}"} # type: ignore + return deserialized # type: ignore @overload async def begin_create_or_update( @@ -334,7 +316,7 @@ async def begin_create_or_update( *, content_type: str = "application/json", **kwargs: Any - ) -> Union[AsyncLROPoller[_models.ManagementGroup], AsyncLROPoller[_models.AzureAsyncOperationResults]]: + ) -> AsyncLROPoller[_models.ManagementGroup]: """Create or update a management group. If a management group is already created and a subsequent create request is issued with different properties, the management group properties will be updated. @@ -350,14 +332,6 @@ async def begin_create_or_update( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either ManagementGroup or An instance of AsyncLROPoller that returns either AzureAsyncOperationResults or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.managementgroups.models.ManagementGroup] @@ -370,12 +344,12 @@ async def begin_create_or_update( async def begin_create_or_update( self, group_id: str, - create_management_group_request: IO, + create_management_group_request: IO[bytes], cache_control: str = "no-cache", *, content_type: str = "application/json", **kwargs: Any - ) -> Union[AsyncLROPoller[_models.ManagementGroup], AsyncLROPoller[_models.AzureAsyncOperationResults]]: + ) -> AsyncLROPoller[_models.ManagementGroup]: """Create or update a management group. If a management group is already created and a subsequent create request is issued with different properties, the management group properties will be updated. @@ -383,21 +357,13 @@ async def begin_create_or_update( :param group_id: Management Group ID. Required. :type group_id: str :param create_management_group_request: Management group creation parameters. Required. - :type create_management_group_request: IO + :type create_management_group_request: IO[bytes] :param cache_control: Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. Default value is "no-cache". :type cache_control: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either ManagementGroup or An instance of AsyncLROPoller that returns either AzureAsyncOperationResults or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.managementgroups.models.ManagementGroup] @@ -410,34 +376,23 @@ async def begin_create_or_update( async def begin_create_or_update( self, group_id: str, - create_management_group_request: Union[_models.CreateManagementGroupRequest, IO], + create_management_group_request: Union[_models.CreateManagementGroupRequest, IO[bytes]], cache_control: str = "no-cache", **kwargs: Any - ) -> Union[AsyncLROPoller[_models.ManagementGroup], AsyncLROPoller[_models.AzureAsyncOperationResults]]: + ) -> AsyncLROPoller[_models.ManagementGroup]: """Create or update a management group. If a management group is already created and a subsequent create request is issued with different properties, the management group properties will be updated. :param group_id: Management Group ID. Required. :type group_id: str - :param create_management_group_request: Management group creation parameters. Is either a model - type or a IO type. Required. + :param create_management_group_request: Management group creation parameters. Is either a + CreateManagementGroupRequest type or a IO[bytes] type. Required. :type create_management_group_request: - ~azure.mgmt.managementgroups.models.CreateManagementGroupRequest or IO + ~azure.mgmt.managementgroups.models.CreateManagementGroupRequest or IO[bytes] :param cache_control: Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. Default value is "no-cache". :type cache_control: str - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either ManagementGroup or An instance of AsyncLROPoller that returns either AzureAsyncOperationResults or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.managementgroups.models.ManagementGroup] @@ -448,16 +403,14 @@ async def begin_create_or_update( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.ManagementGroup] - polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementGroup] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = await self._create_or_update_initial( # type: ignore + raw_result = await self._create_or_update_initial( group_id=group_id, create_management_group_request=create_management_group_request, cache_control=cache_control, @@ -468,33 +421,34 @@ async def begin_create_or_update( params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ManagementGroup", pipeline_response) + deserialized = self._deserialize("ManagementGroup", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: - polling_method = cast( + polling_method: AsyncPollingMethod = cast( AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs), - ) # type: AsyncPollingMethod + ) elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.ManagementGroup].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - - begin_create_or_update.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}"} # type: ignore + return AsyncLROPoller[_models.ManagementGroup]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) @overload async def update( @@ -518,7 +472,6 @@ async def update( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ManagementGroup or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.ManagementGroup :raises ~azure.core.exceptions.HttpResponseError: @@ -528,7 +481,7 @@ async def update( async def update( self, group_id: str, - patch_group_request: IO, + patch_group_request: IO[bytes], cache_control: str = "no-cache", *, content_type: str = "application/json", @@ -539,14 +492,13 @@ async def update( :param group_id: Management Group ID. Required. :type group_id: str :param patch_group_request: Management group patch parameters. Required. - :type patch_group_request: IO + :type patch_group_request: IO[bytes] :param cache_control: Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. Default value is "no-cache". :type cache_control: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ManagementGroup or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.ManagementGroup :raises ~azure.core.exceptions.HttpResponseError: @@ -556,7 +508,7 @@ async def update( async def update( self, group_id: str, - patch_group_request: Union[_models.PatchManagementGroupRequest, IO], + patch_group_request: Union[_models.PatchManagementGroupRequest, IO[bytes]], cache_control: str = "no-cache", **kwargs: Any ) -> _models.ManagementGroup: @@ -564,22 +516,18 @@ async def update( :param group_id: Management Group ID. Required. :type group_id: str - :param patch_group_request: Management group patch parameters. Is either a model type or a IO - type. Required. + :param patch_group_request: Management group patch parameters. Is either a + PatchManagementGroupRequest type or a IO[bytes] type. Required. :type patch_group_request: ~azure.mgmt.managementgroups.models.PatchManagementGroupRequest or - IO + IO[bytes] :param cache_control: Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. Default value is "no-cache". :type cache_control: str - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ManagementGroup or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.ManagementGroup :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -590,36 +538,33 @@ async def update( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.ManagementGroup] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementGroup] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(patch_group_request, (IO, bytes)): + if isinstance(patch_group_request, (IOBase, bytes)): _content = patch_group_request else: _json = self._serialize.body(patch_group_request, "PatchManagementGroupRequest") - request = build_update_request( + _request = build_update_request( group_id=group_id, cache_control=cache_control, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.update.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -629,19 +574,17 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ManagementGroup", pipeline_response) + deserialized = self._deserialize("ManagementGroup", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - update.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}"} # type: ignore + return deserialized # type: ignore async def _delete_initial( self, group_id: str, cache_control: str = "no-cache", **kwargs: Any - ) -> Optional[_models.AzureAsyncOperationResults]: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -652,34 +595,35 @@ async def _delete_initial( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.AzureAsyncOperationResults]] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( group_id=group_id, cache_control=cache_control, api_version=api_version, - template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [202, 204]: + 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) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = None response_headers = {} if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) @@ -687,14 +631,12 @@ async def _delete_initial( "str", response.headers.get("Azure-AsyncOperation") ) - deserialized = self._deserialize("AzureAsyncOperationResults", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: - return cls(pipeline_response, deserialized, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized - - _delete_initial.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}"} # type: ignore + return deserialized # type: ignore @distributed_trace_async async def begin_delete( @@ -708,14 +650,6 @@ async def begin_delete( :param cache_control: Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. Default value is "no-cache". :type cache_control: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either AzureAsyncOperationResults or the result of cls(response) :rtype: @@ -725,15 +659,13 @@ async def begin_delete( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AzureAsyncOperationResults] - polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.AzureAsyncOperationResults] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = await self._delete_initial( # type: ignore + raw_result = await self._delete_initial( group_id=group_id, cache_control=cache_control, api_version=api_version, @@ -742,6 +674,7 @@ async def begin_delete( params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): @@ -752,30 +685,30 @@ def get_long_running_output(pipeline_response): "str", response.headers.get("Azure-AsyncOperation") ) - deserialized = self._deserialize("AzureAsyncOperationResults", pipeline_response) + deserialized = self._deserialize("AzureAsyncOperationResults", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized if polling is True: - polling_method = cast( + polling_method: AsyncPollingMethod = cast( AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs), - ) # type: AsyncPollingMethod + ) elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.AzureAsyncOperationResults].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - - begin_delete.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}"} # type: ignore + return AsyncLROPoller[_models.AzureAsyncOperationResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) @distributed_trace def get_descendants( @@ -794,7 +727,6 @@ def get_descendants( :param top: Number of elements to return when retrieving results. Passing this in will override $skipToken. Default value is None. :type top: int - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DescendantInfo or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.managementgroups.models.DescendantInfo] @@ -803,12 +735,10 @@ def get_descendants( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.DescendantListResult] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DescendantListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -819,17 +749,15 @@ def get_descendants( def prepare_request(next_link=None): if not next_link: - request = build_get_descendants_request( + _request = build_get_descendants_request( group_id=group_id, skiptoken=skiptoken, top=top, api_version=api_version, - template_url=self.get_descendants.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -841,26 +769,26 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("DescendantListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -872,5 +800,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - get_descendants.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}/descendants"} # type: ignore diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/operations/_operations.py b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/operations/_operations.py index 49a474cb2bf6..9e46fe69fbaa 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/operations/_operations.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/aio/operations/_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,7 +7,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList @@ -20,21 +20,18 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request from ...operations._operations import build_list_request -from .._vendor import ManagementGroupsAPIMixinABC -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -62,7 +59,6 @@ def __init__(self, *args, **kwargs) -> None: def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: """Lists all of the available Management REST API operations. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Operation or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.managementgroups.models.Operation] :raises ~azure.core.exceptions.HttpResponseError: @@ -70,12 +66,10 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -86,14 +80,12 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -105,26 +97,26 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -136,5 +128,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/providers/Microsoft.Management/operations"} # type: ignore diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/models/__init__.py b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/models/__init__.py index 54fb93ced4c1..118960055d79 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/models/__init__.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/models/__init__.py @@ -37,7 +37,6 @@ from ._models_py3 import OperationDisplayProperties from ._models_py3 import OperationListResult from ._models_py3 import OperationResults -from ._models_py3 import ParentGroupBagInfo from ._models_py3 import ParentGroupInfo from ._models_py3 import PatchManagementGroupRequest from ._models_py3 import SubscriptionUnderManagementGroup @@ -51,7 +50,7 @@ from ._management_groups_api_enums import Reason from ._management_groups_api_enums import Status from ._patch import __all__ as _patch_all -from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import * # pylint: disable=unused-wildcard-import from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -86,7 +85,6 @@ "OperationDisplayProperties", "OperationListResult", "OperationResults", - "ParentGroupBagInfo", "ParentGroupInfo", "PatchManagementGroupRequest", "SubscriptionUnderManagementGroup", diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/models/_models_py3.py b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/models/_models_py3.py index 50b3f7130433..85432e7f5f8e 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/models/_models_py3.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/models/_models_py3.py @@ -8,16 +8,10 @@ # -------------------------------------------------------------------------- import datetime -import sys -from typing import List, Optional, TYPE_CHECKING, Union +from typing import Any, List, Literal, Optional, TYPE_CHECKING, Union from .. import _serialization -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports - if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from .. import models as _models @@ -62,7 +56,7 @@ class AzureAsyncOperationResults(_serialization.Model): "display_name": {"key": "properties.displayName", "type": "str"}, } - def __init__(self, *, tenant_id: Optional[str] = None, display_name: Optional[str] = None, **kwargs): + def __init__(self, *, tenant_id: Optional[str] = None, display_name: Optional[str] = None, **kwargs: Any) -> None: """ :keyword tenant_id: The AAD Tenant ID associated with the management group. For example, 00000000-0000-0000-0000-000000000000. @@ -99,8 +93,8 @@ def __init__( *, name: Optional[str] = None, type: Optional[Literal["Microsoft.Management/managementGroups"]] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword name: the name to check for availability. :paramtype name: str @@ -145,7 +139,7 @@ class CheckNameAvailabilityResult(_serialization.Model): "message": {"key": "message", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.name_available = None @@ -190,7 +184,7 @@ class CreateManagementGroupChildInfo(_serialization.Model): "children": {"key": "children", "type": "[CreateManagementGroupChildInfo]"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.type = None @@ -228,7 +222,7 @@ class CreateManagementGroupDetails(_serialization.Model): "parent": {"key": "parent", "type": "CreateParentGroupInfo"}, } - def __init__(self, *, parent: Optional["_models.CreateParentGroupInfo"] = None, **kwargs): + def __init__(self, *, parent: Optional["_models.CreateParentGroupInfo"] = None, **kwargs: Any) -> None: """ :keyword parent: (Optional) The ID of the parent management group used during creation. :paramtype parent: ~azure.mgmt.managementgroups.models.CreateParentGroupInfo @@ -288,8 +282,8 @@ def __init__( name: Optional[str] = None, display_name: Optional[str] = None, details: Optional["_models.CreateManagementGroupDetails"] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword name: The name of the management group. For example, 00000000-0000-0000-0000-000000000000. @@ -338,8 +332,8 @@ def __init__( *, require_authorization_for_group_creation: Optional[bool] = None, default_management_group: Optional[str] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword require_authorization_for_group_creation: Indicates whether RBAC access is required upon group creation under the root Management Group. If set to true, user will require @@ -382,7 +376,7 @@ class CreateParentGroupInfo(_serialization.Model): "display_name": {"key": "displayName", "type": "str"}, } - def __init__(self, *, id: Optional[str] = None, **kwargs): # pylint: disable=redefined-builtin + def __init__(self, *, id: Optional[str] = None, **kwargs: Any) -> None: # pylint: disable=redefined-builtin """ :keyword id: The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. @@ -433,8 +427,8 @@ def __init__( *, display_name: Optional[str] = None, parent: Optional["_models.DescendantParentGroupInfo"] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword display_name: The friendly name of the management group. :paramtype display_name: str @@ -469,7 +463,7 @@ class DescendantListResult(_serialization.Model): "next_link": {"key": "nextLink", "type": "str"}, } - def __init__(self, *, value: Optional[List["_models.DescendantInfo"]] = None, **kwargs): + def __init__(self, *, value: Optional[List["_models.DescendantInfo"]] = None, **kwargs: Any) -> None: """ :keyword value: The list of descendants. :paramtype value: list[~azure.mgmt.managementgroups.models.DescendantInfo] @@ -491,7 +485,7 @@ class DescendantParentGroupInfo(_serialization.Model): "id": {"key": "id", "type": "str"}, } - def __init__(self, *, id: Optional[str] = None, **kwargs): # pylint: disable=redefined-builtin + def __init__(self, *, id: Optional[str] = None, **kwargs: Any) -> None: # pylint: disable=redefined-builtin """ :keyword id: The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. @@ -544,8 +538,8 @@ def __init__( display_name: Optional[str] = None, permissions: Optional[Union[str, "_models.Permissions"]] = None, children: Optional[List["_models.EntityHierarchyItem"]] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword display_name: The friendly name of the management group. :paramtype display_name: str @@ -639,8 +633,8 @@ def __init__( number_of_child_groups: Optional[int] = None, parent_display_name_chain: Optional[List[str]] = None, parent_name_chain: Optional[List[str]] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword tenant_id: The AAD Tenant ID associated with the entity. For example, 00000000-0000-0000-0000-000000000000. @@ -709,7 +703,7 @@ class EntityListResult(_serialization.Model): "next_link": {"key": "nextLink", "type": "str"}, } - def __init__(self, *, value: Optional[List["_models.EntityInfo"]] = None, **kwargs): + def __init__(self, *, value: Optional[List["_models.EntityInfo"]] = None, **kwargs: Any) -> None: """ :keyword value: The list of entities. :paramtype value: list[~azure.mgmt.managementgroups.models.EntityInfo] @@ -732,7 +726,7 @@ class EntityParentGroupInfo(_serialization.Model): "id": {"key": "id", "type": "str"}, } - def __init__(self, *, id: Optional[str] = None, **kwargs): # pylint: disable=redefined-builtin + def __init__(self, *, id: Optional[str] = None, **kwargs: Any) -> None: # pylint: disable=redefined-builtin """ :keyword id: The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. @@ -760,8 +754,8 @@ class ErrorDetails(_serialization.Model): } def __init__( - self, *, code: Optional[str] = None, message: Optional[str] = None, details: Optional[str] = None, **kwargs - ): + self, *, code: Optional[str] = None, message: Optional[str] = None, details: Optional[str] = None, **kwargs: Any + ) -> None: """ :keyword code: One of a server-defined set of error codes. :paramtype code: str @@ -787,7 +781,7 @@ class ErrorResponse(_serialization.Model): "error": {"key": "error", "type": "ErrorDetails"}, } - def __init__(self, *, error: Optional["_models.ErrorDetails"] = None, **kwargs): + def __init__(self, *, error: Optional["_models.ErrorDetails"] = None, **kwargs: Any) -> None: """ :keyword error: The details of the error. :paramtype error: ~azure.mgmt.managementgroups.models.ErrorDetails @@ -848,8 +842,8 @@ def __init__( tenant_id: Optional[str] = None, require_authorization_for_group_creation: Optional[bool] = None, default_management_group: Optional[str] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword tenant_id: The AAD Tenant ID associated with the hierarchy settings. For example, 00000000-0000-0000-0000-000000000000. @@ -926,8 +920,8 @@ def __init__( tenant_id: Optional[str] = None, require_authorization_for_group_creation: Optional[bool] = None, default_management_group: Optional[str] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword tenant_id: The AAD Tenant ID associated with the hierarchy settings. For example, 00000000-0000-0000-0000-000000000000. @@ -969,10 +963,10 @@ class HierarchySettingsList(_serialization.Model): _attribute_map = { "value": {"key": "value", "type": "[HierarchySettingsInfo]"}, - "next_link": {"key": "nextLink", "type": "str"}, + "next_link": {"key": "@nextLink", "type": "str"}, } - def __init__(self, *, value: Optional[List["_models.HierarchySettingsInfo"]] = None, **kwargs): + def __init__(self, *, value: Optional[List["_models.HierarchySettingsInfo"]] = None, **kwargs: Any) -> None: """ :keyword value: The list of hierarchy settings. :paramtype value: list[~azure.mgmt.managementgroups.models.HierarchySettingsInfo] @@ -1002,7 +996,9 @@ class ListSubscriptionUnderManagementGroup(_serialization.Model): "next_link": {"key": "nextLink", "type": "str"}, } - def __init__(self, *, value: Optional[List["_models.SubscriptionUnderManagementGroup"]] = None, **kwargs): + def __init__( + self, *, value: Optional[List["_models.SubscriptionUnderManagementGroup"]] = None, **kwargs: Any + ) -> None: """ :keyword value: The list of subscriptions. :paramtype value: list[~azure.mgmt.managementgroups.models.SubscriptionUnderManagementGroup] @@ -1059,8 +1055,8 @@ def __init__( display_name: Optional[str] = None, details: Optional["_models.ManagementGroupDetails"] = None, children: Optional[List["_models.ManagementGroupChildInfo"]] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword tenant_id: The AAD Tenant ID associated with the management group. For example, 00000000-0000-0000-0000-000000000000. @@ -1117,8 +1113,8 @@ def __init__( name: Optional[str] = None, display_name: Optional[str] = None, children: Optional[List["_models.ManagementGroupChildInfo"]] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword type: The fully qualified resource type which includes provider namespace (e.g. Microsoft.Management/managementGroups). Known values are: @@ -1187,8 +1183,8 @@ def __init__( path: Optional[List["_models.ManagementGroupPathElement"]] = None, management_group_ancestors: Optional[List[str]] = None, management_group_ancestors_chain: Optional[List["_models.ManagementGroupPathElement"]] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword version: The version number of the object. :paramtype version: int @@ -1251,7 +1247,7 @@ class ManagementGroupInfo(_serialization.Model): "display_name": {"key": "properties.displayName", "type": "str"}, } - def __init__(self, *, tenant_id: Optional[str] = None, display_name: Optional[str] = None, **kwargs): + def __init__(self, *, tenant_id: Optional[str] = None, display_name: Optional[str] = None, **kwargs: Any) -> None: """ :keyword tenant_id: The AAD Tenant ID associated with the management group. For example, 00000000-0000-0000-0000-000000000000. @@ -1284,10 +1280,10 @@ class ManagementGroupListResult(_serialization.Model): _attribute_map = { "value": {"key": "value", "type": "[ManagementGroupInfo]"}, - "next_link": {"key": "nextLink", "type": "str"}, + "next_link": {"key": "@nextLink", "type": "str"}, } - def __init__(self, *, value: Optional[List["_models.ManagementGroupInfo"]] = None, **kwargs): + def __init__(self, *, value: Optional[List["_models.ManagementGroupInfo"]] = None, **kwargs: Any) -> None: """ :keyword value: The list of management groups. :paramtype value: list[~azure.mgmt.managementgroups.models.ManagementGroupInfo] @@ -1311,7 +1307,7 @@ class ManagementGroupPathElement(_serialization.Model): "display_name": {"key": "displayName", "type": "str"}, } - def __init__(self, *, name: Optional[str] = None, display_name: Optional[str] = None, **kwargs): + def __init__(self, *, name: Optional[str] = None, display_name: Optional[str] = None, **kwargs: Any) -> None: """ :keyword name: The name of the group. :paramtype name: str @@ -1343,7 +1339,7 @@ class Operation(_serialization.Model): "display": {"key": "display", "type": "OperationDisplayProperties"}, } - def __init__(self, *, display: Optional["_models.OperationDisplayProperties"] = None, **kwargs): + def __init__(self, *, display: Optional["_models.OperationDisplayProperties"] = None, **kwargs: Any) -> None: """ :keyword display: The object that represents the operation. :paramtype display: ~azure.mgmt.managementgroups.models.OperationDisplayProperties @@ -1382,7 +1378,7 @@ class OperationDisplayProperties(_serialization.Model): "description": {"key": "description", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.provider = None @@ -1412,7 +1408,7 @@ class OperationListResult(_serialization.Model): "next_link": {"key": "nextLink", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.value = None @@ -1453,7 +1449,7 @@ class OperationResults(_serialization.Model): "display_name": {"key": "properties.displayName", "type": "str"}, } - def __init__(self, *, tenant_id: Optional[str] = None, display_name: Optional[str] = None, **kwargs): + def __init__(self, *, tenant_id: Optional[str] = None, display_name: Optional[str] = None, **kwargs: Any) -> None: """ :keyword tenant_id: The AAD Tenant ID associated with the management group. For example, 00000000-0000-0000-0000-000000000000. @@ -1469,49 +1465,6 @@ def __init__(self, *, tenant_id: Optional[str] = None, display_name: Optional[st self.display_name = display_name -class ParentGroupBagInfo(_serialization.Model): - """The ID, name and displayName of the parent management group. - - :ivar id: The fully qualified ID for the parent management group. For example, - /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - :vartype id: str - :ivar name: The name of the parent management group. For example, - 00000000-0000-0000-0000-000000000000. - :vartype name: str - :ivar display_name: The friendly name of the parent management group. - :vartype display_name: str - """ - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "display_name": {"key": "displayName", "type": "str"}, - } - - def __init__( - self, - *, - id: Optional[str] = None, # pylint: disable=redefined-builtin - name: Optional[str] = None, - display_name: Optional[str] = None, - **kwargs - ): - """ - :keyword id: The fully qualified ID for the parent management group. For example, - /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - :paramtype id: str - :keyword name: The name of the parent management group. For example, - 00000000-0000-0000-0000-000000000000. - :paramtype name: str - :keyword display_name: The friendly name of the parent management group. - :paramtype display_name: str - """ - super().__init__(**kwargs) - self.id = id - self.name = name - self.display_name = display_name - - class ParentGroupInfo(_serialization.Model): """(Optional) The ID of the parent management group. @@ -1536,8 +1489,8 @@ def __init__( id: Optional[str] = None, # pylint: disable=redefined-builtin name: Optional[str] = None, display_name: Optional[str] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword id: The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. @@ -1568,7 +1521,9 @@ class PatchManagementGroupRequest(_serialization.Model): "parent_group_id": {"key": "parentGroupId", "type": "str"}, } - def __init__(self, *, display_name: Optional[str] = None, parent_group_id: Optional[str] = None, **kwargs): + def __init__( + self, *, display_name: Optional[str] = None, parent_group_id: Optional[str] = None, **kwargs: Any + ) -> None: """ :keyword display_name: The friendly name of the management group. :paramtype display_name: str @@ -1588,7 +1543,7 @@ class SubscriptionUnderManagementGroup(_serialization.Model): Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The fully qualified ID for the subscription. For example, - /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000/subscriptions/0000000-0000-0000-0000-000000000001. + /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000/subscriptions/0000000-0000-0000-0000-000000000001. # pylint: disable=line-too-long :vartype id: str :ivar type: The type of the resource. For example, Microsoft.Management/managementGroups/subscriptions. @@ -1601,8 +1556,8 @@ class SubscriptionUnderManagementGroup(_serialization.Model): :vartype tenant: str :ivar display_name: The friendly name of the subscription. :vartype display_name: str - :ivar parent: The ID, name and displayName of the parent management group. - :vartype parent: ~azure.mgmt.managementgroups.models.ParentGroupBagInfo + :ivar parent: The ID of the parent management group. + :vartype parent: ~azure.mgmt.managementgroups.models.DescendantParentGroupInfo :ivar state: The state of the subscription. :vartype state: str """ @@ -1619,7 +1574,7 @@ class SubscriptionUnderManagementGroup(_serialization.Model): "name": {"key": "name", "type": "str"}, "tenant": {"key": "properties.tenant", "type": "str"}, "display_name": {"key": "properties.displayName", "type": "str"}, - "parent": {"key": "properties.parent", "type": "ParentGroupBagInfo"}, + "parent": {"key": "properties.parent", "type": "DescendantParentGroupInfo"}, "state": {"key": "properties.state", "type": "str"}, } @@ -1628,18 +1583,18 @@ def __init__( *, tenant: Optional[str] = None, display_name: Optional[str] = None, - parent: Optional["_models.ParentGroupBagInfo"] = None, + parent: Optional["_models.DescendantParentGroupInfo"] = None, state: Optional[str] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword tenant: The AAD Tenant ID associated with the subscription. For example, 00000000-0000-0000-0000-000000000000. :paramtype tenant: str :keyword display_name: The friendly name of the subscription. :paramtype display_name: str - :keyword parent: The ID, name and displayName of the parent management group. - :paramtype parent: ~azure.mgmt.managementgroups.models.ParentGroupBagInfo + :keyword parent: The ID of the parent management group. + :paramtype parent: ~azure.mgmt.managementgroups.models.DescendantParentGroupInfo :keyword state: The state of the subscription. :paramtype state: str """ @@ -1676,7 +1631,7 @@ class TenantBackfillStatusResult(_serialization.Model): "status": {"key": "status", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.tenant_id = None diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/operations/__init__.py b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/operations/__init__.py index 2d20b499bdbe..17da0c8d00e0 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/operations/__init__.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/operations/__init__.py @@ -14,7 +14,7 @@ from ._entities_operations import EntitiesOperations from ._patch import __all__ as _patch_all -from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import * # pylint: disable=unused-wildcard-import from ._patch import patch_sdk as _patch_sdk __all__ = [ diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/operations/_entities_operations.py b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/operations/_entities_operations.py index f48b3816c479..848a0c91605d 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/operations/_entities_operations.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/operations/_entities_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,7 +7,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import sys -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar, Union import urllib.parse from azure.core.exceptions import ( @@ -20,20 +20,18 @@ ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer -from .._vendor import ManagementGroupsAPIMixinABC, _convert_request -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -57,7 +55,7 @@ def build_list_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) # type: Literal["2021-04-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -176,7 +174,6 @@ def list( :param cache_control: Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. Default value is "no-cache". :type cache_control: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either EntityInfo or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.managementgroups.models.EntityInfo] :raises ~azure.core.exceptions.HttpResponseError: @@ -184,12 +181,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.EntityListResult] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.EntityListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -200,7 +195,7 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( skiptoken=skiptoken, skip=skip, top=top, @@ -211,12 +206,10 @@ def prepare_request(next_link=None): group_name=group_name, cache_control=cache_control, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -228,26 +221,26 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("EntityListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -259,5 +252,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/providers/Microsoft.Management/getEntities"} # type: ignore diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/operations/_hierarchy_settings_operations.py b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/operations/_hierarchy_settings_operations.py index ef3c8ad2a1fc..d7cb37ab15bf 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/operations/_hierarchy_settings_operations.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/operations/_hierarchy_settings_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,8 +6,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase import sys -from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload +from typing import Any, Callable, Dict, IO, Optional, Type, TypeVar, Union, overload from azure.core.exceptions import ( ClientAuthenticationError, @@ -18,20 +19,18 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer -from .._vendor import ManagementGroupsAPIMixinABC, _convert_request, _format_url_section -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -43,7 +42,7 @@ def build_list_request(group_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) # type: Literal["2021-04-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -52,7 +51,7 @@ def build_list_request(group_id: str, **kwargs: Any) -> HttpRequest: "groupId": _SERIALIZER.url("group_id", group_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -67,7 +66,7 @@ def build_get_request(group_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) # type: Literal["2021-04-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -76,7 +75,7 @@ def build_get_request(group_id: str, **kwargs: Any) -> HttpRequest: "groupId": _SERIALIZER.url("group_id", group_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -91,8 +90,8 @@ def build_create_or_update_request(group_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) # type: Literal["2021-04-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -101,7 +100,7 @@ def build_create_or_update_request(group_id: str, **kwargs: Any) -> HttpRequest: "groupId": _SERIALIZER.url("group_id", group_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -118,8 +117,8 @@ def build_update_request(group_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) # type: Literal["2021-04-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -128,7 +127,7 @@ def build_update_request(group_id: str, **kwargs: Any) -> HttpRequest: "groupId": _SERIALIZER.url("group_id", group_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -145,7 +144,7 @@ def build_delete_request(group_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) # type: Literal["2021-04-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -154,7 +153,7 @@ def build_delete_request(group_id: str, **kwargs: Any) -> HttpRequest: "groupId": _SERIALIZER.url("group_id", group_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -191,12 +190,11 @@ def list(self, group_id: str, **kwargs: Any) -> _models.HierarchySettingsList: :param group_id: Management Group ID. Required. :type group_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: HierarchySettingsList or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.HierarchySettingsList :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -207,23 +205,20 @@ def list(self, group_id: str, **kwargs: Any) -> _models.HierarchySettingsList: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.HierarchySettingsList] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.HierarchySettingsList] = kwargs.pop("cls", None) - request = build_list_request( + _request = build_list_request( group_id=group_id, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -233,14 +228,12 @@ def list(self, group_id: str, **kwargs: Any) -> _models.HierarchySettingsList: error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("HierarchySettingsList", pipeline_response) + deserialized = self._deserialize("HierarchySettingsList", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - list.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}/settings"} # type: ignore + return deserialized # type: ignore @distributed_trace def get(self, group_id: str, **kwargs: Any) -> _models.HierarchySettings: @@ -249,12 +242,11 @@ def get(self, group_id: str, **kwargs: Any) -> _models.HierarchySettings: :param group_id: Management Group ID. Required. :type group_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: HierarchySettings or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -265,23 +257,20 @@ def get(self, group_id: str, **kwargs: Any) -> _models.HierarchySettings: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.HierarchySettings] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.HierarchySettings] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( group_id=group_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -291,14 +280,12 @@ def get(self, group_id: str, **kwargs: Any) -> _models.HierarchySettings: error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("HierarchySettings", pipeline_response) + deserialized = self._deserialize("HierarchySettings", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}/settings/default"} # type: ignore + return deserialized # type: ignore @overload def create_or_update( @@ -319,7 +306,6 @@ def create_or_update( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: HierarchySettings or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings :raises ~azure.core.exceptions.HttpResponseError: @@ -329,7 +315,7 @@ def create_or_update( def create_or_update( self, group_id: str, - create_tenant_settings_request: IO, + create_tenant_settings_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -339,11 +325,10 @@ def create_or_update( :param group_id: Management Group ID. Required. :type group_id: str :param create_tenant_settings_request: Tenant level settings request parameter. Required. - :type create_tenant_settings_request: IO + :type create_tenant_settings_request: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: HierarchySettings or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings :raises ~azure.core.exceptions.HttpResponseError: @@ -353,7 +338,7 @@ def create_or_update( def create_or_update( self, group_id: str, - create_tenant_settings_request: Union[_models.CreateOrUpdateSettingsRequest, IO], + create_tenant_settings_request: Union[_models.CreateOrUpdateSettingsRequest, IO[bytes]], **kwargs: Any ) -> _models.HierarchySettings: """Creates or updates the hierarchy settings defined at the Management Group level. @@ -361,18 +346,14 @@ def create_or_update( :param group_id: Management Group ID. Required. :type group_id: str :param create_tenant_settings_request: Tenant level settings request parameter. Is either a - model type or a IO type. Required. + CreateOrUpdateSettingsRequest type or a IO[bytes] type. Required. :type create_tenant_settings_request: - ~azure.mgmt.managementgroups.models.CreateOrUpdateSettingsRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + ~azure.mgmt.managementgroups.models.CreateOrUpdateSettingsRequest or IO[bytes] :return: HierarchySettings or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -383,35 +364,32 @@ def create_or_update( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.HierarchySettings] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.HierarchySettings] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(create_tenant_settings_request, (IO, bytes)): + if isinstance(create_tenant_settings_request, (IOBase, bytes)): _content = create_tenant_settings_request else: _json = self._serialize.body(create_tenant_settings_request, "CreateOrUpdateSettingsRequest") - request = build_create_or_update_request( + _request = build_create_or_update_request( group_id=group_id, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.create_or_update.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -421,14 +399,12 @@ def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("HierarchySettings", pipeline_response) + deserialized = self._deserialize("HierarchySettings", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - create_or_update.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}/settings/default"} # type: ignore + return deserialized # type: ignore @overload def update( @@ -449,7 +425,6 @@ def update( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: HierarchySettings or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings :raises ~azure.core.exceptions.HttpResponseError: @@ -459,7 +434,7 @@ def update( def update( self, group_id: str, - create_tenant_settings_request: IO, + create_tenant_settings_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -469,11 +444,10 @@ def update( :param group_id: Management Group ID. Required. :type group_id: str :param create_tenant_settings_request: Tenant level settings request parameter. Required. - :type create_tenant_settings_request: IO + :type create_tenant_settings_request: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: HierarchySettings or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings :raises ~azure.core.exceptions.HttpResponseError: @@ -483,7 +457,7 @@ def update( def update( self, group_id: str, - create_tenant_settings_request: Union[_models.CreateOrUpdateSettingsRequest, IO], + create_tenant_settings_request: Union[_models.CreateOrUpdateSettingsRequest, IO[bytes]], **kwargs: Any ) -> _models.HierarchySettings: """Updates the hierarchy settings defined at the Management Group level. @@ -491,18 +465,14 @@ def update( :param group_id: Management Group ID. Required. :type group_id: str :param create_tenant_settings_request: Tenant level settings request parameter. Is either a - model type or a IO type. Required. + CreateOrUpdateSettingsRequest type or a IO[bytes] type. Required. :type create_tenant_settings_request: - ~azure.mgmt.managementgroups.models.CreateOrUpdateSettingsRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + ~azure.mgmt.managementgroups.models.CreateOrUpdateSettingsRequest or IO[bytes] :return: HierarchySettings or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -513,35 +483,32 @@ def update( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.HierarchySettings] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.HierarchySettings] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(create_tenant_settings_request, (IO, bytes)): + if isinstance(create_tenant_settings_request, (IOBase, bytes)): _content = create_tenant_settings_request else: _json = self._serialize.body(create_tenant_settings_request, "CreateOrUpdateSettingsRequest") - request = build_update_request( + _request = build_update_request( group_id=group_id, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.update.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -551,14 +518,12 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("HierarchySettings", pipeline_response) + deserialized = self._deserialize("HierarchySettings", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - update.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}/settings/default"} # type: ignore + return deserialized # type: ignore @distributed_trace def delete(self, group_id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements @@ -566,12 +531,11 @@ def delete(self, group_id: str, **kwargs: Any) -> None: # pylint: disable=incon :param group_id: Management Group ID. Required. :type group_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -582,23 +546,20 @@ def delete(self, group_id: str, **kwargs: Any) -> None: # pylint: disable=incon _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[None] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( group_id=group_id, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -609,6 +570,4 @@ def delete(self, group_id: str, **kwargs: Any) -> None: # pylint: disable=incon raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}/settings/default"} # type: ignore + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/operations/_management_group_subscriptions_operations.py b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/operations/_management_group_subscriptions_operations.py index db2fb22bc452..a1ba0e701465 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/operations/_management_group_subscriptions_operations.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/operations/_management_group_subscriptions_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,7 +7,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import sys -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar import urllib.parse from azure.core.exceptions import ( @@ -20,20 +20,18 @@ ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer -from .._vendor import ManagementGroupsAPIMixinABC, _convert_request, _format_url_section -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -47,7 +45,7 @@ def build_create_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) # type: Literal["2021-04-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -59,7 +57,7 @@ def build_create_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -78,7 +76,7 @@ def build_delete_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) # type: Literal["2021-04-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -90,7 +88,7 @@ def build_delete_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -109,7 +107,7 @@ def build_get_subscription_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) # type: Literal["2021-04-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -121,7 +119,7 @@ def build_get_subscription_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -134,13 +132,13 @@ def build_get_subscription_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_get_subscriptions_under_management_group_request( +def build_get_subscriptions_under_management_group_request( # pylint: disable=name-too-long group_id: str, *, skiptoken: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) # type: Literal["2021-04-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -149,7 +147,7 @@ def build_get_subscriptions_under_management_group_request( "groupId": _SERIALIZER.url("group_id", group_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -194,12 +192,11 @@ def create( :param cache_control: Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. Default value is "no-cache". :type cache_control: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: SubscriptionUnderManagementGroup or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.SubscriptionUnderManagementGroup :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -210,25 +207,22 @@ def create( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.SubscriptionUnderManagementGroup] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SubscriptionUnderManagementGroup] = kwargs.pop("cls", None) - request = build_create_request( + _request = build_create_request( group_id=group_id, subscription_id=subscription_id, cache_control=cache_control, api_version=api_version, - template_url=self.create.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -238,14 +232,12 @@ def create( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("SubscriptionUnderManagementGroup", pipeline_response) + deserialized = self._deserialize("SubscriptionUnderManagementGroup", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - create.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId}"} # type: ignore + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -260,12 +252,11 @@ def delete( # pylint: disable=inconsistent-return-statements :param cache_control: Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. Default value is "no-cache". :type cache_control: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -276,25 +267,22 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[None] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( group_id=group_id, subscription_id=subscription_id, cache_control=cache_control, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -305,9 +293,7 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId}"} # type: ignore + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def get_subscription( @@ -322,12 +308,11 @@ def get_subscription( :param cache_control: Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. Default value is "no-cache". :type cache_control: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: SubscriptionUnderManagementGroup or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.SubscriptionUnderManagementGroup :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -338,25 +323,22 @@ def get_subscription( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.SubscriptionUnderManagementGroup] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SubscriptionUnderManagementGroup] = kwargs.pop("cls", None) - request = build_get_subscription_request( + _request = build_get_subscription_request( group_id=group_id, subscription_id=subscription_id, cache_control=cache_control, api_version=api_version, - template_url=self.get_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -366,14 +348,12 @@ def get_subscription( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("SubscriptionUnderManagementGroup", pipeline_response) + deserialized = self._deserialize("SubscriptionUnderManagementGroup", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - get_subscription.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId}"} # type: ignore + return deserialized # type: ignore @distributed_trace def get_subscriptions_under_management_group( @@ -389,7 +369,6 @@ def get_subscriptions_under_management_group( include a token parameter that specifies a starting point to use for subsequent calls. Default value is None. :type skiptoken: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either SubscriptionUnderManagementGroup or the result of cls(response) :rtype: @@ -399,12 +378,10 @@ def get_subscriptions_under_management_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.ListSubscriptionUnderManagementGroup] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ListSubscriptionUnderManagementGroup] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -415,16 +392,14 @@ def get_subscriptions_under_management_group( def prepare_request(next_link=None): if not next_link: - request = build_get_subscriptions_under_management_group_request( + _request = build_get_subscriptions_under_management_group_request( group_id=group_id, skiptoken=skiptoken, api_version=api_version, - template_url=self.get_subscriptions_under_management_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -436,26 +411,26 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ListSubscriptionUnderManagementGroup", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -467,5 +442,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - get_subscriptions_under_management_group.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}/subscriptions"} # type: ignore diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/operations/_management_groups_api_operations.py b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/operations/_management_groups_api_operations.py index ba664f389d09..665856ed4c5a 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/operations/_management_groups_api_operations.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/operations/_management_groups_api_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,8 +6,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase import sys -from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload +from typing import Any, Callable, Dict, IO, Optional, Type, TypeVar, Union, overload from azure.core.exceptions import ( ClientAuthenticationError, @@ -18,20 +19,19 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer -from .._vendor import ManagementGroupsAPIMixinABC, _convert_request +from .._vendor import ManagementGroupsAPIMixinABC -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -43,8 +43,8 @@ def build_check_name_availability_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) # type: Literal["2021-04-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -65,7 +65,7 @@ def build_start_tenant_backfill_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) # type: Literal["2021-04-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -84,7 +84,7 @@ def build_tenant_backfill_status_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) # type: Literal["2021-04-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -100,6 +100,7 @@ def build_tenant_backfill_status_request(**kwargs: Any) -> HttpRequest: class ManagementGroupsAPIOperationsMixin(ManagementGroupsAPIMixinABC): + @overload def check_name_availability( self, @@ -117,7 +118,6 @@ def check_name_availability( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: CheckNameAvailabilityResult or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.CheckNameAvailabilityResult :raises ~azure.core.exceptions.HttpResponseError: @@ -125,17 +125,16 @@ def check_name_availability( @overload def check_name_availability( - self, check_name_availability_request: IO, *, content_type: str = "application/json", **kwargs: Any + self, check_name_availability_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.CheckNameAvailabilityResult: """Checks if the specified management group name is valid and unique. :param check_name_availability_request: Management group name availability check parameters. Required. - :type check_name_availability_request: IO + :type check_name_availability_request: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: CheckNameAvailabilityResult or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.CheckNameAvailabilityResult :raises ~azure.core.exceptions.HttpResponseError: @@ -143,23 +142,19 @@ def check_name_availability( @distributed_trace def check_name_availability( - self, check_name_availability_request: Union[_models.CheckNameAvailabilityRequest, IO], **kwargs: Any + self, check_name_availability_request: Union[_models.CheckNameAvailabilityRequest, IO[bytes]], **kwargs: Any ) -> _models.CheckNameAvailabilityResult: """Checks if the specified management group name is valid and unique. :param check_name_availability_request: Management group name availability check parameters. Is - either a model type or a IO type. Required. + either a CheckNameAvailabilityRequest type or a IO[bytes] type. Required. :type check_name_availability_request: - ~azure.mgmt.managementgroups.models.CheckNameAvailabilityRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + ~azure.mgmt.managementgroups.models.CheckNameAvailabilityRequest or IO[bytes] :return: CheckNameAvailabilityResult or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.CheckNameAvailabilityResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -170,34 +165,31 @@ def check_name_availability( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckNameAvailabilityResult] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CheckNameAvailabilityResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(check_name_availability_request, (IO, bytes)): + if isinstance(check_name_availability_request, (IOBase, bytes)): _content = check_name_availability_request else: _json = self._serialize.body(check_name_availability_request, "CheckNameAvailabilityRequest") - request = build_check_name_availability_request( + _request = build_check_name_availability_request( api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.check_name_availability.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -207,25 +199,22 @@ def check_name_availability( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("CheckNameAvailabilityResult", pipeline_response) + deserialized = self._deserialize("CheckNameAvailabilityResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - check_name_availability.metadata = {"url": "/providers/Microsoft.Management/checkNameAvailability"} # type: ignore + return deserialized # type: ignore @distributed_trace def start_tenant_backfill(self, **kwargs: Any) -> _models.TenantBackfillStatusResult: """Starts backfilling subscriptions for the Tenant. - :keyword callable cls: A custom type or function that will be passed the direct response :return: TenantBackfillStatusResult or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.TenantBackfillStatusResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -236,22 +225,19 @@ def start_tenant_backfill(self, **kwargs: Any) -> _models.TenantBackfillStatusRe _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.TenantBackfillStatusResult] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.TenantBackfillStatusResult] = kwargs.pop("cls", None) - request = build_start_tenant_backfill_request( + _request = build_start_tenant_backfill_request( api_version=api_version, - template_url=self.start_tenant_backfill.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -261,25 +247,22 @@ def start_tenant_backfill(self, **kwargs: Any) -> _models.TenantBackfillStatusRe error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("TenantBackfillStatusResult", pipeline_response) + deserialized = self._deserialize("TenantBackfillStatusResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - start_tenant_backfill.metadata = {"url": "/providers/Microsoft.Management/startTenantBackfill"} # type: ignore + return deserialized # type: ignore @distributed_trace def tenant_backfill_status(self, **kwargs: Any) -> _models.TenantBackfillStatusResult: """Gets tenant backfill status. - :keyword callable cls: A custom type or function that will be passed the direct response :return: TenantBackfillStatusResult or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.TenantBackfillStatusResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -290,22 +273,19 @@ def tenant_backfill_status(self, **kwargs: Any) -> _models.TenantBackfillStatusR _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.TenantBackfillStatusResult] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.TenantBackfillStatusResult] = kwargs.pop("cls", None) - request = build_tenant_backfill_status_request( + _request = build_tenant_backfill_status_request( api_version=api_version, - template_url=self.tenant_backfill_status.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -315,11 +295,9 @@ def tenant_backfill_status(self, **kwargs: Any) -> _models.TenantBackfillStatusR error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("TenantBackfillStatusResult", pipeline_response) + deserialized = self._deserialize("TenantBackfillStatusResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - tenant_backfill_status.metadata = {"url": "/providers/Microsoft.Management/tenantBackfillStatus"} # type: ignore + return deserialized # type: ignore diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/operations/_management_groups_operations.py b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/operations/_management_groups_operations.py index cc4bd933384a..62631da53036 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/operations/_management_groups_operations.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/operations/_management_groups_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,8 +6,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase import sys -from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload import urllib.parse from azure.core.exceptions import ( @@ -16,13 +17,14 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat @@ -30,12 +32,11 @@ from .. import models as _models from .._serialization import Serializer -from .._vendor import ManagementGroupsAPIMixinABC, _convert_request, _format_url_section -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -49,7 +50,7 @@ def build_list_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) # type: Literal["2021-04-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -80,7 +81,7 @@ def build_get_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) # type: Literal["2021-04-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -89,7 +90,7 @@ def build_get_request( "groupId": _SERIALIZER.url("group_id", group_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -112,8 +113,8 @@ def build_create_or_update_request(group_id: str, *, cache_control: str = "no-ca _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) # type: Literal["2021-04-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -122,7 +123,7 @@ def build_create_or_update_request(group_id: str, *, cache_control: str = "no-ca "groupId": _SERIALIZER.url("group_id", group_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -141,8 +142,8 @@ def build_update_request(group_id: str, *, cache_control: str = "no-cache", **kw _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) # type: Literal["2021-04-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -151,7 +152,7 @@ def build_update_request(group_id: str, *, cache_control: str = "no-cache", **kw "groupId": _SERIALIZER.url("group_id", group_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -170,7 +171,7 @@ def build_delete_request(group_id: str, *, cache_control: str = "no-cache", **kw _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) # type: Literal["2021-04-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -179,7 +180,7 @@ def build_delete_request(group_id: str, *, cache_control: str = "no-cache", **kw "groupId": _SERIALIZER.url("group_id", group_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -198,7 +199,7 @@ def build_get_descendants_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) # type: Literal["2021-04-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -207,7 +208,7 @@ def build_get_descendants_request( "groupId": _SERIALIZER.url("group_id", group_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -256,7 +257,6 @@ def list( include a token parameter that specifies a starting point to use for subsequent calls. Default value is None. :type skiptoken: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ManagementGroupInfo or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.managementgroups.models.ManagementGroupInfo] :raises ~azure.core.exceptions.HttpResponseError: @@ -264,12 +264,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.ManagementGroupListResult] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ManagementGroupListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -280,16 +278,14 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( cache_control=cache_control, skiptoken=skiptoken, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -301,26 +297,26 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ManagementGroupListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -333,8 +329,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list.metadata = {"url": "/providers/Microsoft.Management/managementGroups"} # type: ignore - @distributed_trace def get( self, @@ -364,12 +358,11 @@ def get( :param cache_control: Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. Default value is "no-cache". :type cache_control: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ManagementGroup or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.ManagementGroup :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -380,27 +373,24 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.ManagementGroup] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ManagementGroup] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( group_id=group_id, expand=expand, recurse=recurse, filter=filter, cache_control=cache_control, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -410,23 +400,21 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ManagementGroup", pipeline_response) + deserialized = self._deserialize("ManagementGroup", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}"} # type: ignore + return deserialized # type: ignore def _create_or_update_initial( self, group_id: str, - create_management_group_request: Union[_models.CreateManagementGroupRequest, IO], + create_management_group_request: Union[_models.CreateManagementGroupRequest, IO[bytes]], cache_control: str = "no-cache", **kwargs: Any - ) -> Union[_models.ManagementGroup, _models.AzureAsyncOperationResults]: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -437,65 +425,60 @@ def _create_or_update_initial( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop( - "cls", None - ) # type: ClsType[Union[_models.ManagementGroup, _models.AzureAsyncOperationResults]] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(create_management_group_request, (IO, bytes)): + if isinstance(create_management_group_request, (IOBase, bytes)): _content = create_management_group_request else: _json = self._serialize.body(create_management_group_request, "CreateManagementGroupRequest") - request = build_create_or_update_request( + _request = build_create_or_update_request( group_id=group_id, cache_control=cache_control, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("ManagementGroup", pipeline_response) - if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Azure-AsyncOperation"] = self._deserialize( "str", response.headers.get("Azure-AsyncOperation") ) - deserialized = self._deserialize("AzureAsyncOperationResults", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: - return cls(pipeline_response, deserialized, response_headers) - - return deserialized + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _create_or_update_initial.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}"} # type: ignore + return deserialized # type: ignore @overload def begin_create_or_update( @@ -506,7 +489,7 @@ def begin_create_or_update( *, content_type: str = "application/json", **kwargs: Any - ) -> Union[LROPoller[_models.ManagementGroup], LROPoller[_models.AzureAsyncOperationResults]]: + ) -> LROPoller[_models.ManagementGroup]: """Create or update a management group. If a management group is already created and a subsequent create request is issued with different properties, the management group properties will be updated. @@ -522,14 +505,6 @@ def begin_create_or_update( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either ManagementGroup or An instance of LROPoller that returns either AzureAsyncOperationResults or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.managementgroups.models.ManagementGroup] or @@ -541,12 +516,12 @@ def begin_create_or_update( def begin_create_or_update( self, group_id: str, - create_management_group_request: IO, + create_management_group_request: IO[bytes], cache_control: str = "no-cache", *, content_type: str = "application/json", **kwargs: Any - ) -> Union[LROPoller[_models.ManagementGroup], LROPoller[_models.AzureAsyncOperationResults]]: + ) -> LROPoller[_models.ManagementGroup]: """Create or update a management group. If a management group is already created and a subsequent create request is issued with different properties, the management group properties will be updated. @@ -554,21 +529,13 @@ def begin_create_or_update( :param group_id: Management Group ID. Required. :type group_id: str :param create_management_group_request: Management group creation parameters. Required. - :type create_management_group_request: IO + :type create_management_group_request: IO[bytes] :param cache_control: Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. Default value is "no-cache". :type cache_control: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either ManagementGroup or An instance of LROPoller that returns either AzureAsyncOperationResults or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.managementgroups.models.ManagementGroup] or @@ -580,34 +547,23 @@ def begin_create_or_update( def begin_create_or_update( self, group_id: str, - create_management_group_request: Union[_models.CreateManagementGroupRequest, IO], + create_management_group_request: Union[_models.CreateManagementGroupRequest, IO[bytes]], cache_control: str = "no-cache", **kwargs: Any - ) -> Union[LROPoller[_models.ManagementGroup], LROPoller[_models.AzureAsyncOperationResults]]: + ) -> LROPoller[_models.ManagementGroup]: """Create or update a management group. If a management group is already created and a subsequent create request is issued with different properties, the management group properties will be updated. :param group_id: Management Group ID. Required. :type group_id: str - :param create_management_group_request: Management group creation parameters. Is either a model - type or a IO type. Required. + :param create_management_group_request: Management group creation parameters. Is either a + CreateManagementGroupRequest type or a IO[bytes] type. Required. :type create_management_group_request: - ~azure.mgmt.managementgroups.models.CreateManagementGroupRequest or IO + ~azure.mgmt.managementgroups.models.CreateManagementGroupRequest or IO[bytes] :param cache_control: Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. Default value is "no-cache". :type cache_control: str - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either ManagementGroup or An instance of LROPoller that returns either AzureAsyncOperationResults or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.managementgroups.models.ManagementGroup] or @@ -617,16 +573,14 @@ def begin_create_or_update( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.ManagementGroup] - polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementGroup] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = self._create_or_update_initial( # type: ignore + raw_result = self._create_or_update_initial( group_id=group_id, create_management_group_request=create_management_group_request, cache_control=cache_control, @@ -637,32 +591,33 @@ def begin_create_or_update( params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ManagementGroup", pipeline_response) + deserialized = self._deserialize("ManagementGroup", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: - polling_method = cast( + polling_method: PollingMethod = cast( PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs) - ) # type: PollingMethod + ) elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.ManagementGroup].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - - begin_create_or_update.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}"} # type: ignore + return LROPoller[_models.ManagementGroup]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) @overload def update( @@ -686,7 +641,6 @@ def update( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ManagementGroup or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.ManagementGroup :raises ~azure.core.exceptions.HttpResponseError: @@ -696,7 +650,7 @@ def update( def update( self, group_id: str, - patch_group_request: IO, + patch_group_request: IO[bytes], cache_control: str = "no-cache", *, content_type: str = "application/json", @@ -707,14 +661,13 @@ def update( :param group_id: Management Group ID. Required. :type group_id: str :param patch_group_request: Management group patch parameters. Required. - :type patch_group_request: IO + :type patch_group_request: IO[bytes] :param cache_control: Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. Default value is "no-cache". :type cache_control: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ManagementGroup or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.ManagementGroup :raises ~azure.core.exceptions.HttpResponseError: @@ -724,7 +677,7 @@ def update( def update( self, group_id: str, - patch_group_request: Union[_models.PatchManagementGroupRequest, IO], + patch_group_request: Union[_models.PatchManagementGroupRequest, IO[bytes]], cache_control: str = "no-cache", **kwargs: Any ) -> _models.ManagementGroup: @@ -732,22 +685,18 @@ def update( :param group_id: Management Group ID. Required. :type group_id: str - :param patch_group_request: Management group patch parameters. Is either a model type or a IO - type. Required. + :param patch_group_request: Management group patch parameters. Is either a + PatchManagementGroupRequest type or a IO[bytes] type. Required. :type patch_group_request: ~azure.mgmt.managementgroups.models.PatchManagementGroupRequest or - IO + IO[bytes] :param cache_control: Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. Default value is "no-cache". :type cache_control: str - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ManagementGroup or the result of cls(response) :rtype: ~azure.mgmt.managementgroups.models.ManagementGroup :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -758,36 +707,33 @@ def update( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.ManagementGroup] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementGroup] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(patch_group_request, (IO, bytes)): + if isinstance(patch_group_request, (IOBase, bytes)): _content = patch_group_request else: _json = self._serialize.body(patch_group_request, "PatchManagementGroupRequest") - request = build_update_request( + _request = build_update_request( group_id=group_id, cache_control=cache_control, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.update.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -797,19 +743,15 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ManagementGroup", pipeline_response) + deserialized = self._deserialize("ManagementGroup", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - update.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}"} # type: ignore + return deserialized # type: ignore - def _delete_initial( - self, group_id: str, cache_control: str = "no-cache", **kwargs: Any - ) -> Optional[_models.AzureAsyncOperationResults]: - error_map = { + def _delete_initial(self, group_id: str, cache_control: str = "no-cache", **kwargs: Any) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -820,34 +762,35 @@ def _delete_initial( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.AzureAsyncOperationResults]] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( group_id=group_id, cache_control=cache_control, api_version=api_version, - template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [202, 204]: + 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) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = None response_headers = {} if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) @@ -855,14 +798,12 @@ def _delete_initial( "str", response.headers.get("Azure-AsyncOperation") ) - deserialized = self._deserialize("AzureAsyncOperationResults", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: - return cls(pipeline_response, deserialized, response_headers) - - return deserialized + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _delete_initial.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}"} # type: ignore + return deserialized # type: ignore @distributed_trace def begin_delete( @@ -876,14 +817,6 @@ def begin_delete( :param cache_control: Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. Default value is "no-cache". :type cache_control: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either AzureAsyncOperationResults or the result of cls(response) :rtype: @@ -893,15 +826,13 @@ def begin_delete( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AzureAsyncOperationResults] - polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.AzureAsyncOperationResults] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = self._delete_initial( # type: ignore + raw_result = self._delete_initial( group_id=group_id, cache_control=cache_control, api_version=api_version, @@ -910,6 +841,7 @@ def begin_delete( params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): @@ -920,29 +852,29 @@ def get_long_running_output(pipeline_response): "str", response.headers.get("Azure-AsyncOperation") ) - deserialized = self._deserialize("AzureAsyncOperationResults", pipeline_response) + deserialized = self._deserialize("AzureAsyncOperationResults", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized if polling is True: - polling_method = cast( + polling_method: PollingMethod = cast( PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs) - ) # type: PollingMethod + ) elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.AzureAsyncOperationResults].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - - begin_delete.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}"} # type: ignore + return LROPoller[_models.AzureAsyncOperationResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) @distributed_trace def get_descendants( @@ -961,7 +893,6 @@ def get_descendants( :param top: Number of elements to return when retrieving results. Passing this in will override $skipToken. Default value is None. :type top: int - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DescendantInfo or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.managementgroups.models.DescendantInfo] :raises ~azure.core.exceptions.HttpResponseError: @@ -969,12 +900,10 @@ def get_descendants( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.DescendantListResult] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DescendantListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -985,17 +914,15 @@ def get_descendants( def prepare_request(next_link=None): if not next_link: - request = build_get_descendants_request( + _request = build_get_descendants_request( group_id=group_id, skiptoken=skiptoken, top=top, api_version=api_version, - template_url=self.get_descendants.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -1007,26 +934,26 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("DescendantListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1038,5 +965,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - get_descendants.metadata = {"url": "/providers/Microsoft.Management/managementGroups/{groupId}/descendants"} # type: ignore diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/operations/_operations.py b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/operations/_operations.py index 4e175edc59bc..a4e8257524b2 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/operations/_operations.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/azure/mgmt/managementgroups/operations/_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,7 +7,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import sys -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar import urllib.parse from azure.core.exceptions import ( @@ -20,20 +20,18 @@ ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer -from .._vendor import ManagementGroupsAPIMixinABC, _convert_request -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -45,7 +43,7 @@ def build_list_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) # type: Literal["2021-04-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -83,7 +81,6 @@ def __init__(self, *args, **kwargs): def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: """Lists all of the available Management REST API operations. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Operation or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.managementgroups.models.Operation] :raises ~azure.core.exceptions.HttpResponseError: @@ -91,12 +88,10 @@ def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-04-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -107,14 +102,12 @@ def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -126,26 +119,26 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -157,5 +150,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/providers/Microsoft.Management/operations"} # type: ignore diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/dev_requirements.txt b/sdk/managementgroups/azure-mgmt-managementgroups/dev_requirements.txt index 6ccb7f031ddd..6195bb36ac8e 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/dev_requirements.txt +++ b/sdk/managementgroups/azure-mgmt-managementgroups/dev_requirements.txt @@ -1 +1,2 @@ -e ../../../tools/azure-sdk-tools +aiohttp \ No newline at end of file diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/add_subscription_to_management_group.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/add_management_group_subscription.py similarity index 96% rename from sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/add_subscription_to_management_group.py rename to sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/add_management_group_subscription.py index 3f6eb8fca9e5..d819ea2f2dd6 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/add_subscription_to_management_group.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/add_management_group_subscription.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.managementgroups import ManagementGroupsAPI """ @@ -14,7 +15,7 @@ pip install azure-identity pip install azure-mgmt-managementgroups # USAGE - python add_subscription_to_management_group.py + python add_management_group_subscription.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, diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/check_management_group_name_availability.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/check_management_group_name_availability.py index be3c3f89842a..ea68c2126682 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/check_management_group_name_availability.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/check_management_group_name_availability.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.managementgroups import ManagementGroupsAPI """ diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/delete_hierarchy_settings.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/delete_hierarchy_settings.py new file mode 100644 index 000000000000..a63f8f1208cc --- /dev/null +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/delete_hierarchy_settings.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.managementgroups import ManagementGroupsAPI + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-managementgroups +# USAGE + python delete_hierarchy_settings.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 = ManagementGroupsAPI( + credential=DefaultAzureCredential(), + ) + + client.hierarchy_settings.delete( + group_id="root", + ) + + +# x-ms-original-file: specification/managementgroups/resource-manager/Microsoft.Management/stable/2021-04-01/examples/DeleteHierarchySettings.json +if __name__ == "__main__": + main() diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/delete_management_group.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/delete_management_group.py index 95e19eb2fda3..3beb74f6f45a 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/delete_management_group.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/delete_management_group.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.managementgroups import ManagementGroupsAPI """ diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_all_subscriptions_from_management_group.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_all_subscriptions_from_management_group.py index 292c1603db16..e48422e5a918 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_all_subscriptions_from_management_group.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_all_subscriptions_from_management_group.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.managementgroups import ManagementGroupsAPI """ diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_descendants.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_descendants.py index be178f479bdb..7d31d56e71d9 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_descendants.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_descendants.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.managementgroups import ManagementGroupsAPI """ diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_entities.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_entities.py index 040a6a57ac54..95b671c9aa7c 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_entities.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_entities.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.managementgroups import ManagementGroupsAPI """ diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_group_settings.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_hierarchy_settings.py similarity index 97% rename from sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_group_settings.py rename to sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_hierarchy_settings.py index dd25c14f9ccd..277b028cccc0 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_group_settings.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_hierarchy_settings.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.managementgroups import ManagementGroupsAPI """ @@ -14,7 +15,7 @@ pip install azure-identity pip install azure-mgmt-managementgroups # USAGE - python get_group_settings.py + python get_hierarchy_settings.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, diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_management_group.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_management_group.py index 3a764da8439a..899379ca04c9 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_management_group.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_management_group.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.managementgroups import ManagementGroupsAPI """ diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_management_group_with_ancestors.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_management_group_with_ancestors.py index fabee1b1ea0c..54945f11d5f5 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_management_group_with_ancestors.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_management_group_with_ancestors.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.managementgroups import ManagementGroupsAPI """ diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_management_group_with_expand.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_management_group_with_expand.py index a072863a8965..1d15fb613e52 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_management_group_with_expand.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_management_group_with_expand.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.managementgroups import ManagementGroupsAPI """ diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_management_groups_with_expand_and_recurse.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_management_group_with_expand_and_recurse.py similarity index 96% rename from sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_management_groups_with_expand_and_recurse.py rename to sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_management_group_with_expand_and_recurse.py index 665cdc610d34..20e26124f02d 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_management_groups_with_expand_and_recurse.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_management_group_with_expand_and_recurse.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.managementgroups import ManagementGroupsAPI """ @@ -14,7 +15,7 @@ pip install azure-identity pip install azure-mgmt-managementgroups # USAGE - python get_management_groups_with_expand_and_recurse.py + python get_management_group_with_expand_and_recurse.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, diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_management_group_with_path.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_management_group_with_path.py index 43196f9607de..d354b4db4192 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_management_group_with_path.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_management_group_with_path.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.managementgroups import ManagementGroupsAPI """ diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_subscription_from_management_group.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_subscription_from_management_group.py index 05d10e574c19..a30e1cd3218a 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_subscription_from_management_group.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/get_subscription_from_management_group.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.managementgroups import ManagementGroupsAPI """ diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/list_group_settings.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/list_hierarchy_settings.py similarity index 97% rename from sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/list_group_settings.py rename to sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/list_hierarchy_settings.py index 0c8be379b7e9..79d043988180 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/list_group_settings.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/list_hierarchy_settings.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.managementgroups import ManagementGroupsAPI """ @@ -14,7 +15,7 @@ pip install azure-identity pip install azure-mgmt-managementgroups # USAGE - python list_group_settings.py + python list_hierarchy_settings.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, diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/list_management_groups.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/list_management_groups.py index 5ff45083374a..c224cd60e988 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/list_management_groups.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/list_management_groups.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.managementgroups import ManagementGroupsAPI """ diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/list_operations.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/list_operations.py index ec5b5eab63d8..425f40edf405 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/list_operations.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/list_operations.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.managementgroups import ManagementGroupsAPI """ diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/patch_management_group.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/patch_management_group.py index 14a85c519473..37f9808f29d7 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/patch_management_group.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/patch_management_group.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.managementgroups import ManagementGroupsAPI """ diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/put_management_group.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/put_management_group.py index aabd30662673..a679c165f0fe 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/put_management_group.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/put_management_group.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.managementgroups import ManagementGroupsAPI """ diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/delete_subscription_from_management_group.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/remove_management_group_subscription.py similarity index 91% rename from sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/delete_subscription_from_management_group.py rename to sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/remove_management_group_subscription.py index 1915a4a85541..31e730d7a20f 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/delete_subscription_from_management_group.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/remove_management_group_subscription.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.managementgroups import ManagementGroupsAPI """ @@ -14,7 +15,7 @@ pip install azure-identity pip install azure-mgmt-managementgroups # USAGE - python delete_subscription_from_management_group.py + python remove_management_group_subscription.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, @@ -28,11 +29,10 @@ def main(): credential=DefaultAzureCredential(), ) - response = client.management_group_subscriptions.delete( + client.management_group_subscriptions.delete( group_id="Group", subscription_id="728bcbe4-8d56-4510-86c2-4921b8beefbc", ) - print(response) # x-ms-original-file: specification/managementgroups/resource-manager/Microsoft.Management/stable/2021-04-01/examples/RemoveManagementGroupSubscription.json diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/start_tenant_backfill.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/start_tenant_backfill_request.py similarity index 96% rename from sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/start_tenant_backfill.py rename to sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/start_tenant_backfill_request.py index f5a2b9bcb862..3e6e8af4eae3 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/start_tenant_backfill.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/start_tenant_backfill_request.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.managementgroups import ManagementGroupsAPI """ @@ -14,7 +15,7 @@ pip install azure-identity pip install azure-mgmt-managementgroups # USAGE - python start_tenant_backfill.py + python start_tenant_backfill_request.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, diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/tenant_backfill_status.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/tenant_backfill_status_request.py similarity index 96% rename from sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/tenant_backfill_status.py rename to sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/tenant_backfill_status_request.py index fc1370507a7d..1845f73eede2 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/tenant_backfill_status.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_samples/tenant_backfill_status_request.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.managementgroups import ManagementGroupsAPI """ @@ -14,7 +15,7 @@ pip install azure-identity pip install azure-mgmt-managementgroups # USAGE - python tenant_backfill_status.py + python tenant_backfill_status_request.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, diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/conftest.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/conftest.py new file mode 100644 index 000000000000..c25467ab34b1 --- /dev/null +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/conftest.py @@ -0,0 +1,37 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import 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() + + +# aovid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + managementgroupsapi_subscription_id = os.environ.get( + "AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000" + ) + managementgroupsapi_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + managementgroupsapi_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + managementgroupsapi_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=managementgroupsapi_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=managementgroupsapi_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=managementgroupsapi_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=managementgroupsapi_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/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api.py new file mode 100644 index 000000000000..a707a4cc4a08 --- /dev/null +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api.py @@ -0,0 +1,50 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.managementgroups import ManagementGroupsAPI + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestManagementGroupsAPI(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementGroupsAPI) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_check_name_availability(self, resource_group): + response = self.client.check_name_availability( + check_name_availability_request={"name": "str", "type": "Microsoft.Management/managementGroups"}, + api_version="2021-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_start_tenant_backfill(self, resource_group): + response = self.client.start_tenant_backfill( + api_version="2021-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_tenant_backfill_status(self, resource_group): + response = self.client.tenant_backfill_status( + api_version="2021-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_async.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_async.py new file mode 100644 index 000000000000..a39cdb6241a2 --- /dev/null +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_async.py @@ -0,0 +1,51 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.managementgroups.aio import ManagementGroupsAPI + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestManagementGroupsAPIAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementGroupsAPI, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_check_name_availability(self, resource_group): + response = await self.client.check_name_availability( + check_name_availability_request={"name": "str", "type": "Microsoft.Management/managementGroups"}, + api_version="2021-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_start_tenant_backfill(self, resource_group): + response = await self.client.start_tenant_backfill( + api_version="2021-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_tenant_backfill_status(self, resource_group): + response = await self.client.tenant_backfill_status( + api_version="2021-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_entities_operations.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_entities_operations.py new file mode 100644 index 000000000000..fa10581070c1 --- /dev/null +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_entities_operations.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.managementgroups import ManagementGroupsAPI + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestManagementGroupsAPIEntitiesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementGroupsAPI) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list(self, resource_group): + response = self.client.entities.list( + api_version="2021-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_entities_operations_async.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_entities_operations_async.py new file mode 100644 index 000000000000..bdf74dcbf38b --- /dev/null +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_entities_operations_async.py @@ -0,0 +1,30 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.managementgroups.aio import ManagementGroupsAPI + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestManagementGroupsAPIEntitiesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementGroupsAPI, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list(self, resource_group): + response = self.client.entities.list( + api_version="2021-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_hierarchy_settings_operations.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_hierarchy_settings_operations.py new file mode 100644 index 000000000000..a80e2be3c554 --- /dev/null +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_hierarchy_settings_operations.py @@ -0,0 +1,82 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.managementgroups import ManagementGroupsAPI + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestManagementGroupsAPIHierarchySettingsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementGroupsAPI) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list(self, resource_group): + response = self.client.hierarchy_settings.list( + group_id="str", + api_version="2021-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_get(self, resource_group): + response = self.client.hierarchy_settings.get( + group_id="str", + api_version="2021-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_create_or_update(self, resource_group): + response = self.client.hierarchy_settings.create_or_update( + group_id="str", + create_tenant_settings_request={ + "defaultManagementGroup": "str", + "requireAuthorizationForGroupCreation": bool, + }, + api_version="2021-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_update(self, resource_group): + response = self.client.hierarchy_settings.update( + group_id="str", + create_tenant_settings_request={ + "defaultManagementGroup": "str", + "requireAuthorizationForGroupCreation": bool, + }, + api_version="2021-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_delete(self, resource_group): + response = self.client.hierarchy_settings.delete( + group_id="str", + api_version="2021-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_hierarchy_settings_operations_async.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_hierarchy_settings_operations_async.py new file mode 100644 index 000000000000..d54f6f497f81 --- /dev/null +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_hierarchy_settings_operations_async.py @@ -0,0 +1,83 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.managementgroups.aio import ManagementGroupsAPI + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestManagementGroupsAPIHierarchySettingsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementGroupsAPI, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list(self, resource_group): + response = await self.client.hierarchy_settings.list( + group_id="str", + api_version="2021-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_get(self, resource_group): + response = await self.client.hierarchy_settings.get( + group_id="str", + api_version="2021-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_create_or_update(self, resource_group): + response = await self.client.hierarchy_settings.create_or_update( + group_id="str", + create_tenant_settings_request={ + "defaultManagementGroup": "str", + "requireAuthorizationForGroupCreation": bool, + }, + api_version="2021-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_update(self, resource_group): + response = await self.client.hierarchy_settings.update( + group_id="str", + create_tenant_settings_request={ + "defaultManagementGroup": "str", + "requireAuthorizationForGroupCreation": bool, + }, + api_version="2021-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_delete(self, resource_group): + response = await self.client.hierarchy_settings.delete( + group_id="str", + api_version="2021-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_management_group_subscriptions_operations.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_management_group_subscriptions_operations.py new file mode 100644 index 000000000000..27a846c4dc15 --- /dev/null +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_management_group_subscriptions_operations.py @@ -0,0 +1,66 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.managementgroups import ManagementGroupsAPI + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestManagementGroupsAPIManagementGroupSubscriptionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementGroupsAPI) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_create(self, resource_group): + response = self.client.management_group_subscriptions.create( + group_id="str", + subscription_id="str", + api_version="2021-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_delete(self, resource_group): + response = self.client.management_group_subscriptions.delete( + group_id="str", + subscription_id="str", + api_version="2021-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_get_subscription(self, resource_group): + response = self.client.management_group_subscriptions.get_subscription( + group_id="str", + subscription_id="str", + api_version="2021-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_get_subscriptions_under_management_group(self, resource_group): + response = self.client.management_group_subscriptions.get_subscriptions_under_management_group( + group_id="str", + api_version="2021-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_management_group_subscriptions_operations_async.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_management_group_subscriptions_operations_async.py new file mode 100644 index 000000000000..68fee623a5d4 --- /dev/null +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_management_group_subscriptions_operations_async.py @@ -0,0 +1,67 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.managementgroups.aio import ManagementGroupsAPI + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestManagementGroupsAPIManagementGroupSubscriptionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementGroupsAPI, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_create(self, resource_group): + response = await self.client.management_group_subscriptions.create( + group_id="str", + subscription_id="str", + api_version="2021-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_delete(self, resource_group): + response = await self.client.management_group_subscriptions.delete( + group_id="str", + subscription_id="str", + api_version="2021-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_get_subscription(self, resource_group): + response = await self.client.management_group_subscriptions.get_subscription( + group_id="str", + subscription_id="str", + api_version="2021-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_get_subscriptions_under_management_group(self, resource_group): + response = self.client.management_group_subscriptions.get_subscriptions_under_management_group( + group_id="str", + api_version="2021-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_management_groups_operations.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_management_groups_operations.py new file mode 100644 index 000000000000..f2aea8b3e992 --- /dev/null +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_management_groups_operations.py @@ -0,0 +1,99 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.managementgroups import ManagementGroupsAPI + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestManagementGroupsAPIManagementGroupsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementGroupsAPI) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list(self, resource_group): + response = self.client.management_groups.list( + api_version="2021-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_get(self, resource_group): + response = self.client.management_groups.get( + group_id="str", + api_version="2021-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_begin_create_or_update(self, resource_group): + response = self.client.management_groups.begin_create_or_update( + group_id="str", + create_management_group_request={ + "children": [{"children": [...], "displayName": "str", "id": "str", "name": "str", "type": "str"}], + "details": { + "parent": {"displayName": "str", "id": "str", "name": "str"}, + "updatedBy": "str", + "updatedTime": "2020-02-20 00:00:00", + "version": 0, + }, + "displayName": "str", + "id": "str", + "name": "str", + "tenantId": "str", + "type": "str", + }, + api_version="2021-04-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_update(self, resource_group): + response = self.client.management_groups.update( + group_id="str", + patch_group_request={"displayName": "str", "parentGroupId": "str"}, + api_version="2021-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_begin_delete(self, resource_group): + response = self.client.management_groups.begin_delete( + group_id="str", + api_version="2021-04-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_get_descendants(self, resource_group): + response = self.client.management_groups.get_descendants( + group_id="str", + api_version="2021-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_management_groups_operations_async.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_management_groups_operations_async.py new file mode 100644 index 000000000000..b66119c1b13d --- /dev/null +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_management_groups_operations_async.py @@ -0,0 +1,104 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.managementgroups.aio import ManagementGroupsAPI + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestManagementGroupsAPIManagementGroupsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementGroupsAPI, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list(self, resource_group): + response = self.client.management_groups.list( + api_version="2021-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_get(self, resource_group): + response = await self.client.management_groups.get( + group_id="str", + api_version="2021-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_begin_create_or_update(self, resource_group): + response = await ( + await self.client.management_groups.begin_create_or_update( + group_id="str", + create_management_group_request={ + "children": [{"children": [...], "displayName": "str", "id": "str", "name": "str", "type": "str"}], + "details": { + "parent": {"displayName": "str", "id": "str", "name": "str"}, + "updatedBy": "str", + "updatedTime": "2020-02-20 00:00:00", + "version": 0, + }, + "displayName": "str", + "id": "str", + "name": "str", + "tenantId": "str", + "type": "str", + }, + api_version="2021-04-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_update(self, resource_group): + response = await self.client.management_groups.update( + group_id="str", + patch_group_request={"displayName": "str", "parentGroupId": "str"}, + api_version="2021-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_begin_delete(self, resource_group): + response = await ( + await self.client.management_groups.begin_delete( + group_id="str", + api_version="2021-04-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_get_descendants(self, resource_group): + response = self.client.management_groups.get_descendants( + group_id="str", + api_version="2021-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_operations.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_operations.py new file mode 100644 index 000000000000..c578d36eabd5 --- /dev/null +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_operations.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.managementgroups import ManagementGroupsAPI + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestManagementGroupsAPIOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementGroupsAPI) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list(self, resource_group): + response = self.client.operations.list( + api_version="2021-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_operations_async.py b/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_operations_async.py new file mode 100644 index 000000000000..bf116af2ca85 --- /dev/null +++ b/sdk/managementgroups/azure-mgmt-managementgroups/generated_tests/test_management_groups_api_operations_async.py @@ -0,0 +1,30 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.managementgroups.aio import ManagementGroupsAPI + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestManagementGroupsAPIOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementGroupsAPI, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list(self, resource_group): + response = self.client.operations.list( + api_version="2021-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/sdk_packaging.toml b/sdk/managementgroups/azure-mgmt-managementgroups/sdk_packaging.toml index 3e050d7af667..18d7edcf0d36 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/sdk_packaging.toml +++ b/sdk/managementgroups/azure-mgmt-managementgroups/sdk_packaging.toml @@ -2,5 +2,5 @@ package_name = "azure-mgmt-managementgroups" package_pprint_name = "Management Groups" package_doc_id = "" -is_stable = false +is_stable = true title = "ManagementGroupsAPI" diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/setup.py b/sdk/managementgroups/azure-mgmt-managementgroups/setup.py index 346aded98b7f..a29615a0d4e6 100644 --- a/sdk/managementgroups/azure-mgmt-managementgroups/setup.py +++ b/sdk/managementgroups/azure-mgmt-managementgroups/setup.py @@ -1,10 +1,10 @@ #!/usr/bin/env python -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. -#-------------------------------------------------------------------------- +# -------------------------------------------------------------------------- import re import os.path @@ -16,63 +16,70 @@ PACKAGE_PPRINT_NAME = "Management Groups" # a-b-c => a/b/c -package_folder_path = PACKAGE_NAME.replace('-', '/') +package_folder_path = PACKAGE_NAME.replace("-", "/") # a-b-c => a.b.c -namespace_name = PACKAGE_NAME.replace('-', '.') +namespace_name = PACKAGE_NAME.replace("-", ".") # Version extraction inspired from 'requests' -with open(os.path.join(package_folder_path, 'version.py') - if os.path.exists(os.path.join(package_folder_path, 'version.py')) - else os.path.join(package_folder_path, '_version.py'), 'r') as fd: - version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', - fd.read(), re.MULTILINE).group(1) +with open( + ( + os.path.join(package_folder_path, "version.py") + if os.path.exists(os.path.join(package_folder_path, "version.py")) + else os.path.join(package_folder_path, "_version.py") + ), + "r", +) as fd: + version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: - raise RuntimeError('Cannot find version information') + raise RuntimeError("Cannot find version information") -with open('README.md', encoding='utf-8') as f: +with open("README.md", encoding="utf-8") as f: readme = f.read() -with open('CHANGELOG.md', encoding='utf-8') as f: +with open("CHANGELOG.md", encoding="utf-8") as f: changelog = f.read() setup( name=PACKAGE_NAME, version=version, - description='Microsoft Azure {} Client Library for Python'.format(PACKAGE_PPRINT_NAME), - long_description=readme + '\n\n' + changelog, - long_description_content_type='text/markdown', - license='MIT License', - author='Microsoft Corporation', - author_email='azpysdkhelp@microsoft.com', - url='https://github.com/Azure/azure-sdk-for-python', + description="Microsoft Azure {} Client Library for Python".format(PACKAGE_PPRINT_NAME), + long_description=readme + "\n\n" + changelog, + long_description_content_type="text/markdown", + license="MIT License", + author="Microsoft Corporation", + author_email="azpysdkhelp@microsoft.com", + url="https://github.com/Azure/azure-sdk-for-python", keywords="azure, azure sdk", # update with search keywords relevant to the azure service / product classifiers=[ - 'Development Status :: 4 - Beta', - 'Programming Language :: Python', - 'Programming Language :: Python :: 3 :: Only', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Programming Language :: Python :: 3.10', - 'License :: OSI Approved :: MIT License', + "Development Status :: 4 - Beta", + "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", + "Programming Language :: Python :: 3.12", + "License :: OSI Approved :: MIT License", ], zip_safe=False, - packages=find_packages(exclude=[ - 'tests', - # Exclude packages that will be covered by PEP420 or nspkg - 'azure', - 'azure.mgmt', - ]), + packages=find_packages( + exclude=[ + "tests", + # Exclude packages that will be covered by PEP420 or nspkg + "azure", + "azure.mgmt", + ] + ), include_package_data=True, package_data={ - 'pytyped': ['py.typed'], + "pytyped": ["py.typed"], }, install_requires=[ - "msrest>=0.7.1", - "azure-common~=1.1", - "azure-mgmt-core>=1.3.2,<2.0.0", - "typing-extensions>=4.3.0; python_version<'3.8.0'", + "isodate>=0.6.1", + "typing-extensions>=4.6.0", + "azure-common>=1.1", + "azure-mgmt-core>=1.3.2", ], - python_requires=">=3.7" + python_requires=">=3.8", ) diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/tests/conftest.py b/sdk/managementgroups/azure-mgmt-managementgroups/tests/conftest.py new file mode 100644 index 000000000000..c25467ab34b1 --- /dev/null +++ b/sdk/managementgroups/azure-mgmt-managementgroups/tests/conftest.py @@ -0,0 +1,37 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import 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() + + +# aovid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + managementgroupsapi_subscription_id = os.environ.get( + "AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000" + ) + managementgroupsapi_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + managementgroupsapi_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + managementgroupsapi_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=managementgroupsapi_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=managementgroupsapi_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=managementgroupsapi_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=managementgroupsapi_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/managementgroups/azure-mgmt-managementgroups/tests/test_management_groups_api_async_test.py b/sdk/managementgroups/azure-mgmt-managementgroups/tests/test_management_groups_api_async_test.py new file mode 100644 index 000000000000..18ff511c3d53 --- /dev/null +++ b/sdk/managementgroups/azure-mgmt-managementgroups/tests/test_management_groups_api_async_test.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) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.managementgroups.aio import ManagementGroupsAPI + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestManagementGroupsAPIAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementGroupsAPI, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_check_name_availability(self, resource_group): + response = await self.client.check_name_availability( + check_name_availability_request={"name": "str", "type": "Microsoft.Management/managementGroups"}, + ) + + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_start_tenant_backfill(self, resource_group): + response = await self.client.start_tenant_backfill() + + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_tenant_backfill_status(self, resource_group): + response = await self.client.tenant_backfill_status() + + assert response diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/tests/test_management_groups_api_entities_operations_async_test.py b/sdk/managementgroups/azure-mgmt-managementgroups/tests/test_management_groups_api_entities_operations_async_test.py new file mode 100644 index 000000000000..c6d9d7243e46 --- /dev/null +++ b/sdk/managementgroups/azure-mgmt-managementgroups/tests/test_management_groups_api_entities_operations_async_test.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.managementgroups.aio import ManagementGroupsAPI + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestManagementGroupsAPIEntitiesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementGroupsAPI, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list(self, resource_group): + response = self.client.entities.list() + result = [r async for r in response] + assert response diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/tests/test_management_groups_api_entities_operations_test.py b/sdk/managementgroups/azure-mgmt-managementgroups/tests/test_management_groups_api_entities_operations_test.py new file mode 100644 index 000000000000..1c13acb3ef64 --- /dev/null +++ b/sdk/managementgroups/azure-mgmt-managementgroups/tests/test_management_groups_api_entities_operations_test.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.managementgroups import ManagementGroupsAPI + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestManagementGroupsAPIEntitiesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementGroupsAPI) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list(self, resource_group): + response = self.client.entities.list() + result = [r for r in response] + assert response diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/tests/test_management_groups_api_operations_async_test.py b/sdk/managementgroups/azure-mgmt-managementgroups/tests/test_management_groups_api_operations_async_test.py new file mode 100644 index 000000000000..7b10d2539018 --- /dev/null +++ b/sdk/managementgroups/azure-mgmt-managementgroups/tests/test_management_groups_api_operations_async_test.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.managementgroups.aio import ManagementGroupsAPI + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestManagementGroupsAPIOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementGroupsAPI, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list(self, resource_group): + response = self.client.operations.list() + result = [r async for r in response] + assert result diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/tests/test_management_groups_api_operations_test.py b/sdk/managementgroups/azure-mgmt-managementgroups/tests/test_management_groups_api_operations_test.py new file mode 100644 index 000000000000..a63257cc620d --- /dev/null +++ b/sdk/managementgroups/azure-mgmt-managementgroups/tests/test_management_groups_api_operations_test.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.managementgroups import ManagementGroupsAPI + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestManagementGroupsAPIOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementGroupsAPI) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list(self, resource_group): + response = self.client.operations.list() + result = [r for r in response] + assert result diff --git a/sdk/managementgroups/azure-mgmt-managementgroups/tests/test_management_groups_api_test.py b/sdk/managementgroups/azure-mgmt-managementgroups/tests/test_management_groups_api_test.py new file mode 100644 index 000000000000..4143c5d8c7ef --- /dev/null +++ b/sdk/managementgroups/azure-mgmt-managementgroups/tests/test_management_groups_api_test.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) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.managementgroups import ManagementGroupsAPI + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestManagementGroupsAPI(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ManagementGroupsAPI) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_check_name_availability(self, resource_group): + response = self.client.check_name_availability( + check_name_availability_request={"name": "str", "type": "Microsoft.Management/managementGroups"}, + ) + + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_start_tenant_backfill(self, resource_group): + response = self.client.start_tenant_backfill() + + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_tenant_backfill_status(self, resource_group): + response = self.client.tenant_backfill_status() + + assert response