diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/CHANGELOG.md b/sdk/selfhelp/azure-mgmt-selfhelp/CHANGELOG.md index 461fc7092f7f..100dac85731b 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/CHANGELOG.md +++ b/sdk/selfhelp/azure-mgmt-selfhelp/CHANGELOG.md @@ -1,5 +1,37 @@ # Release History +## 2.0.0b5 (2025-05-09) + +### Features Added + + - Method `DiagnosticsOperations.begin_create` has a new overload `def begin_create(self: None, scope: str, diagnostics_resource_name: str, diagnostic_resource_request: DiagnosticResource, content_type: str)` + - Method `DiagnosticsOperations.begin_create` has a new overload `def begin_create(self: None, scope: str, diagnostics_resource_name: str, diagnostic_resource_request: IO[bytes], content_type: str)` + - Method `DiscoverySolutionNLPOperations.discover_solutions` has a new overload `def discover_solutions(self: None, discover_solution_request: DiscoveryNlpRequest, content_type: str)` + - Method `DiscoverySolutionNLPOperations.discover_solutions` has a new overload `def discover_solutions(self: None, discover_solution_request: IO[bytes], content_type: str)` + - Method `DiscoverySolutionNLPOperations.discover_solutions_by_subscription` has a new overload `def discover_solutions_by_subscription(self: None, discover_solution_request: DiscoveryNlpRequest, content_type: str)` + - Method `DiscoverySolutionNLPOperations.discover_solutions_by_subscription` has a new overload `def discover_solutions_by_subscription(self: None, discover_solution_request: IO[bytes], content_type: str)` + - Method `SimplifiedSolutionsOperations.begin_create` has a new overload `def begin_create(self: None, scope: str, simplified_solutions_resource_name: str, simplified_solutions_request_body: SimplifiedSolutionsResource, content_type: str)` + - Method `SimplifiedSolutionsOperations.begin_create` has a new overload `def begin_create(self: None, scope: str, simplified_solutions_resource_name: str, simplified_solutions_request_body: IO[bytes], content_type: str)` + - Method `SolutionOperations.begin_create` has a new overload `def begin_create(self: None, scope: str, solution_resource_name: str, solution_request_body: SolutionResource, content_type: str)` + - Method `SolutionOperations.begin_create` has a new overload `def begin_create(self: None, scope: str, solution_resource_name: str, solution_request_body: IO[bytes], content_type: str)` + - Method `SolutionOperations.begin_update` has a new overload `def begin_update(self: None, scope: str, solution_resource_name: str, solution_patch_request_body: SolutionPatchRequestBody, content_type: str)` + - Method `SolutionOperations.begin_update` has a new overload `def begin_update(self: None, scope: str, solution_resource_name: str, solution_patch_request_body: IO[bytes], content_type: str)` + - Method `TroubleshootersOperations.create` has a new overload `def create(self: None, scope: str, troubleshooter_name: str, create_troubleshooter_request_body: TroubleshooterResource, content_type: str)` + - Method `TroubleshootersOperations.create` has a new overload `def create(self: None, scope: str, troubleshooter_name: str, create_troubleshooter_request_body: IO[bytes], content_type: str)` + +### Breaking Changes + + - Method `SelfHelpMgmtClient.__init__` inserted a `positional_or_keyword` parameter `subscription_id` + - Method `DiscoveryResponse.__init__` removed default value `None` from its parameter `value` + - Method `DiagnosticsOperations.begin_create` removed default value `None` from its parameter `diagnostic_resource_request` + - Method `DiscoverySolutionNLPOperations.discover_solutions` removed default value `None` from its parameter `discover_solution_request` + - Method `DiscoverySolutionNLPOperations.discover_solutions_by_subscription` removed default value `None` from its parameter `discover_solution_request` + - Method `DiscoverySolutionNLPOperations.discover_solutions_by_subscription` deleted or renamed its parameter `subscription_id` of kind `positional_or_keyword` + - Method `SimplifiedSolutionsOperations.begin_create` removed default value `None` from its parameter `simplified_solutions_request_body` + - Method `SolutionOperations.begin_create` removed default value `None` from its parameter `solution_request_body` + - Method `SolutionOperations.begin_update` removed default value `None` from its parameter `solution_patch_request_body` + - Method `TroubleshootersOperations.create` removed default value `None` from its parameter `create_troubleshooter_request_body` + ## 2.0.0b4 (2024-05-27) ### Features Added diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/README.md b/sdk/selfhelp/azure-mgmt-selfhelp/README.md index 3cbc9e9a5fbe..4dac2ff5205c 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/README.md +++ b/sdk/selfhelp/azure-mgmt-selfhelp/README.md @@ -1,7 +1,7 @@ # Microsoft Azure SDK for Python This is the Microsoft Azure Selfhelp Management Client Library. -This package has been tested with Python 3.8+. +This package has been tested with Python 3.9+. For a more complete view of Azure libraries, see the [azure sdk python release](https://aka.ms/azsdk/python/all). ## _Disclaimer_ @@ -12,7 +12,7 @@ _Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For ### Prerequisites -- Python 3.8+ is required to use this package. +- Python 3.9+ is required to use this package. - [Azure subscription](https://azure.microsoft.com/free/) ### Install the package @@ -24,7 +24,7 @@ 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. +By default, [Azure Active Directory](https://aka.ms/awps/aad) token authentication depends on correct configuration of the following environment variables. - `AZURE_CLIENT_ID` for Azure client ID. - `AZURE_TENANT_ID` for Azure tenant ID. diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/_meta.json b/sdk/selfhelp/azure-mgmt-selfhelp/_meta.json index 7e1f7db47d33..98eb86ed35ec 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/_meta.json +++ b/sdk/selfhelp/azure-mgmt-selfhelp/_meta.json @@ -1,11 +1,11 @@ { - "commit": "c3cc9abe085093ba880ee3eeb792edb4fa789553", + "commit": "51be344f3e6ae8e3e9b2a8b4c2676ee74c31bd4a", "repository_url": "https://github.com/Azure/azure-rest-api-specs", "autorest": "3.10.2", "use": [ - "@autorest/python@6.13.16", + "@autorest/python@6.34.1", "@autorest/modelerfour@4.27.0" ], - "autorest_command": "autorest specification/help/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.13.16 --use=@autorest/modelerfour@4.27.0 --version=3.10.2 --version-tolerant=False", + "autorest_command": "autorest specification/help/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/s/azure-sdk-for-python/sdk --use=@autorest/python@6.34.1 --use=@autorest/modelerfour@4.27.0 --version=3.10.2 --version-tolerant=False", "readme": "specification/help/resource-manager/readme.md" } \ No newline at end of file diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/__init__.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/__init__.py index 174ad8954ec4..246df0d39260 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/__init__.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/__init__.py @@ -5,15 +5,21 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._self_help_mgmt_client import SelfHelpMgmtClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._self_help_mgmt_client import SelfHelpMgmtClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # pylint: disable=unused-wildcard-import + from ._patch import * except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk @@ -21,6 +27,6 @@ __all__ = [ "SelfHelpMgmtClient", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/_configuration.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/_configuration.py index 9ee92792a083..ce27684e4ae0 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/_configuration.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/_configuration.py @@ -14,11 +14,10 @@ from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class SelfHelpMgmtClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long +class SelfHelpMgmtClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for SelfHelpMgmtClient. Note that all parameters used to create this instance are saved as instance @@ -26,18 +25,23 @@ class SelfHelpMgmtClientConfiguration: # pylint: disable=too-many-instance-attr :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str :keyword api_version: Api Version. Default value is "2024-03-01-preview". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__(self, credential: "TokenCredential", **kwargs: Any) -> None: + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: api_version: str = kwargs.pop("api_version", "2024-03-01-preview") if credential is None: raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") self.credential = credential + self.subscription_id = subscription_id self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-selfhelp/{}".format(VERSION)) diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/_self_help_mgmt_client.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/_self_help_mgmt_client.py index 4decd2050880..705279931546 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/_self_help_mgmt_client.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/_self_help_mgmt_client.py @@ -7,16 +7,19 @@ # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, TYPE_CHECKING +from typing import Any, Optional, TYPE_CHECKING, cast +from typing_extensions import Self from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse +from azure.core.settings import settings from azure.mgmt.core import ARMPipelineClient from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints from . import models as _models from ._configuration import SelfHelpMgmtClientConfiguration -from ._serialization import Deserializer, Serializer +from ._utils.serialization import Deserializer, Serializer from .operations import ( CheckNameAvailabilityOperations, DiagnosticsOperations, @@ -30,35 +33,36 @@ ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class SelfHelpMgmtClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes +class SelfHelpMgmtClient: # pylint: disable=too-many-instance-attributes """Help RP provider. - :ivar operations: Operations operations - :vartype operations: azure.mgmt.selfhelp.operations.Operations :ivar check_name_availability: CheckNameAvailabilityOperations operations :vartype check_name_availability: azure.mgmt.selfhelp.operations.CheckNameAvailabilityOperations :ivar diagnostics: DiagnosticsOperations operations :vartype diagnostics: azure.mgmt.selfhelp.operations.DiagnosticsOperations - :ivar discovery_solution: DiscoverySolutionOperations operations - :vartype discovery_solution: azure.mgmt.selfhelp.operations.DiscoverySolutionOperations - :ivar solution: SolutionOperations operations - :vartype solution: azure.mgmt.selfhelp.operations.SolutionOperations :ivar simplified_solutions: SimplifiedSolutionsOperations operations :vartype simplified_solutions: azure.mgmt.selfhelp.operations.SimplifiedSolutionsOperations + :ivar solution: SolutionOperations operations + :vartype solution: azure.mgmt.selfhelp.operations.SolutionOperations :ivar troubleshooters: TroubleshootersOperations operations :vartype troubleshooters: azure.mgmt.selfhelp.operations.TroubleshootersOperations - :ivar solution_self_help: SolutionSelfHelpOperations operations - :vartype solution_self_help: azure.mgmt.selfhelp.operations.SolutionSelfHelpOperations :ivar discovery_solution_nlp: DiscoverySolutionNLPOperations operations :vartype discovery_solution_nlp: azure.mgmt.selfhelp.operations.DiscoverySolutionNLPOperations + :ivar discovery_solution: DiscoverySolutionOperations operations + :vartype discovery_solution: azure.mgmt.selfhelp.operations.DiscoverySolutionOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.selfhelp.operations.Operations + :ivar solution_self_help: SolutionSelfHelpOperations operations + :vartype solution_self_help: azure.mgmt.selfhelp.operations.SolutionSelfHelpOperations :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param base_url: Service URL. Default value is "https://management.azure.com". + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is None. :type base_url: str :keyword api_version: Api Version. Default value is "2024-03-01-preview". Note that overriding this default value may result in unsupported behavior. @@ -68,9 +72,17 @@ class SelfHelpMgmtClient: # pylint: disable=client-accepts-api-version-keyword, """ def __init__( - self, credential: "TokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any + self, credential: "TokenCredential", subscription_id: str, base_url: Optional[str] = None, **kwargs: Any ) -> None: - self._config = SelfHelpMgmtClientConfiguration(credential=credential, **kwargs) + _cloud = kwargs.pop("cloud_setting", None) or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = SelfHelpMgmtClientConfiguration( + credential=credential, subscription_id=subscription_id, credential_scopes=credential_scopes, **kwargs + ) + _policies = kwargs.pop("policies", None) if _policies is None: _policies = [ @@ -89,29 +101,29 @@ def __init__( 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) + self._client: ARMPipelineClient = ARMPipelineClient(base_url=cast(str, 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 - self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) self.check_name_availability = CheckNameAvailabilityOperations( self._client, self._config, self._serialize, self._deserialize ) self.diagnostics = DiagnosticsOperations(self._client, self._config, self._serialize, self._deserialize) - self.discovery_solution = DiscoverySolutionOperations( + self.simplified_solutions = SimplifiedSolutionsOperations( self._client, self._config, self._serialize, self._deserialize ) self.solution = SolutionOperations(self._client, self._config, self._serialize, self._deserialize) - self.simplified_solutions = SimplifiedSolutionsOperations( + self.troubleshooters = TroubleshootersOperations(self._client, self._config, self._serialize, self._deserialize) + self.discovery_solution_nlp = DiscoverySolutionNLPOperations( self._client, self._config, self._serialize, self._deserialize ) - self.troubleshooters = TroubleshootersOperations(self._client, self._config, self._serialize, self._deserialize) - self.solution_self_help = SolutionSelfHelpOperations( + self.discovery_solution = DiscoverySolutionOperations( self._client, self._config, self._serialize, self._deserialize ) - self.discovery_solution_nlp = DiscoverySolutionNLPOperations( + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.solution_self_help = SolutionSelfHelpOperations( self._client, self._config, self._serialize, self._deserialize ) @@ -140,7 +152,7 @@ def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: def close(self) -> None: self._client.close() - def __enter__(self) -> "SelfHelpMgmtClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/_vendor.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/_utils/__init__.py similarity index 58% rename from sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/_vendor.py rename to sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/_utils/__init__.py index 0dafe0e287ff..0af9b28f6607 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/_vendor.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/_utils/__init__.py @@ -4,13 +4,3 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- - -from azure.core.pipeline.transport import HttpRequest - - -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 diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/_serialization.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/_utils/serialization.py similarity index 82% rename from sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/_serialization.py rename to sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/_utils/serialization.py index 2f781d740827..f5187701d7be 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/_serialization.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/_utils/serialization.py @@ -1,30 +1,12 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 # -------------------------------------------------------------------------- -# # Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -# pylint: skip-file # pyright: reportUnnecessaryTypeIgnoreComment=false from base64 import b64decode, b64encode @@ -48,11 +30,8 @@ IO, Mapping, Callable, - TypeVar, MutableMapping, - Type, List, - Mapping, ) try: @@ -62,13 +41,13 @@ import xml.etree.ElementTree as ET import isodate # type: ignore +from typing_extensions import Self from azure.core.exceptions import DeserializationError, SerializationError from azure.core.serialization import NULL as CoreNull _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") -ModelType = TypeVar("ModelType", bound="Model") JSON = MutableMapping[str, Any] @@ -91,6 +70,8 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: :param data: Input, could be bytes or stream (will be decoded with UTF8) or text :type data: str or bytes or IO :param str content_type: The content type. + :return: The deserialized data. + :rtype: object """ if hasattr(data, "read"): # Assume a stream @@ -112,7 +93,7 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: try: return json.loads(data_as_str) except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) + raise DeserializationError("JSON is invalid: {}".format(err), err) from err elif "xml" in (content_type or []): try: @@ -144,6 +125,8 @@ def _json_attemp(data): # context otherwise. _LOGGER.critical("Wasn't XML not JSON, failing") raise DeserializationError("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) @classmethod @@ -153,6 +136,11 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], Use bytes and headers to NOT use any requests/aiohttp or whatever specific implementation. Headers will tested for "content-type" + + :param bytes body_bytes: The body of the response. + :param dict headers: The headers of the response. + :returns: The deserialized data. + :rtype: object """ # Try to use content-type from headers if available content_type = None @@ -177,80 +165,31 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], except NameError: _long_type = int - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -try: - from datetime import timezone as _FixedOffset # type: ignore -except ImportError: # Python 2.7 - - class _FixedOffset(datetime.tzinfo): # type: ignore - """Fixed offset in minutes east from UTC. - Copy/pasted from Python doc - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc -except ImportError: - TZ_UTC = UTC() # type: ignore +TZ_UTC = datetime.timezone.utc _FLATTEN = re.compile(r"(? None: self.additional_properties: Optional[Dict[str, Any]] = {} - for k in kwargs: + for k in kwargs: # pylint: disable=consider-using-dict-items if k not in self._attribute_map: _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) elif k in self._validation and self._validation[k].get("readonly", False): @@ -298,13 +244,23 @@ def __init__(self, **kwargs: Any) -> None: setattr(self, k, kwargs[k]) def __eq__(self, other: Any) -> bool: - """Compare objects by comparing all attributes.""" + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ return False def __ne__(self, other: Any) -> bool: - """Compare objects by comparing all attributes.""" + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ return not self.__eq__(other) def __str__(self) -> str: @@ -324,7 +280,11 @@ def is_xml_model(cls) -> bool: @classmethod def _create_xml_node(cls): - """Create XML node.""" + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ try: xml_map = cls._xml_map # type: ignore except AttributeError: @@ -344,7 +304,9 @@ def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) # type: ignore + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) def as_dict( self, @@ -378,12 +340,15 @@ def my_key_transformer(key, attr_desc, value): If you want XML serialization, you can pass the kwargs is_xml=True. + :param bool keep_readonly: If you want to serialize the readonly attributes :param function key_transformer: A key transformer function. :returns: A dict JSON compatible object :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) # type: ignore + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs + ) @classmethod def _infer_class_models(cls): @@ -393,30 +358,31 @@ def _infer_class_models(cls): client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} if cls.__name__ not in client_models: raise ValueError("Not Autorest generated code") - except Exception: + except Exception: # pylint: disable=broad-exception-caught # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. client_models = {cls.__name__: cls} return client_models @classmethod - def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = None) -> ModelType: + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: """Parse a str using the RestAPI syntax and return a model. :param str data: A str using RestAPI structure. JSON by default. :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model - :raises: DeserializationError if something went wrong + :raises DeserializationError: if something went wrong + :rtype: Self """ deserializer = Deserializer(cls._infer_class_models()) return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod def from_dict( - cls: Type[ModelType], + cls, data: Any, key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, content_type: Optional[str] = None, - ) -> ModelType: + ) -> Self: """Parse a dict using given key extractor return a model. By default consider key @@ -424,9 +390,11 @@ def from_dict( and last_rest_key_case_insensitive_extractor) :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model - :raises: DeserializationError if something went wrong + :raises DeserializationError: if something went wrong + :rtype: Self """ deserializer = Deserializer(cls._infer_class_models()) deserializer.key_extractors = ( # type: ignore @@ -446,21 +414,25 @@ def _flatten_subtype(cls, key, objects): return {} result = dict(cls._subtype_map[key]) for valuetype in cls._subtype_map[key].values(): - result.update(objects[valuetype]._flatten_subtype(key, objects)) + result.update(objects[valuetype]._flatten_subtype(key, objects)) # pylint: disable=protected-access return result @classmethod def _classify(cls, response, objects): """Check the class _subtype_map for any child classes. We want to ignore any inherited _subtype_maps. - Remove the polymorphic key from the initial data. + + :param dict response: The initial data + :param dict objects: The class objects + :returns: The class to be used + :rtype: class """ for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): subtype_value = None if not isinstance(response, ET.Element): rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] - subtype_value = response.pop(rest_api_response_key, None) or response.pop(subtype_key, None) + subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) else: subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) if subtype_value: @@ -499,11 +471,13 @@ def _decode_attribute_map_key(key): inside the received data. :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str """ return key.replace("\\.", ".") -class Serializer(object): +class Serializer: # pylint: disable=too-many-public-methods """Request object model serializer.""" basic_types = {str: "str", int: "int", bool: "bool", float: "float"} @@ -538,7 +512,7 @@ class Serializer(object): "multiple": lambda x, y: x % y != 0, } - def __init__(self, classes: Optional[Mapping[str, type]] = None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.serialize_type = { "iso-8601": Serializer.serialize_iso, "rfc-1123": Serializer.serialize_rfc, @@ -558,13 +532,16 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None): self.key_transformer = full_restapi_key_transformer self.client_side_validation = True - def _serialize(self, target_obj, data_type=None, **kwargs): + def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals + self, target_obj, data_type=None, **kwargs + ): """Serialize data into a string according to type. - :param target_obj: The data to be serialized. + :param object target_obj: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str, dict - :raises: SerializationError if serialization fails. + :raises SerializationError: if serialization fails. + :returns: The serialized data. """ key_transformer = kwargs.get("key_transformer", self.key_transformer) keep_readonly = kwargs.get("keep_readonly", False) @@ -590,12 +567,14 @@ def _serialize(self, target_obj, data_type=None, **kwargs): serialized = {} if is_xml_model_serialization: - serialized = target_obj._create_xml_node() + serialized = target_obj._create_xml_node() # pylint: disable=protected-access try: - attributes = target_obj._attribute_map + attributes = target_obj._attribute_map # pylint: disable=protected-access for attr, attr_desc in attributes.items(): attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + attr_name, {} + ).get("readonly", False): continue if attr_name == "additional_properties" and attr_desc["key"] == "": @@ -631,7 +610,8 @@ def _serialize(self, target_obj, data_type=None, **kwargs): if isinstance(new_attr, list): serialized.extend(new_attr) # type: ignore elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. + # If the down XML has no XML/Name, + # we MUST replace the tag with the local tag. But keeping the namespaces. if "name" not in getattr(orig_attr, "_xml_map", {}): splitted_tag = new_attr.tag.split("}") if len(splitted_tag) == 2: # Namespace @@ -662,17 +642,17 @@ def _serialize(self, target_obj, data_type=None, **kwargs): except (AttributeError, KeyError, TypeError) as err: msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) raise SerializationError(msg) from err - else: - return serialized + return serialized def body(self, data, data_type, **kwargs): """Serialize data intended for a request body. - :param data: The data to be serialized. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None + :raises SerializationError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized request body """ # Just in case this is a dict @@ -701,7 +681,7 @@ def body(self, data, data_type, **kwargs): attribute_key_case_insensitive_extractor, last_rest_key_case_insensitive_extractor, ] - data = deserializer._deserialize(data_type, data) + data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access except DeserializationError as err: raise SerializationError("Unable to build a model: " + str(err)) from err @@ -710,11 +690,13 @@ def body(self, data, data_type, **kwargs): def url(self, name, data, data_type, **kwargs): """Serialize data intended for a URL path. - :param data: The data to be serialized. + :param str name: The name of the URL path parameter. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None + :returns: The serialized URL path + :raises TypeError: if serialization fails. + :raises ValueError: if data is None """ try: output = self.serialize_data(data, data_type, **kwargs) @@ -726,21 +708,20 @@ def url(self, name, data, data_type, **kwargs): output = output.replace("{", quote("{")).replace("}", quote("}")) else: output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return output def query(self, name, data, data_type, **kwargs): """Serialize data intended for a URL query. - :param data: The data to be serialized. + :param str name: The name of the query parameter. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. - :keyword bool skip_quote: Whether to skip quote the serialized result. - Defaults to False. :rtype: str, list - :raises: TypeError if serialization fails. - :raises: ValueError if data is None + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized query parameter """ try: # Treat the list aside, since we don't want to encode the div separator @@ -757,19 +738,20 @@ def query(self, name, data, data_type, **kwargs): output = str(output) else: output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) def header(self, name, data, data_type, **kwargs): """Serialize data intended for a request header. - :param data: The data to be serialized. + :param str name: The name of the header. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized header """ try: if data_type in ["[str]"]: @@ -778,21 +760,20 @@ def header(self, name, data, data_type, **kwargs): output = self.serialize_data(data, data_type, **kwargs) if data_type == "bool": output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) def serialize_data(self, data, data_type, **kwargs): """Serialize generic data according to supplied data type. - :param data: The data to be serialized. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. + :raises AttributeError: if required data is None. + :raises ValueError: if data is None + :raises SerializationError: if serialization fails. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list """ if data is None: raise ValueError("No value for given attribute") @@ -803,7 +784,7 @@ def serialize_data(self, data, data_type, **kwargs): if data_type in self.basic_types.values(): return self.serialize_basic(data, data_type, **kwargs) - elif data_type in self.serialize_type: + if data_type in self.serialize_type: return self.serialize_type[data_type](data, **kwargs) # If dependencies is empty, try with current data class @@ -819,11 +800,10 @@ def serialize_data(self, data, data_type, **kwargs): except (ValueError, TypeError) as err: msg = "Unable to serialize value: {!r} as type: {!r}." raise SerializationError(msg.format(data, data_type)) from err - else: - return self._serialize(data, **kwargs) + return self._serialize(data, **kwargs) @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): + def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) if custom_serializer: return custom_serializer @@ -839,23 +819,26 @@ def serialize_basic(cls, data, data_type, **kwargs): - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - is_xml bool : If set, use xml_basic_types_serializers - :param data: Object to be serialized. + :param obj data: Object to be serialized. :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object """ custom_serializer = cls._get_custom_serializers(data_type, **kwargs) if custom_serializer: return custom_serializer(data) if data_type == "str": return cls.serialize_unicode(data) - return eval(data_type)(data) # nosec + return eval(data_type)(data) # nosec # pylint: disable=eval-used @classmethod def serialize_unicode(cls, data): """Special handling for serializing unicode strings in Py2. Encode to UTF-8 if unicode, otherwise handle as a str. - :param data: Object to be serialized. + :param str data: Object to be serialized. :rtype: str + :return: serialized object """ try: # If I received an enum, return its value return data.value @@ -869,8 +852,7 @@ def serialize_unicode(cls, data): return data except NameError: return str(data) - else: - return str(data) + return str(data) def serialize_iter(self, data, iter_type, div=None, **kwargs): """Serialize iterable. @@ -880,15 +862,13 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): serialization_ctxt['type'] should be same as data_type. - is_xml bool : If set, serialize as XML - :param list attr: Object to be serialized. + :param list data: Object to be serialized. :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. :param str div: If set, this str will be used to combine the elements in the iterable into a combined string. Default is 'None'. - :keyword bool do_quote: Whether to quote the serialized result of each iterable element. Defaults to False. :rtype: list, str + :return: serialized iterable """ if isinstance(data, str): raise SerializationError("Refuse str type as a valid iter type.") @@ -943,9 +923,8 @@ def serialize_dict(self, attr, dict_type, **kwargs): :param dict attr: Object to be serialized. :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. :rtype: dict + :return: serialized dictionary """ serialization_ctxt = kwargs.get("serialization_ctxt", {}) serialized = {} @@ -969,7 +948,7 @@ def serialize_dict(self, attr, dict_type, **kwargs): return serialized - def serialize_object(self, attr, **kwargs): + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements """Serialize a generic object. This will be handled as a dictionary. If object passed in is not a basic type (str, int, float, dict, list) it will simply be @@ -977,6 +956,7 @@ def serialize_object(self, attr, **kwargs): :param dict attr: Object to be serialized. :rtype: dict or str + :return: serialized object """ if attr is None: return None @@ -1001,7 +981,7 @@ def serialize_object(self, attr, **kwargs): return self.serialize_decimal(attr) # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): + if obj_type in self.dependencies.values() or isinstance(attr, Model): return self._serialize(attr) if obj_type == dict: @@ -1032,56 +1012,61 @@ def serialize_enum(attr, enum_obj=None): try: enum_obj(result) # type: ignore return result - except ValueError: + except ValueError as exc: for enum_value in enum_obj: # type: ignore if enum_value.value.lower() == str(attr).lower(): return enum_value.value error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) + raise SerializationError(error.format(attr, enum_obj)) from exc @staticmethod - def serialize_bytearray(attr, **kwargs): + def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument """Serialize bytearray into base-64 string. - :param attr: Object to be serialized. + :param str attr: Object to be serialized. :rtype: str + :return: serialized base64 """ return b64encode(attr).decode() @staticmethod - def serialize_base64(attr, **kwargs): + def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument """Serialize str into base-64 string. - :param attr: Object to be serialized. + :param str attr: Object to be serialized. :rtype: str + :return: serialized base64 """ encoded = b64encode(attr).decode("ascii") return encoded.strip("=").replace("+", "-").replace("/", "_") @staticmethod - def serialize_decimal(attr, **kwargs): + def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument """Serialize Decimal object to float. - :param attr: Object to be serialized. + :param decimal attr: Object to be serialized. :rtype: float + :return: serialized decimal """ return float(attr) @staticmethod - def serialize_long(attr, **kwargs): + def serialize_long(attr, **kwargs): # pylint: disable=unused-argument """Serialize long (Py2) or int (Py3). - :param attr: Object to be serialized. + :param int attr: Object to be serialized. :rtype: int/long + :return: serialized long """ return _long_type(attr) @staticmethod - def serialize_date(attr, **kwargs): + def serialize_date(attr, **kwargs): # pylint: disable=unused-argument """Serialize Date object into ISO-8601 formatted string. :param Date attr: Object to be serialized. :rtype: str + :return: serialized date """ if isinstance(attr, str): attr = isodate.parse_date(attr) @@ -1089,11 +1074,12 @@ def serialize_date(attr, **kwargs): return t @staticmethod - def serialize_time(attr, **kwargs): + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument """Serialize Time object into ISO-8601 formatted string. :param datetime.time attr: Object to be serialized. :rtype: str + :return: serialized time """ if isinstance(attr, str): attr = isodate.parse_time(attr) @@ -1103,30 +1089,32 @@ def serialize_time(attr, **kwargs): return t @staticmethod - def serialize_duration(attr, **kwargs): + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument """Serialize TimeDelta object into ISO-8601 formatted string. :param TimeDelta attr: Object to be serialized. :rtype: str + :return: serialized duration """ if isinstance(attr, str): attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) @staticmethod - def serialize_rfc(attr, **kwargs): + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. :param Datetime attr: Object to be serialized. :rtype: str - :raises: TypeError if format invalid. + :raises TypeError: if format invalid. + :return: serialized rfc """ try: if not attr.tzinfo: _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( Serializer.days[utc.tm_wday], @@ -1139,12 +1127,13 @@ def serialize_rfc(attr, **kwargs): ) @staticmethod - def serialize_iso(attr, **kwargs): + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into ISO-8601 formatted string. :param Datetime attr: Object to be serialized. :rtype: str - :raises: SerializationError if format invalid. + :raises SerializationError: if format invalid. + :return: serialized iso """ if isinstance(attr, str): attr = isodate.parse_datetime(attr) @@ -1170,13 +1159,14 @@ def serialize_iso(attr, **kwargs): raise TypeError(msg) from err @staticmethod - def serialize_unix(attr, **kwargs): + def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into IntTime format. This is represented as seconds. :param Datetime attr: Object to be serialized. :rtype: int - :raises: SerializationError if format invalid + :raises SerializationError: if format invalid + :return: serialied unix """ if isinstance(attr, int): return attr @@ -1184,11 +1174,11 @@ def serialize_unix(attr, **kwargs): if not attr.tzinfo: _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc -def rest_key_extractor(attr, attr_desc, data): +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument key = attr_desc["key"] working_data = data @@ -1209,7 +1199,9 @@ def rest_key_extractor(attr, attr_desc, data): return working_data.get(key) -def rest_key_case_insensitive_extractor(attr, attr_desc, data): +def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements + attr, attr_desc, data +): key = attr_desc["key"] working_data = data @@ -1230,17 +1222,29 @@ def rest_key_case_insensitive_extractor(attr, attr_desc, data): return attribute_key_case_insensitive_extractor(key, None, working_data) -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ key = attr_desc["key"] dict_keys = _FLATTEN.split(key) return attribute_key_extractor(dict_keys[-1], None, data) -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument """Extract the attribute in "data" based on the last part of the JSON path key. This is the case insensitive version of "last_rest_key_extractor" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute """ key = attr_desc["key"] dict_keys = _FLATTEN.split(key) @@ -1277,7 +1281,7 @@ def _extract_name_from_internal_type(internal_type): return xml_name -def xml_key_extractor(attr, attr_desc, data): +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements if isinstance(data, dict): return None @@ -1329,22 +1333,21 @@ def xml_key_extractor(attr, attr_desc, data): if is_iter_type: if is_wrapped: return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list + return [] # not wrapped, assume empty list return None # Assume it's not there, maybe an optional node. # If is_iter_type and not wrapped, return all found children if is_iter_type: if not is_wrapped: return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) + # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name ) - return list(children[0]) # Might be empty list and that's ok. + ) + return list(children[0]) # Might be empty list and that's ok. # Here it's not a itertype, we should have found one element only or empty if len(children) > 1: @@ -1352,7 +1355,7 @@ def xml_key_extractor(attr, attr_desc, data): return children[0] -class Deserializer(object): +class Deserializer: """Response object model deserializer. :param dict classes: Class type dictionary for deserializing complex types. @@ -1361,9 +1364,9 @@ class Deserializer(object): basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - def __init__(self, classes: Optional[Mapping[str, type]] = None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.deserialize_type = { "iso-8601": Deserializer.deserialize_iso, "rfc-1123": Deserializer.deserialize_rfc, @@ -1399,27 +1402,29 @@ def __call__(self, target_obj, response_data, content_type=None): :param str target_obj: Target data type to deserialize to. :param requests.Response response_data: REST response object. :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. + :rtype: object """ data = self._unpack_content(response_data, content_type) return self._deserialize(target_obj, data) - def _deserialize(self, target_obj, data): + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements """Call the deserializer on a model. Data needs to be already deserialized as JSON or XML ElementTree :param str target_obj: Target data type to deserialize to. :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. + :rtype: object """ # This is already a model, go recursive just in case if hasattr(data, "_attribute_map"): constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] try: - for attr, mapconfig in data._attribute_map.items(): + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access if attr in constants: continue value = getattr(data, attr) @@ -1438,13 +1443,13 @@ def _deserialize(self, target_obj, data): if isinstance(response, str): return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): + if isinstance(response, type) and issubclass(response, Enum): return self.deserialize_enum(data, response) - if data is None: + if data is None or data is CoreNull: return data try: - attributes = response._attribute_map # type: ignore + attributes = response._attribute_map # type: ignore # pylint: disable=protected-access d_attrs = {} for attr, attr_desc in attributes.items(): # Check empty string. If it's not empty, someone has a real "additionalProperties"... @@ -1474,9 +1479,8 @@ def _deserialize(self, target_obj, data): except (AttributeError, TypeError, KeyError) as err: msg = "Unable to deserialize to object: " + class_name # type: ignore raise DeserializationError(msg) from err - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) def _build_additional_properties(self, attribute_map, data): if not self.additional_properties_detection: @@ -1503,6 +1507,8 @@ def _classify_target(self, target, data): :param str target: The target object type to deserialize to. :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple """ if target is None: return None, None @@ -1514,7 +1520,7 @@ def _classify_target(self, target, data): return target, target try: - target = target._classify(data, self.dependencies) # type: ignore + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access except AttributeError: pass # Target is not a Model, no classify return target, target.__class__.__name__ # type: ignore @@ -1529,10 +1535,12 @@ def failsafe_deserialize(self, target_obj, data, content_type=None): :param str target_obj: The target object type to deserialize to. :param str/dict data: The response data to deserialize. :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object """ try: return self(target_obj, data, content_type=content_type) - except: + except: # pylint: disable=bare-except _LOGGER.debug( "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True ) @@ -1550,10 +1558,12 @@ def _unpack_content(raw_data, content_type=None): If raw_data is something else, bypass all logic and return it directly. - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. + :param obj raw_data: Data to be processed. + :param str content_type: How to parse if raw_data is a string/bytes. :raises JSONDecodeError: If JSON is requested and parsing is impossible. :raises UnicodeDecodeError: If bytes is not UTF8 + :rtype: object + :return: Unpacked content. """ # Assume this is enough to detect a Pipeline Response without importing it context = getattr(raw_data, "context", {}) @@ -1577,24 +1587,35 @@ def _unpack_content(raw_data, content_type=None): def _instantiate_model(self, response, attrs, additional_properties=None): """Instantiate a response model passing in deserialized args. - :param response: The response model class. - :param d_attrs: The deserialized response attributes. + :param Response response: The response model class. + :param dict attrs: The deserialized response attributes. + :param dict additional_properties: Additional properties to be set. + :rtype: Response + :return: The instantiated response model. """ if callable(response): subtype = getattr(response, "_subtype_map", {}) try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] + readonly = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("readonly") + ] + const = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("constant") + ] kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} response_obj = response(**kwargs) for attr in readonly: setattr(response_obj, attr, attrs.get(attr)) if additional_properties: - response_obj.additional_properties = additional_properties + response_obj.additional_properties = additional_properties # type: ignore return response_obj except TypeError as err: msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore - raise DeserializationError(msg + str(err)) + raise DeserializationError(msg + str(err)) from err else: try: for attr, value in attrs.items(): @@ -1603,15 +1624,16 @@ def _instantiate_model(self, response, attrs, additional_properties=None): except Exception as exp: msg = "Unable to populate response model. " msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) + raise DeserializationError(msg) from exp - def deserialize_data(self, data, data_type): + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements """Process data for deserialization according to data type. :param str data: The response string to be deserialized. :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. + :rtype: object """ if data is None: return data @@ -1625,7 +1647,11 @@ def deserialize_data(self, data, data_type): if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): return data - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "object", + "[]", + r"{}", + ] if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: return None data_val = self.deserialize_type[data_type](data) @@ -1645,14 +1671,14 @@ def deserialize_data(self, data, data_type): msg = "Unable to deserialize response data." msg += " Data: {}, {}".format(data, data_type) raise DeserializationError(msg) from err - else: - return self._deserialize(obj_type, data) + return self._deserialize(obj_type, data) def deserialize_iter(self, attr, iter_type): """Deserialize an iterable. :param list attr: Iterable to be deserialized. :param str iter_type: The type of object in the iterable. + :return: Deserialized iterable. :rtype: list """ if attr is None: @@ -1669,6 +1695,7 @@ def deserialize_dict(self, attr, dict_type): :param dict/list attr: Dictionary to be deserialized. Also accepts a list of key, value pairs. :param str dict_type: The object type of the items in the dictionary. + :return: Deserialized dictionary. :rtype: dict """ if isinstance(attr, list): @@ -1679,13 +1706,14 @@ def deserialize_dict(self, attr, dict_type): attr = {el.tag: el.text for el in attr} return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - def deserialize_object(self, attr, **kwargs): + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements """Deserialize a generic object. This will be handled as a dictionary. :param dict attr: Dictionary to be deserialized. + :return: Deserialized object. :rtype: dict - :raises: TypeError if non-builtin datatype encountered. + :raises TypeError: if non-builtin datatype encountered. """ if attr is None: return None @@ -1718,11 +1746,10 @@ def deserialize_object(self, attr, **kwargs): pass return deserialized - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) - def deserialize_basic(self, attr, data_type): + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements """Deserialize basic builtin data type from string. Will attempt to convert to str, int, float and bool. This function will also accept '1', '0', 'true' and 'false' as @@ -1730,8 +1757,9 @@ def deserialize_basic(self, attr, data_type): :param str attr: response string to be deserialized. :param str data_type: deserialization data type. + :return: Deserialized basic type. :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. + :raises TypeError: if string format is not valid. """ # If we're here, data is supposed to be a basic type. # If it's still an XML node, take the text @@ -1741,24 +1769,23 @@ def deserialize_basic(self, attr, data_type): if data_type == "str": # None or '', node is empty string. return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None if data_type == "bool": if attr in [True, False, 1, 0]: return bool(attr) - elif isinstance(attr, str): + if isinstance(attr, str): if attr.lower() in ["true", "1"]: return True - elif attr.lower() in ["false", "0"]: + if attr.lower() in ["false", "0"]: return False raise TypeError("Invalid boolean value: {}".format(attr)) if data_type == "str": return self.deserialize_unicode(attr) - return eval(data_type)(attr) # nosec + return eval(data_type)(attr) # nosec # pylint: disable=eval-used @staticmethod def deserialize_unicode(data): @@ -1766,6 +1793,7 @@ def deserialize_unicode(data): as a string. :param str data: response string to be deserialized. + :return: Deserialized string. :rtype: str or unicode """ # We might be here because we have an enum modeled as string, @@ -1779,8 +1807,7 @@ def deserialize_unicode(data): return data except NameError: return str(data) - else: - return str(data) + return str(data) @staticmethod def deserialize_enum(data, enum_obj): @@ -1792,6 +1819,7 @@ def deserialize_enum(data, enum_obj): :param str data: Response string to be deserialized. If this value is None or invalid it will be returned as-is. :param Enum enum_obj: Enum object to deserialize to. + :return: Deserialized enum object. :rtype: Enum """ if isinstance(data, enum_obj) or data is None: @@ -1802,9 +1830,9 @@ def deserialize_enum(data, enum_obj): # Workaround. We might consider remove it in the future. try: return list(enum_obj.__members__.values())[data] - except IndexError: + except IndexError as exc: error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) + raise DeserializationError(error.format(data, enum_obj)) from exc try: return enum_obj(str(data)) except ValueError: @@ -1820,8 +1848,9 @@ def deserialize_bytearray(attr): """Deserialize string into bytearray. :param str attr: response string to be deserialized. + :return: Deserialized bytearray :rtype: bytearray - :raises: TypeError if string format invalid. + :raises TypeError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1832,8 +1861,9 @@ def deserialize_base64(attr): """Deserialize base64 encoded string into string. :param str attr: response string to be deserialized. + :return: Deserialized base64 string :rtype: bytearray - :raises: TypeError if string format invalid. + :raises TypeError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1847,8 +1877,9 @@ def deserialize_decimal(attr): """Deserialize string into Decimal object. :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. + :return: Deserialized decimal + :raises DeserializationError: if string format invalid. + :rtype: decimal """ if isinstance(attr, ET.Element): attr = attr.text @@ -1863,8 +1894,9 @@ def deserialize_long(attr): """Deserialize string into long (Py2) or int (Py3). :param str attr: response string to be deserialized. + :return: Deserialized int :rtype: long or int - :raises: ValueError if string format invalid. + :raises ValueError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1875,8 +1907,9 @@ def deserialize_duration(attr): """Deserialize ISO-8601 formatted string into TimeDelta object. :param str attr: response string to be deserialized. + :return: Deserialized duration :rtype: TimeDelta - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1885,16 +1918,16 @@ def deserialize_duration(attr): except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize duration object." raise DeserializationError(msg) from err - else: - return duration + return duration @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. :param str attr: response string to be deserialized. + :return: Deserialized date :rtype: Date - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1908,8 +1941,9 @@ def deserialize_time(attr): """Deserialize ISO-8601 formatted string into time object. :param str attr: response string to be deserialized. + :return: Deserialized time :rtype: datetime.time - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1922,31 +1956,32 @@ def deserialize_rfc(attr): """Deserialize RFC-1123 formatted string into Datetime object. :param str attr: response string to be deserialized. + :return: Deserialized RFC datetime :rtype: Datetime - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text try: parsed_date = email.utils.parsedate_tz(attr) # type: ignore date_obj = datetime.datetime( - *parsed_date[:6], tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) ) if not date_obj.tzinfo: date_obj = date_obj.astimezone(tz=TZ_UTC) except ValueError as err: msg = "Cannot deserialize to rfc datetime object." raise DeserializationError(msg) from err - else: - return date_obj + return date_obj @staticmethod def deserialize_iso(attr): """Deserialize ISO-8601 formatted string into Datetime object. :param str attr: response string to be deserialized. + :return: Deserialized ISO datetime :rtype: Datetime - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1974,8 +2009,7 @@ def deserialize_iso(attr): except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize datetime object." raise DeserializationError(msg) from err - else: - return date_obj + return date_obj @staticmethod def deserialize_unix(attr): @@ -1983,8 +2017,9 @@ def deserialize_unix(attr): This is represented as seconds. :param int attr: Object to be serialized. + :return: Deserialized datetime :rtype: Datetime - :raises: DeserializationError if format invalid + :raises DeserializationError: if format invalid """ if isinstance(attr, ET.Element): attr = int(attr.text) # type: ignore @@ -1994,5 +2029,4 @@ def deserialize_unix(attr): except ValueError as err: msg = "Cannot deserialize to unix datetime object." raise DeserializationError(msg) from err - else: - return date_obj + return date_obj diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/_version.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/_version.py index 1ac60b8d8979..6399a016fdd6 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/_version.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "2.0.0b4" +VERSION = "2.0.0b5" diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/__init__.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/__init__.py index 7ae946aaacf0..e74a98774071 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/__init__.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/__init__.py @@ -5,12 +5,18 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._self_help_mgmt_client import SelfHelpMgmtClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._self_help_mgmt_client import SelfHelpMgmtClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # pylint: disable=unused-wildcard-import + from ._patch import * except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk @@ -18,6 +24,6 @@ __all__ = [ "SelfHelpMgmtClient", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/_configuration.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/_configuration.py index dcfab9bfaeb4..52310e50cf75 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/_configuration.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/_configuration.py @@ -14,11 +14,10 @@ from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class SelfHelpMgmtClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long +class SelfHelpMgmtClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for SelfHelpMgmtClient. Note that all parameters used to create this instance are saved as instance @@ -26,18 +25,23 @@ class SelfHelpMgmtClientConfiguration: # pylint: disable=too-many-instance-attr :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str :keyword api_version: Api Version. Default value is "2024-03-01-preview". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None: + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: api_version: str = kwargs.pop("api_version", "2024-03-01-preview") if credential is None: raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") self.credential = credential + self.subscription_id = subscription_id self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-selfhelp/{}".format(VERSION)) diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/_self_help_mgmt_client.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/_self_help_mgmt_client.py index 2cbe1eaee1d8..579a306475ae 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/_self_help_mgmt_client.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/_self_help_mgmt_client.py @@ -7,15 +7,18 @@ # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING +from typing import Any, Awaitable, Optional, TYPE_CHECKING, cast +from typing_extensions import Self from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.settings import settings from azure.mgmt.core import AsyncARMPipelineClient from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints from .. import models as _models -from .._serialization import Deserializer, Serializer +from .._utils.serialization import Deserializer, Serializer from ._configuration import SelfHelpMgmtClientConfiguration from .operations import ( CheckNameAvailabilityOperations, @@ -30,36 +33,37 @@ ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class SelfHelpMgmtClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes +class SelfHelpMgmtClient: # pylint: disable=too-many-instance-attributes """Help RP provider. - :ivar operations: Operations operations - :vartype operations: azure.mgmt.selfhelp.aio.operations.Operations :ivar check_name_availability: CheckNameAvailabilityOperations operations :vartype check_name_availability: azure.mgmt.selfhelp.aio.operations.CheckNameAvailabilityOperations :ivar diagnostics: DiagnosticsOperations operations :vartype diagnostics: azure.mgmt.selfhelp.aio.operations.DiagnosticsOperations - :ivar discovery_solution: DiscoverySolutionOperations operations - :vartype discovery_solution: azure.mgmt.selfhelp.aio.operations.DiscoverySolutionOperations - :ivar solution: SolutionOperations operations - :vartype solution: azure.mgmt.selfhelp.aio.operations.SolutionOperations :ivar simplified_solutions: SimplifiedSolutionsOperations operations :vartype simplified_solutions: azure.mgmt.selfhelp.aio.operations.SimplifiedSolutionsOperations + :ivar solution: SolutionOperations operations + :vartype solution: azure.mgmt.selfhelp.aio.operations.SolutionOperations :ivar troubleshooters: TroubleshootersOperations operations :vartype troubleshooters: azure.mgmt.selfhelp.aio.operations.TroubleshootersOperations - :ivar solution_self_help: SolutionSelfHelpOperations operations - :vartype solution_self_help: azure.mgmt.selfhelp.aio.operations.SolutionSelfHelpOperations :ivar discovery_solution_nlp: DiscoverySolutionNLPOperations operations :vartype discovery_solution_nlp: azure.mgmt.selfhelp.aio.operations.DiscoverySolutionNLPOperations + :ivar discovery_solution: DiscoverySolutionOperations operations + :vartype discovery_solution: azure.mgmt.selfhelp.aio.operations.DiscoverySolutionOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.selfhelp.aio.operations.Operations + :ivar solution_self_help: SolutionSelfHelpOperations operations + :vartype solution_self_help: azure.mgmt.selfhelp.aio.operations.SolutionSelfHelpOperations :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param base_url: Service URL. Default value is "https://management.azure.com". + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is None. :type base_url: str :keyword api_version: Api Version. Default value is "2024-03-01-preview". Note that overriding this default value may result in unsupported behavior. @@ -69,9 +73,17 @@ class SelfHelpMgmtClient: # pylint: disable=client-accepts-api-version-keyword, """ def __init__( - self, credential: "AsyncTokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any + self, credential: "AsyncTokenCredential", subscription_id: str, base_url: Optional[str] = None, **kwargs: Any ) -> None: - self._config = SelfHelpMgmtClientConfiguration(credential=credential, **kwargs) + _cloud = kwargs.pop("cloud_setting", None) or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = SelfHelpMgmtClientConfiguration( + credential=credential, subscription_id=subscription_id, credential_scopes=credential_scopes, **kwargs + ) + _policies = kwargs.pop("policies", None) if _policies is None: _policies = [ @@ -90,29 +102,31 @@ def __init__( 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) + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient( + base_url=cast(str, 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 - self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) self.check_name_availability = CheckNameAvailabilityOperations( self._client, self._config, self._serialize, self._deserialize ) self.diagnostics = DiagnosticsOperations(self._client, self._config, self._serialize, self._deserialize) - self.discovery_solution = DiscoverySolutionOperations( + self.simplified_solutions = SimplifiedSolutionsOperations( self._client, self._config, self._serialize, self._deserialize ) self.solution = SolutionOperations(self._client, self._config, self._serialize, self._deserialize) - self.simplified_solutions = SimplifiedSolutionsOperations( + self.troubleshooters = TroubleshootersOperations(self._client, self._config, self._serialize, self._deserialize) + self.discovery_solution_nlp = DiscoverySolutionNLPOperations( self._client, self._config, self._serialize, self._deserialize ) - self.troubleshooters = TroubleshootersOperations(self._client, self._config, self._serialize, self._deserialize) - self.solution_self_help = SolutionSelfHelpOperations( + self.discovery_solution = DiscoverySolutionOperations( self._client, self._config, self._serialize, self._deserialize ) - self.discovery_solution_nlp = DiscoverySolutionNLPOperations( + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.solution_self_help = SolutionSelfHelpOperations( self._client, self._config, self._serialize, self._deserialize ) @@ -143,7 +157,7 @@ def _send_request( async def close(self) -> None: await self._client.close() - async def __aenter__(self) -> "SelfHelpMgmtClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/__init__.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/__init__.py index 8769d976fa3d..add80b5e618b 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/__init__.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/__init__.py @@ -5,31 +5,37 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._operations import Operations -from ._check_name_availability_operations import CheckNameAvailabilityOperations -from ._diagnostics_operations import DiagnosticsOperations -from ._discovery_solution_operations import DiscoverySolutionOperations -from ._solution_operations import SolutionOperations -from ._simplified_solutions_operations import SimplifiedSolutionsOperations -from ._troubleshooters_operations import TroubleshootersOperations -from ._solution_self_help_operations import SolutionSelfHelpOperations -from ._discovery_solution_nlp_operations import DiscoverySolutionNLPOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._check_name_availability_operations import CheckNameAvailabilityOperations # type: ignore +from ._diagnostics_operations import DiagnosticsOperations # type: ignore +from ._simplified_solutions_operations import SimplifiedSolutionsOperations # type: ignore +from ._solution_operations import SolutionOperations # type: ignore +from ._troubleshooters_operations import TroubleshootersOperations # type: ignore +from ._discovery_solution_nlp_operations import DiscoverySolutionNLPOperations # type: ignore +from ._discovery_solution_operations import DiscoverySolutionOperations # type: ignore +from ._operations import Operations # type: ignore +from ._solution_self_help_operations import SolutionSelfHelpOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ - "Operations", "CheckNameAvailabilityOperations", "DiagnosticsOperations", - "DiscoverySolutionOperations", - "SolutionOperations", "SimplifiedSolutionsOperations", + "SolutionOperations", "TroubleshootersOperations", - "SolutionSelfHelpOperations", "DiscoverySolutionNLPOperations", + "DiscoverySolutionOperations", + "Operations", + "SolutionSelfHelpOperations", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_check_name_availability_operations.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_check_name_availability_operations.py index 08300a6fd71b..c3e6d8f9613a 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_check_name_availability_operations.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_check_name_availability_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +5,11 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from collections.abc import MutableMapping from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Optional, Type, TypeVar, Union, overload +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload +from azure.core import AsyncPipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -19,20 +19,16 @@ 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 ..._utils.serialization import Deserializer, Serializer from ...operations._check_name_availability_operations import build_check_availability_request +from .._configuration import SelfHelpMgmtClientConfiguration -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -51,10 +47,10 @@ class CheckNameAvailabilityOperations: def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SelfHelpMgmtClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @overload async def check_availability( @@ -68,9 +64,7 @@ async def check_availability( """This API is used to check the uniqueness of a resource name used for a diagnostic, troubleshooter or solutions. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param check_name_availability_request: The required parameters for availability check. Default value is None. @@ -95,9 +89,7 @@ async def check_availability( """This API is used to check the uniqueness of a resource name used for a diagnostic, troubleshooter or solutions. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param check_name_availability_request: The required parameters for availability check. Default value is None. @@ -120,9 +112,7 @@ async def check_availability( """This API is used to check the uniqueness of a resource name used for a diagnostic, troubleshooter or solutions. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param check_name_availability_request: The required parameters for availability check. Is either a CheckNameAvailabilityRequest type or a IO[bytes] type. Default value is None. @@ -132,7 +122,7 @@ async def check_availability( :rtype: ~azure.mgmt.selfhelp.models.CheckNameAvailabilityResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -167,7 +157,6 @@ async def check_availability( headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) _stream = False @@ -182,7 +171,7 @@ async def check_availability( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("CheckNameAvailabilityResponse", pipeline_response) + deserialized = self._deserialize("CheckNameAvailabilityResponse", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_diagnostics_operations.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_diagnostics_operations.py index 1c0c2998ab3a..f148583b5835 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_diagnostics_operations.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_diagnostics_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,35 +5,34 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from collections.abc import MutableMapping from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload +from typing import Any, AsyncIterator, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +from azure.core import AsyncPipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, 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_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models -from ..._vendor import _convert_request +from ..._utils.serialization import Deserializer, Serializer from ...operations._diagnostics_operations import build_create_request, build_get_request +from .._configuration import SelfHelpMgmtClientConfiguration -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -53,19 +51,74 @@ class DiagnosticsOperations: def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SelfHelpMgmtClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get(self, scope: str, diagnostics_resource_name: str, **kwargs: Any) -> _models.DiagnosticResource: + """Get the diagnostics using the 'diagnosticsResourceName' you chose while creating the + diagnostic. + + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. + :type scope: str + :param diagnostics_resource_name: Unique resource name for insight resources. Required. + :type diagnostics_resource_name: str + :return: DiagnosticResource or the result of cls(response) + :rtype: ~azure.mgmt.selfhelp.models.DiagnosticResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DiagnosticResource] = kwargs.pop("cls", None) + + _request = build_get_request( + scope=scope, + diagnostics_resource_name=diagnostics_resource_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + 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]: + 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 = self._deserialize("DiagnosticResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore async def _create_initial( self, scope: str, diagnostics_resource_name: str, - diagnostic_resource_request: Optional[Union[_models.DiagnosticResource, IO[bytes]]] = None, + diagnostic_resource_request: Union[_models.DiagnosticResource, IO[bytes]], **kwargs: Any - ) -> _models.DiagnosticResource: - error_map: MutableMapping[int, Type[HttpResponseError]] = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -78,7 +131,7 @@ async def _create_initial( 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.DiagnosticResource] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None @@ -86,10 +139,7 @@ async def _create_initial( if isinstance(diagnostic_resource_request, (IOBase, bytes)): _content = diagnostic_resource_request else: - if diagnostic_resource_request is not None: - _json = self._serialize.body(diagnostic_resource_request, "DiagnosticResource") - else: - _json = None + _json = self._serialize.body(diagnostic_resource_request, "DiagnosticResource") _request = build_create_request( scope=scope, @@ -101,10 +151,10 @@ async def _create_initial( headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -112,18 +162,25 @@ async def _create_initial( response = pipeline_response.http_response if response.status_code not in [200, 201]: + 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) - if response.status_code == 200: - deserialized = self._deserialize("DiagnosticResource", pipeline_response) - + response_headers = {} if response.status_code == 201: - deserialized = self._deserialize("DiagnosticResource", pipeline_response) + response_headers["Azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-AsyncOperation") + ) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized # type: ignore @@ -132,24 +189,22 @@ async def begin_create( self, scope: str, diagnostics_resource_name: str, - diagnostic_resource_request: Optional[_models.DiagnosticResource] = None, + diagnostic_resource_request: _models.DiagnosticResource, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.DiagnosticResource]: """Creates a diagnostic for the specific resource using solutionId from discovery solutions. :code:`
`Diagnostics are powerful solutions that access product resources or other relevant - data and provide the root cause of the issue and the steps to address the - issue.:code:`
`:code:`
`. + data and provide the root cause of the issue and the steps to address the issue.\\ + :code:`
`\\ :code:`
`. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param diagnostics_resource_name: Unique resource name for insight resources. Required. :type diagnostics_resource_name: str :param diagnostic_resource_request: The required request body for this insightResource - invocation. Default value is None. + invocation. Required. :type diagnostic_resource_request: ~azure.mgmt.selfhelp.models.DiagnosticResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". @@ -165,24 +220,22 @@ async def begin_create( self, scope: str, diagnostics_resource_name: str, - diagnostic_resource_request: Optional[IO[bytes]] = None, + diagnostic_resource_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.DiagnosticResource]: """Creates a diagnostic for the specific resource using solutionId from discovery solutions. :code:`
`Diagnostics are powerful solutions that access product resources or other relevant - data and provide the root cause of the issue and the steps to address the - issue.:code:`
`:code:`
`. + data and provide the root cause of the issue and the steps to address the issue.\\ + :code:`
`\\ :code:`
`. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param diagnostics_resource_name: Unique resource name for insight resources. Required. :type diagnostics_resource_name: str :param diagnostic_resource_request: The required request body for this insightResource - invocation. Default value is None. + invocation. Required. :type diagnostic_resource_request: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". @@ -198,22 +251,20 @@ async def begin_create( self, scope: str, diagnostics_resource_name: str, - diagnostic_resource_request: Optional[Union[_models.DiagnosticResource, IO[bytes]]] = None, + diagnostic_resource_request: Union[_models.DiagnosticResource, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.DiagnosticResource]: """Creates a diagnostic for the specific resource using solutionId from discovery solutions. :code:`
`Diagnostics are powerful solutions that access product resources or other relevant - data and provide the root cause of the issue and the steps to address the - issue.:code:`
`:code:`
`. + data and provide the root cause of the issue and the steps to address the issue.\\ + :code:`
`\\ :code:`
`. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param diagnostics_resource_name: Unique resource name for insight resources. Required. :type diagnostics_resource_name: str :param diagnostic_resource_request: The required request body for this insightResource - invocation. Is either a DiagnosticResource type or a IO[bytes] type. Default value is None. + invocation. Is either a DiagnosticResource type or a IO[bytes] type. Required. :type diagnostic_resource_request: ~azure.mgmt.selfhelp.models.DiagnosticResource or IO[bytes] :return: An instance of AsyncLROPoller that returns either DiagnosticResource or the result of cls(response) @@ -241,10 +292,11 @@ async def begin_create( 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("DiagnosticResource", pipeline_response) + deserialized = self._deserialize("DiagnosticResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized @@ -268,61 +320,3 @@ def get_long_running_output(pipeline_response): return AsyncLROPoller[_models.DiagnosticResource]( self._client, raw_result, get_long_running_output, polling_method # type: ignore ) - - @distributed_trace_async - async def get(self, scope: str, diagnostics_resource_name: str, **kwargs: Any) -> _models.DiagnosticResource: - """Get the diagnostics using the 'diagnosticsResourceName' you chose while creating the - diagnostic. - - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. - :type scope: str - :param diagnostics_resource_name: Unique resource name for insight resources. Required. - :type diagnostics_resource_name: str - :return: DiagnosticResource or the result of cls(response) - :rtype: ~azure.mgmt.selfhelp.models.DiagnosticResource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DiagnosticResource] = kwargs.pop("cls", None) - - _request = build_get_request( - scope=scope, - diagnostics_resource_name=diagnostics_resource_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request = _convert_request(_request) - _request.url = self._client.format_url(_request.url) - - _stream = False - 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]: - 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 = self._deserialize("DiagnosticResource", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_discovery_solution_nlp_operations.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_discovery_solution_nlp_operations.py index 81a9fa2618d1..29a43ec1f950 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_discovery_solution_nlp_operations.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_discovery_solution_nlp_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +5,11 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from collections.abc import MutableMapping from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Optional, Type, TypeVar, Union, overload +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload +from azure.core import AsyncPipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -19,23 +19,19 @@ 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 ..._utils.serialization import Deserializer, Serializer from ...operations._discovery_solution_nlp_operations import ( build_discover_solutions_by_subscription_request, build_discover_solutions_request, ) +from .._configuration import SelfHelpMgmtClientConfiguration -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -54,15 +50,15 @@ class DiscoverySolutionNLPOperations: def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SelfHelpMgmtClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @overload async def discover_solutions( self, - discover_solution_request: Optional[_models.DiscoveryNlpRequest] = None, + discover_solution_request: _models.DiscoveryNlpRequest, *, content_type: str = "application/json", **kwargs: Any @@ -70,8 +66,7 @@ async def discover_solutions( """Search for relevant Azure Diagnostics, Solutions and Troubleshooters using a natural language issue summary. - :param discover_solution_request: Request body for discovering solutions using NLP. Default - value is None. + :param discover_solution_request: The request body. Required. :type discover_solution_request: ~azure.mgmt.selfhelp.models.DiscoveryNlpRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". @@ -83,17 +78,12 @@ async def discover_solutions( @overload async def discover_solutions( - self, - discover_solution_request: Optional[IO[bytes]] = None, - *, - content_type: str = "application/json", - **kwargs: Any + self, discover_solution_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.DiscoveryNlpResponse: """Search for relevant Azure Diagnostics, Solutions and Troubleshooters using a natural language issue summary. - :param discover_solution_request: Request body for discovering solutions using NLP. Default - value is None. + :param discover_solution_request: The request body. Required. :type discover_solution_request: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". @@ -105,19 +95,19 @@ async def discover_solutions( @distributed_trace_async async def discover_solutions( - self, discover_solution_request: Optional[Union[_models.DiscoveryNlpRequest, IO[bytes]]] = None, **kwargs: Any + self, discover_solution_request: Union[_models.DiscoveryNlpRequest, IO[bytes]], **kwargs: Any ) -> _models.DiscoveryNlpResponse: """Search for relevant Azure Diagnostics, Solutions and Troubleshooters using a natural language issue summary. - :param discover_solution_request: Request body for discovering solutions using NLP. Is either a - DiscoveryNlpRequest type or a IO[bytes] type. Default value is None. + :param discover_solution_request: The request body. Is either a DiscoveryNlpRequest type or a + IO[bytes] type. Required. :type discover_solution_request: ~azure.mgmt.selfhelp.models.DiscoveryNlpRequest or IO[bytes] :return: DiscoveryNlpResponse or the result of cls(response) :rtype: ~azure.mgmt.selfhelp.models.DiscoveryNlpResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -138,10 +128,7 @@ async def discover_solutions( if isinstance(discover_solution_request, (IOBase, bytes)): _content = discover_solution_request else: - if discover_solution_request is not None: - _json = self._serialize.body(discover_solution_request, "DiscoveryNlpRequest") - else: - _json = None + _json = self._serialize.body(discover_solution_request, "DiscoveryNlpRequest") _request = build_discover_solutions_request( api_version=api_version, @@ -151,7 +138,6 @@ async def discover_solutions( headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) _stream = False @@ -166,7 +152,7 @@ async def discover_solutions( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DiscoveryNlpResponse", pipeline_response) + deserialized = self._deserialize("DiscoveryNlpResponse", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -176,8 +162,7 @@ async def discover_solutions( @overload async def discover_solutions_by_subscription( self, - subscription_id: str, - discover_solution_request: Optional[_models.DiscoveryNlpRequest] = None, + discover_solution_request: _models.DiscoveryNlpRequest, *, content_type: str = "application/json", **kwargs: Any @@ -185,10 +170,7 @@ async def discover_solutions_by_subscription( """Search for relevant Azure Diagnostics, Solutions and Troubleshooters using a natural language issue summary and subscription. - :param subscription_id: The Azure subscription ID. Required. - :type subscription_id: str - :param discover_solution_request: Request body for discovering solutions using NLP. Default - value is None. + :param discover_solution_request: The request body. Required. :type discover_solution_request: ~azure.mgmt.selfhelp.models.DiscoveryNlpRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". @@ -200,20 +182,12 @@ async def discover_solutions_by_subscription( @overload async def discover_solutions_by_subscription( - self, - subscription_id: str, - discover_solution_request: Optional[IO[bytes]] = None, - *, - content_type: str = "application/json", - **kwargs: Any + self, discover_solution_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.DiscoveryNlpResponse: """Search for relevant Azure Diagnostics, Solutions and Troubleshooters using a natural language issue summary and subscription. - :param subscription_id: The Azure subscription ID. Required. - :type subscription_id: str - :param discover_solution_request: Request body for discovering solutions using NLP. Default - value is None. + :param discover_solution_request: The request body. Required. :type discover_solution_request: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". @@ -225,24 +199,19 @@ async def discover_solutions_by_subscription( @distributed_trace_async async def discover_solutions_by_subscription( - self, - subscription_id: str, - discover_solution_request: Optional[Union[_models.DiscoveryNlpRequest, IO[bytes]]] = None, - **kwargs: Any + self, discover_solution_request: Union[_models.DiscoveryNlpRequest, IO[bytes]], **kwargs: Any ) -> _models.DiscoveryNlpResponse: """Search for relevant Azure Diagnostics, Solutions and Troubleshooters using a natural language issue summary and subscription. - :param subscription_id: The Azure subscription ID. Required. - :type subscription_id: str - :param discover_solution_request: Request body for discovering solutions using NLP. Is either a - DiscoveryNlpRequest type or a IO[bytes] type. Default value is None. + :param discover_solution_request: The request body. Is either a DiscoveryNlpRequest type or a + IO[bytes] type. Required. :type discover_solution_request: ~azure.mgmt.selfhelp.models.DiscoveryNlpRequest or IO[bytes] :return: DiscoveryNlpResponse or the result of cls(response) :rtype: ~azure.mgmt.selfhelp.models.DiscoveryNlpResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -263,13 +232,10 @@ async def discover_solutions_by_subscription( if isinstance(discover_solution_request, (IOBase, bytes)): _content = discover_solution_request else: - if discover_solution_request is not None: - _json = self._serialize.body(discover_solution_request, "DiscoveryNlpRequest") - else: - _json = None + _json = self._serialize.body(discover_solution_request, "DiscoveryNlpRequest") _request = build_discover_solutions_by_subscription_request( - subscription_id=subscription_id, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, @@ -277,7 +243,6 @@ async def discover_solutions_by_subscription( headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) _stream = False @@ -292,7 +257,7 @@ async def discover_solutions_by_subscription( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DiscoveryNlpResponse", pipeline_response) + deserialized = self._deserialize("DiscoveryNlpResponse", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_discovery_solution_operations.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_discovery_solution_operations.py index 31bdf3bbae91..9bf7b184aa9d 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_discovery_solution_operations.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_discovery_solution_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +5,11 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +from collections.abc import MutableMapping +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar import urllib.parse +from azure.core import AsyncPipelineClient from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, @@ -20,20 +20,16 @@ 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 ..._utils.serialization import Deserializer, Serializer from ...operations._discovery_solution_operations import build_list_request +from .._configuration import SelfHelpMgmtClientConfiguration -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -52,10 +48,10 @@ class DiscoverySolutionOperations: def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SelfHelpMgmtClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list( @@ -64,11 +60,11 @@ def list( """Lists the relevant Azure Diagnostics, Solutions and Troubleshooters using `problemClassification API `_\\ ) AND - resourceUri or resourceType.:code:`
` Discovery Solutions is the initial entry point within - Help API, which identifies relevant Azure diagnostics and solutions. :code:`
`:code:`
` - Required Input : problemClassificationId (Use the `problemClassification API + resourceUri or resourceType.\\ :code:`
` Discovery Solutions is the initial entry point + within Help API, which identifies relevant Azure diagnostics and solutions. :code:`
`\\ + :code:`
` Required Input : problemClassificationId (Use the `problemClassification API `_\\ ) - :code:`
`Optional input: resourceUri OR resource Type :code:`
`:code:`
` + :code:`
`Optional input: resourceUri OR resource Type :code:`
`\\ :code:`
` :code:`Note: ` ‘requiredInputs’ from Discovery solutions response must be passed via ‘additionalParameters’ as an input to Diagnostics and Solutions API. @@ -93,7 +89,7 @@ def list( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.DiscoveryResponse] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -111,7 +107,6 @@ def prepare_request(next_link=None): headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) else: @@ -127,7 +122,6 @@ def prepare_request(next_link=None): _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) _request.method = "GET" return _request diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_operations.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_operations.py index ab6c59a61dc3..27da52cdfb84 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_operations.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +5,11 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +from collections.abc import MutableMapping +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar import urllib.parse +from azure.core import AsyncPipelineClient from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, @@ -20,20 +20,16 @@ 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 ..._utils.serialization import Deserializer, Serializer from ...operations._operations import build_list_request +from .._configuration import SelfHelpMgmtClientConfiguration -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -52,14 +48,14 @@ class Operations: def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SelfHelpMgmtClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: - """Returns list of operations. + """List the operations for the provider. :return: An iterator like instance of either Operation or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.selfhelp.models.Operation] @@ -71,7 +67,7 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: 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: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -87,7 +83,6 @@ def prepare_request(next_link=None): headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) else: @@ -103,7 +98,6 @@ def prepare_request(next_link=None): _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) _request.method = "GET" return _request diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_simplified_solutions_operations.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_simplified_solutions_operations.py index ed50ef28db0d..aac922681172 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_simplified_solutions_operations.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_simplified_solutions_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,35 +5,34 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from collections.abc import MutableMapping from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload +from typing import Any, AsyncIterator, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +from azure.core import AsyncPipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, 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_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models -from ..._vendor import _convert_request +from ..._utils.serialization import Deserializer, Serializer from ...operations._simplified_solutions_operations import build_create_request, build_get_request +from .._configuration import SelfHelpMgmtClientConfiguration -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -53,19 +51,76 @@ class SimplifiedSolutionsOperations: def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SelfHelpMgmtClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get( + self, scope: str, simplified_solutions_resource_name: str, **kwargs: Any + ) -> _models.SimplifiedSolutionsResource: + """Get the simplified Solutions using the applicable solutionResourceName while creating the + simplified Solutions. + + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. + :type scope: str + :param simplified_solutions_resource_name: Simplified Solutions Resource Name. Required. + :type simplified_solutions_resource_name: str + :return: SimplifiedSolutionsResource or the result of cls(response) + :rtype: ~azure.mgmt.selfhelp.models.SimplifiedSolutionsResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SimplifiedSolutionsResource] = kwargs.pop("cls", None) + + _request = build_get_request( + scope=scope, + simplified_solutions_resource_name=simplified_solutions_resource_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + 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]: + 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 = self._deserialize("SimplifiedSolutionsResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore async def _create_initial( self, scope: str, simplified_solutions_resource_name: str, - simplified_solutions_request_body: Optional[Union[_models.SimplifiedSolutionsResource, IO[bytes]]] = None, + simplified_solutions_request_body: Union[_models.SimplifiedSolutionsResource, IO[bytes]], **kwargs: Any - ) -> _models.SimplifiedSolutionsResource: - error_map: MutableMapping[int, Type[HttpResponseError]] = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -78,7 +133,7 @@ async def _create_initial( 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.SimplifiedSolutionsResource] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None @@ -86,10 +141,7 @@ async def _create_initial( if isinstance(simplified_solutions_request_body, (IOBase, bytes)): _content = simplified_solutions_request_body else: - if simplified_solutions_request_body is not None: - _json = self._serialize.body(simplified_solutions_request_body, "SimplifiedSolutionsResource") - else: - _json = None + _json = self._serialize.body(simplified_solutions_request_body, "SimplifiedSolutionsResource") _request = build_create_request( scope=scope, @@ -101,10 +153,10 @@ async def _create_initial( headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -112,18 +164,25 @@ async def _create_initial( response = pipeline_response.http_response if response.status_code not in [200, 201]: + 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) - if response.status_code == 200: - deserialized = self._deserialize("SimplifiedSolutionsResource", pipeline_response) - + response_headers = {} if response.status_code == 201: - deserialized = self._deserialize("SimplifiedSolutionsResource", pipeline_response) + response_headers["Azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-AsyncOperation") + ) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized # type: ignore @@ -132,26 +191,24 @@ async def begin_create( self, scope: str, simplified_solutions_resource_name: str, - simplified_solutions_request_body: Optional[_models.SimplifiedSolutionsResource] = None, + simplified_solutions_request_body: _models.SimplifiedSolutionsResource, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.SimplifiedSolutionsResource]: """Creates Simplified Solutions for an Azure subscription using 'solutionId' from Discovery - Solutions as the input. :code:`
`:code:`
` Simplified Solutions API makes the + Solutions as the input. :code:`
`\\ :code:`
` Simplified Solutions API makes the consumption of solutions APIs easier while still providing access to the same powerful solutions rendered in Solutions API. With Simplified Solutions, users don't have to worry about stitching together the article using replacement maps and can use the content in the API - response to directly render as HTML content.:code:`
`. + response to directly render as HTML content.\\ :code:`
`. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param simplified_solutions_resource_name: Simplified Solutions Resource Name. Required. :type simplified_solutions_resource_name: str :param simplified_solutions_request_body: The required request body for simplified Solutions - resource creation. Default value is None. + resource creation. Required. :type simplified_solutions_request_body: ~azure.mgmt.selfhelp.models.SimplifiedSolutionsResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -169,26 +226,24 @@ async def begin_create( self, scope: str, simplified_solutions_resource_name: str, - simplified_solutions_request_body: Optional[IO[bytes]] = None, + simplified_solutions_request_body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.SimplifiedSolutionsResource]: """Creates Simplified Solutions for an Azure subscription using 'solutionId' from Discovery - Solutions as the input. :code:`
`:code:`
` Simplified Solutions API makes the + Solutions as the input. :code:`
`\\ :code:`
` Simplified Solutions API makes the consumption of solutions APIs easier while still providing access to the same powerful solutions rendered in Solutions API. With Simplified Solutions, users don't have to worry about stitching together the article using replacement maps and can use the content in the API - response to directly render as HTML content.:code:`
`. + response to directly render as HTML content.\\ :code:`
`. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param simplified_solutions_resource_name: Simplified Solutions Resource Name. Required. :type simplified_solutions_resource_name: str :param simplified_solutions_request_body: The required request body for simplified Solutions - resource creation. Default value is None. + resource creation. Required. :type simplified_solutions_request_body: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". @@ -205,25 +260,22 @@ async def begin_create( self, scope: str, simplified_solutions_resource_name: str, - simplified_solutions_request_body: Optional[Union[_models.SimplifiedSolutionsResource, IO[bytes]]] = None, + simplified_solutions_request_body: Union[_models.SimplifiedSolutionsResource, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.SimplifiedSolutionsResource]: """Creates Simplified Solutions for an Azure subscription using 'solutionId' from Discovery - Solutions as the input. :code:`
`:code:`
` Simplified Solutions API makes the + Solutions as the input. :code:`
`\\ :code:`
` Simplified Solutions API makes the consumption of solutions APIs easier while still providing access to the same powerful solutions rendered in Solutions API. With Simplified Solutions, users don't have to worry about stitching together the article using replacement maps and can use the content in the API - response to directly render as HTML content.:code:`
`. + response to directly render as HTML content.\\ :code:`
`. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param simplified_solutions_resource_name: Simplified Solutions Resource Name. Required. :type simplified_solutions_resource_name: str :param simplified_solutions_request_body: The required request body for simplified Solutions - resource creation. Is either a SimplifiedSolutionsResource type or a IO[bytes] type. Default - value is None. + resource creation. Is either a SimplifiedSolutionsResource type or a IO[bytes] type. Required. :type simplified_solutions_request_body: ~azure.mgmt.selfhelp.models.SimplifiedSolutionsResource or IO[bytes] :return: An instance of AsyncLROPoller that returns either SimplifiedSolutionsResource or the @@ -253,10 +305,11 @@ async def begin_create( 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("SimplifiedSolutionsResource", pipeline_response) + deserialized = self._deserialize("SimplifiedSolutionsResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized @@ -280,63 +333,3 @@ def get_long_running_output(pipeline_response): return AsyncLROPoller[_models.SimplifiedSolutionsResource]( self._client, raw_result, get_long_running_output, polling_method # type: ignore ) - - @distributed_trace_async - async def get( - self, scope: str, simplified_solutions_resource_name: str, **kwargs: Any - ) -> _models.SimplifiedSolutionsResource: - """Get the simplified Solutions using the applicable solutionResourceName while creating the - simplified Solutions. - - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. - :type scope: str - :param simplified_solutions_resource_name: Simplified Solutions Resource Name. Required. - :type simplified_solutions_resource_name: str - :return: SimplifiedSolutionsResource or the result of cls(response) - :rtype: ~azure.mgmt.selfhelp.models.SimplifiedSolutionsResource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SimplifiedSolutionsResource] = kwargs.pop("cls", None) - - _request = build_get_request( - scope=scope, - simplified_solutions_resource_name=simplified_solutions_resource_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request = _convert_request(_request) - _request.url = self._client.format_url(_request.url) - - _stream = False - 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]: - 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 = self._deserialize("SimplifiedSolutionsResource", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_solution_operations.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_solution_operations.py index 192d973abba6..4ca0b2df7923 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_solution_operations.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_solution_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,40 +5,39 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from collections.abc import MutableMapping from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload +from typing import Any, AsyncIterator, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +from azure.core import AsyncPipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, 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_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models -from ..._vendor import _convert_request +from ..._utils.serialization import Deserializer, Serializer from ...operations._solution_operations import ( build_create_request, build_get_request, build_update_request, build_warm_up_request, ) +from .._configuration import SelfHelpMgmtClientConfiguration -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -58,19 +56,73 @@ class SolutionOperations: def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SelfHelpMgmtClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get(self, scope: str, solution_resource_name: str, **kwargs: Any) -> _models.SolutionResource: + """Get the solution using the applicable solutionResourceName while creating the solution. + + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. + :type scope: str + :param solution_resource_name: Solution resource Name. Required. + :type solution_resource_name: str + :return: SolutionResource or the result of cls(response) + :rtype: ~azure.mgmt.selfhelp.models.SolutionResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SolutionResource] = kwargs.pop("cls", None) + + _request = build_get_request( + scope=scope, + solution_resource_name=solution_resource_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + 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]: + 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 = self._deserialize("SolutionResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore async def _create_initial( self, scope: str, solution_resource_name: str, - solution_request_body: Optional[Union[_models.SolutionResource, IO[bytes]]] = None, + solution_request_body: Union[_models.SolutionResource, IO[bytes]], **kwargs: Any - ) -> _models.SolutionResource: - error_map: MutableMapping[int, Type[HttpResponseError]] = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -83,7 +135,7 @@ async def _create_initial( 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.SolutionResource] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None @@ -91,10 +143,7 @@ async def _create_initial( if isinstance(solution_request_body, (IOBase, bytes)): _content = solution_request_body else: - if solution_request_body is not None: - _json = self._serialize.body(solution_request_body, "SolutionResource") - else: - _json = None + _json = self._serialize.body(solution_request_body, "SolutionResource") _request = build_create_request( scope=scope, @@ -106,10 +155,10 @@ async def _create_initial( headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -117,18 +166,25 @@ async def _create_initial( response = pipeline_response.http_response if response.status_code not in [200, 201]: + 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) - if response.status_code == 200: - deserialized = self._deserialize("SolutionResource", pipeline_response) - + response_headers = {} if response.status_code == 201: - deserialized = self._deserialize("SolutionResource", pipeline_response) + response_headers["Azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-AsyncOperation") + ) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized # type: ignore @@ -137,7 +193,7 @@ async def begin_create( self, scope: str, solution_resource_name: str, - solution_request_body: Optional[_models.SolutionResource] = None, + solution_request_body: _models.SolutionResource, *, content_type: str = "application/json", **kwargs: Any @@ -152,14 +208,12 @@ async def begin_create( troubleshooting instructions. :code:`
` All these components are seamlessly converged into unified solutions tailored to address a specific support problem area. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param solution_resource_name: Solution resource Name. Required. :type solution_resource_name: str :param solution_request_body: The required request body for this solution resource creation. - Default value is None. + Required. :type solution_request_body: ~azure.mgmt.selfhelp.models.SolutionResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". @@ -175,7 +229,7 @@ async def begin_create( self, scope: str, solution_resource_name: str, - solution_request_body: Optional[IO[bytes]] = None, + solution_request_body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -190,14 +244,12 @@ async def begin_create( troubleshooting instructions. :code:`
` All these components are seamlessly converged into unified solutions tailored to address a specific support problem area. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param solution_resource_name: Solution resource Name. Required. :type solution_resource_name: str :param solution_request_body: The required request body for this solution resource creation. - Default value is None. + Required. :type solution_request_body: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". @@ -213,7 +265,7 @@ async def begin_create( self, scope: str, solution_resource_name: str, - solution_request_body: Optional[Union[_models.SolutionResource, IO[bytes]]] = None, + solution_request_body: Union[_models.SolutionResource, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.SolutionResource]: """Creates a solution for the specific Azure resource or subscription using the inputs ‘solutionId @@ -226,14 +278,12 @@ async def begin_create( troubleshooting instructions. :code:`
` All these components are seamlessly converged into unified solutions tailored to address a specific support problem area. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param solution_resource_name: Solution resource Name. Required. :type solution_resource_name: str :param solution_request_body: The required request body for this solution resource creation. Is - either a SolutionResource type or a IO[bytes] type. Default value is None. + either a SolutionResource type or a IO[bytes] type. Required. :type solution_request_body: ~azure.mgmt.selfhelp.models.SolutionResource or IO[bytes] :return: An instance of AsyncLROPoller that returns either SolutionResource or the result of cls(response) @@ -261,10 +311,11 @@ async def begin_create( 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("SolutionResource", pipeline_response) + deserialized = self._deserialize("SolutionResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized @@ -289,71 +340,14 @@ def get_long_running_output(pipeline_response): self._client, raw_result, get_long_running_output, polling_method # type: ignore ) - @distributed_trace_async - async def get(self, scope: str, solution_resource_name: str, **kwargs: Any) -> _models.SolutionResource: - """Get the solution using the applicable solutionResourceName while creating the solution. - - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. - :type scope: str - :param solution_resource_name: Solution resource Name. Required. - :type solution_resource_name: str - :return: SolutionResource or the result of cls(response) - :rtype: ~azure.mgmt.selfhelp.models.SolutionResource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SolutionResource] = kwargs.pop("cls", None) - - _request = build_get_request( - scope=scope, - solution_resource_name=solution_resource_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request = _convert_request(_request) - _request.url = self._client.format_url(_request.url) - - _stream = False - 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]: - 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 = self._deserialize("SolutionResource", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - async def _update_initial( self, scope: str, solution_resource_name: str, - solution_patch_request_body: Optional[Union[_models.SolutionPatchRequestBody, IO[bytes]]] = None, + solution_patch_request_body: Union[_models.SolutionPatchRequestBody, IO[bytes]], **kwargs: Any - ) -> _models.SolutionResource: - error_map: MutableMapping[int, Type[HttpResponseError]] = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -366,7 +360,7 @@ async def _update_initial( 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.SolutionResource] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None @@ -374,10 +368,7 @@ async def _update_initial( if isinstance(solution_patch_request_body, (IOBase, bytes)): _content = solution_patch_request_body else: - if solution_patch_request_body is not None: - _json = self._serialize.body(solution_patch_request_body, "SolutionPatchRequestBody") - else: - _json = None + _json = self._serialize.body(solution_patch_request_body, "SolutionPatchRequestBody") _request = build_update_request( scope=scope, @@ -389,10 +380,10 @@ async def _update_initial( headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -400,20 +391,21 @@ async def _update_initial( 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: - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - - deserialized = self._deserialize("SolutionResource", 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("SolutionResource", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -425,21 +417,19 @@ async def begin_update( self, scope: str, solution_resource_name: str, - solution_patch_request_body: Optional[_models.SolutionPatchRequestBody] = None, + solution_patch_request_body: _models.SolutionPatchRequestBody, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.SolutionResource]: """Update the requiredInputs or additional information needed to execute the solution. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param solution_resource_name: Solution resource Name. Required. :type solution_resource_name: str :param solution_patch_request_body: The required request body for updating a solution resource. - Default value is None. + Required. :type solution_patch_request_body: ~azure.mgmt.selfhelp.models.SolutionPatchRequestBody :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". @@ -455,21 +445,19 @@ async def begin_update( self, scope: str, solution_resource_name: str, - solution_patch_request_body: Optional[IO[bytes]] = None, + solution_patch_request_body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.SolutionResource]: """Update the requiredInputs or additional information needed to execute the solution. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param solution_resource_name: Solution resource Name. Required. :type solution_resource_name: str :param solution_patch_request_body: The required request body for updating a solution resource. - Default value is None. + Required. :type solution_patch_request_body: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". @@ -485,19 +473,17 @@ async def begin_update( self, scope: str, solution_resource_name: str, - solution_patch_request_body: Optional[Union[_models.SolutionPatchRequestBody, IO[bytes]]] = None, + solution_patch_request_body: Union[_models.SolutionPatchRequestBody, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.SolutionResource]: """Update the requiredInputs or additional information needed to execute the solution. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param solution_resource_name: Solution resource Name. Required. :type solution_resource_name: str :param solution_patch_request_body: The required request body for updating a solution resource. - Is either a SolutionPatchRequestBody type or a IO[bytes] type. Default value is None. + Is either a SolutionPatchRequestBody type or a IO[bytes] type. Required. :type solution_patch_request_body: ~azure.mgmt.selfhelp.models.SolutionPatchRequestBody or IO[bytes] :return: An instance of AsyncLROPoller that returns either SolutionResource or the result of @@ -526,16 +512,13 @@ async def begin_update( params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response_headers = {} - response = pipeline_response.http_response - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - - deserialized = self._deserialize("SolutionResource", pipeline_response) + deserialized = self._deserialize("SolutionResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -559,7 +542,7 @@ def get_long_running_output(pipeline_response): ) @overload - async def warm_up( # pylint: disable=inconsistent-return-statements + async def warm_up( self, scope: str, solution_resource_name: str, @@ -570,9 +553,7 @@ async def warm_up( # pylint: disable=inconsistent-return-statements ) -> None: """Warm up the solution resource by preloading asynchronous diagnostics results into cache. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param solution_resource_name: Solution resource Name. Required. :type solution_resource_name: str @@ -588,7 +569,7 @@ async def warm_up( # pylint: disable=inconsistent-return-statements """ @overload - async def warm_up( # pylint: disable=inconsistent-return-statements + async def warm_up( self, scope: str, solution_resource_name: str, @@ -599,9 +580,7 @@ async def warm_up( # pylint: disable=inconsistent-return-statements ) -> None: """Warm up the solution resource by preloading asynchronous diagnostics results into cache. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param solution_resource_name: Solution resource Name. Required. :type solution_resource_name: str @@ -617,7 +596,7 @@ async def warm_up( # pylint: disable=inconsistent-return-statements """ @distributed_trace_async - async def warm_up( # pylint: disable=inconsistent-return-statements + async def warm_up( self, scope: str, solution_resource_name: str, @@ -626,9 +605,7 @@ async def warm_up( # pylint: disable=inconsistent-return-statements ) -> None: """Warm up the solution resource by preloading asynchronous diagnostics results into cache. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param solution_resource_name: Solution resource Name. Required. :type solution_resource_name: str @@ -641,7 +618,7 @@ async def warm_up( # pylint: disable=inconsistent-return-statements :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -677,7 +654,6 @@ async def warm_up( # pylint: disable=inconsistent-return-statements headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) _stream = False diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_solution_self_help_operations.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_solution_self_help_operations.py index e245913c50a5..ba53025ac19b 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_solution_self_help_operations.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_solution_self_help_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines,too-many-statements +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,9 +6,10 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Optional, Type, TypeVar +from collections.abc import MutableMapping +from typing import Any, Callable, Dict, Optional, TypeVar +from azure.core import AsyncPipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -18,20 +19,16 @@ 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 ..._utils.serialization import Deserializer, Serializer from ...operations._solution_self_help_operations import build_get_request +from .._configuration import SelfHelpMgmtClientConfiguration -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -50,10 +47,10 @@ class SolutionSelfHelpOperations: def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SelfHelpMgmtClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace_async async def get(self, solution_id: str, **kwargs: Any) -> _models.SolutionResourceSelfHelp: @@ -70,7 +67,7 @@ async def get(self, solution_id: str, **kwargs: Any) -> _models.SolutionResource :rtype: ~azure.mgmt.selfhelp.models.SolutionResourceSelfHelp :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -90,7 +87,6 @@ async def get(self, solution_id: str, **kwargs: Any) -> _models.SolutionResource headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) _stream = False @@ -105,7 +101,7 @@ async def get(self, solution_id: str, **kwargs: Any) -> _models.SolutionResource error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("SolutionResourceSelfHelp", pipeline_response) + deserialized = self._deserialize("SolutionResourceSelfHelp", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_troubleshooters_operations.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_troubleshooters_operations.py index 70ce2b40d6f1..50fad786b3ec 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_troubleshooters_operations.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/aio/operations/_troubleshooters_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +5,11 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from collections.abc import MutableMapping from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Optional, Type, TypeVar, Union, overload +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload +from azure.core import AsyncPipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -19,14 +19,13 @@ 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 ..._utils.serialization import Deserializer, Serializer from ...operations._troubleshooters_operations import ( build_continue_method_request, build_create_request, @@ -34,11 +33,8 @@ build_get_request, build_restart_request, ) +from .._configuration import SelfHelpMgmtClientConfiguration -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -57,17 +53,75 @@ class TroubleshootersOperations: def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SelfHelpMgmtClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get(self, scope: str, troubleshooter_name: str, **kwargs: Any) -> _models.TroubleshooterResource: + """Gets troubleshooter instance result which includes the step status/result of the troubleshooter + resource name that is being executed.\\ :code:`
` Get API is used to retrieve the result of + a Troubleshooter instance, which includes the status and result of each step in the + Troubleshooter workflow. This API requires the Troubleshooter resource name that was created + using the Create API. + + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. + :type scope: str + :param troubleshooter_name: Troubleshooter resource Name. Required. + :type troubleshooter_name: str + :return: TroubleshooterResource or the result of cls(response) + :rtype: ~azure.mgmt.selfhelp.models.TroubleshooterResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.TroubleshooterResource] = kwargs.pop("cls", None) + + _request = build_get_request( + scope=scope, + troubleshooter_name=troubleshooter_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + 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]: + 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 = self._deserialize("TroubleshooterResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore @overload async def create( self, scope: str, troubleshooter_name: str, - create_troubleshooter_request_body: Optional[_models.TroubleshooterResource] = None, + create_troubleshooter_request_body: _models.TroubleshooterResource, *, content_type: str = "application/json", **kwargs: Any @@ -82,14 +136,12 @@ async def create( requests raised by customers. Troubleshooters terminate at a well curated solution based off of resource backend signals and customer manual selections. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param troubleshooter_name: Troubleshooter resource Name. Required. :type troubleshooter_name: str :param create_troubleshooter_request_body: The required request body for this Troubleshooter - resource creation. Default value is None. + resource creation. Required. :type create_troubleshooter_request_body: ~azure.mgmt.selfhelp.models.TroubleshooterResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". @@ -104,7 +156,7 @@ async def create( self, scope: str, troubleshooter_name: str, - create_troubleshooter_request_body: Optional[IO[bytes]] = None, + create_troubleshooter_request_body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -119,14 +171,12 @@ async def create( requests raised by customers. Troubleshooters terminate at a well curated solution based off of resource backend signals and customer manual selections. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param troubleshooter_name: Troubleshooter resource Name. Required. :type troubleshooter_name: str :param create_troubleshooter_request_body: The required request body for this Troubleshooter - resource creation. Default value is None. + resource creation. Required. :type create_troubleshooter_request_body: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". @@ -141,7 +191,7 @@ async def create( self, scope: str, troubleshooter_name: str, - create_troubleshooter_request_body: Optional[Union[_models.TroubleshooterResource, IO[bytes]]] = None, + create_troubleshooter_request_body: Union[_models.TroubleshooterResource, IO[bytes]], **kwargs: Any ) -> _models.TroubleshooterResource: """Creates the specific troubleshooter action under a resource or subscription using the @@ -154,22 +204,19 @@ async def create( requests raised by customers. Troubleshooters terminate at a well curated solution based off of resource backend signals and customer manual selections. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param troubleshooter_name: Troubleshooter resource Name. Required. :type troubleshooter_name: str :param create_troubleshooter_request_body: The required request body for this Troubleshooter - resource creation. Is either a TroubleshooterResource type or a IO[bytes] type. Default value - is None. + resource creation. Is either a TroubleshooterResource type or a IO[bytes] type. Required. :type create_troubleshooter_request_body: ~azure.mgmt.selfhelp.models.TroubleshooterResource or IO[bytes] :return: TroubleshooterResource or the result of cls(response) :rtype: ~azure.mgmt.selfhelp.models.TroubleshooterResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -190,10 +237,7 @@ async def create( if isinstance(create_troubleshooter_request_body, (IOBase, bytes)): _content = create_troubleshooter_request_body else: - if create_troubleshooter_request_body is not None: - _json = self._serialize.body(create_troubleshooter_request_body, "TroubleshooterResource") - else: - _json = None + _json = self._serialize.body(create_troubleshooter_request_body, "TroubleshooterResource") _request = build_create_request( scope=scope, @@ -205,7 +249,6 @@ async def create( headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) _stream = False @@ -220,72 +263,7 @@ async def create( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("TroubleshooterResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("TroubleshooterResource", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get(self, scope: str, troubleshooter_name: str, **kwargs: Any) -> _models.TroubleshooterResource: - """Gets troubleshooter instance result which includes the step status/result of the troubleshooter - resource name that is being executed.:code:`
` Get API is used to retrieve the result of a - Troubleshooter instance, which includes the status and result of each step in the - Troubleshooter workflow. This API requires the Troubleshooter resource name that was created - using the Create API. - - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. - :type scope: str - :param troubleshooter_name: Troubleshooter resource Name. Required. - :type troubleshooter_name: str - :return: TroubleshooterResource or the result of cls(response) - :rtype: ~azure.mgmt.selfhelp.models.TroubleshooterResource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.TroubleshooterResource] = kwargs.pop("cls", None) - - _request = build_get_request( - scope=scope, - troubleshooter_name=troubleshooter_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request = _convert_request(_request) - _request.url = self._client.format_url(_request.url) - - _stream = False - 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]: - 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 = self._deserialize("TroubleshooterResource", pipeline_response) + deserialized = self._deserialize("TroubleshooterResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -293,7 +271,7 @@ async def get(self, scope: str, troubleshooter_name: str, **kwargs: Any) -> _mod return deserialized # type: ignore @overload - async def continue_method( # pylint: disable=inconsistent-return-statements + async def continue_method( self, scope: str, troubleshooter_name: str, @@ -307,9 +285,7 @@ async def continue_method( # pylint: disable=inconsistent-return-statements that are required for the specific troubleshooter to progress into the next step in the process. This API is used after the Troubleshooter has been created using the Create API. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param troubleshooter_name: Troubleshooter resource Name. Required. :type troubleshooter_name: str @@ -325,7 +301,7 @@ async def continue_method( # pylint: disable=inconsistent-return-statements """ @overload - async def continue_method( # pylint: disable=inconsistent-return-statements + async def continue_method( self, scope: str, troubleshooter_name: str, @@ -339,9 +315,7 @@ async def continue_method( # pylint: disable=inconsistent-return-statements that are required for the specific troubleshooter to progress into the next step in the process. This API is used after the Troubleshooter has been created using the Create API. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param troubleshooter_name: Troubleshooter resource Name. Required. :type troubleshooter_name: str @@ -357,7 +331,7 @@ async def continue_method( # pylint: disable=inconsistent-return-statements """ @distributed_trace_async - async def continue_method( # pylint: disable=inconsistent-return-statements + async def continue_method( self, scope: str, troubleshooter_name: str, @@ -369,9 +343,7 @@ async def continue_method( # pylint: disable=inconsistent-return-statements that are required for the specific troubleshooter to progress into the next step in the process. This API is used after the Troubleshooter has been created using the Create API. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param troubleshooter_name: Troubleshooter resource Name. Required. :type troubleshooter_name: str @@ -383,7 +355,7 @@ async def continue_method( # pylint: disable=inconsistent-return-statements :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -419,7 +391,6 @@ async def continue_method( # pylint: disable=inconsistent-return-statements headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) _stream = False @@ -434,21 +405,14 @@ async def continue_method( # pylint: disable=inconsistent-return-statements error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def end( # pylint: disable=inconsistent-return-statements - self, scope: str, troubleshooter_name: str, **kwargs: Any - ) -> None: + async def end(self, scope: str, troubleshooter_name: str, **kwargs: Any) -> None: """Ends the troubleshooter action. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param troubleshooter_name: Troubleshooter resource Name. Required. :type troubleshooter_name: str @@ -456,7 +420,7 @@ async def end( # pylint: disable=inconsistent-return-statements :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -477,7 +441,6 @@ async def end( # pylint: disable=inconsistent-return-statements headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) _stream = False @@ -492,23 +455,18 @@ async def end( # pylint: disable=inconsistent-return-statements error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async async def restart( self, scope: str, troubleshooter_name: str, **kwargs: Any ) -> _models.RestartTroubleshooterResponse: - """Restarts the troubleshooter API using applicable troubleshooter resource name as the - input.:code:`
` It returns new resource name which should be used in subsequent request. - The old resource name is obsolete after this API is invoked. + """Restarts the troubleshooter API using applicable troubleshooter resource name as the input.\\ + :code:`
` It returns new resource name which should be used in subsequent request. The old + resource name is obsolete after this API is invoked. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param troubleshooter_name: Troubleshooter resource Name. Required. :type troubleshooter_name: str @@ -516,7 +474,7 @@ async def restart( :rtype: ~azure.mgmt.selfhelp.models.RestartTroubleshooterResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -537,7 +495,6 @@ async def restart( headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) _stream = False @@ -552,12 +509,9 @@ async def restart( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - - deserialized = self._deserialize("RestartTroubleshooterResponse", pipeline_response) + deserialized = self._deserialize("RestartTroubleshooterResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/models/__init__.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/models/__init__.py index dd39ac7dacb1..0440668f2f9c 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/models/__init__.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/models/__init__.py @@ -5,81 +5,92 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._models_py3 import AutomatedCheckResult -from ._models_py3 import CheckNameAvailabilityRequest -from ._models_py3 import CheckNameAvailabilityResponse -from ._models_py3 import ClassificationService -from ._models_py3 import ContinueRequestBody -from ._models_py3 import Diagnostic -from ._models_py3 import DiagnosticInvocation -from ._models_py3 import DiagnosticResource -from ._models_py3 import DiscoveryNlpRequest -from ._models_py3 import DiscoveryNlpResponse -from ._models_py3 import DiscoveryResponse -from ._models_py3 import Error -from ._models_py3 import ErrorAdditionalInfo -from ._models_py3 import ErrorDetail -from ._models_py3 import ErrorResponse -from ._models_py3 import Filter -from ._models_py3 import FilterGroup -from ._models_py3 import Insight -from ._models_py3 import MetricsBasedChart -from ._models_py3 import Operation -from ._models_py3 import OperationDisplay -from ._models_py3 import OperationListResult -from ._models_py3 import ProxyResource -from ._models_py3 import ReplacementMaps -from ._models_py3 import ReplacementMapsSelfHelp -from ._models_py3 import Resource -from ._models_py3 import ResponseOption -from ._models_py3 import ResponseValidationProperties -from ._models_py3 import RestartTroubleshooterResponse -from ._models_py3 import SearchResult -from ._models_py3 import Section -from ._models_py3 import SectionSelfHelp -from ._models_py3 import SimplifiedSolutionsResource -from ._models_py3 import SolutionMetadataProperties -from ._models_py3 import SolutionMetadataResource -from ._models_py3 import SolutionNlpMetadataResource -from ._models_py3 import SolutionPatchRequestBody -from ._models_py3 import SolutionResource -from ._models_py3 import SolutionResourceSelfHelp -from ._models_py3 import SolutionWarmUpRequestBody -from ._models_py3 import SolutionsDiagnostic -from ._models_py3 import SolutionsTroubleshooters -from ._models_py3 import Step -from ._models_py3 import StepInput -from ._models_py3 import SystemData -from ._models_py3 import TriggerCriterion -from ._models_py3 import TroubleshooterResource -from ._models_py3 import TroubleshooterResponse -from ._models_py3 import Video -from ._models_py3 import VideoGroup -from ._models_py3 import VideoGroupVideo -from ._models_py3 import WebResult +from typing import TYPE_CHECKING -from ._self_help_mgmt_client_enums import ActionType -from ._self_help_mgmt_client_enums import AggregationType -from ._self_help_mgmt_client_enums import AutomatedCheckResultType -from ._self_help_mgmt_client_enums import Confidence -from ._self_help_mgmt_client_enums import CreatedByType -from ._self_help_mgmt_client_enums import DiagnosticProvisioningState -from ._self_help_mgmt_client_enums import ExecutionStatus -from ._self_help_mgmt_client_enums import ImportanceLevel -from ._self_help_mgmt_client_enums import Name -from ._self_help_mgmt_client_enums import Origin -from ._self_help_mgmt_client_enums import QuestionContentType -from ._self_help_mgmt_client_enums import QuestionType -from ._self_help_mgmt_client_enums import ResultType -from ._self_help_mgmt_client_enums import SolutionProvisioningState -from ._self_help_mgmt_client_enums import SolutionType -from ._self_help_mgmt_client_enums import Status -from ._self_help_mgmt_client_enums import TroubleshooterProvisioningState -from ._self_help_mgmt_client_enums import Type -from ._self_help_mgmt_client_enums import ValidationScope +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + AutomatedCheckResult, + CheckNameAvailabilityRequest, + CheckNameAvailabilityResponse, + ClassificationService, + ContinueRequestBody, + Diagnostic, + DiagnosticInvocation, + DiagnosticResource, + DiscoveryNlpRequest, + DiscoveryNlpResponse, + DiscoveryResponse, + Error, + ErrorAdditionalInfo, + ErrorDetail, + ErrorResponse, + Filter, + FilterGroup, + Insight, + MetricsBasedChart, + Operation, + OperationDisplay, + OperationListResult, + ProxyResource, + ReplacementMaps, + ReplacementMapsSelfHelp, + Resource, + ResponseOption, + ResponseValidationProperties, + RestartTroubleshooterResponse, + SearchResult, + Section, + SectionSelfHelp, + SimplifiedSolutionsResource, + SolutionMetadataProperties, + SolutionMetadataResource, + SolutionNlpMetadataResource, + SolutionPatchRequestBody, + SolutionResource, + SolutionResourceSelfHelp, + SolutionWarmUpRequestBody, + SolutionsDiagnostic, + SolutionsTroubleshooters, + Step, + StepInput, + SystemData, + TriggerCriterion, + TroubleshooterResource, + TroubleshooterResponse, + Video, + VideoGroup, + VideoGroupVideo, + WebResult, +) + +from ._self_help_mgmt_client_enums import ( # type: ignore + ActionType, + AggregationType, + AutomatedCheckResultType, + Confidence, + CreatedByType, + DiagnosticProvisioningState, + ExecutionStatus, + ImportanceLevel, + Name, + Origin, + QuestionContentType, + QuestionType, + ResultType, + SolutionProvisioningState, + SolutionType, + Status, + TroubleshooterProvisioningState, + Type, + ValidationScope, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -155,5 +166,5 @@ "Type", "ValidationScope", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/models/_models_py3.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/models/_models_py3.py index 63157dd2720f..3879fbbdf75a 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/models/_models_py3.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/models/_models_py3.py @@ -1,5 +1,5 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 -# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. @@ -10,10 +10,9 @@ import datetime from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union -from .. import _serialization +from .._utils import serialization as _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models @@ -163,8 +162,8 @@ def __init__(self, *, resource_types: Optional[List[str]] = None, **kwargs: Any) :paramtype resource_types: list[str] """ super().__init__(**kwargs) - self.service_id = None - self.display_name = None + self.service_id: Optional[str] = None + self.display_name: Optional[str] = None self.resource_types = resource_types @@ -286,7 +285,7 @@ class Resource(_serialization.Model): Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource ID for the resource. E.g. - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -315,10 +314,10 @@ class Resource(_serialization.Model): def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.system_data = None + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + self.system_data: Optional["_models.SystemData"] = None class ProxyResource(Resource): @@ -328,7 +327,7 @@ class ProxyResource(Resource): Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource ID for the resource. E.g. - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -347,7 +346,7 @@ class DiagnosticResource(ProxyResource): Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource ID for the resource. E.g. - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -410,9 +409,9 @@ def __init__( super().__init__(**kwargs) self.global_parameters = global_parameters self.insights = insights - self.accepted_at = None - self.provisioning_state = None - self.diagnostics = None + self.accepted_at: Optional[str] = None + self.provisioning_state: Optional[Union[str, "_models.DiagnosticProvisioningState"]] = None + self.diagnostics: Optional[List["_models.Diagnostic"]] = None class DiscoveryNlpRequest(_serialization.Model): @@ -495,28 +494,30 @@ def __init__(self, *, value: Optional[List["_models.SolutionNlpMetadataResource" class DiscoveryResponse(_serialization.Model): """Discovery response. - :ivar value: The list of metadata. + All required parameters must be populated in order to send to server. + + :ivar value: The SolutionMetadataResource items on this page. Required. :vartype value: list[~azure.mgmt.selfhelp.models.SolutionMetadataResource] - :ivar next_link: The link used to get the next page of solution metadata. + :ivar next_link: The link to the next page of items. :vartype next_link: str """ + _validation = { + "value": {"required": True}, + } + _attribute_map = { "value": {"key": "value", "type": "[SolutionMetadataResource]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["_models.SolutionMetadataResource"]] = None, - next_link: Optional[str] = None, - **kwargs: Any + self, *, value: List["_models.SolutionMetadataResource"], next_link: Optional[str] = None, **kwargs: Any ) -> None: """ - :keyword value: The list of metadata. + :keyword value: The SolutionMetadataResource items on this page. Required. :paramtype value: list[~azure.mgmt.selfhelp.models.SolutionMetadataResource] - :keyword next_link: The link used to get the next page of solution metadata. + :keyword next_link: The link to the next page of items. :paramtype next_link: str """ super().__init__(**kwargs) @@ -561,9 +562,9 @@ def __init__(self, *, details: Optional[List["_models.Error"]] = None, **kwargs: :paramtype details: list[~azure.mgmt.selfhelp.models.Error] """ super().__init__(**kwargs) - self.code = None - self.type = None - self.message = None + self.code: Optional[str] = None + self.type: Optional[str] = None + self.message: Optional[str] = None self.details = details @@ -591,8 +592,8 @@ class ErrorAdditionalInfo(_serialization.Model): def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.type = None - self.info = None + self.type: Optional[str] = None + self.info: Optional[JSON] = None class ErrorDetail(_serialization.Model): @@ -631,11 +632,11 @@ class ErrorDetail(_serialization.Model): def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.code = None - self.message = None - self.target = None - self.details = None - self.additional_info = None + self.code: Optional[str] = None + self.message: Optional[str] = None + self.target: Optional[str] = None + self.details: Optional[List["_models.ErrorDetail"]] = None + self.additional_info: Optional[List["_models.ErrorAdditionalInfo"]] = None class ErrorResponse(_serialization.Model): @@ -868,11 +869,11 @@ def __init__(self, *, display: Optional["_models.OperationDisplay"] = None, **kw :paramtype display: ~azure.mgmt.selfhelp.models.OperationDisplay """ super().__init__(**kwargs) - self.name = None - self.is_data_action = None + self.name: Optional[str] = None + self.is_data_action: Optional[bool] = None self.display = display - self.origin = None - self.action_type = None + self.origin: Optional[Union[str, "_models.Origin"]] = None + self.action_type: Optional[Union[str, "_models.ActionType"]] = None class OperationDisplay(_serialization.Model): @@ -911,10 +912,10 @@ class OperationDisplay(_serialization.Model): def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.provider = None - self.resource = None - self.operation = None - self.description = None + self.provider: Optional[str] = None + self.resource: Optional[str] = None + self.operation: Optional[str] = None + self.description: Optional[str] = None class OperationListResult(_serialization.Model): @@ -942,8 +943,8 @@ class OperationListResult(_serialization.Model): def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.value = None - self.next_link = None + self.value: Optional[List["_models.Operation"]] = None + self.next_link: Optional[str] = None class ReplacementMaps(_serialization.Model): @@ -1150,7 +1151,7 @@ class RestartTroubleshooterResponse(_serialization.Model): def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.troubleshooter_resource_name = None + self.troubleshooter_resource_name: Optional[str] = None class SearchResult(_serialization.Model): @@ -1315,7 +1316,7 @@ class SimplifiedSolutionsResource(ProxyResource): Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource ID for the resource. E.g. - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -1376,10 +1377,10 @@ def __init__( super().__init__(**kwargs) self.solution_id = solution_id self.parameters = parameters - self.title = None - self.appendix = None - self.content = None - self.provisioning_state = None + self.title: Optional[str] = None + self.appendix: Optional[Dict[str, str]] = None + self.content: Optional[str] = None + self.provisioning_state: Optional[Union[str, "_models.SolutionProvisioningState"]] = None class SolutionMetadataProperties(_serialization.Model): @@ -1418,9 +1419,9 @@ def __init__(self, *, solution_id: Optional[str] = None, **kwargs: Any) -> None: """ super().__init__(**kwargs) self.solution_id = solution_id - self.solution_type = None - self.description = None - self.required_inputs = None + self.solution_type: Optional[Union[str, "_models.SolutionType"]] = None + self.description: Optional[str] = None + self.required_inputs: Optional[List[str]] = None class SolutionMetadataResource(ProxyResource): @@ -1429,7 +1430,7 @@ class SolutionMetadataResource(ProxyResource): Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource ID for the resource. E.g. - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -1475,7 +1476,7 @@ class SolutionNlpMetadataResource(ProxyResource): Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource ID for the resource. E.g. - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -1625,21 +1626,21 @@ def __init__( super().__init__(**kwargs) self.trigger_criteria = trigger_criteria self.parameters = parameters - self.solution_id = None - self.provisioning_state = None - self.title = None - self.content = None - self.replacement_maps = None - self.sections = None + self.solution_id: Optional[str] = None + self.provisioning_state: Optional[Union[str, "_models.SolutionProvisioningState"]] = None + self.title: Optional[str] = None + self.content: Optional[str] = None + self.replacement_maps: Optional["_models.ReplacementMaps"] = None + self.sections: Optional[List["_models.Section"]] = None -class SolutionResource(ProxyResource): # pylint: disable=too-many-instance-attributes +class SolutionResource(ProxyResource): """Solution response. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource ID for the resource. E.g. - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -1712,12 +1713,12 @@ def __init__( super().__init__(**kwargs) self.trigger_criteria = trigger_criteria self.parameters = parameters - self.solution_id = None - self.provisioning_state = None - self.title = None - self.content = None - self.replacement_maps = None - self.sections = None + self.solution_id: Optional[str] = None + self.provisioning_state: Optional[Union[str, "_models.SolutionProvisioningState"]] = None + self.title: Optional[str] = None + self.content: Optional[str] = None + self.replacement_maps: Optional["_models.ReplacementMaps"] = None + self.sections: Optional[List["_models.Section"]] = None class SolutionResourceSelfHelp(ProxyResource): @@ -1726,7 +1727,7 @@ class SolutionResourceSelfHelp(ProxyResource): Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource ID for the resource. E.g. - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -1738,7 +1739,7 @@ class SolutionResourceSelfHelp(ProxyResource): :vartype system_data: ~azure.mgmt.selfhelp.models.SystemData :ivar solution_id: SolutionId is a unique id to identify a solution. You can retrieve the solution id using the Discovery api - - https://learn.microsoft.com/en-us/rest/api/help/discovery-solution/list?view=rest-help-2023-09-01-preview&tabs=HTTP. # pylint: disable=line-too-long + https://learn.microsoft.com/en-us/rest/api/help/discovery-solution/list?view=rest-help-2023-09-01-preview&tabs=HTTP. :vartype solution_id: str :ivar title: The title. :vartype title: str @@ -1777,11 +1778,11 @@ class SolutionResourceSelfHelp(ProxyResource): def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.solution_id = None - self.title = None - self.content = None - self.replacement_maps = None - self.sections = None + self.solution_id: Optional[str] = None + self.title: Optional[str] = None + self.content: Optional[str] = None + self.replacement_maps: Optional["_models.ReplacementMapsSelfHelp"] = None + self.sections: Optional[List["_models.SectionSelfHelp"]] = None class SolutionsDiagnostic(_serialization.Model): @@ -1912,7 +1913,7 @@ def __init__(self, *, parameters: Optional[Dict[str, str]] = None, **kwargs: Any self.parameters = parameters -class Step(_serialization.Model): # pylint: disable=too-many-instance-attributes +class Step(_serialization.Model): """Troubleshooter step. :ivar id: Unique step id. @@ -2219,7 +2220,7 @@ class TroubleshooterResource(ProxyResource): Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource ID for the resource. E.g. - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -2272,8 +2273,8 @@ def __init__( super().__init__(**kwargs) self.solution_id = solution_id self.parameters = parameters - self.provisioning_state = None - self.steps = None + self.provisioning_state: Optional[Union[str, "_models.TroubleshooterProvisioningState"]] = None + self.steps: Optional[List["_models.Step"]] = None class TroubleshooterResponse(_serialization.Model): diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/__init__.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/__init__.py index 8769d976fa3d..add80b5e618b 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/__init__.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/__init__.py @@ -5,31 +5,37 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._operations import Operations -from ._check_name_availability_operations import CheckNameAvailabilityOperations -from ._diagnostics_operations import DiagnosticsOperations -from ._discovery_solution_operations import DiscoverySolutionOperations -from ._solution_operations import SolutionOperations -from ._simplified_solutions_operations import SimplifiedSolutionsOperations -from ._troubleshooters_operations import TroubleshootersOperations -from ._solution_self_help_operations import SolutionSelfHelpOperations -from ._discovery_solution_nlp_operations import DiscoverySolutionNLPOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._check_name_availability_operations import CheckNameAvailabilityOperations # type: ignore +from ._diagnostics_operations import DiagnosticsOperations # type: ignore +from ._simplified_solutions_operations import SimplifiedSolutionsOperations # type: ignore +from ._solution_operations import SolutionOperations # type: ignore +from ._troubleshooters_operations import TroubleshootersOperations # type: ignore +from ._discovery_solution_nlp_operations import DiscoverySolutionNLPOperations # type: ignore +from ._discovery_solution_operations import DiscoverySolutionOperations # type: ignore +from ._operations import Operations # type: ignore +from ._solution_self_help_operations import SolutionSelfHelpOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ - "Operations", "CheckNameAvailabilityOperations", "DiagnosticsOperations", - "DiscoverySolutionOperations", - "SolutionOperations", "SimplifiedSolutionsOperations", + "SolutionOperations", "TroubleshootersOperations", - "SolutionSelfHelpOperations", "DiscoverySolutionNLPOperations", + "DiscoverySolutionOperations", + "Operations", + "SolutionSelfHelpOperations", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_check_name_availability_operations.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_check_name_availability_operations.py index 6ec976514f77..7508a8160816 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_check_name_availability_operations.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_check_name_availability_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +5,11 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from collections.abc import MutableMapping from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Optional, Type, TypeVar, Union, overload +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -19,20 +19,15 @@ 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 _convert_request +from .._configuration import SelfHelpMgmtClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -81,10 +76,10 @@ class CheckNameAvailabilityOperations: def __init__(self, *args, **kwargs): input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SelfHelpMgmtClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @overload def check_availability( @@ -98,9 +93,7 @@ def check_availability( """This API is used to check the uniqueness of a resource name used for a diagnostic, troubleshooter or solutions. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param check_name_availability_request: The required parameters for availability check. Default value is None. @@ -125,9 +118,7 @@ def check_availability( """This API is used to check the uniqueness of a resource name used for a diagnostic, troubleshooter or solutions. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param check_name_availability_request: The required parameters for availability check. Default value is None. @@ -150,9 +141,7 @@ def check_availability( """This API is used to check the uniqueness of a resource name used for a diagnostic, troubleshooter or solutions. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param check_name_availability_request: The required parameters for availability check. Is either a CheckNameAvailabilityRequest type or a IO[bytes] type. Default value is None. @@ -162,7 +151,7 @@ def check_availability( :rtype: ~azure.mgmt.selfhelp.models.CheckNameAvailabilityResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -197,7 +186,6 @@ def check_availability( headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) _stream = False @@ -212,7 +200,7 @@ def check_availability( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("CheckNameAvailabilityResponse", pipeline_response) + deserialized = self._deserialize("CheckNameAvailabilityResponse", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_diagnostics_operations.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_diagnostics_operations.py index 505b19fbbfff..3e670fe5c1d5 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_diagnostics_operations.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_diagnostics_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,35 +5,33 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from collections.abc import MutableMapping from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload +from typing import Any, Callable, Dict, IO, Iterator, Optional, TypeVar, Union, cast, overload +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) 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 from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request +from .._configuration import SelfHelpMgmtClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -42,12 +39,11 @@ _SERIALIZER.client_side_validation = False -def build_create_request(scope: str, diagnostics_resource_name: str, **kwargs: Any) -> HttpRequest: +def build_get_request(scope: str, diagnostics_resource_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -70,18 +66,17 @@ def build_create_request(scope: str, diagnostics_resource_name: str, **kwargs: A _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_get_request(scope: str, diagnostics_resource_name: str, **kwargs: Any) -> HttpRequest: +def build_create_request(scope: str, diagnostics_resource_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -104,9 +99,11 @@ def build_get_request(scope: str, diagnostics_resource_name: str, **kwargs: Any) _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) class DiagnosticsOperations: @@ -123,19 +120,74 @@ class DiagnosticsOperations: def __init__(self, *args, **kwargs): input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SelfHelpMgmtClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, scope: str, diagnostics_resource_name: str, **kwargs: Any) -> _models.DiagnosticResource: + """Get the diagnostics using the 'diagnosticsResourceName' you chose while creating the + diagnostic. + + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. + :type scope: str + :param diagnostics_resource_name: Unique resource name for insight resources. Required. + :type diagnostics_resource_name: str + :return: DiagnosticResource or the result of cls(response) + :rtype: ~azure.mgmt.selfhelp.models.DiagnosticResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.DiagnosticResource] = kwargs.pop("cls", None) + + _request = build_get_request( + scope=scope, + diagnostics_resource_name=diagnostics_resource_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + 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]: + 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 = self._deserialize("DiagnosticResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore def _create_initial( self, scope: str, diagnostics_resource_name: str, - diagnostic_resource_request: Optional[Union[_models.DiagnosticResource, IO[bytes]]] = None, + diagnostic_resource_request: Union[_models.DiagnosticResource, IO[bytes]], **kwargs: Any - ) -> _models.DiagnosticResource: - error_map: MutableMapping[int, Type[HttpResponseError]] = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -148,7 +200,7 @@ def _create_initial( 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.DiagnosticResource] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None @@ -156,10 +208,7 @@ def _create_initial( if isinstance(diagnostic_resource_request, (IOBase, bytes)): _content = diagnostic_resource_request else: - if diagnostic_resource_request is not None: - _json = self._serialize.body(diagnostic_resource_request, "DiagnosticResource") - else: - _json = None + _json = self._serialize.body(diagnostic_resource_request, "DiagnosticResource") _request = build_create_request( scope=scope, @@ -171,10 +220,10 @@ def _create_initial( headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -182,18 +231,25 @@ def _create_initial( response = pipeline_response.http_response if response.status_code not in [200, 201]: + 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) - if response.status_code == 200: - deserialized = self._deserialize("DiagnosticResource", pipeline_response) - + response_headers = {} if response.status_code == 201: - deserialized = self._deserialize("DiagnosticResource", pipeline_response) + response_headers["Azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-AsyncOperation") + ) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized # type: ignore @@ -202,24 +258,22 @@ def begin_create( self, scope: str, diagnostics_resource_name: str, - diagnostic_resource_request: Optional[_models.DiagnosticResource] = None, + diagnostic_resource_request: _models.DiagnosticResource, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.DiagnosticResource]: """Creates a diagnostic for the specific resource using solutionId from discovery solutions. :code:`
`Diagnostics are powerful solutions that access product resources or other relevant - data and provide the root cause of the issue and the steps to address the - issue.:code:`
`:code:`
`. + data and provide the root cause of the issue and the steps to address the issue.\\ + :code:`
`\\ :code:`
`. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param diagnostics_resource_name: Unique resource name for insight resources. Required. :type diagnostics_resource_name: str :param diagnostic_resource_request: The required request body for this insightResource - invocation. Default value is None. + invocation. Required. :type diagnostic_resource_request: ~azure.mgmt.selfhelp.models.DiagnosticResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". @@ -235,24 +289,22 @@ def begin_create( self, scope: str, diagnostics_resource_name: str, - diagnostic_resource_request: Optional[IO[bytes]] = None, + diagnostic_resource_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.DiagnosticResource]: """Creates a diagnostic for the specific resource using solutionId from discovery solutions. :code:`
`Diagnostics are powerful solutions that access product resources or other relevant - data and provide the root cause of the issue and the steps to address the - issue.:code:`
`:code:`
`. + data and provide the root cause of the issue and the steps to address the issue.\\ + :code:`
`\\ :code:`
`. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param diagnostics_resource_name: Unique resource name for insight resources. Required. :type diagnostics_resource_name: str :param diagnostic_resource_request: The required request body for this insightResource - invocation. Default value is None. + invocation. Required. :type diagnostic_resource_request: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". @@ -268,22 +320,20 @@ def begin_create( self, scope: str, diagnostics_resource_name: str, - diagnostic_resource_request: Optional[Union[_models.DiagnosticResource, IO[bytes]]] = None, + diagnostic_resource_request: Union[_models.DiagnosticResource, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.DiagnosticResource]: """Creates a diagnostic for the specific resource using solutionId from discovery solutions. :code:`
`Diagnostics are powerful solutions that access product resources or other relevant - data and provide the root cause of the issue and the steps to address the - issue.:code:`
`:code:`
`. + data and provide the root cause of the issue and the steps to address the issue.\\ + :code:`
`\\ :code:`
`. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param diagnostics_resource_name: Unique resource name for insight resources. Required. :type diagnostics_resource_name: str :param diagnostic_resource_request: The required request body for this insightResource - invocation. Is either a DiagnosticResource type or a IO[bytes] type. Default value is None. + invocation. Is either a DiagnosticResource type or a IO[bytes] type. Required. :type diagnostic_resource_request: ~azure.mgmt.selfhelp.models.DiagnosticResource or IO[bytes] :return: An instance of LROPoller that returns either DiagnosticResource or the result of cls(response) @@ -311,10 +361,11 @@ def begin_create( 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("DiagnosticResource", pipeline_response) + deserialized = self._deserialize("DiagnosticResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized @@ -337,61 +388,3 @@ def get_long_running_output(pipeline_response): return LROPoller[_models.DiagnosticResource]( self._client, raw_result, get_long_running_output, polling_method # type: ignore ) - - @distributed_trace - def get(self, scope: str, diagnostics_resource_name: str, **kwargs: Any) -> _models.DiagnosticResource: - """Get the diagnostics using the 'diagnosticsResourceName' you chose while creating the - diagnostic. - - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. - :type scope: str - :param diagnostics_resource_name: Unique resource name for insight resources. Required. - :type diagnostics_resource_name: str - :return: DiagnosticResource or the result of cls(response) - :rtype: ~azure.mgmt.selfhelp.models.DiagnosticResource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.DiagnosticResource] = kwargs.pop("cls", None) - - _request = build_get_request( - scope=scope, - diagnostics_resource_name=diagnostics_resource_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request = _convert_request(_request) - _request.url = self._client.format_url(_request.url) - - _stream = False - 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]: - 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 = self._deserialize("DiagnosticResource", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_discovery_solution_nlp_operations.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_discovery_solution_nlp_operations.py index 4b1804711658..1910b939e4aa 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_discovery_solution_nlp_operations.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_discovery_solution_nlp_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +5,11 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from collections.abc import MutableMapping from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Optional, Type, TypeVar, Union, overload +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -19,20 +19,15 @@ 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 _convert_request +from .._configuration import SelfHelpMgmtClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -75,7 +70,7 @@ def build_discover_solutions_by_subscription_request( # pylint: disable=name-to # Construct URL _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Help/discoverSolutions") path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", skip_quote=True), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -105,15 +100,15 @@ class DiscoverySolutionNLPOperations: def __init__(self, *args, **kwargs): input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SelfHelpMgmtClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @overload def discover_solutions( self, - discover_solution_request: Optional[_models.DiscoveryNlpRequest] = None, + discover_solution_request: _models.DiscoveryNlpRequest, *, content_type: str = "application/json", **kwargs: Any @@ -121,8 +116,7 @@ def discover_solutions( """Search for relevant Azure Diagnostics, Solutions and Troubleshooters using a natural language issue summary. - :param discover_solution_request: Request body for discovering solutions using NLP. Default - value is None. + :param discover_solution_request: The request body. Required. :type discover_solution_request: ~azure.mgmt.selfhelp.models.DiscoveryNlpRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". @@ -134,17 +128,12 @@ def discover_solutions( @overload def discover_solutions( - self, - discover_solution_request: Optional[IO[bytes]] = None, - *, - content_type: str = "application/json", - **kwargs: Any + self, discover_solution_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.DiscoveryNlpResponse: """Search for relevant Azure Diagnostics, Solutions and Troubleshooters using a natural language issue summary. - :param discover_solution_request: Request body for discovering solutions using NLP. Default - value is None. + :param discover_solution_request: The request body. Required. :type discover_solution_request: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". @@ -156,19 +145,19 @@ def discover_solutions( @distributed_trace def discover_solutions( - self, discover_solution_request: Optional[Union[_models.DiscoveryNlpRequest, IO[bytes]]] = None, **kwargs: Any + self, discover_solution_request: Union[_models.DiscoveryNlpRequest, IO[bytes]], **kwargs: Any ) -> _models.DiscoveryNlpResponse: """Search for relevant Azure Diagnostics, Solutions and Troubleshooters using a natural language issue summary. - :param discover_solution_request: Request body for discovering solutions using NLP. Is either a - DiscoveryNlpRequest type or a IO[bytes] type. Default value is None. + :param discover_solution_request: The request body. Is either a DiscoveryNlpRequest type or a + IO[bytes] type. Required. :type discover_solution_request: ~azure.mgmt.selfhelp.models.DiscoveryNlpRequest or IO[bytes] :return: DiscoveryNlpResponse or the result of cls(response) :rtype: ~azure.mgmt.selfhelp.models.DiscoveryNlpResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -189,10 +178,7 @@ def discover_solutions( if isinstance(discover_solution_request, (IOBase, bytes)): _content = discover_solution_request else: - if discover_solution_request is not None: - _json = self._serialize.body(discover_solution_request, "DiscoveryNlpRequest") - else: - _json = None + _json = self._serialize.body(discover_solution_request, "DiscoveryNlpRequest") _request = build_discover_solutions_request( api_version=api_version, @@ -202,7 +188,6 @@ def discover_solutions( headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) _stream = False @@ -217,7 +202,7 @@ def discover_solutions( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DiscoveryNlpResponse", pipeline_response) + deserialized = self._deserialize("DiscoveryNlpResponse", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -227,8 +212,7 @@ def discover_solutions( @overload def discover_solutions_by_subscription( self, - subscription_id: str, - discover_solution_request: Optional[_models.DiscoveryNlpRequest] = None, + discover_solution_request: _models.DiscoveryNlpRequest, *, content_type: str = "application/json", **kwargs: Any @@ -236,10 +220,7 @@ def discover_solutions_by_subscription( """Search for relevant Azure Diagnostics, Solutions and Troubleshooters using a natural language issue summary and subscription. - :param subscription_id: The Azure subscription ID. Required. - :type subscription_id: str - :param discover_solution_request: Request body for discovering solutions using NLP. Default - value is None. + :param discover_solution_request: The request body. Required. :type discover_solution_request: ~azure.mgmt.selfhelp.models.DiscoveryNlpRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". @@ -251,20 +232,12 @@ def discover_solutions_by_subscription( @overload def discover_solutions_by_subscription( - self, - subscription_id: str, - discover_solution_request: Optional[IO[bytes]] = None, - *, - content_type: str = "application/json", - **kwargs: Any + self, discover_solution_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.DiscoveryNlpResponse: """Search for relevant Azure Diagnostics, Solutions and Troubleshooters using a natural language issue summary and subscription. - :param subscription_id: The Azure subscription ID. Required. - :type subscription_id: str - :param discover_solution_request: Request body for discovering solutions using NLP. Default - value is None. + :param discover_solution_request: The request body. Required. :type discover_solution_request: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". @@ -276,24 +249,19 @@ def discover_solutions_by_subscription( @distributed_trace def discover_solutions_by_subscription( - self, - subscription_id: str, - discover_solution_request: Optional[Union[_models.DiscoveryNlpRequest, IO[bytes]]] = None, - **kwargs: Any + self, discover_solution_request: Union[_models.DiscoveryNlpRequest, IO[bytes]], **kwargs: Any ) -> _models.DiscoveryNlpResponse: """Search for relevant Azure Diagnostics, Solutions and Troubleshooters using a natural language issue summary and subscription. - :param subscription_id: The Azure subscription ID. Required. - :type subscription_id: str - :param discover_solution_request: Request body for discovering solutions using NLP. Is either a - DiscoveryNlpRequest type or a IO[bytes] type. Default value is None. + :param discover_solution_request: The request body. Is either a DiscoveryNlpRequest type or a + IO[bytes] type. Required. :type discover_solution_request: ~azure.mgmt.selfhelp.models.DiscoveryNlpRequest or IO[bytes] :return: DiscoveryNlpResponse or the result of cls(response) :rtype: ~azure.mgmt.selfhelp.models.DiscoveryNlpResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -314,13 +282,10 @@ def discover_solutions_by_subscription( if isinstance(discover_solution_request, (IOBase, bytes)): _content = discover_solution_request else: - if discover_solution_request is not None: - _json = self._serialize.body(discover_solution_request, "DiscoveryNlpRequest") - else: - _json = None + _json = self._serialize.body(discover_solution_request, "DiscoveryNlpRequest") _request = build_discover_solutions_by_subscription_request( - subscription_id=subscription_id, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, @@ -328,7 +293,6 @@ def discover_solutions_by_subscription( headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) _stream = False @@ -343,7 +307,7 @@ def discover_solutions_by_subscription( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DiscoveryNlpResponse", pipeline_response) + deserialized = self._deserialize("DiscoveryNlpResponse", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_discovery_solution_operations.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_discovery_solution_operations.py index 57bdcda42d75..25fe6a6bd823 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_discovery_solution_operations.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_discovery_solution_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +5,11 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +from collections.abc import MutableMapping +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar import urllib.parse +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -20,20 +20,15 @@ ) 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 _convert_request +from .._configuration import SelfHelpMgmtClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -54,7 +49,7 @@ def build_list_request(*, filter: Optional[str] = None, skiptoken: Optional[str] # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") if skiptoken is not None: _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "str") @@ -78,10 +73,10 @@ class DiscoverySolutionOperations: def __init__(self, *args, **kwargs): input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SelfHelpMgmtClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list( @@ -90,11 +85,11 @@ def list( """Lists the relevant Azure Diagnostics, Solutions and Troubleshooters using `problemClassification API `_\\ ) AND - resourceUri or resourceType.:code:`
` Discovery Solutions is the initial entry point within - Help API, which identifies relevant Azure diagnostics and solutions. :code:`
`:code:`
` - Required Input : problemClassificationId (Use the `problemClassification API + resourceUri or resourceType.\\ :code:`
` Discovery Solutions is the initial entry point + within Help API, which identifies relevant Azure diagnostics and solutions. :code:`
`\\ + :code:`
` Required Input : problemClassificationId (Use the `problemClassification API `_\\ ) - :code:`
`Optional input: resourceUri OR resource Type :code:`
`:code:`
` + :code:`
`Optional input: resourceUri OR resource Type :code:`
`\\ :code:`
` :code:`Note: ` ‘requiredInputs’ from Discovery solutions response must be passed via ‘additionalParameters’ as an input to Diagnostics and Solutions API. @@ -118,7 +113,7 @@ def list( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.DiscoveryResponse] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -136,7 +131,6 @@ def prepare_request(next_link=None): headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) else: @@ -152,7 +146,6 @@ def prepare_request(next_link=None): _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) _request.method = "GET" return _request diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_operations.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_operations.py index 813b6eac8b0c..72078c1bbc48 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_operations.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +5,11 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +from collections.abc import MutableMapping +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar import urllib.parse +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -20,20 +20,15 @@ ) 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 _convert_request +from .._configuration import SelfHelpMgmtClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -74,14 +69,14 @@ class Operations: def __init__(self, *args, **kwargs): input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SelfHelpMgmtClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: - """Returns list of operations. + """List the operations for the provider. :return: An iterator like instance of either Operation or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.selfhelp.models.Operation] @@ -93,7 +88,7 @@ def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: 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: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -109,7 +104,6 @@ def prepare_request(next_link=None): headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) else: @@ -125,7 +119,6 @@ def prepare_request(next_link=None): _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) _request.method = "GET" return _request diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_simplified_solutions_operations.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_simplified_solutions_operations.py index 3974b230c7a5..78cf23037658 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_simplified_solutions_operations.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_simplified_solutions_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,35 +5,33 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from collections.abc import MutableMapping from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload +from typing import Any, Callable, Dict, IO, Iterator, Optional, TypeVar, Union, cast, overload +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) 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 from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request +from .._configuration import SelfHelpMgmtClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -42,18 +39,17 @@ _SERIALIZER.client_side_validation = False -def build_create_request(scope: str, simplified_solutions_resource_name: str, **kwargs: Any) -> HttpRequest: +def build_get_request(scope: str, simplified_solutions_resource_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/{scope}/providers/Microsoft.Help/simplifiedSolutions/{simplifiedSolutionsResourceName}" - ) # pylint: disable=line-too-long + ) path_format_arguments = { "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), "simplifiedSolutionsResourceName": _SERIALIZER.url( @@ -72,24 +68,23 @@ def build_create_request(scope: str, simplified_solutions_resource_name: str, ** _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_get_request(scope: str, simplified_solutions_resource_name: str, **kwargs: Any) -> HttpRequest: +def build_create_request(scope: str, simplified_solutions_resource_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/{scope}/providers/Microsoft.Help/simplifiedSolutions/{simplifiedSolutionsResourceName}" - ) # pylint: disable=line-too-long + ) path_format_arguments = { "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), "simplifiedSolutionsResourceName": _SERIALIZER.url( @@ -108,9 +103,11 @@ def build_get_request(scope: str, simplified_solutions_resource_name: str, **kwa _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) class SimplifiedSolutionsOperations: @@ -127,19 +124,76 @@ class SimplifiedSolutionsOperations: def __init__(self, *args, **kwargs): input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SelfHelpMgmtClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get( + self, scope: str, simplified_solutions_resource_name: str, **kwargs: Any + ) -> _models.SimplifiedSolutionsResource: + """Get the simplified Solutions using the applicable solutionResourceName while creating the + simplified Solutions. + + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. + :type scope: str + :param simplified_solutions_resource_name: Simplified Solutions Resource Name. Required. + :type simplified_solutions_resource_name: str + :return: SimplifiedSolutionsResource or the result of cls(response) + :rtype: ~azure.mgmt.selfhelp.models.SimplifiedSolutionsResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SimplifiedSolutionsResource] = kwargs.pop("cls", None) + + _request = build_get_request( + scope=scope, + simplified_solutions_resource_name=simplified_solutions_resource_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + 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]: + 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 = self._deserialize("SimplifiedSolutionsResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore def _create_initial( self, scope: str, simplified_solutions_resource_name: str, - simplified_solutions_request_body: Optional[Union[_models.SimplifiedSolutionsResource, IO[bytes]]] = None, + simplified_solutions_request_body: Union[_models.SimplifiedSolutionsResource, IO[bytes]], **kwargs: Any - ) -> _models.SimplifiedSolutionsResource: - error_map: MutableMapping[int, Type[HttpResponseError]] = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -152,7 +206,7 @@ def _create_initial( 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.SimplifiedSolutionsResource] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None @@ -160,10 +214,7 @@ def _create_initial( if isinstance(simplified_solutions_request_body, (IOBase, bytes)): _content = simplified_solutions_request_body else: - if simplified_solutions_request_body is not None: - _json = self._serialize.body(simplified_solutions_request_body, "SimplifiedSolutionsResource") - else: - _json = None + _json = self._serialize.body(simplified_solutions_request_body, "SimplifiedSolutionsResource") _request = build_create_request( scope=scope, @@ -175,10 +226,10 @@ def _create_initial( headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -186,18 +237,25 @@ def _create_initial( response = pipeline_response.http_response if response.status_code not in [200, 201]: + 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) - if response.status_code == 200: - deserialized = self._deserialize("SimplifiedSolutionsResource", pipeline_response) - + response_headers = {} if response.status_code == 201: - deserialized = self._deserialize("SimplifiedSolutionsResource", pipeline_response) + response_headers["Azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-AsyncOperation") + ) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized # type: ignore @@ -206,26 +264,24 @@ def begin_create( self, scope: str, simplified_solutions_resource_name: str, - simplified_solutions_request_body: Optional[_models.SimplifiedSolutionsResource] = None, + simplified_solutions_request_body: _models.SimplifiedSolutionsResource, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.SimplifiedSolutionsResource]: """Creates Simplified Solutions for an Azure subscription using 'solutionId' from Discovery - Solutions as the input. :code:`
`:code:`
` Simplified Solutions API makes the + Solutions as the input. :code:`
`\\ :code:`
` Simplified Solutions API makes the consumption of solutions APIs easier while still providing access to the same powerful solutions rendered in Solutions API. With Simplified Solutions, users don't have to worry about stitching together the article using replacement maps and can use the content in the API - response to directly render as HTML content.:code:`
`. + response to directly render as HTML content.\\ :code:`
`. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param simplified_solutions_resource_name: Simplified Solutions Resource Name. Required. :type simplified_solutions_resource_name: str :param simplified_solutions_request_body: The required request body for simplified Solutions - resource creation. Default value is None. + resource creation. Required. :type simplified_solutions_request_body: ~azure.mgmt.selfhelp.models.SimplifiedSolutionsResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -242,26 +298,24 @@ def begin_create( self, scope: str, simplified_solutions_resource_name: str, - simplified_solutions_request_body: Optional[IO[bytes]] = None, + simplified_solutions_request_body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.SimplifiedSolutionsResource]: """Creates Simplified Solutions for an Azure subscription using 'solutionId' from Discovery - Solutions as the input. :code:`
`:code:`
` Simplified Solutions API makes the + Solutions as the input. :code:`
`\\ :code:`
` Simplified Solutions API makes the consumption of solutions APIs easier while still providing access to the same powerful solutions rendered in Solutions API. With Simplified Solutions, users don't have to worry about stitching together the article using replacement maps and can use the content in the API - response to directly render as HTML content.:code:`
`. + response to directly render as HTML content.\\ :code:`
`. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param simplified_solutions_resource_name: Simplified Solutions Resource Name. Required. :type simplified_solutions_resource_name: str :param simplified_solutions_request_body: The required request body for simplified Solutions - resource creation. Default value is None. + resource creation. Required. :type simplified_solutions_request_body: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". @@ -277,25 +331,22 @@ def begin_create( self, scope: str, simplified_solutions_resource_name: str, - simplified_solutions_request_body: Optional[Union[_models.SimplifiedSolutionsResource, IO[bytes]]] = None, + simplified_solutions_request_body: Union[_models.SimplifiedSolutionsResource, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.SimplifiedSolutionsResource]: """Creates Simplified Solutions for an Azure subscription using 'solutionId' from Discovery - Solutions as the input. :code:`
`:code:`
` Simplified Solutions API makes the + Solutions as the input. :code:`
`\\ :code:`
` Simplified Solutions API makes the consumption of solutions APIs easier while still providing access to the same powerful solutions rendered in Solutions API. With Simplified Solutions, users don't have to worry about stitching together the article using replacement maps and can use the content in the API - response to directly render as HTML content.:code:`
`. + response to directly render as HTML content.\\ :code:`
`. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param simplified_solutions_resource_name: Simplified Solutions Resource Name. Required. :type simplified_solutions_resource_name: str :param simplified_solutions_request_body: The required request body for simplified Solutions - resource creation. Is either a SimplifiedSolutionsResource type or a IO[bytes] type. Default - value is None. + resource creation. Is either a SimplifiedSolutionsResource type or a IO[bytes] type. Required. :type simplified_solutions_request_body: ~azure.mgmt.selfhelp.models.SimplifiedSolutionsResource or IO[bytes] :return: An instance of LROPoller that returns either SimplifiedSolutionsResource or the result @@ -324,10 +375,11 @@ def begin_create( 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("SimplifiedSolutionsResource", pipeline_response) + deserialized = self._deserialize("SimplifiedSolutionsResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized @@ -350,63 +402,3 @@ def get_long_running_output(pipeline_response): return LROPoller[_models.SimplifiedSolutionsResource]( self._client, raw_result, get_long_running_output, polling_method # type: ignore ) - - @distributed_trace - def get( - self, scope: str, simplified_solutions_resource_name: str, **kwargs: Any - ) -> _models.SimplifiedSolutionsResource: - """Get the simplified Solutions using the applicable solutionResourceName while creating the - simplified Solutions. - - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. - :type scope: str - :param simplified_solutions_resource_name: Simplified Solutions Resource Name. Required. - :type simplified_solutions_resource_name: str - :return: SimplifiedSolutionsResource or the result of cls(response) - :rtype: ~azure.mgmt.selfhelp.models.SimplifiedSolutionsResource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SimplifiedSolutionsResource] = kwargs.pop("cls", None) - - _request = build_get_request( - scope=scope, - simplified_solutions_resource_name=simplified_solutions_resource_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request = _convert_request(_request) - _request.url = self._client.format_url(_request.url) - - _stream = False - 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]: - 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 = self._deserialize("SimplifiedSolutionsResource", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_solution_operations.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_solution_operations.py index 636c5c96da2e..559d3eafc987 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_solution_operations.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_solution_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,35 +5,33 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from collections.abc import MutableMapping from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload +from typing import Any, Callable, Dict, IO, Iterator, Optional, TypeVar, Union, cast, overload +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) 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 from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request +from .._configuration import SelfHelpMgmtClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -42,12 +39,11 @@ _SERIALIZER.client_side_validation = False -def build_create_request(scope: str, solution_resource_name: str, **kwargs: Any) -> HttpRequest: +def build_get_request(scope: str, solution_resource_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -70,18 +66,17 @@ def build_create_request(scope: str, solution_resource_name: str, **kwargs: Any) _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_get_request(scope: str, solution_resource_name: str, **kwargs: Any) -> HttpRequest: +def build_create_request(scope: str, solution_resource_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -104,9 +99,11 @@ def build_get_request(scope: str, solution_resource_name: str, **kwargs: Any) -> _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) def build_update_request(scope: str, solution_resource_name: str, **kwargs: Any) -> HttpRequest: @@ -193,19 +190,73 @@ class SolutionOperations: def __init__(self, *args, **kwargs): input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SelfHelpMgmtClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, scope: str, solution_resource_name: str, **kwargs: Any) -> _models.SolutionResource: + """Get the solution using the applicable solutionResourceName while creating the solution. + + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. + :type scope: str + :param solution_resource_name: Solution resource Name. Required. + :type solution_resource_name: str + :return: SolutionResource or the result of cls(response) + :rtype: ~azure.mgmt.selfhelp.models.SolutionResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SolutionResource] = kwargs.pop("cls", None) + + _request = build_get_request( + scope=scope, + solution_resource_name=solution_resource_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + 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]: + 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 = self._deserialize("SolutionResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore def _create_initial( self, scope: str, solution_resource_name: str, - solution_request_body: Optional[Union[_models.SolutionResource, IO[bytes]]] = None, + solution_request_body: Union[_models.SolutionResource, IO[bytes]], **kwargs: Any - ) -> _models.SolutionResource: - error_map: MutableMapping[int, Type[HttpResponseError]] = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -218,7 +269,7 @@ def _create_initial( 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.SolutionResource] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None @@ -226,10 +277,7 @@ def _create_initial( if isinstance(solution_request_body, (IOBase, bytes)): _content = solution_request_body else: - if solution_request_body is not None: - _json = self._serialize.body(solution_request_body, "SolutionResource") - else: - _json = None + _json = self._serialize.body(solution_request_body, "SolutionResource") _request = build_create_request( scope=scope, @@ -241,10 +289,10 @@ def _create_initial( headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -252,18 +300,25 @@ def _create_initial( response = pipeline_response.http_response if response.status_code not in [200, 201]: + 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) - if response.status_code == 200: - deserialized = self._deserialize("SolutionResource", pipeline_response) - + response_headers = {} if response.status_code == 201: - deserialized = self._deserialize("SolutionResource", pipeline_response) + response_headers["Azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-AsyncOperation") + ) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized # type: ignore @@ -272,7 +327,7 @@ def begin_create( self, scope: str, solution_resource_name: str, - solution_request_body: Optional[_models.SolutionResource] = None, + solution_request_body: _models.SolutionResource, *, content_type: str = "application/json", **kwargs: Any @@ -287,14 +342,12 @@ def begin_create( troubleshooting instructions. :code:`
` All these components are seamlessly converged into unified solutions tailored to address a specific support problem area. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param solution_resource_name: Solution resource Name. Required. :type solution_resource_name: str :param solution_request_body: The required request body for this solution resource creation. - Default value is None. + Required. :type solution_request_body: ~azure.mgmt.selfhelp.models.SolutionResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". @@ -310,7 +363,7 @@ def begin_create( self, scope: str, solution_resource_name: str, - solution_request_body: Optional[IO[bytes]] = None, + solution_request_body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -325,14 +378,12 @@ def begin_create( troubleshooting instructions. :code:`
` All these components are seamlessly converged into unified solutions tailored to address a specific support problem area. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param solution_resource_name: Solution resource Name. Required. :type solution_resource_name: str :param solution_request_body: The required request body for this solution resource creation. - Default value is None. + Required. :type solution_request_body: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". @@ -348,7 +399,7 @@ def begin_create( self, scope: str, solution_resource_name: str, - solution_request_body: Optional[Union[_models.SolutionResource, IO[bytes]]] = None, + solution_request_body: Union[_models.SolutionResource, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.SolutionResource]: """Creates a solution for the specific Azure resource or subscription using the inputs ‘solutionId @@ -361,14 +412,12 @@ def begin_create( troubleshooting instructions. :code:`
` All these components are seamlessly converged into unified solutions tailored to address a specific support problem area. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param solution_resource_name: Solution resource Name. Required. :type solution_resource_name: str :param solution_request_body: The required request body for this solution resource creation. Is - either a SolutionResource type or a IO[bytes] type. Default value is None. + either a SolutionResource type or a IO[bytes] type. Required. :type solution_request_body: ~azure.mgmt.selfhelp.models.SolutionResource or IO[bytes] :return: An instance of LROPoller that returns either SolutionResource or the result of cls(response) @@ -396,10 +445,11 @@ def begin_create( 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("SolutionResource", pipeline_response) + deserialized = self._deserialize("SolutionResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized @@ -423,71 +473,14 @@ def get_long_running_output(pipeline_response): self._client, raw_result, get_long_running_output, polling_method # type: ignore ) - @distributed_trace - def get(self, scope: str, solution_resource_name: str, **kwargs: Any) -> _models.SolutionResource: - """Get the solution using the applicable solutionResourceName while creating the solution. - - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. - :type scope: str - :param solution_resource_name: Solution resource Name. Required. - :type solution_resource_name: str - :return: SolutionResource or the result of cls(response) - :rtype: ~azure.mgmt.selfhelp.models.SolutionResource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SolutionResource] = kwargs.pop("cls", None) - - _request = build_get_request( - scope=scope, - solution_resource_name=solution_resource_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request = _convert_request(_request) - _request.url = self._client.format_url(_request.url) - - _stream = False - 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]: - 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 = self._deserialize("SolutionResource", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - def _update_initial( self, scope: str, solution_resource_name: str, - solution_patch_request_body: Optional[Union[_models.SolutionPatchRequestBody, IO[bytes]]] = None, + solution_patch_request_body: Union[_models.SolutionPatchRequestBody, IO[bytes]], **kwargs: Any - ) -> _models.SolutionResource: - error_map: MutableMapping[int, Type[HttpResponseError]] = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -500,7 +493,7 @@ def _update_initial( 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.SolutionResource] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None @@ -508,10 +501,7 @@ def _update_initial( if isinstance(solution_patch_request_body, (IOBase, bytes)): _content = solution_patch_request_body else: - if solution_patch_request_body is not None: - _json = self._serialize.body(solution_patch_request_body, "SolutionPatchRequestBody") - else: - _json = None + _json = self._serialize.body(solution_patch_request_body, "SolutionPatchRequestBody") _request = build_update_request( scope=scope, @@ -523,10 +513,10 @@ def _update_initial( headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -534,20 +524,21 @@ def _update_initial( 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: - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - - deserialized = self._deserialize("SolutionResource", 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("SolutionResource", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -559,21 +550,19 @@ def begin_update( self, scope: str, solution_resource_name: str, - solution_patch_request_body: Optional[_models.SolutionPatchRequestBody] = None, + solution_patch_request_body: _models.SolutionPatchRequestBody, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.SolutionResource]: """Update the requiredInputs or additional information needed to execute the solution. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param solution_resource_name: Solution resource Name. Required. :type solution_resource_name: str :param solution_patch_request_body: The required request body for updating a solution resource. - Default value is None. + Required. :type solution_patch_request_body: ~azure.mgmt.selfhelp.models.SolutionPatchRequestBody :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". @@ -589,21 +578,19 @@ def begin_update( self, scope: str, solution_resource_name: str, - solution_patch_request_body: Optional[IO[bytes]] = None, + solution_patch_request_body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.SolutionResource]: """Update the requiredInputs or additional information needed to execute the solution. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param solution_resource_name: Solution resource Name. Required. :type solution_resource_name: str :param solution_patch_request_body: The required request body for updating a solution resource. - Default value is None. + Required. :type solution_patch_request_body: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". @@ -619,19 +606,17 @@ def begin_update( self, scope: str, solution_resource_name: str, - solution_patch_request_body: Optional[Union[_models.SolutionPatchRequestBody, IO[bytes]]] = None, + solution_patch_request_body: Union[_models.SolutionPatchRequestBody, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.SolutionResource]: """Update the requiredInputs or additional information needed to execute the solution. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param solution_resource_name: Solution resource Name. Required. :type solution_resource_name: str :param solution_patch_request_body: The required request body for updating a solution resource. - Is either a SolutionPatchRequestBody type or a IO[bytes] type. Default value is None. + Is either a SolutionPatchRequestBody type or a IO[bytes] type. Required. :type solution_patch_request_body: ~azure.mgmt.selfhelp.models.SolutionPatchRequestBody or IO[bytes] :return: An instance of LROPoller that returns either SolutionResource or the result of @@ -660,16 +645,13 @@ def begin_update( params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response_headers = {} - response = pipeline_response.http_response - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - - deserialized = self._deserialize("SolutionResource", pipeline_response) + deserialized = self._deserialize("SolutionResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -692,7 +674,7 @@ def get_long_running_output(pipeline_response): ) @overload - def warm_up( # pylint: disable=inconsistent-return-statements + def warm_up( self, scope: str, solution_resource_name: str, @@ -703,9 +685,7 @@ def warm_up( # pylint: disable=inconsistent-return-statements ) -> None: """Warm up the solution resource by preloading asynchronous diagnostics results into cache. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param solution_resource_name: Solution resource Name. Required. :type solution_resource_name: str @@ -721,7 +701,7 @@ def warm_up( # pylint: disable=inconsistent-return-statements """ @overload - def warm_up( # pylint: disable=inconsistent-return-statements + def warm_up( self, scope: str, solution_resource_name: str, @@ -732,9 +712,7 @@ def warm_up( # pylint: disable=inconsistent-return-statements ) -> None: """Warm up the solution resource by preloading asynchronous diagnostics results into cache. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param solution_resource_name: Solution resource Name. Required. :type solution_resource_name: str @@ -759,9 +737,7 @@ def warm_up( # pylint: disable=inconsistent-return-statements ) -> None: """Warm up the solution resource by preloading asynchronous diagnostics results into cache. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param solution_resource_name: Solution resource Name. Required. :type solution_resource_name: str @@ -774,7 +750,7 @@ def warm_up( # pylint: disable=inconsistent-return-statements :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -810,7 +786,6 @@ def warm_up( # pylint: disable=inconsistent-return-statements headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) _stream = False diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_solution_self_help_operations.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_solution_self_help_operations.py index c9ffdad866df..467411a1d07b 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_solution_self_help_operations.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_solution_self_help_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines,too-many-statements +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,9 +6,10 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Optional, Type, TypeVar +from collections.abc import MutableMapping +from typing import Any, Callable, Dict, Optional, TypeVar +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -18,20 +19,15 @@ 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 _convert_request +from .._configuration import SelfHelpMgmtClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -77,10 +73,10 @@ class SolutionSelfHelpOperations: def __init__(self, *args, **kwargs): input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SelfHelpMgmtClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def get(self, solution_id: str, **kwargs: Any) -> _models.SolutionResourceSelfHelp: @@ -97,7 +93,7 @@ def get(self, solution_id: str, **kwargs: Any) -> _models.SolutionResourceSelfHe :rtype: ~azure.mgmt.selfhelp.models.SolutionResourceSelfHelp :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -117,7 +113,6 @@ def get(self, solution_id: str, **kwargs: Any) -> _models.SolutionResourceSelfHe headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) _stream = False @@ -132,7 +127,7 @@ def get(self, solution_id: str, **kwargs: Any) -> _models.SolutionResourceSelfHe error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("SolutionResourceSelfHelp", pipeline_response) + deserialized = self._deserialize("SolutionResourceSelfHelp", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_troubleshooters_operations.py b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_troubleshooters_operations.py index 68ca6033fce4..b977e2b7a70b 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_troubleshooters_operations.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/azure/mgmt/selfhelp/operations/_troubleshooters_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +5,11 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from collections.abc import MutableMapping from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Optional, Type, TypeVar, Union, overload +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -19,20 +19,15 @@ 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 _convert_request +from .._configuration import SelfHelpMgmtClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -40,12 +35,11 @@ _SERIALIZER.client_side_validation = False -def build_create_request(scope: str, troubleshooter_name: str, **kwargs: Any) -> HttpRequest: +def build_get_request(scope: str, troubleshooter_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -68,18 +62,17 @@ def build_create_request(scope: str, troubleshooter_name: str, **kwargs: Any) -> _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_get_request(scope: str, troubleshooter_name: str, **kwargs: Any) -> HttpRequest: +def build_create_request(scope: str, troubleshooter_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -102,9 +95,11 @@ def build_get_request(scope: str, troubleshooter_name: str, **kwargs: Any) -> Ht _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) def build_continue_method_request(scope: str, troubleshooter_name: str, **kwargs: Any) -> HttpRequest: @@ -220,17 +215,75 @@ class TroubleshootersOperations: def __init__(self, *args, **kwargs): input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: SelfHelpMgmtClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, scope: str, troubleshooter_name: str, **kwargs: Any) -> _models.TroubleshooterResource: + """Gets troubleshooter instance result which includes the step status/result of the troubleshooter + resource name that is being executed.\\ :code:`
` Get API is used to retrieve the result of + a Troubleshooter instance, which includes the status and result of each step in the + Troubleshooter workflow. This API requires the Troubleshooter resource name that was created + using the Create API. + + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. + :type scope: str + :param troubleshooter_name: Troubleshooter resource Name. Required. + :type troubleshooter_name: str + :return: TroubleshooterResource or the result of cls(response) + :rtype: ~azure.mgmt.selfhelp.models.TroubleshooterResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.TroubleshooterResource] = kwargs.pop("cls", None) + + _request = build_get_request( + scope=scope, + troubleshooter_name=troubleshooter_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + 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]: + 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 = self._deserialize("TroubleshooterResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore @overload def create( self, scope: str, troubleshooter_name: str, - create_troubleshooter_request_body: Optional[_models.TroubleshooterResource] = None, + create_troubleshooter_request_body: _models.TroubleshooterResource, *, content_type: str = "application/json", **kwargs: Any @@ -245,14 +298,12 @@ def create( requests raised by customers. Troubleshooters terminate at a well curated solution based off of resource backend signals and customer manual selections. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param troubleshooter_name: Troubleshooter resource Name. Required. :type troubleshooter_name: str :param create_troubleshooter_request_body: The required request body for this Troubleshooter - resource creation. Default value is None. + resource creation. Required. :type create_troubleshooter_request_body: ~azure.mgmt.selfhelp.models.TroubleshooterResource :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". @@ -267,7 +318,7 @@ def create( self, scope: str, troubleshooter_name: str, - create_troubleshooter_request_body: Optional[IO[bytes]] = None, + create_troubleshooter_request_body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -282,14 +333,12 @@ def create( requests raised by customers. Troubleshooters terminate at a well curated solution based off of resource backend signals and customer manual selections. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param troubleshooter_name: Troubleshooter resource Name. Required. :type troubleshooter_name: str :param create_troubleshooter_request_body: The required request body for this Troubleshooter - resource creation. Default value is None. + resource creation. Required. :type create_troubleshooter_request_body: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". @@ -304,7 +353,7 @@ def create( self, scope: str, troubleshooter_name: str, - create_troubleshooter_request_body: Optional[Union[_models.TroubleshooterResource, IO[bytes]]] = None, + create_troubleshooter_request_body: Union[_models.TroubleshooterResource, IO[bytes]], **kwargs: Any ) -> _models.TroubleshooterResource: """Creates the specific troubleshooter action under a resource or subscription using the @@ -317,22 +366,19 @@ def create( requests raised by customers. Troubleshooters terminate at a well curated solution based off of resource backend signals and customer manual selections. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param troubleshooter_name: Troubleshooter resource Name. Required. :type troubleshooter_name: str :param create_troubleshooter_request_body: The required request body for this Troubleshooter - resource creation. Is either a TroubleshooterResource type or a IO[bytes] type. Default value - is None. + resource creation. Is either a TroubleshooterResource type or a IO[bytes] type. Required. :type create_troubleshooter_request_body: ~azure.mgmt.selfhelp.models.TroubleshooterResource or IO[bytes] :return: TroubleshooterResource or the result of cls(response) :rtype: ~azure.mgmt.selfhelp.models.TroubleshooterResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -353,10 +399,7 @@ def create( if isinstance(create_troubleshooter_request_body, (IOBase, bytes)): _content = create_troubleshooter_request_body else: - if create_troubleshooter_request_body is not None: - _json = self._serialize.body(create_troubleshooter_request_body, "TroubleshooterResource") - else: - _json = None + _json = self._serialize.body(create_troubleshooter_request_body, "TroubleshooterResource") _request = build_create_request( scope=scope, @@ -368,7 +411,6 @@ def create( headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) _stream = False @@ -383,72 +425,7 @@ def create( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("TroubleshooterResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("TroubleshooterResource", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get(self, scope: str, troubleshooter_name: str, **kwargs: Any) -> _models.TroubleshooterResource: - """Gets troubleshooter instance result which includes the step status/result of the troubleshooter - resource name that is being executed.:code:`
` Get API is used to retrieve the result of a - Troubleshooter instance, which includes the status and result of each step in the - Troubleshooter workflow. This API requires the Troubleshooter resource name that was created - using the Create API. - - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. - :type scope: str - :param troubleshooter_name: Troubleshooter resource Name. Required. - :type troubleshooter_name: str - :return: TroubleshooterResource or the result of cls(response) - :rtype: ~azure.mgmt.selfhelp.models.TroubleshooterResource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.TroubleshooterResource] = kwargs.pop("cls", None) - - _request = build_get_request( - scope=scope, - troubleshooter_name=troubleshooter_name, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request = _convert_request(_request) - _request.url = self._client.format_url(_request.url) - - _stream = False - 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]: - 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 = self._deserialize("TroubleshooterResource", pipeline_response) + deserialized = self._deserialize("TroubleshooterResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -456,7 +433,7 @@ def get(self, scope: str, troubleshooter_name: str, **kwargs: Any) -> _models.Tr return deserialized # type: ignore @overload - def continue_method( # pylint: disable=inconsistent-return-statements + def continue_method( self, scope: str, troubleshooter_name: str, @@ -470,9 +447,7 @@ def continue_method( # pylint: disable=inconsistent-return-statements that are required for the specific troubleshooter to progress into the next step in the process. This API is used after the Troubleshooter has been created using the Create API. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param troubleshooter_name: Troubleshooter resource Name. Required. :type troubleshooter_name: str @@ -488,7 +463,7 @@ def continue_method( # pylint: disable=inconsistent-return-statements """ @overload - def continue_method( # pylint: disable=inconsistent-return-statements + def continue_method( self, scope: str, troubleshooter_name: str, @@ -502,9 +477,7 @@ def continue_method( # pylint: disable=inconsistent-return-statements that are required for the specific troubleshooter to progress into the next step in the process. This API is used after the Troubleshooter has been created using the Create API. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param troubleshooter_name: Troubleshooter resource Name. Required. :type troubleshooter_name: str @@ -532,9 +505,7 @@ def continue_method( # pylint: disable=inconsistent-return-statements that are required for the specific troubleshooter to progress into the next step in the process. This API is used after the Troubleshooter has been created using the Create API. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param troubleshooter_name: Troubleshooter resource Name. Required. :type troubleshooter_name: str @@ -546,7 +517,7 @@ def continue_method( # pylint: disable=inconsistent-return-statements :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -582,7 +553,6 @@ def continue_method( # pylint: disable=inconsistent-return-statements headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) _stream = False @@ -597,11 +567,8 @@ def continue_method( # pylint: disable=inconsistent-return-statements error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def end( # pylint: disable=inconsistent-return-statements @@ -609,9 +576,7 @@ def end( # pylint: disable=inconsistent-return-statements ) -> None: """Ends the troubleshooter action. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param troubleshooter_name: Troubleshooter resource Name. Required. :type troubleshooter_name: str @@ -619,7 +584,7 @@ def end( # pylint: disable=inconsistent-return-statements :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -640,7 +605,6 @@ def end( # pylint: disable=inconsistent-return-statements headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) _stream = False @@ -655,21 +619,16 @@ def end( # pylint: disable=inconsistent-return-statements error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def restart(self, scope: str, troubleshooter_name: str, **kwargs: Any) -> _models.RestartTroubleshooterResponse: - """Restarts the troubleshooter API using applicable troubleshooter resource name as the - input.:code:`
` It returns new resource name which should be used in subsequent request. - The old resource name is obsolete after this API is invoked. + """Restarts the troubleshooter API using applicable troubleshooter resource name as the input.\\ + :code:`
` It returns new resource name which should be used in subsequent request. The old + resource name is obsolete after this API is invoked. - :param scope: scope = resourceUri of affected resource.:code:`
` For example: - /subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read. - Required. + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. :type scope: str :param troubleshooter_name: Troubleshooter resource Name. Required. :type troubleshooter_name: str @@ -677,7 +636,7 @@ def restart(self, scope: str, troubleshooter_name: str, **kwargs: Any) -> _model :rtype: ~azure.mgmt.selfhelp.models.RestartTroubleshooterResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -698,7 +657,6 @@ def restart(self, scope: str, troubleshooter_name: str, **kwargs: Any) -> _model headers=_headers, params=_params, ) - _request = _convert_request(_request) _request.url = self._client.format_url(_request.url) _stream = False @@ -713,12 +671,9 @@ def restart(self, scope: str, troubleshooter_name: str, **kwargs: Any) -> _model error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - - deserialized = self._deserialize("RestartTroubleshooterResponse", pipeline_response) + deserialized = self._deserialize("RestartTroubleshooterResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/check_name_availability_for_diagnostic_when_name_is_available.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/check_name_availability_for_diagnostic_when_name_is_available.py index 587d9363cdbe..3bcae899527f 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/check_name_availability_for_diagnostic_when_name_is_available.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/check_name_availability_for_diagnostic_when_name_is_available.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -27,6 +28,7 @@ def main(): client = SelfHelpMgmtClient( credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", ) response = client.check_name_availability.check_availability( diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/check_name_availability_for_diagnostic_when_name_is_not_available.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/check_name_availability_for_diagnostic_when_name_is_not_available.py index 25d722907896..c109c1edaa10 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/check_name_availability_for_diagnostic_when_name_is_not_available.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/check_name_availability_for_diagnostic_when_name_is_not_available.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -27,6 +28,7 @@ def main(): client = SelfHelpMgmtClient( credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", ) response = client.check_name_availability.check_availability( diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/create_diagnostic_for_key_vault_resource.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/create_diagnostic_for_key_vault_resource.py deleted file mode 100644 index 575e5bcda0b1..000000000000 --- a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/create_diagnostic_for_key_vault_resource.py +++ /dev/null @@ -1,41 +0,0 @@ -# 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.selfhelp import SelfHelpMgmtClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-selfhelp -# USAGE - python create_diagnostic_for_key_vault_resource.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 = SelfHelpMgmtClient( - credential=DefaultAzureCredential(), - ) - - response = client.diagnostics.begin_create( - scope="subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourceGroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read", - diagnostics_resource_name="VMNotWorkingInsight", - ).result() - print(response) - - -# x-ms-original-file: specification/help/resource-manager/Microsoft.Help/preview/2024-03-01-preview/examples/CreateDiagnosticForKeyVaultResource.json -if __name__ == "__main__": - main() diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/discover_solutions_at_subscription_scope.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/discover_solutions_at_subscription_scope.py index 049a3fca8a2b..b0e22aecde8d 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/discover_solutions_at_subscription_scope.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/discover_solutions_at_subscription_scope.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -27,10 +28,15 @@ def main(): client = SelfHelpMgmtClient( credential=DefaultAzureCredential(), + subscription_id="0d0fcd2e-c4fd-4349-8497-200edb3923c6", ) response = client.discovery_solution_nlp.discover_solutions_by_subscription( - subscription_id="0d0fcd2e-c4fd-4349-8497-200edb3923c6", + discover_solution_request={ + "issueSummary": "how to retrieve certs from deleted keyvault.", + "resourceId": "subscriptions/0d0fcd2e-c4fd-4349-8497-200edb3923c6/resourceGroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-non-read", + "serviceId": "0d0fcd2e-c4fd-4349-8497-200edb39s3ca", + }, ) print(response) diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/discover_solutions_at_tenant_scope.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/discover_solutions_at_tenant_scope.py index 9f32c05bc0b3..ac032bcdd92a 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/discover_solutions_at_tenant_scope.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/discover_solutions_at_tenant_scope.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -27,9 +28,15 @@ def main(): client = SelfHelpMgmtClient( credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", ) - response = client.discovery_solution_nlp.discover_solutions() + response = client.discovery_solution_nlp.discover_solutions( + discover_solution_request={ + "issueSummary": "how to retrieve certs from deleted keyvault.", + "serviceId": "0d0fcd2e-c4fd-4349-8497-200edb39s3ca", + }, + ) print(response) diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/get_diagnostic_for_key_vault_resource.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/get_diagnostic_for_key_vault_resource.py index 7b4e284ae633..23f5b4f03f60 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/get_diagnostic_for_key_vault_resource.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/get_diagnostic_for_key_vault_resource.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -27,6 +28,7 @@ def main(): client = SelfHelpMgmtClient( credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", ) response = client.diagnostics.get( diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/list_discovery_solutions_at_tenant_scope.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/list_discovery_solutions_at_tenant_scope.py index 5a05afd65adb..c88e2109299a 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/list_discovery_solutions_at_tenant_scope.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/list_discovery_solutions_at_tenant_scope.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -27,6 +28,7 @@ def main(): client = SelfHelpMgmtClient( credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", ) response = client.discovery_solution.list() diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/list_operations.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/list_operations.py index 3c003d4b4aa7..91d028552296 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/list_operations.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/list_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -27,6 +28,7 @@ def main(): client = SelfHelpMgmtClient( credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", ) response = client.operations.list() diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/self_help_solution_get.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/self_help_solution_get.py index 58ab8547a2dd..a1fea2e9f1f0 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/self_help_solution_get.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/self_help_solution_get.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -27,6 +28,7 @@ def main(): client = SelfHelpMgmtClient( credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", ) response = client.solution_self_help.get( diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/simplified_solutions_create.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/simplified_solutions_create.py index 353124f85dea..731a963b972a 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/simplified_solutions_create.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/simplified_solutions_create.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -27,11 +28,20 @@ def main(): client = SelfHelpMgmtClient( credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", ) response = client.simplified_solutions.begin_create( scope="subscriptions/mySubscription/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-rp", simplified_solutions_resource_name="simplifiedSolutionsResourceName1", + simplified_solutions_request_body={ + "properties": { + "parameters": { + "resourceUri": "subscriptions/mySubscription/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-rp" + }, + "solutionId": "sampleSolutionId", + } + }, ).result() print(response) diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/simplified_solutions_get.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/simplified_solutions_get.py index 5ef81bbee61a..a47961617d34 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/simplified_solutions_get.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/simplified_solutions_get.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -27,6 +28,7 @@ def main(): client = SelfHelpMgmtClient( credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", ) response = client.simplified_solutions.get( diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/solution_create.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/solution_create.py index ce760b118151..dc5fd6732ce1 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/solution_create.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/solution_create.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -27,11 +28,20 @@ def main(): client = SelfHelpMgmtClient( credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", ) response = client.solution.begin_create( scope="subscriptions/mySubscription/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-rp", solution_resource_name="SolutionResourceName1", + solution_request_body={ + "properties": { + "parameters": { + "resourceUri": "subscriptions/mySubscription/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-rp" + }, + "triggerCriteria": [{"name": "SolutionId", "value": "SolutionId1"}], + } + }, ).result() print(response) diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/solution_get.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/solution_get.py index 3304aaaf09f9..0d95b9ec036d 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/solution_get.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/solution_get.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -27,6 +28,7 @@ def main(): client = SelfHelpMgmtClient( credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", ) response = client.solution.get( diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/solution_update.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/solution_update.py deleted file mode 100644 index 82c9d41ff553..000000000000 --- a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/solution_update.py +++ /dev/null @@ -1,41 +0,0 @@ -# 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.selfhelp import SelfHelpMgmtClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-selfhelp -# USAGE - python solution_update.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 = SelfHelpMgmtClient( - credential=DefaultAzureCredential(), - ) - - response = client.solution.begin_update( - scope="subscriptions/mySubscription/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-rp", - solution_resource_name="SolutionResourceName1", - ).result() - print(response) - - -# x-ms-original-file: specification/help/resource-manager/Microsoft.Help/preview/2024-03-01-preview/examples/Solution_Update.json -if __name__ == "__main__": - main() diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/solution_warm_up.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/solution_warm_up.py index b1c906b39496..48399757209d 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/solution_warm_up.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/solution_warm_up.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -27,6 +28,7 @@ def main(): client = SelfHelpMgmtClient( credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", ) client.solution.warm_up( diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/troubleshooter_continue.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/troubleshooter_continue.py index 9703f5747755..cf0d50bcbe16 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/troubleshooter_continue.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/troubleshooter_continue.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -27,6 +28,7 @@ def main(): client = SelfHelpMgmtClient( credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", ) client.troubleshooters.continue_method( diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/troubleshooter_create.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/troubleshooter_create.py index 607149fdfb39..669a62b59df7 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/troubleshooter_create.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/troubleshooter_create.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -27,11 +28,20 @@ def main(): client = SelfHelpMgmtClient( credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", ) response = client.troubleshooters.create( scope="subscriptions/mySubscription/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-rp", troubleshooter_name="abf168ed-1b54-454a-86f6-e4b62253d3b1", + create_troubleshooter_request_body={ + "properties": { + "parameters": { + "ResourceURI": "subscriptions/mySubscription/resourcegroups/myresourceGroup/providers/Microsoft.KeyVault/vaults/test-keyvault-rp" + }, + "solutionId": "SampleTroubleshooterSolutionId", + } + }, ) print(response) diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/troubleshooter_end.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/troubleshooter_end.py index c0ce35c87685..328a6268e99e 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/troubleshooter_end.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/troubleshooter_end.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -27,6 +28,7 @@ def main(): client = SelfHelpMgmtClient( credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", ) client.troubleshooters.end( diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/troubleshooter_get.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/troubleshooter_get.py index ae806f4cc1f4..67e0391f416d 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/troubleshooter_get.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/troubleshooter_get.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -27,6 +28,7 @@ def main(): client = SelfHelpMgmtClient( credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", ) response = client.troubleshooters.get( diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/troubleshooter_restart.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/troubleshooter_restart.py index 36f1d301413b..ea9a5ca7e18d 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/troubleshooter_restart.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_samples/troubleshooter_restart.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -27,6 +28,7 @@ def main(): client = SelfHelpMgmtClient( credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", ) response = client.troubleshooters.restart( diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/conftest.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/conftest.py new file mode 100644 index 000000000000..c5e696b3d16c --- /dev/null +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/conftest.py @@ -0,0 +1,35 @@ +# 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() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + selfhelpmgmt_subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + selfhelpmgmt_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + selfhelpmgmt_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + selfhelpmgmt_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=selfhelpmgmt_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=selfhelpmgmt_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=selfhelpmgmt_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=selfhelpmgmt_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/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_check_name_availability_operations.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_check_name_availability_operations.py new file mode 100644 index 000000000000..9bbe71836aaa --- /dev/null +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_check_name_availability_operations.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.selfhelp import SelfHelpMgmtClient + +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 TestSelfHelpMgmtCheckNameAvailabilityOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SelfHelpMgmtClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_check_name_availability_check_availability(self, resource_group): + response = self.client.check_name_availability.check_availability( + scope="str", + api_version="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_check_name_availability_operations_async.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_check_name_availability_operations_async.py new file mode 100644 index 000000000000..896ae2a98a5c --- /dev/null +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_check_name_availability_operations_async.py @@ -0,0 +1,31 @@ +# 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.selfhelp.aio import SelfHelpMgmtClient + +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 TestSelfHelpMgmtCheckNameAvailabilityOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SelfHelpMgmtClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_check_name_availability_check_availability(self, resource_group): + response = await self.client.check_name_availability.check_availability( + scope="str", + api_version="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_diagnostics_operations.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_diagnostics_operations.py new file mode 100644 index 000000000000..4004e2defce2 --- /dev/null +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_diagnostics_operations.py @@ -0,0 +1,68 @@ +# 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.selfhelp import SelfHelpMgmtClient + +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 TestSelfHelpMgmtDiagnosticsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SelfHelpMgmtClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_diagnostics_get(self, resource_group): + response = self.client.diagnostics.get( + scope="str", + diagnostics_resource_name="str", + api_version="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_diagnostics_begin_create(self, resource_group): + response = self.client.diagnostics.begin_create( + scope="str", + diagnostics_resource_name="str", + diagnostic_resource_request={ + "acceptedAt": "str", + "diagnostics": [ + { + "error": {"code": "str", "details": [...], "message": "str", "type": "str"}, + "insights": [{"id": "str", "importanceLevel": "str", "results": "str", "title": "str"}], + "solutionId": "str", + "status": "str", + } + ], + "globalParameters": {"str": "str"}, + "id": "str", + "insights": [{"additionalParameters": {"str": "str"}, "solutionId": "str"}], + "name": "str", + "provisioningState": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2024-03-01-preview", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_diagnostics_operations_async.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_diagnostics_operations_async.py new file mode 100644 index 000000000000..c26e7bb70a9c --- /dev/null +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_diagnostics_operations_async.py @@ -0,0 +1,71 @@ +# 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.selfhelp.aio import SelfHelpMgmtClient + +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 TestSelfHelpMgmtDiagnosticsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SelfHelpMgmtClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_diagnostics_get(self, resource_group): + response = await self.client.diagnostics.get( + scope="str", + diagnostics_resource_name="str", + api_version="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_diagnostics_begin_create(self, resource_group): + response = await ( + await self.client.diagnostics.begin_create( + scope="str", + diagnostics_resource_name="str", + diagnostic_resource_request={ + "acceptedAt": "str", + "diagnostics": [ + { + "error": {"code": "str", "details": [...], "message": "str", "type": "str"}, + "insights": [{"id": "str", "importanceLevel": "str", "results": "str", "title": "str"}], + "solutionId": "str", + "status": "str", + } + ], + "globalParameters": {"str": "str"}, + "id": "str", + "insights": [{"additionalParameters": {"str": "str"}, "solutionId": "str"}], + "name": "str", + "provisioningState": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2024-03-01-preview", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_discovery_solution_nlp_operations.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_discovery_solution_nlp_operations.py new file mode 100644 index 000000000000..e611cc4dbeec --- /dev/null +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_discovery_solution_nlp_operations.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.selfhelp import SelfHelpMgmtClient + +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 TestSelfHelpMgmtDiscoverySolutionNLPOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SelfHelpMgmtClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_discovery_solution_nlp_discover_solutions(self, resource_group): + response = self.client.discovery_solution_nlp.discover_solutions( + discover_solution_request={ + "issueSummary": "str", + "additionalContext": "str", + "resourceId": "str", + "serviceId": "str", + }, + api_version="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_discovery_solution_nlp_discover_solutions_by_subscription(self, resource_group): + response = self.client.discovery_solution_nlp.discover_solutions_by_subscription( + discover_solution_request={ + "issueSummary": "str", + "additionalContext": "str", + "resourceId": "str", + "serviceId": "str", + }, + api_version="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_discovery_solution_nlp_operations_async.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_discovery_solution_nlp_operations_async.py new file mode 100644 index 000000000000..8847ed6b5da3 --- /dev/null +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_discovery_solution_nlp_operations_async.py @@ -0,0 +1,52 @@ +# 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.selfhelp.aio import SelfHelpMgmtClient + +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 TestSelfHelpMgmtDiscoverySolutionNLPOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SelfHelpMgmtClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_discovery_solution_nlp_discover_solutions(self, resource_group): + response = await self.client.discovery_solution_nlp.discover_solutions( + discover_solution_request={ + "issueSummary": "str", + "additionalContext": "str", + "resourceId": "str", + "serviceId": "str", + }, + api_version="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_discovery_solution_nlp_discover_solutions_by_subscription(self, resource_group): + response = await self.client.discovery_solution_nlp.discover_solutions_by_subscription( + discover_solution_request={ + "issueSummary": "str", + "additionalContext": "str", + "resourceId": "str", + "serviceId": "str", + }, + api_version="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_discovery_solution_operations.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_discovery_solution_operations.py new file mode 100644 index 000000000000..d8cfbbd7b6df --- /dev/null +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_discovery_solution_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.selfhelp import SelfHelpMgmtClient + +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 TestSelfHelpMgmtDiscoverySolutionOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SelfHelpMgmtClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_discovery_solution_list(self, resource_group): + response = self.client.discovery_solution.list( + api_version="2024-03-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_discovery_solution_operations_async.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_discovery_solution_operations_async.py new file mode 100644 index 000000000000..93cbcd9c2ca0 --- /dev/null +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_discovery_solution_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.selfhelp.aio import SelfHelpMgmtClient + +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 TestSelfHelpMgmtDiscoverySolutionOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SelfHelpMgmtClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_discovery_solution_list(self, resource_group): + response = self.client.discovery_solution.list( + api_version="2024-03-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_operations.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_operations.py new file mode 100644 index 000000000000..b43563ad851e --- /dev/null +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_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.selfhelp import SelfHelpMgmtClient + +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 TestSelfHelpMgmtOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SelfHelpMgmtClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_operations_list(self, resource_group): + response = self.client.operations.list( + api_version="2024-03-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_operations_async.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_operations_async.py new file mode 100644 index 000000000000..b39241a0ce67 --- /dev/null +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_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.selfhelp.aio import SelfHelpMgmtClient + +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 TestSelfHelpMgmtOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SelfHelpMgmtClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_operations_list(self, resource_group): + response = self.client.operations.list( + api_version="2024-03-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_simplified_solutions_operations.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_simplified_solutions_operations.py new file mode 100644 index 000000000000..5d9c00101c1c --- /dev/null +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_simplified_solutions_operations.py @@ -0,0 +1,62 @@ +# 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.selfhelp import SelfHelpMgmtClient + +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 TestSelfHelpMgmtSimplifiedSolutionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SelfHelpMgmtClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_simplified_solutions_get(self, resource_group): + response = self.client.simplified_solutions.get( + scope="str", + simplified_solutions_resource_name="str", + api_version="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_simplified_solutions_begin_create(self, resource_group): + response = self.client.simplified_solutions.begin_create( + scope="str", + simplified_solutions_resource_name="str", + simplified_solutions_request_body={ + "appendix": {"str": "str"}, + "content": "str", + "id": "str", + "name": "str", + "parameters": {"str": "str"}, + "provisioningState": "str", + "solutionId": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "title": "str", + "type": "str", + }, + api_version="2024-03-01-preview", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_simplified_solutions_operations_async.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_simplified_solutions_operations_async.py new file mode 100644 index 000000000000..b3f028a6d1f7 --- /dev/null +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_simplified_solutions_operations_async.py @@ -0,0 +1,65 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.selfhelp.aio import SelfHelpMgmtClient + +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 TestSelfHelpMgmtSimplifiedSolutionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SelfHelpMgmtClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_simplified_solutions_get(self, resource_group): + response = await self.client.simplified_solutions.get( + scope="str", + simplified_solutions_resource_name="str", + api_version="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_simplified_solutions_begin_create(self, resource_group): + response = await ( + await self.client.simplified_solutions.begin_create( + scope="str", + simplified_solutions_resource_name="str", + simplified_solutions_request_body={ + "appendix": {"str": "str"}, + "content": "str", + "id": "str", + "name": "str", + "parameters": {"str": "str"}, + "provisioningState": "str", + "solutionId": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "title": "str", + "type": "str", + }, + api_version="2024-03-01-preview", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_solution_operations.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_solution_operations.py new file mode 100644 index 000000000000..269c694b2611 --- /dev/null +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_solution_operations.py @@ -0,0 +1,282 @@ +# 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.selfhelp import SelfHelpMgmtClient + +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 TestSelfHelpMgmtSolutionOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SelfHelpMgmtClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_solution_get(self, resource_group): + response = self.client.solution.get( + scope="str", + solution_resource_name="str", + api_version="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_solution_begin_create(self, resource_group): + response = self.client.solution.begin_create( + scope="str", + solution_resource_name="str", + solution_request_body={ + "content": "str", + "id": "str", + "name": "str", + "parameters": {"str": "str"}, + "provisioningState": "str", + "replacementMaps": { + "diagnostics": [ + { + "estimatedCompletionTime": "str", + "insights": [{"id": "str", "importanceLevel": "str", "results": "str", "title": "str"}], + "replacementKey": "str", + "requiredParameters": ["str"], + "solutionId": "str", + "status": "str", + "statusDetails": "str", + } + ], + "metricsBasedCharts": [ + { + "aggregationType": "str", + "filterGroup": {"filter": [{"name": "str", "operator": "str", "values": "str"}]}, + "name": "str", + "replacementKey": "str", + "timeSpanDuration": "str", + "title": "str", + } + ], + "troubleshooters": [{"solutionId": "str", "summary": "str", "title": "str"}], + "videoGroups": [{"replacementKey": "str", "videos": [{"src": "str", "title": "str"}]}], + "videos": [{"replacementKey": "str", "src": "str", "title": "str"}], + "webResults": [ + { + "replacementKey": "str", + "searchResults": [ + { + "confidence": "str", + "content": "str", + "link": "str", + "rank": 0, + "resultType": "str", + "solutionId": "str", + "source": "str", + "title": "str", + } + ], + } + ], + }, + "sections": [ + { + "content": "str", + "replacementMaps": { + "diagnostics": [ + { + "estimatedCompletionTime": "str", + "insights": [ + {"id": "str", "importanceLevel": "str", "results": "str", "title": "str"} + ], + "replacementKey": "str", + "requiredParameters": ["str"], + "solutionId": "str", + "status": "str", + "statusDetails": "str", + } + ], + "metricsBasedCharts": [ + { + "aggregationType": "str", + "filterGroup": {"filter": [{"name": "str", "operator": "str", "values": "str"}]}, + "name": "str", + "replacementKey": "str", + "timeSpanDuration": "str", + "title": "str", + } + ], + "troubleshooters": [{"solutionId": "str", "summary": "str", "title": "str"}], + "videoGroups": [{"replacementKey": "str", "videos": [{"src": "str", "title": "str"}]}], + "videos": [{"replacementKey": "str", "src": "str", "title": "str"}], + "webResults": [ + { + "replacementKey": "str", + "searchResults": [ + { + "confidence": "str", + "content": "str", + "link": "str", + "rank": 0, + "resultType": "str", + "solutionId": "str", + "source": "str", + "title": "str", + } + ], + } + ], + }, + "title": "str", + } + ], + "solutionId": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "title": "str", + "triggerCriteria": [{"name": "str", "value": "str"}], + "type": "str", + }, + api_version="2024-03-01-preview", + ).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_solution_begin_update(self, resource_group): + response = self.client.solution.begin_update( + scope="str", + solution_resource_name="str", + solution_patch_request_body={ + "content": "str", + "parameters": {"str": "str"}, + "provisioningState": "str", + "replacementMaps": { + "diagnostics": [ + { + "estimatedCompletionTime": "str", + "insights": [{"id": "str", "importanceLevel": "str", "results": "str", "title": "str"}], + "replacementKey": "str", + "requiredParameters": ["str"], + "solutionId": "str", + "status": "str", + "statusDetails": "str", + } + ], + "metricsBasedCharts": [ + { + "aggregationType": "str", + "filterGroup": {"filter": [{"name": "str", "operator": "str", "values": "str"}]}, + "name": "str", + "replacementKey": "str", + "timeSpanDuration": "str", + "title": "str", + } + ], + "troubleshooters": [{"solutionId": "str", "summary": "str", "title": "str"}], + "videoGroups": [{"replacementKey": "str", "videos": [{"src": "str", "title": "str"}]}], + "videos": [{"replacementKey": "str", "src": "str", "title": "str"}], + "webResults": [ + { + "replacementKey": "str", + "searchResults": [ + { + "confidence": "str", + "content": "str", + "link": "str", + "rank": 0, + "resultType": "str", + "solutionId": "str", + "source": "str", + "title": "str", + } + ], + } + ], + }, + "sections": [ + { + "content": "str", + "replacementMaps": { + "diagnostics": [ + { + "estimatedCompletionTime": "str", + "insights": [ + {"id": "str", "importanceLevel": "str", "results": "str", "title": "str"} + ], + "replacementKey": "str", + "requiredParameters": ["str"], + "solutionId": "str", + "status": "str", + "statusDetails": "str", + } + ], + "metricsBasedCharts": [ + { + "aggregationType": "str", + "filterGroup": {"filter": [{"name": "str", "operator": "str", "values": "str"}]}, + "name": "str", + "replacementKey": "str", + "timeSpanDuration": "str", + "title": "str", + } + ], + "troubleshooters": [{"solutionId": "str", "summary": "str", "title": "str"}], + "videoGroups": [{"replacementKey": "str", "videos": [{"src": "str", "title": "str"}]}], + "videos": [{"replacementKey": "str", "src": "str", "title": "str"}], + "webResults": [ + { + "replacementKey": "str", + "searchResults": [ + { + "confidence": "str", + "content": "str", + "link": "str", + "rank": 0, + "resultType": "str", + "solutionId": "str", + "source": "str", + "title": "str", + } + ], + } + ], + }, + "title": "str", + } + ], + "solutionId": "str", + "title": "str", + "triggerCriteria": [{"name": "str", "value": "str"}], + }, + api_version="2024-03-01-preview", + ).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_solution_warm_up(self, resource_group): + response = self.client.solution.warm_up( + scope="str", + solution_resource_name="str", + api_version="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_solution_operations_async.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_solution_operations_async.py new file mode 100644 index 000000000000..920abaa2c19c --- /dev/null +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_solution_operations_async.py @@ -0,0 +1,291 @@ +# 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.selfhelp.aio import SelfHelpMgmtClient + +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 TestSelfHelpMgmtSolutionOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SelfHelpMgmtClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_solution_get(self, resource_group): + response = await self.client.solution.get( + scope="str", + solution_resource_name="str", + api_version="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_solution_begin_create(self, resource_group): + response = await ( + await self.client.solution.begin_create( + scope="str", + solution_resource_name="str", + solution_request_body={ + "content": "str", + "id": "str", + "name": "str", + "parameters": {"str": "str"}, + "provisioningState": "str", + "replacementMaps": { + "diagnostics": [ + { + "estimatedCompletionTime": "str", + "insights": [{"id": "str", "importanceLevel": "str", "results": "str", "title": "str"}], + "replacementKey": "str", + "requiredParameters": ["str"], + "solutionId": "str", + "status": "str", + "statusDetails": "str", + } + ], + "metricsBasedCharts": [ + { + "aggregationType": "str", + "filterGroup": {"filter": [{"name": "str", "operator": "str", "values": "str"}]}, + "name": "str", + "replacementKey": "str", + "timeSpanDuration": "str", + "title": "str", + } + ], + "troubleshooters": [{"solutionId": "str", "summary": "str", "title": "str"}], + "videoGroups": [{"replacementKey": "str", "videos": [{"src": "str", "title": "str"}]}], + "videos": [{"replacementKey": "str", "src": "str", "title": "str"}], + "webResults": [ + { + "replacementKey": "str", + "searchResults": [ + { + "confidence": "str", + "content": "str", + "link": "str", + "rank": 0, + "resultType": "str", + "solutionId": "str", + "source": "str", + "title": "str", + } + ], + } + ], + }, + "sections": [ + { + "content": "str", + "replacementMaps": { + "diagnostics": [ + { + "estimatedCompletionTime": "str", + "insights": [ + {"id": "str", "importanceLevel": "str", "results": "str", "title": "str"} + ], + "replacementKey": "str", + "requiredParameters": ["str"], + "solutionId": "str", + "status": "str", + "statusDetails": "str", + } + ], + "metricsBasedCharts": [ + { + "aggregationType": "str", + "filterGroup": { + "filter": [{"name": "str", "operator": "str", "values": "str"}] + }, + "name": "str", + "replacementKey": "str", + "timeSpanDuration": "str", + "title": "str", + } + ], + "troubleshooters": [{"solutionId": "str", "summary": "str", "title": "str"}], + "videoGroups": [{"replacementKey": "str", "videos": [{"src": "str", "title": "str"}]}], + "videos": [{"replacementKey": "str", "src": "str", "title": "str"}], + "webResults": [ + { + "replacementKey": "str", + "searchResults": [ + { + "confidence": "str", + "content": "str", + "link": "str", + "rank": 0, + "resultType": "str", + "solutionId": "str", + "source": "str", + "title": "str", + } + ], + } + ], + }, + "title": "str", + } + ], + "solutionId": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "title": "str", + "triggerCriteria": [{"name": "str", "value": "str"}], + "type": "str", + }, + api_version="2024-03-01-preview", + ) + ).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_solution_begin_update(self, resource_group): + response = await ( + await self.client.solution.begin_update( + scope="str", + solution_resource_name="str", + solution_patch_request_body={ + "content": "str", + "parameters": {"str": "str"}, + "provisioningState": "str", + "replacementMaps": { + "diagnostics": [ + { + "estimatedCompletionTime": "str", + "insights": [{"id": "str", "importanceLevel": "str", "results": "str", "title": "str"}], + "replacementKey": "str", + "requiredParameters": ["str"], + "solutionId": "str", + "status": "str", + "statusDetails": "str", + } + ], + "metricsBasedCharts": [ + { + "aggregationType": "str", + "filterGroup": {"filter": [{"name": "str", "operator": "str", "values": "str"}]}, + "name": "str", + "replacementKey": "str", + "timeSpanDuration": "str", + "title": "str", + } + ], + "troubleshooters": [{"solutionId": "str", "summary": "str", "title": "str"}], + "videoGroups": [{"replacementKey": "str", "videos": [{"src": "str", "title": "str"}]}], + "videos": [{"replacementKey": "str", "src": "str", "title": "str"}], + "webResults": [ + { + "replacementKey": "str", + "searchResults": [ + { + "confidence": "str", + "content": "str", + "link": "str", + "rank": 0, + "resultType": "str", + "solutionId": "str", + "source": "str", + "title": "str", + } + ], + } + ], + }, + "sections": [ + { + "content": "str", + "replacementMaps": { + "diagnostics": [ + { + "estimatedCompletionTime": "str", + "insights": [ + {"id": "str", "importanceLevel": "str", "results": "str", "title": "str"} + ], + "replacementKey": "str", + "requiredParameters": ["str"], + "solutionId": "str", + "status": "str", + "statusDetails": "str", + } + ], + "metricsBasedCharts": [ + { + "aggregationType": "str", + "filterGroup": { + "filter": [{"name": "str", "operator": "str", "values": "str"}] + }, + "name": "str", + "replacementKey": "str", + "timeSpanDuration": "str", + "title": "str", + } + ], + "troubleshooters": [{"solutionId": "str", "summary": "str", "title": "str"}], + "videoGroups": [{"replacementKey": "str", "videos": [{"src": "str", "title": "str"}]}], + "videos": [{"replacementKey": "str", "src": "str", "title": "str"}], + "webResults": [ + { + "replacementKey": "str", + "searchResults": [ + { + "confidence": "str", + "content": "str", + "link": "str", + "rank": 0, + "resultType": "str", + "solutionId": "str", + "source": "str", + "title": "str", + } + ], + } + ], + }, + "title": "str", + } + ], + "solutionId": "str", + "title": "str", + "triggerCriteria": [{"name": "str", "value": "str"}], + }, + api_version="2024-03-01-preview", + ) + ).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_solution_warm_up(self, resource_group): + response = await self.client.solution.warm_up( + scope="str", + solution_resource_name="str", + api_version="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_solution_self_help_operations.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_solution_self_help_operations.py new file mode 100644 index 000000000000..68d414be4b01 --- /dev/null +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_solution_self_help_operations.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.selfhelp import SelfHelpMgmtClient + +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 TestSelfHelpMgmtSolutionSelfHelpOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SelfHelpMgmtClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_solution_self_help_get(self, resource_group): + response = self.client.solution_self_help.get( + solution_id="str", + api_version="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_solution_self_help_operations_async.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_solution_self_help_operations_async.py new file mode 100644 index 000000000000..84599a4fce73 --- /dev/null +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_solution_self_help_operations_async.py @@ -0,0 +1,31 @@ +# 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.selfhelp.aio import SelfHelpMgmtClient + +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 TestSelfHelpMgmtSolutionSelfHelpOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SelfHelpMgmtClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_solution_self_help_get(self, resource_group): + response = await self.client.solution_self_help.get( + solution_id="str", + api_version="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_troubleshooters_operations.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_troubleshooters_operations.py new file mode 100644 index 000000000000..9268bc88aaa5 --- /dev/null +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_troubleshooters_operations.py @@ -0,0 +1,136 @@ +# 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.selfhelp import SelfHelpMgmtClient + +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 TestSelfHelpMgmtTroubleshootersOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SelfHelpMgmtClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_troubleshooters_get(self, resource_group): + response = self.client.troubleshooters.get( + scope="str", + troubleshooter_name="str", + api_version="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_troubleshooters_create(self, resource_group): + response = self.client.troubleshooters.create( + scope="str", + troubleshooter_name="str", + create_troubleshooter_request_body={ + "id": "str", + "name": "str", + "parameters": {"str": "str"}, + "provisioningState": "str", + "solutionId": "str", + "steps": [ + { + "automatedCheckResults": {"result": "str", "status": "str", "type": "str", "version": "str"}, + "description": "str", + "error": { + "additionalInfo": [{"info": {}, "type": "str"}], + "code": "str", + "details": [...], + "message": "str", + "target": "str", + }, + "executionStatus": "str", + "executionStatusDescription": "str", + "guidance": "str", + "id": "str", + "inputs": [ + { + "questionContent": "str", + "questionContentType": "str", + "questionId": "str", + "questionTitle": "str", + "questionType": "str", + "recommendedOption": "str", + "responseHint": "str", + "responseOptions": [{"key": "str", "value": "str"}], + "responseValidationProperties": { + "isRequired": bool, + "maxLength": 0, + "regex": "str", + "validationErrorMessage": "str", + "validationScope": "str", + }, + "selectedOptionValue": "str", + } + ], + "insights": [{"id": "str", "importanceLevel": "str", "results": "str", "title": "str"}], + "isLastStep": bool, + "title": "str", + "type": "str", + } + ], + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_troubleshooters_continue_method(self, resource_group): + response = self.client.troubleshooters.continue_method( + scope="str", + troubleshooter_name="str", + api_version="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_troubleshooters_end(self, resource_group): + response = self.client.troubleshooters.end( + scope="str", + troubleshooter_name="str", + api_version="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_troubleshooters_restart(self, resource_group): + response = self.client.troubleshooters.restart( + scope="str", + troubleshooter_name="str", + api_version="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_troubleshooters_operations_async.py b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_troubleshooters_operations_async.py new file mode 100644 index 000000000000..880016f32a18 --- /dev/null +++ b/sdk/selfhelp/azure-mgmt-selfhelp/generated_tests/test_self_help_mgmt_troubleshooters_operations_async.py @@ -0,0 +1,137 @@ +# 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.selfhelp.aio import SelfHelpMgmtClient + +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 TestSelfHelpMgmtTroubleshootersOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(SelfHelpMgmtClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_troubleshooters_get(self, resource_group): + response = await self.client.troubleshooters.get( + scope="str", + troubleshooter_name="str", + api_version="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_troubleshooters_create(self, resource_group): + response = await self.client.troubleshooters.create( + scope="str", + troubleshooter_name="str", + create_troubleshooter_request_body={ + "id": "str", + "name": "str", + "parameters": {"str": "str"}, + "provisioningState": "str", + "solutionId": "str", + "steps": [ + { + "automatedCheckResults": {"result": "str", "status": "str", "type": "str", "version": "str"}, + "description": "str", + "error": { + "additionalInfo": [{"info": {}, "type": "str"}], + "code": "str", + "details": [...], + "message": "str", + "target": "str", + }, + "executionStatus": "str", + "executionStatusDescription": "str", + "guidance": "str", + "id": "str", + "inputs": [ + { + "questionContent": "str", + "questionContentType": "str", + "questionId": "str", + "questionTitle": "str", + "questionType": "str", + "recommendedOption": "str", + "responseHint": "str", + "responseOptions": [{"key": "str", "value": "str"}], + "responseValidationProperties": { + "isRequired": bool, + "maxLength": 0, + "regex": "str", + "validationErrorMessage": "str", + "validationScope": "str", + }, + "selectedOptionValue": "str", + } + ], + "insights": [{"id": "str", "importanceLevel": "str", "results": "str", "title": "str"}], + "isLastStep": bool, + "title": "str", + "type": "str", + } + ], + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_troubleshooters_continue_method(self, resource_group): + response = await self.client.troubleshooters.continue_method( + scope="str", + troubleshooter_name="str", + api_version="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_troubleshooters_end(self, resource_group): + response = await self.client.troubleshooters.end( + scope="str", + troubleshooter_name="str", + api_version="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_troubleshooters_restart(self, resource_group): + response = await self.client.troubleshooters.restart( + scope="str", + troubleshooter_name="str", + api_version="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/selfhelp/azure-mgmt-selfhelp/setup.py b/sdk/selfhelp/azure-mgmt-selfhelp/setup.py index 831c7b6b977a..46ca36bdfc94 100644 --- a/sdk/selfhelp/azure-mgmt-selfhelp/setup.py +++ b/sdk/selfhelp/azure-mgmt-selfhelp/setup.py @@ -53,7 +53,6 @@ "Programming Language :: Python", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", @@ -75,8 +74,9 @@ }, install_requires=[ "isodate>=0.6.1", + "typing-extensions>=4.6.0", "azure-common>=1.1", - "azure-mgmt-core>=1.3.2", + "azure-mgmt-core>=1.5.0", ], - python_requires=">=3.8", + python_requires=">=3.9", )