diff --git a/sdk/consumption/azure-mgmt-consumption/CHANGELOG.md b/sdk/consumption/azure-mgmt-consumption/CHANGELOG.md index 728ecaec94e3..13ffd300b0c9 100644 --- a/sdk/consumption/azure-mgmt-consumption/CHANGELOG.md +++ b/sdk/consumption/azure-mgmt-consumption/CHANGELOG.md @@ -1,5 +1,56 @@ # Release History +## 11.0.0 (2025-05-12) + +### Features Added + + - Model `Balance` added property `overage_refund` + - Model `CreditSummary` added property `is_estimated_balance` + - Model `CreditSummary` added property `e_tag_properties_e_tag` + - Model `EventSummary` added property `charges_in_lot_currency` + - Model `EventSummary` added property `closed_balance_in_lot_currency` + - Model `EventSummary` added property `billing_account_id` + - Model `EventSummary` added property `billing_account_display_name` + - Model `EventSummary` added property `is_estimated_balance` + - Model `LegacyChargeSummary` added property `azure_marketplace_charges` + - Model `LegacyReservationRecommendation` added property `last_usage_date` + - Model `LegacyReservationRecommendation` added property `total_hours` + - Model `LegacyReservationRecommendationProperties` added property `last_usage_date` + - Model `LegacyReservationRecommendationProperties` added property `total_hours` + - Model `LegacySharedScopeReservationRecommendationProperties` added property `last_usage_date` + - Model `LegacySharedScopeReservationRecommendationProperties` added property `total_hours` + - Model `LegacySingleScopeReservationRecommendationProperties` added property `last_usage_date` + - Model `LegacySingleScopeReservationRecommendationProperties` added property `total_hours` + - Model `LotSummary` added property `is_estimated_balance` + - Model `LotSummary` added property `organization_type` + - Model `LotSummary` added property `used_amount` + - Model `ModernChargeSummary` added property `subscription_id` + - Model `ModernReservationRecommendation` added property `resource_type` + - Model `ModernReservationRecommendation` added property `last_usage_date` + - Model `ModernReservationRecommendation` added property `total_hours` + - Model `PriceSheetProperties` added property `savings_plan` + - Enum `Term` added member `P1_M` + - Added model `ErrorAdditionalInfo` + - Added model `ErrorDetail` + - Added model `ErrorResponseAutoGenerated` + - Added model `ModernReservationRecommendationProperties` + - Added model `ModernSharedScopeReservationRecommendationProperties` + - Added model `ModernSingleScopeReservationRecommendationProperties` + - Added model `OperationStatus` + - Added enum `OperationStatusType` + - Added enum `OrganizationType` + - Added model `SavingsPlan` + - Model `PriceSheetOperations` added method `begin_download_by_billing_account_period` + - Method `BudgetsOperations.create_or_update` has a new overload `def create_or_update(self: None, scope: str, budget_name: str, parameters: Budget, content_type: str)` + - Method `BudgetsOperations.create_or_update` has a new overload `def create_or_update(self: None, scope: str, budget_name: str, parameters: IO[bytes], content_type: str)` + +### Breaking Changes + + - Deleted or renamed enum value `BudgetOperatorType.IN_ENUM` + - Model `CreditSummary` deleted or renamed its instance variable `etag` + - Model `CreditSummary` deleted or renamed its instance variable `tags` + - Model `LegacyChargeSummary` deleted or renamed its instance variable `marketplace_charges` + ## 11.0.0b1 (2022-12-07) ### Features Added diff --git a/sdk/consumption/azure-mgmt-consumption/README.md b/sdk/consumption/azure-mgmt-consumption/README.md index d18e0a3b34fa..2e4dd3916171 100644 --- a/sdk/consumption/azure-mgmt-consumption/README.md +++ b/sdk/consumption/azure-mgmt-consumption/README.md @@ -1,28 +1,61 @@ # Microsoft Azure SDK for Python This is the Microsoft Azure Consumption Client Library. -This package has been tested with Python 3.7+. +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_ _Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691_ -# Usage +## Getting started +### Prerequisites -To learn how to use this package, see the [quickstart guide](https://aka.ms/azsdk/python/mgmt) - -For docs and references, see [Python SDK References](https://docs.microsoft.com/python/api/overview/azure/consumption) -Code samples for this package can be found at [Consumption](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com. -Additional code samples for different Azure services are available at [Samples Repo](https://github.com/Azure-Samples/azure-samples-python-management/tree/main/samples/consumption) +- Python 3.9+ is required to use this package. +- [Azure subscription](https://azure.microsoft.com/free/) +### Install the package -# Provide Feedback +```bash +pip install azure-mgmt-consumption +pip install azure-identity +``` -If you encounter any bugs or have suggestions, please file an issue in the -[Issues](https://github.com/Azure/azure-sdk-for-python/issues) -section of the project. +### Authentication + +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. +- `AZURE_CLIENT_SECRET` for Azure client secret. + +In addition, Azure subscription ID can be configured via environment variable `AZURE_SUBSCRIPTION_ID`. + +With above configuration, client can be authenticated by following code: + +```python +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient +import os +sub_id = os.getenv("AZURE_SUBSCRIPTION_ID") +client = ConsumptionManagementClient(credential=DefaultAzureCredential(), subscription_id=sub_id) +``` +## Examples +Code samples for this package can be found at: +- [Search Consumption](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com +- [Azure Python Mgmt SDK Samples Repo](https://aka.ms/azsdk/python/mgmt/samples) + + +## Troubleshooting + +## Next steps + +## Provide Feedback + +If you encounter any bugs or have suggestions, please file an issue in the +[Issues](https://github.com/Azure/azure-sdk-for-python/issues) +section of the project. diff --git a/sdk/consumption/azure-mgmt-consumption/_meta.json b/sdk/consumption/azure-mgmt-consumption/_meta.json index 2bff1506a305..8f91d422a009 100644 --- a/sdk/consumption/azure-mgmt-consumption/_meta.json +++ b/sdk/consumption/azure-mgmt-consumption/_meta.json @@ -1,11 +1,11 @@ { - "commit": "1be09531e4c6edeafde41d6562371566d39669e8", + "commit": "b2a6fabe6eb292817a8bcfc4581b4f25e7161582", "repository_url": "https://github.com/Azure/azure-rest-api-specs", - "autorest": "3.9.2", + "autorest": "3.10.2", "use": [ - "@autorest/python@6.2.7", - "@autorest/modelerfour@4.24.3" + "@autorest/python@6.34.1", + "@autorest/modelerfour@4.27.0" ], - "autorest_command": "autorest specification/consumption/resource-manager/readme.md --generate-sample=True --include-x-ms-examples-original-file=True --python --python-sdks-folder=/home/vsts/work/1/azure-sdk-for-python/sdk --use=@autorest/python@6.2.7 --use=@autorest/modelerfour@4.24.3 --version=3.9.2 --version-tolerant=False", + "autorest_command": "autorest specification/consumption/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/consumption/resource-manager/readme.md" } \ No newline at end of file diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/__init__.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/__init__.py index fcba3ab9cc05..6a5e55da8c5d 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/__init__.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/__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 ._consumption_management_client import ConsumptionManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._consumption_management_client import ConsumptionManagementClient # 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__ = [ "ConsumptionManagementClient", ] -__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/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_configuration.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_configuration.py index 013feb87a864..62a908332d0e 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_configuration.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_configuration.py @@ -6,26 +6,18 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports - if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class ConsumptionManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class ConsumptionManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for ConsumptionManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,14 +27,13 @@ class ConsumptionManagementClientConfiguration(Configuration): # pylint: disabl :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: Azure Subscription ID. Required. :type subscription_id: str - :keyword api_version: Api Version. Default value is "2021-10-01". Note that overriding this + :keyword api_version: Api Version. Default value is "2025-04-01". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(ConsumptionManagementClientConfiguration, self).__init__(**kwargs) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", "2021-10-01") + api_version: str = kwargs.pop("api_version", "2025-04-01") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -54,6 +45,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-consumption/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -62,9 +54,9 @@ def _configure(self, **kwargs: Any) -> None: self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: self.authentication_policy = ARMChallengeAuthenticationPolicy( diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_consumption_management_client.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_consumption_management_client.py index e4acefe4f418..f40ef7b3c03c 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_consumption_management_client.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_consumption_management_client.py @@ -7,14 +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 ConsumptionManagementClientConfiguration -from ._serialization import Deserializer, Serializer +from ._utils.serialization import Deserializer, Serializer from .operations import ( AggregatedCostOperations, BalancesOperations, @@ -36,14 +41,15 @@ ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class ConsumptionManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes +class ConsumptionManagementClient: # pylint: disable=too-many-instance-attributes """Consumption management client provides access to consumption resources for Azure Enterprise Subscriptions. + :ivar price_sheet: PriceSheetOperations operations + :vartype price_sheet: azure.mgmt.consumption.operations.PriceSheetOperations :ivar usage_details: UsageDetailsOperations operations :vartype usage_details: azure.mgmt.consumption.operations.UsageDetailsOperations :ivar marketplaces: MarketplacesOperations operations @@ -70,8 +76,6 @@ class ConsumptionManagementClient: # pylint: disable=client-accepts-api-version :ivar reservation_transactions: ReservationTransactionsOperations operations :vartype reservation_transactions: azure.mgmt.consumption.operations.ReservationTransactionsOperations - :ivar price_sheet: PriceSheetOperations operations - :vartype price_sheet: azure.mgmt.consumption.operations.PriceSheetOperations :ivar operations: Operations operations :vartype operations: azure.mgmt.consumption.operations.Operations :ivar aggregated_cost: AggregatedCostOperations operations @@ -86,29 +90,52 @@ class ConsumptionManagementClient: # pylint: disable=client-accepts-api-version :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: Azure Subscription ID. Required. :type subscription_id: str - :param base_url: Service URL. Default value is "https://management.azure.com". + :param base_url: Service URL. Default value is None. :type base_url: str - :keyword api_version: Api Version. Default value is "2021-10-01". Note that overriding this + :keyword api_version: Api Version. Default value is "2025-04-01". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. """ def __init__( - self, - credential: "TokenCredential", - subscription_id: str, - base_url: str = "https://management.azure.com", - **kwargs: Any + self, credential: "TokenCredential", subscription_id: str, base_url: Optional[str] = None, **kwargs: Any ) -> None: + _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 = ConsumptionManagementClientConfiguration( - credential=credential, subscription_id=subscription_id, **kwargs + credential=credential, subscription_id=subscription_id, credential_scopes=credential_scopes, **kwargs ) - self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + ARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: ARMPipelineClient = ARMPipelineClient(base_url=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.price_sheet = PriceSheetOperations(self._client, self._config, self._serialize, self._deserialize) self.usage_details = UsageDetailsOperations(self._client, self._config, self._serialize, self._deserialize) self.marketplaces = MarketplacesOperations(self._client, self._config, self._serialize, self._deserialize) self.budgets = BudgetsOperations(self._client, self._config, self._serialize, self._deserialize) @@ -130,14 +157,13 @@ def __init__( self.reservation_transactions = ReservationTransactionsOperations( self._client, self._config, self._serialize, self._deserialize ) - self.price_sheet = PriceSheetOperations(self._client, self._config, self._serialize, self._deserialize) self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) self.aggregated_cost = AggregatedCostOperations(self._client, self._config, self._serialize, self._deserialize) self.events = EventsOperations(self._client, self._config, self._serialize, self._deserialize) self.lots = LotsOperations(self._client, self._config, self._serialize, self._deserialize) self.credits = CreditsOperations(self._client, self._config, self._serialize, self._deserialize) - def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -157,14 +183,14 @@ def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: request_copy = deepcopy(request) request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore def close(self) -> None: self._client.close() - def __enter__(self) -> "ConsumptionManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self - def __exit__(self, *exc_details) -> None: + def __exit__(self, *exc_details: Any) -> None: self._client.__exit__(*exc_details) diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_patch.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_patch.py index f99e77fef986..17dbc073e01b 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_patch.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_patch.py @@ -25,6 +25,7 @@ # # -------------------------------------------------------------------------- + # This file is used for handwritten extensions to the generated code. Example: # https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md def patch_sdk(): diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_utils/__init__.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_utils/__init__.py new file mode 100644 index 000000000000..0af9b28f6607 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_utils/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_serialization.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_utils/serialization.py similarity index 77% rename from sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_serialization.py rename to sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_utils/serialization.py index 2c170e28dbca..f5187701d7be 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_serialization.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_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 @@ -38,7 +20,19 @@ import re import sys import codecs -from typing import Optional, Union, AnyStr, IO, Mapping +from typing import ( + Dict, + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + MutableMapping, + List, +) try: from urllib import quote # type: ignore @@ -47,13 +41,15 @@ import xml.etree.ElementTree as ET import isodate # type: ignore +from typing_extensions import Self -from typing import Dict, Any, cast - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") +JSON = MutableMapping[str, Any] + class RawDeserializer: @@ -74,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 @@ -95,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: @@ -107,7 +105,7 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: pass return ET.fromstring(data_as_str) # nosec - except ET.ParseError: + except ET.ParseError as err: # It might be because the server has an issue, and returned JSON with # content-type XML.... # So let's try a JSON load, and if it's still broken @@ -126,7 +124,9 @@ def _json_attemp(data): # The function hack is because Py2.7 messes up with exception # context otherwise. _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") + raise DeserializationError("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) @classmethod @@ -136,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 @@ -153,13 +158,6 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], return None -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str - unicode_str = str - _LOGGER = logging.getLogger(__name__) try: @@ -167,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: # 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): @@ -287,25 +243,35 @@ def __init__(self, **kwargs): else: setattr(self, k, kwargs[k]) - def __eq__(self, other): - """Compare objects by comparing all attributes.""" + def __eq__(self, other: Any) -> bool: + """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): - """Compare objects by comparing all attributes.""" + def __ne__(self, other: Any) -> bool: + """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): + def __str__(self) -> str: return str(self.__dict__) @classmethod - def enable_additional_properties_sending(cls): + def enable_additional_properties_sending(cls) -> None: cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} @classmethod - def is_xml_model(cls): + def is_xml_model(cls) -> bool: try: cls._xml_map # type: ignore except AttributeError: @@ -314,7 +280,11 @@ def is_xml_model(cls): @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: @@ -322,8 +292,8 @@ def _create_xml_node(cls): return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) - def serialize(self, keep_readonly=False, **kwargs): - """Return the JSON that would be sent to azure from this model. + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. @@ -334,10 +304,17 @@ def serialize(self, keep_readonly=False, **kwargs): :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) - def as_dict(self, keep_readonly=True, key_transformer=attribute_transformer, **kwargs): - """Return a dict that can be JSONify using json.dump. + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, Dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. Advanced usage might optionally use a callback as parameter: @@ -363,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) + 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): @@ -378,25 +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, data, content_type=None): + 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) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod - def from_dict(cls, data, key_extractors=None, content_type=None): + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> Self: """Parse a dict using given key extractor return a model. By default consider key @@ -404,13 +390,15 @@ def from_dict(cls, data, key_extractors=None, content_type=None): 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 = ( - [ + deserializer.key_extractors = ( # type: ignore + [ # type: ignore attribute_key_case_insensitive_extractor, rest_key_case_insensitive_extractor, last_rest_key_case_insensitive_extractor, @@ -418,7 +406,7 @@ def from_dict(cls, data, key_extractors=None, content_type=None): if key_extractors is None else key_extractors ) - return deserializer(cls.__name__, data, content_type=content_type) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod def _flatten_subtype(cls, key, objects): @@ -426,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: @@ -479,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"} @@ -518,7 +512,7 @@ class Serializer(object): "multiple": lambda x, y: x % y != 0, } - def __init__(self, classes=None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.serialize_type = { "iso-8601": Serializer.serialize_iso, "rfc-1123": Serializer.serialize_rfc, @@ -534,17 +528,20 @@ def __init__(self, classes=None): "[]": self.serialize_iter, "{}": self.serialize_dict, } - self.dependencies = dict(classes) if classes else {} + self.dependencies: Dict[str, type] = dict(classes) if classes else {} self.key_transformer = full_restapi_key_transformer self.client_side_validation = True - 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) @@ -570,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"] == "": @@ -602,7 +601,7 @@ def _serialize(self, target_obj, data_type=None, **kwargs): if xml_desc.get("attr", False): if xml_ns: ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) serialized.set(xml_name, new_attr) # type: ignore continue if xml_desc.get("text", False): @@ -611,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 @@ -622,12 +622,11 @@ def _serialize(self, target_obj, data_type=None, **kwargs): else: # That's a basic type # Integrate namespace if necessary local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) + local_node.text = str(new_attr) serialized.append(local_node) # type: ignore else: # JSON for k in reversed(keys): # type: ignore - unflattened = {k: new_attr} - new_attr = unflattened + new_attr = {k: new_attr} _new_attr = new_attr _serialized = serialized @@ -636,28 +635,29 @@ def _serialize(self, target_obj, data_type=None, **kwargs): _serialized.update(_new_attr) # type: ignore _new_attr = _new_attr[k] # type: ignore _serialized = _serialized[k] - except ValueError: - continue + except ValueError as err: + if isinstance(err, SerializationError): + raise except (AttributeError, KeyError, TypeError) as err: msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized + raise SerializationError(msg) from err + 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 - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) try: is_xml_model_serialization = kwargs["is_xml"] except KeyError: @@ -681,20 +681,22 @@ 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_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) + raise SerializationError("Unable to build a model: " + str(err)) from err return self._serialize(data, data_type, **kwargs) 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) @@ -703,30 +705,30 @@ def url(self, name, data, data_type, **kwargs): if kwargs.get("skip_quote") is True: output = str(output) + output = output.replace("{", quote("{")).replace("}", quote("}")) else: output = quote(str(output), safe="") - except SerializationError: - 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. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None + :rtype: str, list + :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 if data_type.startswith("["): internal_data_type = data_type[1:-1] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) # Not a list, regular serialization output = self.serialize_data(data, data_type, **kwargs) @@ -736,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]"]: @@ -757,30 +760,31 @@ 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") try: + if data is CoreNull: + return None 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 @@ -795,12 +799,11 @@ def serialize_data(self, data, data_type, **kwargs): except (ValueError, TypeError) as err: msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) + raise SerializationError(msg.format(data, data_type)) from err + 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 @@ -816,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 @@ -846,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. @@ -857,13 +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'. + Defaults to False. :rtype: list, str + :return: serialized iterable """ if isinstance(data, str): raise SerializationError("Refuse str type as a valid iter type.") @@ -875,9 +880,14 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): for d in data: try: serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: + except ValueError as err: + if isinstance(err, SerializationError): + raise serialized.append(None) + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + if div: serialized = ["" if s is None else str(s) for s in serialized] serialized = div.join(serialized) @@ -913,16 +923,17 @@ 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 = {} for key, value in attr.items(): try: serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: + except ValueError as err: + if isinstance(err, SerializationError): + raise serialized[self.serialize_unicode(key)] = None if "xml" in serialization_ctxt: @@ -937,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 @@ -945,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 @@ -955,7 +967,7 @@ def serialize_object(self, attr, **kwargs): return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) if obj_type is _long_type: return self.serialize_long(attr) - if obj_type is unicode_str: + if obj_type is str: return self.serialize_unicode(attr) if obj_type is datetime.datetime: return self.serialize_iso(attr) @@ -969,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: @@ -1000,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) @@ -1057,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) @@ -1071,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], @@ -1107,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) @@ -1132,19 +1153,20 @@ def serialize_iso(attr, **kwargs): return date + microseconds + "Z" except (ValueError, OverflowError) as err: msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) + raise SerializationError(msg) from err except AttributeError as err: msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) + raise TypeError(msg) from err @staticmethod - def serialize_unix(attr, **kwargs): + 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 @@ -1152,16 +1174,17 @@ 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 while "." in key: - dict_keys = _FLATTEN.split(key) + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(List[str], _FLATTEN.split(key)) if len(dict_keys) == 1: key = _decode_attribute_map_key(dict_keys[0]) break @@ -1170,14 +1193,15 @@ def rest_key_extractor(attr, attr_desc, data): if working_data is None: # If at any point while following flatten JSON path see None, it means # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 return None key = ".".join(dict_keys[1:]) 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 @@ -1191,7 +1215,6 @@ def rest_key_case_insensitive_extractor(attr, attr_desc, data): if working_data is None: # If at any point while following flatten JSON path see None, it means # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 return None key = ".".join(dict_keys[1:]) @@ -1199,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) @@ -1242,11 +1277,11 @@ def _extract_name_from_internal_type(internal_type): xml_name = internal_type_xml_map.get("name", internal_type.__name__) xml_ns = internal_type_xml_map.get("ns", None) if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) return xml_name -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 @@ -1266,7 +1301,7 @@ def xml_key_extractor(attr, attr_desc, data): # Integrate namespace if necessary xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) # If it's an attribute, that's simple if xml_desc.get("attr", False): @@ -1298,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: @@ -1321,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. @@ -1330,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=None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.deserialize_type = { "iso-8601": Deserializer.deserialize_iso, "rfc-1123": Deserializer.deserialize_rfc, @@ -1352,7 +1386,7 @@ def __init__(self, classes=None): "duration": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } - self.dependencies = dict(classes) if classes else {} + self.dependencies: Dict[str, type] = dict(classes) if classes else {} self.key_extractors = [rest_key_extractor, xml_key_extractor] # Additional properties only works if the "rest_key_extractor" is used to # extract the keys. Making it to work whatever the key extractor is too much @@ -1368,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) @@ -1405,15 +1441,15 @@ def _deserialize(self, target_obj, data): response, class_name = self._classify_target(target_obj, data) - if isinstance(response, basestring): + if isinstance(response, str): return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): + 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"... @@ -1442,10 +1478,9 @@ def _deserialize(self, target_obj, data): d_attrs[attr] = value except (AttributeError, TypeError, KeyError) as err: msg = "Unable to deserialize to object: " + class_name # type: ignore - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) + raise DeserializationError(msg) from err + 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: @@ -1471,22 +1506,24 @@ def _classify_target(self, target, data): Once classification has been determined, initialize object. :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. + :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple """ if target is None: return None, None - if isinstance(target, basestring): + if isinstance(target, str): try: target = self.dependencies[target] except KeyError: return target, target try: - target = target._classify(data, self.dependencies) + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access except AttributeError: pass # Target is not a Model, no classify - return target, target.__class__.__name__ + return target, target.__class__.__name__ # type: ignore def failsafe_deserialize(self, target_obj, data, content_type=None): """Ignores any errors encountered in deserialization, @@ -1496,12 +1533,14 @@ def failsafe_deserialize(self, target_obj, data, content_type=None): a deserialization error. :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. + :param str/dict data: The response data to deserialize. :param str content_type: Swagger "produces" if available. + :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 ) @@ -1519,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", {}) @@ -1539,31 +1580,42 @@ def _unpack_content(raw_data, content_type=None): if hasattr(raw_data, "_content_consumed"): return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore return raw_data 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(): @@ -1572,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 @@ -1594,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) @@ -1613,15 +1670,15 @@ def deserialize_data(self, data, data_type): except (ValueError, TypeError, AttributeError) as err: msg = "Unable to deserialize response data." msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) + raise DeserializationError(msg) from err + 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: @@ -1638,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): @@ -1648,20 +1706,21 @@ 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 if isinstance(attr, ET.Element): # Do no recurse on XML, just return the tree as-is return attr - if isinstance(attr, basestring): + if isinstance(attr, str): return self.deserialize_basic(attr, "str") obj_type = type(attr) if obj_type in self.basic_types: @@ -1687,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 @@ -1699,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 @@ -1710,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, basestring): + 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): @@ -1735,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, @@ -1748,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): @@ -1761,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: @@ -1769,12 +1828,11 @@ def deserialize_enum(data, enum_obj): data = data.value if isinstance(data, int): # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 try: return list(enum_obj.__members__.values())[data] - except IndexError: + 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: @@ -1790,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 @@ -1802,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 @@ -1817,24 +1877,26 @@ 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 try: - return decimal.Decimal(attr) # type: ignore + return decimal.Decimal(str(attr)) # type: ignore except decimal.DecimalException as err: msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err @staticmethod 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 @@ -1845,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 @@ -1854,32 +1917,33 @@ def deserialize_duration(attr): duration = isodate.parse_duration(attr) except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration + raise DeserializationError(msg) from err + 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 if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore raise DeserializationError("Date must have only digits and -. Received: %s" % attr) # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) @staticmethod def deserialize_time(attr): """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 @@ -1892,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_with_traceback(DeserializationError, msg, err) - else: - return date_obj + raise DeserializationError(msg) from err + 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 @@ -1943,9 +2008,8 @@ def deserialize_iso(attr): raise OverflowError("Hit max or min date") except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj + raise DeserializationError(msg) from err + return date_obj @staticmethod def deserialize_unix(attr): @@ -1953,15 +2017,16 @@ 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 try: + attr = int(attr) date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) except ValueError as err: msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj + raise DeserializationError(msg) from err + return date_obj diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_vendor.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_vendor.py deleted file mode 100644 index 9aad73fc743e..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_vendor.py +++ /dev/null @@ -1,27 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) 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 - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - formatted_components = template.split("/") - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_version.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_version.py index 75a1436b862f..ae876c37f272 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_version.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "11.0.0b1" +VERSION = "11.0.0" diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/__init__.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/__init__.py index 9cde86302a9b..01196d181627 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/__init__.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/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 ._consumption_management_client import ConsumptionManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._consumption_management_client import ConsumptionManagementClient # 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__ = [ "ConsumptionManagementClient", ] -__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/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/_configuration.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/_configuration.py index 92d21cc93087..94b599d09488 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/_configuration.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/_configuration.py @@ -6,26 +6,18 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports - if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class ConsumptionManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class ConsumptionManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for ConsumptionManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,14 +27,13 @@ class ConsumptionManagementClientConfiguration(Configuration): # pylint: disabl :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: Azure Subscription ID. Required. :type subscription_id: str - :keyword api_version: Api Version. Default value is "2021-10-01". Note that overriding this + :keyword api_version: Api Version. Default value is "2025-04-01". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(ConsumptionManagementClientConfiguration, self).__init__(**kwargs) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", "2021-10-01") + api_version: str = kwargs.pop("api_version", "2025-04-01") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -54,6 +45,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-consumption/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -62,9 +54,9 @@ def _configure(self, **kwargs: Any) -> None: self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/_consumption_management_client.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/_consumption_management_client.py index bbfde391df8d..1405094b60f6 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/_consumption_management_client.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/_consumption_management_client.py @@ -7,13 +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 ConsumptionManagementClientConfiguration from .operations import ( AggregatedCostOperations, @@ -36,14 +41,15 @@ ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class ConsumptionManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes +class ConsumptionManagementClient: # pylint: disable=too-many-instance-attributes """Consumption management client provides access to consumption resources for Azure Enterprise Subscriptions. + :ivar price_sheet: PriceSheetOperations operations + :vartype price_sheet: azure.mgmt.consumption.aio.operations.PriceSheetOperations :ivar usage_details: UsageDetailsOperations operations :vartype usage_details: azure.mgmt.consumption.aio.operations.UsageDetailsOperations :ivar marketplaces: MarketplacesOperations operations @@ -71,8 +77,6 @@ class ConsumptionManagementClient: # pylint: disable=client-accepts-api-version :ivar reservation_transactions: ReservationTransactionsOperations operations :vartype reservation_transactions: azure.mgmt.consumption.aio.operations.ReservationTransactionsOperations - :ivar price_sheet: PriceSheetOperations operations - :vartype price_sheet: azure.mgmt.consumption.aio.operations.PriceSheetOperations :ivar operations: Operations operations :vartype operations: azure.mgmt.consumption.aio.operations.Operations :ivar aggregated_cost: AggregatedCostOperations operations @@ -87,29 +91,54 @@ class ConsumptionManagementClient: # pylint: disable=client-accepts-api-version :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: Azure Subscription ID. Required. :type subscription_id: str - :param base_url: Service URL. Default value is "https://management.azure.com". + :param base_url: Service URL. Default value is None. :type base_url: str - :keyword api_version: Api Version. Default value is "2021-10-01". Note that overriding this + :keyword api_version: Api Version. Default value is "2025-04-01". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. """ def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - base_url: str = "https://management.azure.com", - **kwargs: Any + self, credential: "AsyncTokenCredential", subscription_id: str, base_url: Optional[str] = None, **kwargs: Any ) -> None: + _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 = ConsumptionManagementClientConfiguration( - credential=credential, subscription_id=subscription_id, **kwargs + credential=credential, subscription_id=subscription_id, credential_scopes=credential_scopes, **kwargs + ) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + AsyncARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient( + base_url=cast(str, base_url), policies=_policies, **kwargs ) - self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False + self.price_sheet = PriceSheetOperations(self._client, self._config, self._serialize, self._deserialize) self.usage_details = UsageDetailsOperations(self._client, self._config, self._serialize, self._deserialize) self.marketplaces = MarketplacesOperations(self._client, self._config, self._serialize, self._deserialize) self.budgets = BudgetsOperations(self._client, self._config, self._serialize, self._deserialize) @@ -131,14 +160,15 @@ def __init__( self.reservation_transactions = ReservationTransactionsOperations( self._client, self._config, self._serialize, self._deserialize ) - self.price_sheet = PriceSheetOperations(self._client, self._config, self._serialize, self._deserialize) self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) self.aggregated_cost = AggregatedCostOperations(self._client, self._config, self._serialize, self._deserialize) self.events = EventsOperations(self._client, self._config, self._serialize, self._deserialize) self.lots = LotsOperations(self._client, self._config, self._serialize, self._deserialize) self.credits = CreditsOperations(self._client, self._config, self._serialize, self._deserialize) - def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + def _send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -158,14 +188,14 @@ def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncH request_copy = deepcopy(request) request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore async def close(self) -> None: await self._client.close() - async def __aenter__(self) -> "ConsumptionManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self - async def __aexit__(self, *exc_details) -> None: + async def __aexit__(self, *exc_details: Any) -> None: await self._client.__aexit__(*exc_details) diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/_patch.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/_patch.py index f99e77fef986..17dbc073e01b 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/_patch.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/_patch.py @@ -25,6 +25,7 @@ # # -------------------------------------------------------------------------- + # This file is used for handwritten extensions to the generated code. Example: # https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md def patch_sdk(): diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/__init__.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/__init__.py index 33de5eb645bc..42a8462b32ee 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/__init__.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/__init__.py @@ -5,30 +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 ._usage_details_operations import UsageDetailsOperations -from ._marketplaces_operations import MarketplacesOperations -from ._budgets_operations import BudgetsOperations -from ._tags_operations import TagsOperations -from ._charges_operations import ChargesOperations -from ._balances_operations import BalancesOperations -from ._reservations_summaries_operations import ReservationsSummariesOperations -from ._reservations_details_operations import ReservationsDetailsOperations -from ._reservation_recommendations_operations import ReservationRecommendationsOperations -from ._reservation_recommendation_details_operations import ReservationRecommendationDetailsOperations -from ._reservation_transactions_operations import ReservationTransactionsOperations -from ._price_sheet_operations import PriceSheetOperations -from ._operations import Operations -from ._aggregated_cost_operations import AggregatedCostOperations -from ._events_operations import EventsOperations -from ._lots_operations import LotsOperations -from ._credits_operations import CreditsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._price_sheet_operations import PriceSheetOperations # type: ignore +from ._usage_details_operations import UsageDetailsOperations # type: ignore +from ._marketplaces_operations import MarketplacesOperations # type: ignore +from ._budgets_operations import BudgetsOperations # type: ignore +from ._tags_operations import TagsOperations # type: ignore +from ._charges_operations import ChargesOperations # type: ignore +from ._balances_operations import BalancesOperations # type: ignore +from ._reservations_summaries_operations import ReservationsSummariesOperations # type: ignore +from ._reservations_details_operations import ReservationsDetailsOperations # type: ignore +from ._reservation_recommendations_operations import ReservationRecommendationsOperations # type: ignore +from ._reservation_recommendation_details_operations import ReservationRecommendationDetailsOperations # type: ignore +from ._reservation_transactions_operations import ReservationTransactionsOperations # type: ignore +from ._operations import Operations # type: ignore +from ._aggregated_cost_operations import AggregatedCostOperations # type: ignore +from ._events_operations import EventsOperations # type: ignore +from ._lots_operations import LotsOperations # type: ignore +from ._credits_operations import CreditsOperations # 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__ = [ + "PriceSheetOperations", "UsageDetailsOperations", "MarketplacesOperations", "BudgetsOperations", @@ -40,12 +47,11 @@ "ReservationRecommendationsOperations", "ReservationRecommendationDetailsOperations", "ReservationTransactionsOperations", - "PriceSheetOperations", "Operations", "AggregatedCostOperations", "EventsOperations", "LotsOperations", "CreditsOperations", ] -__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/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_aggregated_cost_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_aggregated_cost_operations.py index 719fcf0fd3ef..bbaadc364f36 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_aggregated_cost_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_aggregated_cost_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,9 +5,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 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,23 +18,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._aggregated_cost_operations import ( build_get_by_management_group_request, build_get_for_billing_period_by_management_group_request, ) +from .._configuration import ConsumptionManagementClientConfiguration -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -53,10 +49,12 @@ class AggregatedCostOperations: 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: ConsumptionManagementClientConfiguration = ( + 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_by_management_group( @@ -65,6 +63,9 @@ async def get_by_management_group( """Provides the aggregate cost of a management group and all child management groups by current billing period. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param management_group_id: Azure Management Group ID. Required. :type management_group_id: str :param filter: May be used to filter aggregated cost by properties/usageStart (Utc time), @@ -72,12 +73,11 @@ async def get_by_management_group( does not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair string where key and value is separated by a colon (:). Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ManagementGroupAggregatedCostResult or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.ManagementGroupAggregatedCostResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -88,61 +88,56 @@ async def get_by_management_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ManagementGroupAggregatedCostResult] = kwargs.pop("cls", None) - request = build_get_by_management_group_request( + _request = build_get_by_management_group_request( management_group_id=management_group_id, filter=filter, api_version=api_version, - template_url=self.get_by_management_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ManagementGroupAggregatedCostResult", pipeline_response) + deserialized = self._deserialize("ManagementGroupAggregatedCostResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_by_management_group.metadata = { - "url": "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Consumption/aggregatedcost" - } + return deserialized # type: ignore @distributed_trace_async - async def get_for_billing_period_by_management_group( + async def get_for_billing_period_by_management_group( # pylint: disable=name-too-long self, management_group_id: str, billing_period_name: str, **kwargs: Any ) -> _models.ManagementGroupAggregatedCostResult: """Provides the aggregate cost of a management group and all child management groups by specified billing period. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param management_group_id: Azure Management Group ID. Required. :type management_group_id: str :param billing_period_name: Billing Period Name. Required. :type billing_period_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ManagementGroupAggregatedCostResult or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.ManagementGroupAggregatedCostResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -153,40 +148,33 @@ async def get_for_billing_period_by_management_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ManagementGroupAggregatedCostResult] = kwargs.pop("cls", None) - request = build_get_for_billing_period_by_management_group_request( + _request = build_get_for_billing_period_by_management_group_request( management_group_id=management_group_id, billing_period_name=billing_period_name, api_version=api_version, - template_url=self.get_for_billing_period_by_management_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ManagementGroupAggregatedCostResult", pipeline_response) + deserialized = self._deserialize("ManagementGroupAggregatedCostResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_for_billing_period_by_management_group.metadata = { - "url": "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/aggregatedCost" - } + return deserialized # type: ignore diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_balances_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_balances_operations.py index bec3e86e7d3d..b03098c8ba83 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_balances_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_balances_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,9 +5,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 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,23 +18,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._balances_operations import ( build_get_by_billing_account_request, build_get_for_billing_period_by_billing_account_request, ) +from .._configuration import ConsumptionManagementClientConfiguration -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -53,24 +49,28 @@ class BalancesOperations: 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: ConsumptionManagementClientConfiguration = ( + 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_by_billing_account(self, billing_account_id: str, **kwargs: Any) -> _models.Balance: """Gets the balances for a scope by billingAccountId. Balances are available via this API only for May 1, 2014 or later. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Balance or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.Balance :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -81,60 +81,55 @@ async def get_by_billing_account(self, billing_account_id: str, **kwargs: Any) - _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Balance] = kwargs.pop("cls", None) - request = build_get_by_billing_account_request( + _request = build_get_by_billing_account_request( billing_account_id=billing_account_id, api_version=api_version, - template_url=self.get_by_billing_account.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Balance", pipeline_response) + deserialized = self._deserialize("Balance", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_by_billing_account.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/balances" - } + return deserialized # type: ignore @distributed_trace_async - async def get_for_billing_period_by_billing_account( + async def get_for_billing_period_by_billing_account( # pylint: disable=name-too-long self, billing_account_id: str, billing_period_name: str, **kwargs: Any ) -> _models.Balance: """Gets the balances for a scope by billing period and billingAccountId. Balances are available via this API only for May 1, 2014 or later. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str :param billing_period_name: Billing Period Name. Required. :type billing_period_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Balance or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.Balance :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -145,40 +140,33 @@ async def get_for_billing_period_by_billing_account( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Balance] = kwargs.pop("cls", None) - request = build_get_for_billing_period_by_billing_account_request( + _request = build_get_for_billing_period_by_billing_account_request( billing_account_id=billing_account_id, billing_period_name=billing_period_name, api_version=api_version, - template_url=self.get_for_billing_period_by_billing_account.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Balance", pipeline_response) + deserialized = self._deserialize("Balance", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_for_billing_period_by_billing_account.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/balances" - } + return deserialized # type: ignore diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_budgets_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_budgets_operations.py index eefdd10b3308..438c82be799d 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_budgets_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_budgets_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +5,12 @@ # 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 collections.abc import MutableMapping +from io import IOBase from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse +from azure.core import AsyncPipelineClient from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, @@ -20,26 +21,22 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request +from ..._utils.serialization import Deserializer, Serializer from ...operations._budgets_operations import ( build_create_or_update_request, build_delete_request, build_get_request, build_list_request, ) +from .._configuration import ConsumptionManagementClientConfiguration -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -58,15 +55,20 @@ class BudgetsOperations: 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: ConsumptionManagementClientConfiguration = ( + 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, scope: str, **kwargs: Any) -> AsyncIterable["_models.Budget"]: """Lists all budgets for the defined scope. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param scope: The scope associated with budget operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, @@ -79,10 +81,9 @@ def list(self, scope: str, **kwargs: Any) -> AsyncIterable["_models.Budget"]: scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' for billingProfile scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope. Required. :type scope: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Budget or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.Budget] :raises ~azure.core.exceptions.HttpResponseError: @@ -90,12 +91,10 @@ def list(self, scope: str, **kwargs: Any) -> AsyncIterable["_models.Budget"]: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BudgetsListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -106,15 +105,13 @@ def list(self, scope: str, **kwargs: Any) -> AsyncIterable["_models.Budget"]: def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( scope=scope, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -126,13 +123,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("BudgetsListResult", pipeline_response) @@ -142,28 +138,30 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) - list.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/budgets"} - @distributed_trace_async async def get(self, scope: str, budget_name: str, **kwargs: Any) -> _models.Budget: """Gets the budget for the scope by budget name. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param scope: The scope associated with budget operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, @@ -176,17 +174,16 @@ async def get(self, scope: str, budget_name: str, **kwargs: Any) -> _models.Budg scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' for billingProfile scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope. Required. :type scope: str :param budget_name: Budget Name. Required. :type budget_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Budget or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.Budget :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -197,41 +194,36 @@ async def get(self, scope: str, budget_name: str, **kwargs: Any) -> _models.Budg _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Budget] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( scope=scope, budget_name=budget_name, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Budget", pipeline_response) + deserialized = self._deserialize("Budget", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/budgets/{budgetName}"} + return deserialized # type: ignore @overload async def create_or_update( @@ -247,6 +239,9 @@ async def create_or_update( form of concurrency control. To obtain the latest eTag for a given budget, perform a get operation prior to your put operation. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param scope: The scope associated with budget operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, @@ -259,7 +254,7 @@ async def create_or_update( scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' for billingProfile scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope. Required. :type scope: str :param budget_name: Budget Name. Required. @@ -269,7 +264,6 @@ async def create_or_update( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Budget or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.Budget :raises ~azure.core.exceptions.HttpResponseError: @@ -277,12 +271,21 @@ async def create_or_update( @overload async def create_or_update( - self, scope: str, budget_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, + scope: str, + budget_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models.Budget: """The operation to create or update a budget. You can optionally provide an eTag if desired as a form of concurrency control. To obtain the latest eTag for a given budget, perform a get operation prior to your put operation. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param scope: The scope associated with budget operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, @@ -295,17 +298,16 @@ async def create_or_update( scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' for billingProfile scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope. Required. :type scope: str :param budget_name: Budget Name. Required. :type budget_name: str :param parameters: Parameters supplied to the Create Budget operation. Required. - :type parameters: IO + :type parameters: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Budget or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.Budget :raises ~azure.core.exceptions.HttpResponseError: @@ -313,12 +315,15 @@ async def create_or_update( @distributed_trace_async async def create_or_update( - self, scope: str, budget_name: str, parameters: Union[_models.Budget, IO], **kwargs: Any + self, scope: str, budget_name: str, parameters: Union[_models.Budget, IO[bytes]], **kwargs: Any ) -> _models.Budget: """The operation to create or update a budget. You can optionally provide an eTag if desired as a form of concurrency control. To obtain the latest eTag for a given budget, perform a get operation prior to your put operation. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param scope: The scope associated with budget operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, @@ -331,23 +336,19 @@ async def create_or_update( scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' for billingProfile scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope. Required. :type scope: str :param budget_name: Budget Name. Required. :type budget_name: str - :param parameters: Parameters supplied to the Create Budget operation. Is either a model type - or a IO type. Required. - :type parameters: ~azure.mgmt.consumption.models.Budget or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + :param parameters: Parameters supplied to the Create Budget operation. Is either a Budget type + or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.consumption.models.Budget or IO[bytes] :return: Budget or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.Budget :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -358,64 +359,56 @@ async def create_or_update( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + 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.Budget] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(parameters, (IO, bytes)): + if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "Budget") - request = build_create_or_update_request( + _request = build_create_or_update_request( scope=scope, budget_name=budget_name, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.create_or_update.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("Budget", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("Budget", pipeline_response) + deserialized = self._deserialize("Budget", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/budgets/{budgetName}"} - @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, scope: str, budget_name: str, **kwargs: Any - ) -> None: + async def delete(self, scope: str, budget_name: str, **kwargs: Any) -> None: """The operation to delete a budget. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param scope: The scope associated with budget operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, @@ -428,17 +421,16 @@ async def delete( # pylint: disable=inconsistent-return-statements scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' for billingProfile scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope. Required. :type scope: str :param budget_name: Budget Name. Required. :type budget_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -449,34 +441,29 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( scope=scope, budget_name=budget_name, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/budgets/{budgetName}"} + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_charges_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_charges_operations.py index a5e80610b7c4..48a52c9c950f 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_charges_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_charges_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# 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 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._charges_operations import build_list_request +from .._configuration import ConsumptionManagementClientConfiguration -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -50,10 +47,12 @@ class ChargesOperations: 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: ConsumptionManagementClientConfiguration = ( + 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 list( @@ -67,6 +66,9 @@ async def list( ) -> _models.ChargesListResult: """Lists the charges based for the defined scope. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param scope: The scope associated with charges operations. This includes '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for Department scope, and @@ -79,9 +81,9 @@ async def list( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' for billingProfile scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' specific for partners. Required. :type scope: str :param start_date: Start date. Default value is None. @@ -98,12 +100,11 @@ async def list( Partner Led), or for billingProfile scope by properties/invoiceSectionId. Default value is None. :type apply: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ChargesListResult or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.ChargesListResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -114,41 +115,36 @@ async def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ChargesListResult] = kwargs.pop("cls", None) - request = build_list_request( + _request = build_list_request( scope=scope, start_date=start_date, end_date=end_date, filter=filter, apply=apply, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ChargesListResult", pipeline_response) + deserialized = self._deserialize("ChargesListResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - list.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/charges"} + return deserialized # type: ignore diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_credits_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_credits_operations.py index e35c87cd3480..b1f9c8eaa74a 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_credits_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_credits_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,9 +5,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 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 +18,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._credits_operations import build_get_request +from .._configuration import ConsumptionManagementClientConfiguration -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -50,10 +46,12 @@ class CreditsOperations: 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: ConsumptionManagementClientConfiguration = ( + 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( @@ -61,16 +59,18 @@ async def get( ) -> Optional[_models.CreditSummary]: """The credit summary by billingAccountId and billingProfileId. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str :param billing_profile_id: Azure Billing Profile ID. Required. :type billing_profile_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: CreditSummary or None or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.CreditSummary or None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -81,42 +81,35 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[Optional[_models.CreditSummary]] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( billing_account_id=billing_account_id, billing_profile_id=billing_profile_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize("CreditSummary", pipeline_response) + deserialized = self._deserialize("CreditSummary", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/credits/balanceSummary" - } + return deserialized # type: ignore diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_events_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_events_operations.py index 91bc7ae68e49..0021b32035a9 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_events_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_events_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # 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 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,23 +20,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 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._events_operations import ( build_list_by_billing_account_request, build_list_by_billing_profile_request, ) +from .._configuration import ConsumptionManagementClientConfiguration -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -55,10 +51,12 @@ class EventsOperations: 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: ConsumptionManagementClientConfiguration = ( + 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_by_billing_profile( @@ -67,6 +65,9 @@ def list_by_billing_profile( """Lists the events that decrements Azure credits or Microsoft Azure consumption commitment for a billing account or a billing profile for a given start and end date. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str :param billing_profile_id: Azure Billing Profile ID. Required. @@ -75,7 +76,6 @@ def list_by_billing_profile( :type start_date: str :param end_date: End date. Required. :type end_date: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either EventSummary or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.EventSummary] :raises ~azure.core.exceptions.HttpResponseError: @@ -83,12 +83,10 @@ def list_by_billing_profile( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Events] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -99,18 +97,16 @@ def list_by_billing_profile( def prepare_request(next_link=None): if not next_link: - request = build_list_by_billing_profile_request( + _request = build_list_by_billing_profile_request( billing_account_id=billing_account_id, billing_profile_id=billing_profile_id, start_date=start_date, end_date=end_date, api_version=api_version, - template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -122,13 +118,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("Events", pipeline_response) @@ -138,26 +133,23 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) - list_by_billing_profile.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/events" - } - @distributed_trace def list_by_billing_account( self, billing_account_id: str, filter: Optional[str] = None, **kwargs: Any @@ -165,6 +157,9 @@ def list_by_billing_account( """Lists the events that decrements Azure credits or Microsoft Azure consumption commitment for a billing account or a billing profile for a given start and end date. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str :param filter: May be used to filter the events by lotId, lotSource etc. The filter supports @@ -172,7 +167,6 @@ def list_by_billing_account( Tag filter is a key value pair string where key and value is separated by a colon (:). Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either EventSummary or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.EventSummary] :raises ~azure.core.exceptions.HttpResponseError: @@ -180,12 +174,10 @@ def list_by_billing_account( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Events] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -196,16 +188,14 @@ def list_by_billing_account( def prepare_request(next_link=None): if not next_link: - request = build_list_by_billing_account_request( + _request = build_list_by_billing_account_request( billing_account_id=billing_account_id, filter=filter, api_version=api_version, - template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -217,13 +207,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("Events", pipeline_response) @@ -233,22 +222,19 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list_by_billing_account.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/events" - } diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_lots_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_lots_operations.py index 300c7aafcca8..5851045eed73 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_lots_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_lots_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # 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 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,24 +20,20 @@ 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._lots_operations import ( build_list_by_billing_account_request, build_list_by_billing_profile_request, build_list_by_customer_request, ) +from .._configuration import ConsumptionManagementClientConfiguration -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -56,10 +52,12 @@ class LotsOperations: 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: ConsumptionManagementClientConfiguration = ( + 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_by_billing_profile( @@ -68,11 +66,13 @@ def list_by_billing_profile( """Lists all Azure credits for a billing account or a billing profile. The API is only supported for Microsoft Customer Agreements (MCA) billing accounts. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str :param billing_profile_id: Azure Billing Profile ID. Required. :type billing_profile_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either LotSummary or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.LotSummary] :raises ~azure.core.exceptions.HttpResponseError: @@ -80,12 +80,10 @@ def list_by_billing_profile( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Lots] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -96,16 +94,14 @@ def list_by_billing_profile( def prepare_request(next_link=None): if not next_link: - request = build_list_by_billing_profile_request( + _request = build_list_by_billing_profile_request( billing_account_id=billing_account_id, billing_profile_id=billing_profile_id, api_version=api_version, - template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -117,13 +113,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("Lots", pipeline_response) @@ -133,26 +128,23 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) - list_by_billing_profile.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/lots" - } - @distributed_trace def list_by_billing_account( self, billing_account_id: str, filter: Optional[str] = None, **kwargs: Any @@ -161,6 +153,9 @@ def list_by_billing_account( supported for Microsoft Customer Agreements (MCA) and Direct Enterprise Agreement (EA) billing accounts. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str :param filter: May be used to filter the lots by Status, Source etc. The filter supports 'eq', @@ -168,7 +163,6 @@ def list_by_billing_account( filter is a key value pair string where key and value is separated by a colon (:). Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either LotSummary or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.LotSummary] :raises ~azure.core.exceptions.HttpResponseError: @@ -176,12 +170,10 @@ def list_by_billing_account( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Lots] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -192,16 +184,14 @@ def list_by_billing_account( def prepare_request(next_link=None): if not next_link: - request = build_list_by_billing_account_request( + _request = build_list_by_billing_account_request( billing_account_id=billing_account_id, filter=filter, api_version=api_version, - template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -213,13 +203,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("Lots", pipeline_response) @@ -229,26 +218,23 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) - list_by_billing_account.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/lots" - } - @distributed_trace def list_by_customer( self, billing_account_id: str, customer_id: str, filter: Optional[str] = None, **kwargs: Any @@ -256,6 +242,9 @@ def list_by_customer( """Lists all Azure credits for a customer. The API is only supported for Microsoft Partner Agreements (MPA) billing accounts. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str :param customer_id: Customer ID. Required. @@ -264,7 +253,6 @@ def list_by_customer( 'lt', 'gt', 'le', 'ge', and 'and'. Tag filter is a key value pair string where key and value is separated by a colon (:). Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either LotSummary or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.LotSummary] :raises ~azure.core.exceptions.HttpResponseError: @@ -272,12 +260,10 @@ def list_by_customer( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Lots] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -288,17 +274,15 @@ def list_by_customer( def prepare_request(next_link=None): if not next_link: - request = build_list_by_customer_request( + _request = build_list_by_customer_request( billing_account_id=billing_account_id, customer_id=customer_id, filter=filter, api_version=api_version, - template_url=self.list_by_customer.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -310,13 +294,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("Lots", pipeline_response) @@ -326,22 +309,19 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list_by_customer.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}/providers/Microsoft.Consumption/lots" - } diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_marketplaces_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_marketplaces_operations.py index 924441566518..45a489fe8f88 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_marketplaces_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_marketplaces_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +6,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 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 +21,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._marketplaces_operations import build_list_request +from .._configuration import ConsumptionManagementClientConfiguration -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -52,10 +49,12 @@ class MarketplacesOperations: 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: ConsumptionManagementClientConfiguration = ( + 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( @@ -69,6 +68,9 @@ def list( """Lists the marketplaces for a scope at the defined scope. Marketplaces are available via this API only for May 1, 2014 or later. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param scope: The scope associated with marketplace operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, @@ -95,7 +97,6 @@ def list( a skiptoken parameter that specifies a starting point to use for subsequent calls. Default value is None. :type skiptoken: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Marketplace or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.Marketplace] :raises ~azure.core.exceptions.HttpResponseError: @@ -103,12 +104,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.MarketplacesListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -119,18 +118,16 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( scope=scope, filter=filter, top=top, skiptoken=skiptoken, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -142,13 +139,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("MarketplacesListResult", pipeline_response) @@ -158,20 +154,19 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/marketplaces"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_operations.py index 715254cec870..f99fdf1afed4 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # 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 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 ConsumptionManagementClientConfiguration -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -52,16 +48,17 @@ 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: ConsumptionManagementClientConfiguration = ( + 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"]: """Lists all of the available consumption REST API operations. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Operation or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.Operation] :raises ~azure.core.exceptions.HttpResponseError: @@ -69,12 +66,10 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -85,14 +80,12 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -104,13 +97,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) @@ -120,20 +112,19 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/providers/Microsoft.Consumption/operations"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_price_sheet_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_price_sheet_operations.py index 4bb0b620ad7f..a5b2ded9bacd 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_price_sheet_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_price_sheet_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,32 +5,37 @@ # 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, TypeVar +from collections.abc import MutableMapping +from typing import Any, AsyncIterator, Callable, Dict, Optional, TypeVar, Union, cast +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.rest import HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +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 ...operations._price_sheet_operations import build_get_by_billing_period_request, build_get_request +from ..._utils.serialization import Deserializer, Serializer +from ...operations._price_sheet_operations import ( + build_download_by_billing_account_period_request, + build_get_by_billing_period_request, + build_get_request, +) +from .._configuration import ConsumptionManagementClientConfiguration -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -50,10 +54,132 @@ class PriceSheetOperations: 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: ConsumptionManagementClientConfiguration = ( + 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") + + async def _download_by_billing_account_period_initial( # pylint: disable=name-too-long + self, billing_account_id: str, billing_period_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + 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[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_download_by_billing_account_period_request( + billing_account_id=billing_account_id, + billing_period_name=billing_period_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + 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, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_download_by_billing_account_period( + self, billing_account_id: str, billing_period_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.OperationStatus]: + """Generates the pricesheet for the provided billing period asynchronously based on the enrollment + id. + + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + + :param billing_account_id: BillingAccount ID. Required. + :type billing_account_id: str + :param billing_period_name: Billing Period Name. Required. + :type billing_period_name: str + :return: An instance of AsyncLROPoller that returns either OperationStatus or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.consumption.models.OperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _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.OperationStatus] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._download_by_billing_account_period_initial( + billing_account_id=billing_account_id, + billing_period_name=billing_period_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + 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("OperationStatus", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.OperationStatus].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.OperationStatus]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) @distributed_trace_async async def get( @@ -62,6 +188,9 @@ async def get( """Gets the price sheet for a subscription. Price sheet is available via this API only for May 1, 2014 or later. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param expand: May be used to expand the properties/meterDetails within a price sheet. By default, these fields are not included when returning price sheet. Default value is None. :type expand: str @@ -73,12 +202,11 @@ async def get( :param top: May be used to limit the number of results to the top N results. Default value is None. :type top: int - :keyword callable cls: A custom type or function that will be passed the direct response :return: PriceSheetResult or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.PriceSheetResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -89,43 +217,38 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.PriceSheetResult] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( subscription_id=self._config.subscription_id, expand=expand, skiptoken=skiptoken, top=top, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("PriceSheetResult", pipeline_response) + deserialized = self._deserialize("PriceSheetResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Consumption/pricesheets/default"} + return deserialized # type: ignore @distributed_trace_async async def get_by_billing_period( @@ -139,6 +262,9 @@ async def get_by_billing_period( """Get the price sheet for a scope by subscriptionId and billing period. Price sheet is available via this API only for May 1, 2014 or later. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param billing_period_name: Billing Period Name. Required. :type billing_period_name: str :param expand: May be used to expand the properties/meterDetails within a price sheet. By @@ -152,12 +278,11 @@ async def get_by_billing_period( :param top: May be used to limit the number of results to the top N results. Default value is None. :type top: int - :keyword callable cls: A custom type or function that will be passed the direct response :return: PriceSheetResult or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.PriceSheetResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -168,43 +293,36 @@ async def get_by_billing_period( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.PriceSheetResult] = kwargs.pop("cls", None) - request = build_get_by_billing_period_request( + _request = build_get_by_billing_period_request( billing_period_name=billing_period_name, subscription_id=self._config.subscription_id, expand=expand, skiptoken=skiptoken, top=top, api_version=api_version, - template_url=self.get_by_billing_period.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("PriceSheetResult", pipeline_response) + deserialized = self._deserialize("PriceSheetResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_by_billing_period.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/pricesheets/default" - } + return deserialized # type: ignore diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservation_recommendation_details_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservation_recommendation_details_operations.py index dd832048dc3e..22199c05c533 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservation_recommendation_details_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservation_recommendation_details_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,9 +5,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 collections.abc import MutableMapping from typing import Any, Callable, Dict, Optional, TypeVar, Union +from azure.core import AsyncPipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -18,25 +18,21 @@ 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._reservation_recommendation_details_operations import build_get_request +from .._configuration import ConsumptionManagementClientConfiguration -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class ReservationRecommendationDetailsOperations: +class ReservationRecommendationDetailsOperations: # pylint: disable=name-too-long """ .. warning:: **DO NOT** instantiate this class directly. @@ -50,10 +46,12 @@ class ReservationRecommendationDetailsOperations: 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: ConsumptionManagementClientConfiguration = ( + 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( @@ -64,10 +62,14 @@ async def get( term: Union[str, _models.Term], look_back_period: Union[str, _models.LookBackPeriod], product: str, + filter: Optional[str] = None, **kwargs: Any ) -> Optional[_models.ReservationRecommendationDetailsModel]: """Details of a reservation recommendation for what-if analysis of reserved instances. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param resource_scope: The scope associated with reservation recommendation details operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resource group scope, @@ -79,8 +81,8 @@ async def get( :type scope: str or ~azure.mgmt.consumption.models.Scope :param region: Used to select the region the recommendation should be generated for. Required. :type region: str - :param term: Specify length of reservation recommendation term. Known values are: "P1Y" and - "P3Y". Required. + :param term: Specify length of reservation recommendation term. Known values are: "P1M", "P1Y", + and "P3Y". Required. :type term: str or ~azure.mgmt.consumption.models.Term :param look_back_period: Filter the time period on which reservation recommendation results are based. Known values are: "Last7Days", "Last30Days", and "Last60Days". Required. @@ -89,12 +91,14 @@ async def get( Examples: Standard_DS1_v2 (for VM), Premium_SSD_Managed_Disks_P30 (for Managed Disks). Required. :type product: str - :keyword callable cls: A custom type or function that will be passed the direct response + :param filter: Used to filter reservation recommendation details by: properties/subscriptionId + can be specified for billing account and billing profile paths. Default value is None. + :type filter: str :return: ReservationRecommendationDetailsModel or None or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.ReservationRecommendationDetailsModel or None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -105,28 +109,26 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[Optional[_models.ReservationRecommendationDetailsModel]] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_scope=resource_scope, scope=scope, region=region, term=term, look_back_period=look_back_period, product=product, + filter=filter, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -138,11 +140,9 @@ async def get( deserialized = None if response.status_code == 200: - deserialized = self._deserialize("ReservationRecommendationDetailsModel", pipeline_response) + deserialized = self._deserialize("ReservationRecommendationDetailsModel", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = {"url": "/{resourceScope}/providers/Microsoft.Consumption/reservationRecommendationDetails"} + return deserialized # type: ignore diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservation_recommendations_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservation_recommendations_operations.py index b23a984c7447..fb771dc7bb88 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservation_recommendations_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservation_recommendations_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # 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 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._reservation_recommendations_operations import build_list_request +from .._configuration import ConsumptionManagementClientConfiguration -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -52,10 +48,12 @@ class ReservationRecommendationsOperations: 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: ConsumptionManagementClientConfiguration = ( + 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( @@ -63,6 +61,9 @@ def list( ) -> AsyncIterable["_models.ReservationRecommendation"]: """List of recommendations for purchasing reserved instances. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param resource_scope: The scope associated with reservation recommendations operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resource group scope, @@ -78,7 +79,6 @@ def list( properties/lookBackPeriod with allowed values ['Last7Days', 'Last30Days', 'Last60Days'] and default value 'Last7Days'. Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ReservationRecommendation or the result of cls(response) :rtype: @@ -88,12 +88,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ReservationRecommendationsListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -104,16 +102,14 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_scope=resource_scope, filter=filter, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -125,13 +121,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ReservationRecommendationsListResult", pipeline_response) @@ -141,20 +136,19 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{resourceScope}/providers/Microsoft.Consumption/reservationRecommendations"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservation_transactions_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservation_transactions_operations.py index 15671e3cf4a9..5c04834fb150 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservation_transactions_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservation_transactions_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # 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 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._reservation_transactions_operations import build_list_by_billing_profile_request, build_list_request +from .._configuration import ConsumptionManagementClientConfiguration -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -52,20 +48,32 @@ class ReservationTransactionsOperations: 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: ConsumptionManagementClientConfiguration = ( + 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, billing_account_id: str, filter: Optional[str] = None, **kwargs: Any + self, + billing_account_id: str, + filter: Optional[str] = None, + use_markup_if_partner: Optional[bool] = None, + preview_markup_percentage: Optional[float] = None, + **kwargs: Any ) -> AsyncIterable["_models.ReservationTransaction"]: """List of transactions for reserved instances on billing account scope. Note: The refund transactions are posted along with its purchase transaction (i.e. in the purchase billing month). For example, The refund is requested in May 2021. This refund transaction will have event date as May 2021 but the billing month as April 2020 when the reservation purchase was - made. + made. Note: ARM has a payload size limit of 12MB, so currently callers get 400 when the + response size exceeds the ARM limit. In such cases, API call should be made with smaller date + ranges. + + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str @@ -76,7 +84,12 @@ def list( the entire December 2020 month (i.e. will contain records for dates December 30 and 31). Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response + :param use_markup_if_partner: Applies mark up to the transactions if the caller is a partner. + Default value is None. + :type use_markup_if_partner: bool + :param preview_markup_percentage: Preview markup percentage to be applied. Default value is + None. + :type preview_markup_percentage: float :return: An iterator like instance of either ReservationTransaction or the result of cls(response) :rtype: @@ -86,12 +99,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ReservationTransactionsListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -102,16 +113,16 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( billing_account_id=billing_account_id, filter=filter, + use_markup_if_partner=use_markup_if_partner, + preview_markup_percentage=preview_markup_percentage, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -123,13 +134,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ReservationTransactionsListResult", pipeline_response) @@ -139,26 +149,23 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) - list.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/reservationTransactions" - } - @distributed_trace def list_by_billing_profile( self, billing_account_id: str, billing_profile_id: str, filter: Optional[str] = None, **kwargs: Any @@ -166,7 +173,12 @@ def list_by_billing_profile( """List of transactions for reserved instances on billing profile scope. The refund transactions are posted along with its purchase transaction (i.e. in the purchase billing month). For example, The refund is requested in May 2021. This refund transaction will have event date as - May 2021 but the billing month as April 2020 when the reservation purchase was made. + May 2021 but the billing month as April 2020 when the reservation purchase was made. Note: ARM + has a payload size limit of 12MB, so currently callers get 400 when the response size exceeds + the ARM limit. In such cases, API call should be made with smaller date ranges. + + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str @@ -179,7 +191,6 @@ def list_by_billing_profile( entire December 2020 month (i.e. will contain records for dates December 30 and 31). Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ModernReservationTransaction or the result of cls(response) :rtype: @@ -189,12 +200,10 @@ def list_by_billing_profile( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ModernReservationTransactionsListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -205,17 +214,15 @@ def list_by_billing_profile( def prepare_request(next_link=None): if not next_link: - request = build_list_by_billing_profile_request( + _request = build_list_by_billing_profile_request( billing_account_id=billing_account_id, billing_profile_id=billing_profile_id, filter=filter, api_version=api_version, - template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -227,13 +234,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ModernReservationTransactionsListResult", pipeline_response) @@ -243,22 +249,19 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list_by_billing_profile.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/reservationTransactions" - } diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservations_details_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservations_details_operations.py index cb74a06054b8..30b554087a85 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservations_details_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservations_details_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # 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 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,24 +20,20 @@ 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._reservations_details_operations import ( build_list_by_reservation_order_and_reservation_request, build_list_by_reservation_order_request, build_list_request, ) +from .._configuration import ConsumptionManagementClientConfiguration -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -56,25 +52,32 @@ class ReservationsDetailsOperations: 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: ConsumptionManagementClientConfiguration = ( + 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_by_reservation_order( self, reservation_order_id: str, filter: str, **kwargs: Any ) -> AsyncIterable["_models.ReservationDetail"]: """Lists the reservations details for provided date range. Note: ARM has a payload size limit of - 12MB, so currently callers get 502 when the response size exceeds the ARM limit. In such cases, - API call should be made with smaller date ranges. + 12MB, so currently callers get 400 when the response size exceeds the ARM limit. If the data + size is too large, customers may also get 504 as the API timed out preparing the data. In such + cases, API call should be made with smaller date ranges or a call to Generate Reservation + Details Report API should be made as it is asynchronous and will not run into response size + time outs. + + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str :param filter: Filter reservation details by date range. The properties/UsageDate for start date and end date. The filter supports 'le' and 'ge'. Required. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ReservationDetail or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationDetail] @@ -83,12 +86,10 @@ def list_by_reservation_order( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ReservationDetailsListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -99,16 +100,14 @@ def list_by_reservation_order( def prepare_request(next_link=None): if not next_link: - request = build_list_by_reservation_order_request( + _request = build_list_by_reservation_order_request( reservation_order_id=reservation_order_id, filter=filter, api_version=api_version, - template_url=self.list_by_reservation_order.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -120,13 +119,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ReservationDetailsListResult", pipeline_response) @@ -136,33 +134,36 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) - list_by_reservation_order.metadata = { - "url": "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/providers/Microsoft.Consumption/reservationDetails" - } - @distributed_trace - def list_by_reservation_order_and_reservation( + def list_by_reservation_order_and_reservation( # pylint: disable=name-too-long self, reservation_order_id: str, reservation_id: str, filter: str, **kwargs: Any ) -> AsyncIterable["_models.ReservationDetail"]: """Lists the reservations details for provided date range. Note: ARM has a payload size limit of - 12MB, so currently callers get 502 when the response size exceeds the ARM limit. In such cases, - API call should be made with smaller date ranges. + 12MB, so currently callers get 400 when the response size exceeds the ARM limit. If the data + size is too large, customers may also get 504 as the API timed out preparing the data. In such + cases, API call should be made with smaller date ranges or a call to Generate Reservation + Details Report API should be made as it is asynchronous and will not run into response size + time outs. + + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str @@ -171,7 +172,6 @@ def list_by_reservation_order_and_reservation( :param filter: Filter reservation details by date range. The properties/UsageDate for start date and end date. The filter supports 'le' and 'ge'. Required. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ReservationDetail or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationDetail] @@ -180,12 +180,10 @@ def list_by_reservation_order_and_reservation( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ReservationDetailsListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -196,17 +194,15 @@ def list_by_reservation_order_and_reservation( def prepare_request(next_link=None): if not next_link: - request = build_list_by_reservation_order_and_reservation_request( + _request = build_list_by_reservation_order_and_reservation_request( reservation_order_id=reservation_order_id, reservation_id=reservation_id, filter=filter, api_version=api_version, - template_url=self.list_by_reservation_order_and_reservation.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -218,13 +214,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ReservationDetailsListResult", pipeline_response) @@ -234,26 +229,23 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) - list_by_reservation_order_and_reservation.metadata = { - "url": "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/reservations/{reservationId}/providers/Microsoft.Consumption/reservationDetails" - } - @distributed_trace def list( self, @@ -265,9 +257,15 @@ def list( reservation_order_id: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.ReservationDetail"]: - """Lists the reservations details for the defined scope and provided date range. Note: ARM has a - payload size limit of 12MB, so currently callers get 502 when the response size exceeds the ARM - limit. In such cases, API call should be made with smaller date ranges. + """Lists the reservations details for provided date range. Note: ARM has a payload size limit of + 12MB, so currently callers get 400 when the response size exceeds the ARM limit. If the data + size is too large, customers may also get 504 as the API timed out preparing the data. In such + cases, API call should be made with smaller date ranges or a call to Generate Reservation + Details Report API should be made as it is asynchronous and will not run into response size + time outs. + + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ :param resource_scope: The scope associated with reservations details operations. This includes '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for BillingAccount scope @@ -291,7 +289,6 @@ def list( :param reservation_order_id: Reservation Order Id GUID. Required if reservationId is provided. Filter to a specific reservation order. Default value is None. :type reservation_order_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ReservationDetail or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationDetail] @@ -300,12 +297,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ReservationDetailsListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -316,7 +311,7 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_scope=resource_scope, start_date=start_date, end_date=end_date, @@ -324,12 +319,10 @@ def prepare_request(next_link=None): reservation_id=reservation_id, reservation_order_id=reservation_order_id, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -341,13 +334,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ReservationDetailsListResult", pipeline_response) @@ -357,20 +349,19 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{resourceScope}/providers/Microsoft.Consumption/reservationDetails"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservations_summaries_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservations_summaries_operations.py index 2c5bb97e1b10..f7dc0dddf147 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservations_summaries_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservations_summaries_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # 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 collections.abc import MutableMapping from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union import urllib.parse +from azure.core import AsyncPipelineClient from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, @@ -20,24 +20,20 @@ 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._reservations_summaries_operations import ( build_list_by_reservation_order_and_reservation_request, build_list_by_reservation_order_request, build_list_request, ) +from .._configuration import ConsumptionManagementClientConfiguration -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -56,10 +52,12 @@ class ReservationsSummariesOperations: 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: ConsumptionManagementClientConfiguration = ( + 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_by_reservation_order( @@ -69,7 +67,12 @@ def list_by_reservation_order( filter: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.ReservationSummary"]: - """Lists the reservations summaries for daily or monthly grain. + """Lists the reservations summaries for daily or monthly grain. Note: ARM has a payload size limit + of 12MB, so currently callers get 400 when the response size exceeds the ARM limit. In such + cases, API call should be made with smaller date ranges. + + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str @@ -78,7 +81,6 @@ def list_by_reservation_order( :param filter: Required only for daily grain. The properties/UsageDate for start date and end date. The filter supports 'le' and 'ge'. Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ReservationSummary or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationSummary] @@ -87,12 +89,10 @@ def list_by_reservation_order( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ReservationSummariesListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -103,17 +103,15 @@ def list_by_reservation_order( def prepare_request(next_link=None): if not next_link: - request = build_list_by_reservation_order_request( + _request = build_list_by_reservation_order_request( reservation_order_id=reservation_order_id, grain=grain, filter=filter, api_version=api_version, - template_url=self.list_by_reservation_order.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -125,13 +123,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ReservationSummariesListResult", pipeline_response) @@ -141,28 +138,25 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) - list_by_reservation_order.metadata = { - "url": "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/providers/Microsoft.Consumption/reservationSummaries" - } - @distributed_trace - def list_by_reservation_order_and_reservation( + def list_by_reservation_order_and_reservation( # pylint: disable=name-too-long self, reservation_order_id: str, reservation_id: str, @@ -170,7 +164,12 @@ def list_by_reservation_order_and_reservation( filter: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.ReservationSummary"]: - """Lists the reservations summaries for daily or monthly grain. + """Lists the reservations summaries for daily or monthly grain. Note: ARM has a payload size limit + of 12MB, so currently callers get 400 when the response size exceeds the ARM limit. In such + cases, API call should be made with smaller date ranges. + + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str @@ -181,7 +180,6 @@ def list_by_reservation_order_and_reservation( :param filter: Required only for daily grain. The properties/UsageDate for start date and end date. The filter supports 'le' and 'ge'. Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ReservationSummary or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationSummary] @@ -190,12 +188,10 @@ def list_by_reservation_order_and_reservation( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ReservationSummariesListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -206,18 +202,16 @@ def list_by_reservation_order_and_reservation( def prepare_request(next_link=None): if not next_link: - request = build_list_by_reservation_order_and_reservation_request( + _request = build_list_by_reservation_order_and_reservation_request( reservation_order_id=reservation_order_id, reservation_id=reservation_id, grain=grain, filter=filter, api_version=api_version, - template_url=self.list_by_reservation_order_and_reservation.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -229,13 +223,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ReservationSummariesListResult", pipeline_response) @@ -245,26 +238,23 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) - list_by_reservation_order_and_reservation.metadata = { - "url": "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/reservations/{reservationId}/providers/Microsoft.Consumption/reservationSummaries" - } - @distributed_trace def list( self, @@ -277,7 +267,12 @@ def list( reservation_order_id: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.ReservationSummary"]: - """Lists the reservations summaries for the defined scope daily or monthly grain. + """Lists the reservations summaries for the defined scope daily or monthly grain. Note: ARM has a + payload size limit of 12MB, so currently callers get 400 when the response size exceeds the ARM + limit. In such cases, API call should be made with smaller date ranges. + + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ :param resource_scope: The scope associated with reservations summaries operations. This includes '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for BillingAccount @@ -303,7 +298,6 @@ def list( :param reservation_order_id: Reservation Order Id GUID. Required if reservationId is provided. Filter to a specific reservation order. Default value is None. :type reservation_order_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ReservationSummary or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationSummary] @@ -312,12 +306,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ReservationSummariesListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -328,7 +320,7 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_scope=resource_scope, grain=grain, start_date=start_date, @@ -337,12 +329,10 @@ def prepare_request(next_link=None): reservation_id=reservation_id, reservation_order_id=reservation_order_id, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -354,13 +344,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ReservationSummariesListResult", pipeline_response) @@ -370,20 +359,19 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{resourceScope}/providers/Microsoft.Consumption/reservationSummaries"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_tags_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_tags_operations.py index ec7c05804fe9..ad7219105652 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_tags_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_tags_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,9 +5,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 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 +18,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._tags_operations import build_get_request +from .._configuration import ConsumptionManagementClientConfiguration -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -50,15 +46,20 @@ class TagsOperations: 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: ConsumptionManagementClientConfiguration = ( + 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, **kwargs: Any) -> Optional[_models.TagsResult]: """Get all available tag keys for the defined scope. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param scope: The scope associated with tags operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, @@ -70,12 +71,11 @@ async def get(self, scope: str, **kwargs: Any) -> Optional[_models.TagsResult]: '/providers/Microsoft.Management/managementGroups/{managementGroupId}' for Management Group scope.. Required. :type scope: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: TagsResult or None or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.TagsResult or None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -86,39 +86,34 @@ async def get(self, scope: str, **kwargs: Any) -> Optional[_models.TagsResult]: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[Optional[_models.TagsResult]] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( scope=scope, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize("TagsResult", pipeline_response) + deserialized = self._deserialize("TagsResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/tags"} + return deserialized # type: ignore diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_usage_details_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_usage_details_operations.py index 9b7ee901cf4c..5e723a963d5b 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_usage_details_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_usage_details_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +6,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 collections.abc import MutableMapping from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union import urllib.parse +from azure.core import AsyncPipelineClient from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, @@ -20,20 +21,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._usage_details_operations import build_list_request +from .._configuration import ConsumptionManagementClientConfiguration -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -52,10 +49,12 @@ class UsageDetailsOperations: 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: ConsumptionManagementClientConfiguration = ( + 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( @@ -71,6 +70,16 @@ def list( """Lists the usage details for the defined scope. Usage details are available via this API only for May 1, 2014 or later. + **Note:Microsoft will be retiring the Consumption Usage Details API at some point in the + future. We do not recommend that you take a new dependency on this API. Please use the Cost + Details API instead. We will notify customers once a date for retirement has been + determined.For Learn more,see `Generate Cost Details Report - Create Operation + `_\\ + **. + + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param scope: The scope associated with usage details operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, @@ -86,9 +95,9 @@ def list( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' for billingProfile scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' specific for partners. Required. :type scope: str :param expand: May be used to expand the properties/additionalInfo or properties/meterDetails @@ -114,7 +123,6 @@ def list( :param metric: Allows to select different type of cost/usage records. Known values are: "actualcost", "amortizedcost", and "usage". Default value is None. :type metric: str or ~azure.mgmt.consumption.models.Metrictype - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either UsageDetail or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.UsageDetail] :raises ~azure.core.exceptions.HttpResponseError: @@ -122,12 +130,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.UsageDetailsListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -138,7 +144,7 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( scope=scope, expand=expand, filter=filter, @@ -146,12 +152,10 @@ def prepare_request(next_link=None): top=top, metric=metric, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -163,13 +167,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("UsageDetailsListResult", pipeline_response) @@ -179,20 +182,19 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/usageDetails"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/__init__.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/__init__.py index 134b6775b069..df9b7cc0e5ba 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/__init__.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/__init__.py @@ -5,104 +5,122 @@ # 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 Amount -from ._models_py3 import AmountWithExchangeRate -from ._models_py3 import Balance -from ._models_py3 import BalancePropertiesAdjustmentDetailsItem -from ._models_py3 import BalancePropertiesNewPurchasesDetailsItem -from ._models_py3 import Budget -from ._models_py3 import BudgetComparisonExpression -from ._models_py3 import BudgetFilter -from ._models_py3 import BudgetFilterProperties -from ._models_py3 import BudgetTimePeriod -from ._models_py3 import BudgetsListResult -from ._models_py3 import ChargeSummary -from ._models_py3 import ChargesListResult -from ._models_py3 import CreditBalanceSummary -from ._models_py3 import CreditSummary -from ._models_py3 import CurrentSpend -from ._models_py3 import DownloadProperties -from ._models_py3 import ErrorDetails -from ._models_py3 import ErrorResponse -from ._models_py3 import EventSummary -from ._models_py3 import Events -from ._models_py3 import ForecastSpend -from ._models_py3 import HighCasedErrorDetails -from ._models_py3 import HighCasedErrorResponse -from ._models_py3 import LegacyChargeSummary -from ._models_py3 import LegacyReservationRecommendation -from ._models_py3 import LegacyReservationRecommendationProperties -from ._models_py3 import LegacyReservationTransaction -from ._models_py3 import LegacySharedScopeReservationRecommendationProperties -from ._models_py3 import LegacySingleScopeReservationRecommendationProperties -from ._models_py3 import LegacyUsageDetail -from ._models_py3 import LotSummary -from ._models_py3 import Lots -from ._models_py3 import ManagementGroupAggregatedCostResult -from ._models_py3 import Marketplace -from ._models_py3 import MarketplacesListResult -from ._models_py3 import MeterDetails -from ._models_py3 import MeterDetailsResponse -from ._models_py3 import ModernChargeSummary -from ._models_py3 import ModernReservationRecommendation -from ._models_py3 import ModernReservationRecommendationProperties -from ._models_py3 import ModernReservationTransaction -from ._models_py3 import ModernReservationTransactionsListResult -from ._models_py3 import ModernSharedScopeReservationRecommendationProperties -from ._models_py3 import ModernSingleScopeReservationRecommendationProperties -from ._models_py3 import ModernUsageDetail -from ._models_py3 import Notification -from ._models_py3 import Operation -from ._models_py3 import OperationDisplay -from ._models_py3 import OperationListResult -from ._models_py3 import PriceSheetProperties -from ._models_py3 import PriceSheetResult -from ._models_py3 import ProxyResource -from ._models_py3 import Reseller -from ._models_py3 import ReservationDetail -from ._models_py3 import ReservationDetailsListResult -from ._models_py3 import ReservationRecommendation -from ._models_py3 import ReservationRecommendationDetailsCalculatedSavingsProperties -from ._models_py3 import ReservationRecommendationDetailsModel -from ._models_py3 import ReservationRecommendationDetailsResourceProperties -from ._models_py3 import ReservationRecommendationDetailsSavingsProperties -from ._models_py3 import ReservationRecommendationDetailsUsageProperties -from ._models_py3 import ReservationRecommendationsListResult -from ._models_py3 import ReservationSummariesListResult -from ._models_py3 import ReservationSummary -from ._models_py3 import ReservationTransaction -from ._models_py3 import ReservationTransactionResource -from ._models_py3 import ReservationTransactionsListResult -from ._models_py3 import Resource -from ._models_py3 import ResourceAttributes -from ._models_py3 import SkuProperty -from ._models_py3 import Tag -from ._models_py3 import TagsResult -from ._models_py3 import UsageDetail -from ._models_py3 import UsageDetailsListResult +from typing import TYPE_CHECKING -from ._consumption_management_client_enums import BillingFrequency -from ._consumption_management_client_enums import BudgetOperatorType -from ._consumption_management_client_enums import CategoryType -from ._consumption_management_client_enums import ChargeSummaryKind -from ._consumption_management_client_enums import CultureCode -from ._consumption_management_client_enums import Datagrain -from ._consumption_management_client_enums import EventType -from ._consumption_management_client_enums import LookBackPeriod -from ._consumption_management_client_enums import LotSource -from ._consumption_management_client_enums import Metrictype -from ._consumption_management_client_enums import OperatorType -from ._consumption_management_client_enums import PricingModelType -from ._consumption_management_client_enums import ReservationRecommendationKind -from ._consumption_management_client_enums import Scope -from ._consumption_management_client_enums import Status -from ._consumption_management_client_enums import Term -from ._consumption_management_client_enums import ThresholdType -from ._consumption_management_client_enums import TimeGrainType -from ._consumption_management_client_enums import UsageDetailsKind +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + Amount, + AmountWithExchangeRate, + Balance, + BalancePropertiesAdjustmentDetailsItem, + BalancePropertiesNewPurchasesDetailsItem, + Budget, + BudgetComparisonExpression, + BudgetFilter, + BudgetFilterProperties, + BudgetTimePeriod, + BudgetsListResult, + ChargeSummary, + ChargesListResult, + CreditBalanceSummary, + CreditSummary, + CurrentSpend, + DownloadProperties, + ErrorAdditionalInfo, + ErrorDetail, + ErrorDetails, + ErrorResponse, + ErrorResponseAutoGenerated, + EventSummary, + Events, + ForecastSpend, + HighCasedErrorDetails, + HighCasedErrorResponse, + LegacyChargeSummary, + LegacyReservationRecommendation, + LegacyReservationRecommendationProperties, + LegacyReservationTransaction, + LegacySharedScopeReservationRecommendationProperties, + LegacySingleScopeReservationRecommendationProperties, + LegacyUsageDetail, + LotSummary, + Lots, + ManagementGroupAggregatedCostResult, + Marketplace, + MarketplacesListResult, + MeterDetails, + MeterDetailsResponse, + ModernChargeSummary, + ModernReservationRecommendation, + ModernReservationRecommendationProperties, + ModernReservationTransaction, + ModernReservationTransactionsListResult, + ModernSharedScopeReservationRecommendationProperties, + ModernSingleScopeReservationRecommendationProperties, + ModernUsageDetail, + Notification, + Operation, + OperationDisplay, + OperationListResult, + OperationStatus, + PriceSheetProperties, + PriceSheetResult, + ProxyResource, + Reseller, + ReservationDetail, + ReservationDetailsListResult, + ReservationRecommendation, + ReservationRecommendationDetailsCalculatedSavingsProperties, + ReservationRecommendationDetailsModel, + ReservationRecommendationDetailsResourceProperties, + ReservationRecommendationDetailsSavingsProperties, + ReservationRecommendationDetailsUsageProperties, + ReservationRecommendationsListResult, + ReservationSummariesListResult, + ReservationSummary, + ReservationTransaction, + ReservationTransactionResource, + ReservationTransactionsListResult, + Resource, + ResourceAttributes, + SavingsPlan, + SkuProperty, + Tag, + TagsResult, + UsageDetail, + UsageDetailsListResult, +) + +from ._consumption_management_client_enums import ( # type: ignore + BillingFrequency, + BudgetOperatorType, + CategoryType, + ChargeSummaryKind, + CultureCode, + Datagrain, + EventType, + LookBackPeriod, + LotSource, + Metrictype, + OperationStatusType, + OperatorType, + OrganizationType, + PricingModelType, + ReservationRecommendationKind, + Scope, + Status, + Term, + ThresholdType, + TimeGrainType, + UsageDetailsKind, +) 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__ = [ @@ -123,8 +141,11 @@ "CreditSummary", "CurrentSpend", "DownloadProperties", + "ErrorAdditionalInfo", + "ErrorDetail", "ErrorDetails", "ErrorResponse", + "ErrorResponseAutoGenerated", "EventSummary", "Events", "ForecastSpend", @@ -156,6 +177,7 @@ "Operation", "OperationDisplay", "OperationListResult", + "OperationStatus", "PriceSheetProperties", "PriceSheetResult", "ProxyResource", @@ -176,6 +198,7 @@ "ReservationTransactionsListResult", "Resource", "ResourceAttributes", + "SavingsPlan", "SkuProperty", "Tag", "TagsResult", @@ -191,7 +214,9 @@ "LookBackPeriod", "LotSource", "Metrictype", + "OperationStatusType", "OperatorType", + "OrganizationType", "PricingModelType", "ReservationRecommendationKind", "Scope", @@ -201,5 +226,5 @@ "TimeGrainType", "UsageDetailsKind", ] -__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/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/_consumption_management_client_enums.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/_consumption_management_client_enums.py index ecb66e0217dd..43df109a8f13 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/_consumption_management_client_enums.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/_consumption_management_client_enums.py @@ -22,6 +22,7 @@ class BudgetOperatorType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The operator to use for comparison.""" IN = "In" + IN_ENUM = "In" class CategoryType(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -66,10 +67,10 @@ class CultureCode(str, Enum, metaclass=CaseInsensitiveEnumMeta): class Datagrain(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Datagrain.""" - #: Daily grain of data DAILY_GRAIN = "daily" - #: Monthly grain of data + """Daily grain of data""" MONTHLY_GRAIN = "monthly" + """Monthly grain of data""" class EventType(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -88,12 +89,12 @@ class EventType(str, Enum, metaclass=CaseInsensitiveEnumMeta): class LookBackPeriod(str, Enum, metaclass=CaseInsensitiveEnumMeta): """LookBackPeriod.""" - #: Use 7 days of data for recommendations LAST07_DAYS = "Last7Days" - #: Use 30 days of data for recommendations + """Use 7 days of data for recommendations""" LAST30_DAYS = "Last30Days" - #: Use 60 days of data for recommendations + """Use 30 days of data for recommendations""" LAST60_DAYS = "Last60Days" + """Use 60 days of data for recommendations""" class LotSource(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -107,27 +108,44 @@ class LotSource(str, Enum, metaclass=CaseInsensitiveEnumMeta): class Metrictype(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Metrictype.""" - #: Actual cost data. ACTUAL_COST_METRIC_TYPE = "actualcost" - #: Amortized cost data. + """Actual cost data.""" AMORTIZED_COST_METRIC_TYPE = "amortizedcost" - #: Usage data. + """Amortized cost data.""" USAGE_METRIC_TYPE = "usage" + """Usage data.""" + + +class OperationStatusType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of the long running operation.""" + + RUNNING = "Running" + COMPLETED = "Completed" + FAILED = "Failed" class OperatorType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The comparison operator.""" - #: Alert will be triggered if the evaluated cost is the same as threshold value. Note: It’s not - #: recommended to use this OperatorType as there’s low chance of cost being exactly the same as - #: threshold value, leading to missing of your alert. This OperatorType will be deprecated in - #: future. EQUAL_TO = "EqualTo" - #: Alert will be triggered if the evaluated cost is greater than the threshold value. Note: This - #: is the recommended OperatorType while configuring Budget Alert. + """Alert will be triggered if the evaluated cost is the same as threshold value. Note: It’s not + recommended to use this OperatorType as there’s low chance of cost being exactly the same as + threshold value, leading to missing of your alert. This OperatorType will be deprecated in + future.""" GREATER_THAN = "GreaterThan" - #: Alert will be triggered if the evaluated cost is greater than or equal to the threshold value. + """Alert will be triggered if the evaluated cost is greater than the threshold value. Note: This + is the recommended OperatorType while configuring Budget Alert.""" GREATER_THAN_OR_EQUAL_TO = "GreaterThanOrEqualTo" + """Alert will be triggered if the evaluated cost is greater than or equal to the threshold value.""" + + +class OrganizationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The organization type of the lot.""" + + PRIMARY_ORGANIZATION_TYPE = "Primary" + """Primary organization type for Multi-Entity consumption commitment.""" + CONTRIBUTOR_ORGANIZATION_TYPE = "Contributor" + """Contributor organization type for Multi-Entity consumption commitment.""" class PricingModelType(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -166,20 +184,22 @@ class Status(str, Enum, metaclass=CaseInsensitiveEnumMeta): class Term(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Term.""" - #: 1 year reservation term + P1_M = "P1M" + """1 month reservation term""" P1_Y = "P1Y" - #: 3 year reservation term + """1 year reservation term""" P3_Y = "P3Y" + """3 year reservation term""" class ThresholdType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The type of threshold.""" - #: Actual costs budget alerts notify when the actual accrued cost exceeds the allocated budget . ACTUAL = "Actual" - #: Forecasted costs budget alerts provide advanced notification that your spending trends are - #: likely to exceed your allocated budget, as it relies on forecasted cost predictions. + """Actual costs budget alerts notify when the actual accrued cost exceeds the allocated budget .""" FORECASTED = "Forecasted" + """Forecasted costs budget alerts provide advanced notification that your spending trends are + likely to exceed your allocated budget, as it relies on forecasted cost predictions.""" class TimeGrainType(str, Enum, metaclass=CaseInsensitiveEnumMeta): diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/_models_py3.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/_models_py3.py index a3d280e095a9..36c3724678d8 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/_models_py3.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/_models_py3.py @@ -1,5 +1,5 @@ -# coding=utf-8 # pylint: disable=too-many-lines +# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. @@ -8,12 +8,11 @@ # -------------------------------------------------------------------------- import datetime -from typing import Dict, List, Optional, TYPE_CHECKING, Union +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 @@ -38,11 +37,11 @@ class Amount(_serialization.Model): "value": {"key": "value", "type": "float"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.currency = None - self.value = None + self.currency: Optional[str] = None + self.value: Optional[float] = None class AmountWithExchangeRate(Amount): @@ -74,11 +73,11 @@ class AmountWithExchangeRate(Amount): "exchange_rate_month": {"key": "exchangeRateMonth", "type": "int"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.exchange_rate = None - self.exchange_rate_month = None + self.exchange_rate: Optional[float] = None + self.exchange_rate_month: Optional[int] = None class Resource(_serialization.Model): @@ -114,17 +113,17 @@ class Resource(_serialization.Model): "tags": {"key": "tags", "type": "{str}"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.etag = None - self.tags = None + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + self.etag: Optional[str] = None + self.tags: Optional[Dict[str, str]] = None -class Balance(Resource): # pylint: disable=too-many-instance-attributes +class Balance(Resource): """A balance resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -167,6 +166,8 @@ class Balance(Resource): # pylint: disable=too-many-instance-attributes :vartype billing_frequency: str or ~azure.mgmt.consumption.models.BillingFrequency :ivar price_hidden: Price is hidden or not. :vartype price_hidden: bool + :ivar overage_refund: Overage Refunds. + :vartype overage_refund: float :ivar new_purchases_details: List of new purchases. :vartype new_purchases_details: list[~azure.mgmt.consumption.models.BalancePropertiesNewPurchasesDetailsItem] @@ -193,6 +194,7 @@ class Balance(Resource): # pylint: disable=too-many-instance-attributes "total_usage": {"readonly": True}, "azure_marketplace_service_charges": {"readonly": True}, "price_hidden": {"readonly": True}, + "overage_refund": {"readonly": True}, "new_purchases_details": {"readonly": True}, "adjustment_details": {"readonly": True}, } @@ -216,6 +218,7 @@ class Balance(Resource): # pylint: disable=too-many-instance-attributes "azure_marketplace_service_charges": {"key": "properties.azureMarketplaceServiceCharges", "type": "float"}, "billing_frequency": {"key": "properties.billingFrequency", "type": "str"}, "price_hidden": {"key": "properties.priceHidden", "type": "bool"}, + "overage_refund": {"key": "properties.overageRefund", "type": "float"}, "new_purchases_details": { "key": "properties.newPurchasesDetails", "type": "[BalancePropertiesNewPurchasesDetailsItem]", @@ -226,28 +229,31 @@ class Balance(Resource): # pylint: disable=too-many-instance-attributes }, } - def __init__(self, *, billing_frequency: Optional[Union[str, "_models.BillingFrequency"]] = None, **kwargs): + def __init__( + self, *, billing_frequency: Optional[Union[str, "_models.BillingFrequency"]] = None, **kwargs: Any + ) -> None: """ :keyword billing_frequency: The billing frequency. Known values are: "Month", "Quarter", and "Year". :paramtype billing_frequency: str or ~azure.mgmt.consumption.models.BillingFrequency """ super().__init__(**kwargs) - self.currency = None - self.beginning_balance = None - self.ending_balance = None - self.new_purchases = None - self.adjustments = None - self.utilized = None - self.service_overage = None - self.charges_billed_separately = None - self.total_overage = None - self.total_usage = None - self.azure_marketplace_service_charges = None + self.currency: Optional[str] = None + self.beginning_balance: Optional[float] = None + self.ending_balance: Optional[float] = None + self.new_purchases: Optional[float] = None + self.adjustments: Optional[float] = None + self.utilized: Optional[float] = None + self.service_overage: Optional[float] = None + self.charges_billed_separately: Optional[float] = None + self.total_overage: Optional[float] = None + self.total_usage: Optional[float] = None + self.azure_marketplace_service_charges: Optional[float] = None self.billing_frequency = billing_frequency - self.price_hidden = None - self.new_purchases_details = None - self.adjustment_details = None + self.price_hidden: Optional[bool] = None + self.overage_refund: Optional[float] = None + self.new_purchases_details: Optional[List["_models.BalancePropertiesNewPurchasesDetailsItem"]] = None + self.adjustment_details: Optional[List["_models.BalancePropertiesAdjustmentDetailsItem"]] = None class BalancePropertiesAdjustmentDetailsItem(_serialization.Model): @@ -271,11 +277,11 @@ class BalancePropertiesAdjustmentDetailsItem(_serialization.Model): "value": {"key": "value", "type": "float"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.name = None - self.value = None + self.name: Optional[str] = None + self.value: Optional[float] = None class BalancePropertiesNewPurchasesDetailsItem(_serialization.Model): @@ -299,11 +305,11 @@ class BalancePropertiesNewPurchasesDetailsItem(_serialization.Model): "value": {"key": "value", "type": "float"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.name = None - self.value = None + self.name: Optional[str] = None + self.value: Optional[float] = None class ProxyResource(_serialization.Model): @@ -335,20 +341,20 @@ class ProxyResource(_serialization.Model): "e_tag": {"key": "eTag", "type": "str"}, } - def __init__(self, *, e_tag: Optional[str] = None, **kwargs): + def __init__(self, *, e_tag: Optional[str] = None, **kwargs: Any) -> None: """ :keyword e_tag: eTag of the resource. To handle concurrent update scenario, this field will be used to determine whether the user is updating the latest version or not. :paramtype e_tag: str """ super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None self.e_tag = e_tag -class Budget(ProxyResource): # pylint: disable=too-many-instance-attributes +class Budget(ProxyResource): """A budget resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -420,8 +426,8 @@ def __init__( time_period: Optional["_models.BudgetTimePeriod"] = None, filter: Optional["_models.BudgetFilter"] = None, # pylint: disable=redefined-builtin notifications: Optional[Dict[str, "_models.Notification"]] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword e_tag: eTag of the resource. To handle concurrent update scenario, this field will be used to determine whether the user is updating the latest version or not. @@ -452,19 +458,19 @@ def __init__( self.time_grain = time_grain self.time_period = time_period self.filter = filter - self.current_spend = None + self.current_spend: Optional["_models.CurrentSpend"] = None self.notifications = notifications - self.forecast_spend = None + self.forecast_spend: Optional["_models.ForecastSpend"] = None class BudgetComparisonExpression(_serialization.Model): """The comparison expression to be used in the budgets. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar name: The name of the column to use in comparison. Required. :vartype name: str - :ivar operator: The operator to use for comparison. Required. "In" + :ivar operator: The operator to use for comparison. Required. Known values are: "In" and "In". :vartype operator: str or ~azure.mgmt.consumption.models.BudgetOperatorType :ivar values: Array of values to use for comparison. Required. :vartype values: list[str] @@ -482,11 +488,14 @@ class BudgetComparisonExpression(_serialization.Model): "values": {"key": "values", "type": "[str]"}, } - def __init__(self, *, name: str, operator: Union[str, "_models.BudgetOperatorType"], values: List[str], **kwargs): + def __init__( + self, *, name: str, operator: Union[str, "_models.BudgetOperatorType"], values: List[str], **kwargs: Any + ) -> None: """ :keyword name: The name of the column to use in comparison. Required. :paramtype name: str - :keyword operator: The operator to use for comparison. Required. "In" + :keyword operator: The operator to use for comparison. Required. Known values are: "In" and + "In". :paramtype operator: str or ~azure.mgmt.consumption.models.BudgetOperatorType :keyword values: Array of values to use for comparison. Required. :paramtype values: list[str] @@ -520,8 +529,8 @@ def __init__( and_property: Optional[List["_models.BudgetFilterProperties"]] = None, dimensions: Optional["_models.BudgetComparisonExpression"] = None, tags: Optional["_models.BudgetComparisonExpression"] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword and_property: The logical "AND" expression. Must have at least 2 items. :paramtype and_property: list[~azure.mgmt.consumption.models.BudgetFilterProperties] @@ -555,8 +564,8 @@ def __init__( *, dimensions: Optional["_models.BudgetComparisonExpression"] = None, tags: Optional["_models.BudgetComparisonExpression"] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword dimensions: Has comparison expression for a dimension. :paramtype dimensions: ~azure.mgmt.consumption.models.BudgetComparisonExpression @@ -589,17 +598,17 @@ class BudgetsListResult(_serialization.Model): "next_link": {"key": "nextLink", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.value = None - self.next_link = None + self.value: Optional[List["_models.Budget"]] = None + self.next_link: Optional[str] = None class BudgetTimePeriod(_serialization.Model): """The start and end date for a budget. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar start_date: The start date for the budget. Required. :vartype start_date: ~datetime.datetime @@ -617,7 +626,9 @@ class BudgetTimePeriod(_serialization.Model): "end_date": {"key": "endDate", "type": "iso-8601"}, } - def __init__(self, *, start_date: datetime.datetime, end_date: Optional[datetime.datetime] = None, **kwargs): + def __init__( + self, *, start_date: datetime.datetime, end_date: Optional[datetime.datetime] = None, **kwargs: Any + ) -> None: """ :keyword start_date: The start date for the budget. Required. :paramtype start_date: ~datetime.datetime @@ -647,13 +658,13 @@ class ChargesListResult(_serialization.Model): "value": {"key": "value", "type": "[ChargeSummary]"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.value = None + self.value: Optional[List["_models.ChargeSummary"]] = None -class ChargeSummary(Resource): +class ChargeSummary(ProxyResource): """A charge summary resource. You probably want to use the sub-classes and not this class directly. Known sub-classes are: @@ -661,18 +672,17 @@ class ChargeSummary(Resource): Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :ivar id: The full qualified ARM ID of an event. + :ivar id: Resource Id. :vartype id: str - :ivar name: The ID that uniquely identifies an event. + :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str - :ivar etag: The etag for the resource. - :vartype etag: str - :ivar tags: Resource tags. - :vartype tags: dict[str, str] + :ivar e_tag: eTag of the resource. To handle concurrent update scenario, this field will be + used to determine whether the user is updating the latest version or not. + :vartype e_tag: str :ivar kind: Specifies the kind of charge summary. Required. Known values are: "legacy" and "modern". :vartype kind: str or ~azure.mgmt.consumption.models.ChargeSummaryKind @@ -682,8 +692,6 @@ class ChargeSummary(Resource): "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, - "etag": {"readonly": True}, - "tags": {"readonly": True}, "kind": {"required": True}, } @@ -691,16 +699,19 @@ class ChargeSummary(Resource): "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, - "etag": {"key": "etag", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, + "e_tag": {"key": "eTag", "type": "str"}, "kind": {"key": "kind", "type": "str"}, } _subtype_map = {"kind": {"legacy": "LegacyChargeSummary", "modern": "ModernChargeSummary"}} - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) + def __init__(self, *, e_tag: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword e_tag: eTag of the resource. To handle concurrent update scenario, this field will be + used to determine whether the user is updating the latest version or not. + :paramtype e_tag: str + """ + super().__init__(e_tag=e_tag, **kwargs) self.kind: Optional[str] = None @@ -733,15 +744,15 @@ class CreditBalanceSummary(_serialization.Model): }, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.estimated_balance = None - self.current_balance = None - self.estimated_balance_in_billing_currency = None + self.estimated_balance: Optional["_models.Amount"] = None + self.current_balance: Optional["_models.Amount"] = None + self.estimated_balance_in_billing_currency: Optional["_models.AmountWithExchangeRate"] = None -class CreditSummary(ProxyResource): # pylint: disable=too-many-instance-attributes +class CreditSummary(ProxyResource): """A credit summary resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -769,6 +780,9 @@ class CreditSummary(ProxyResource): # pylint: disable=too-many-instance-attribu :vartype billing_currency: str :ivar reseller: Credit's reseller. :vartype reseller: ~azure.mgmt.consumption.models.Reseller + :ivar is_estimated_balance: If true, the listed details are based on an estimation and it will + be subjected to change. + :vartype is_estimated_balance: bool :ivar e_tag_properties_e_tag: The eTag for the resource. :vartype e_tag_properties_e_tag: str """ @@ -784,6 +798,7 @@ class CreditSummary(ProxyResource): # pylint: disable=too-many-instance-attribu "credit_currency": {"readonly": True}, "billing_currency": {"readonly": True}, "reseller": {"readonly": True}, + "is_estimated_balance": {"readonly": True}, "e_tag_properties_e_tag": {"readonly": True}, } @@ -799,24 +814,26 @@ class CreditSummary(ProxyResource): # pylint: disable=too-many-instance-attribu "credit_currency": {"key": "properties.creditCurrency", "type": "str"}, "billing_currency": {"key": "properties.billingCurrency", "type": "str"}, "reseller": {"key": "properties.reseller", "type": "Reseller"}, + "is_estimated_balance": {"key": "properties.isEstimatedBalance", "type": "bool"}, "e_tag_properties_e_tag": {"key": "properties.eTag", "type": "str"}, } - def __init__(self, *, e_tag: Optional[str] = None, **kwargs): + def __init__(self, *, e_tag: Optional[str] = None, **kwargs: Any) -> None: """ :keyword e_tag: eTag of the resource. To handle concurrent update scenario, this field will be used to determine whether the user is updating the latest version or not. :paramtype e_tag: str """ super().__init__(e_tag=e_tag, **kwargs) - self.balance_summary = None - self.pending_credit_adjustments = None - self.expired_credit = None - self.pending_eligible_charges = None - self.credit_currency = None - self.billing_currency = None - self.reseller = None - self.e_tag_properties_e_tag = None + self.balance_summary: Optional["_models.CreditBalanceSummary"] = None + self.pending_credit_adjustments: Optional["_models.Amount"] = None + self.expired_credit: Optional["_models.Amount"] = None + self.pending_eligible_charges: Optional["_models.Amount"] = None + self.credit_currency: Optional[str] = None + self.billing_currency: Optional[str] = None + self.reseller: Optional["_models.Reseller"] = None + self.is_estimated_balance: Optional[bool] = None + self.e_tag_properties_e_tag: Optional[str] = None class CurrentSpend(_serialization.Model): @@ -840,11 +857,11 @@ class CurrentSpend(_serialization.Model): "unit": {"key": "unit", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.amount = None - self.unit = None + self.amount: Optional[float] = None + self.unit: Optional[str] = None class DownloadProperties(_serialization.Model): @@ -868,11 +885,82 @@ class DownloadProperties(_serialization.Model): "valid_till": {"key": "validTill", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.download_url: Optional[str] = None + self.valid_till: Optional[str] = None + + +class ErrorAdditionalInfo(_serialization.Model): + """The resource management error additional info. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: JSON + """ + + _validation = { + "type": {"readonly": True}, + "info": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.type: Optional[str] = None + self.info: Optional[JSON] = None + + +class ErrorDetail(_serialization.Model): + """The error detail. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.mgmt.consumption.models.ErrorDetail] + :ivar additional_info: The error additional info. + :vartype additional_info: list[~azure.mgmt.consumption.models.ErrorAdditionalInfo] + """ + + _validation = { + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDetail]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, + } + + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.download_url = None - self.valid_till = 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 ErrorDetails(_serialization.Model): @@ -896,34 +984,62 @@ class ErrorDetails(_serialization.Model): "message": {"key": "message", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.code = None - self.message = None + self.code: Optional[str] = None + self.message: Optional[str] = None class ErrorResponse(_serialization.Model): - """Error response indicates that the service is not able to process the incoming request. The reason is provided in the error message. + """Common error response for all Azure Resource Manager APIs to return error details for failed + operations. (This also follows the OData error response format.). + + :ivar error: The error object. + :vartype error: ~azure.mgmt.consumption.models.ErrorDetail + """ + + _attribute_map = { + "error": {"key": "error", "type": "ErrorDetail"}, + } + + def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs: Any) -> None: + """ + :keyword error: The error object. + :paramtype error: ~azure.mgmt.consumption.models.ErrorDetail + """ + super().__init__(**kwargs) + self.error = error + + +class ErrorResponseAutoGenerated(_serialization.Model): + """Error response indicates that the service is not able to process the incoming request. The + reason is provided in the error message. Some Error responses: * - 429 TooManyRequests - Request is throttled. Retry after waiting for the time specified in the "x-ms-ratelimit-microsoft.consumption-retry-after" header. + 429 TooManyRequests - Request is throttled. Retry after waiting for the time specified in the + "x-ms-ratelimit-microsoft.consumption-retry-after" header. * - 503 ServiceUnavailable - Service is temporarily unavailable. Retry after waiting for the time specified in the "Retry-After" header. + 503 ServiceUnavailable - Service is temporarily unavailable. Retry after waiting for the time + specified in the "Retry-After" header. - :ivar error: The details of the error. - :vartype error: ~azure.mgmt.consumption.models.ErrorDetails + * + 504 Gateway Timeout - Service timed out while processing the request. Reduce the date range + in the request, if possible. + + :ivar error: The details of the error. + :vartype error: ~azure.mgmt.consumption.models.ErrorDetails """ _attribute_map = { "error": {"key": "error", "type": "ErrorDetails"}, } - def __init__(self, *, error: Optional["_models.ErrorDetails"] = None, **kwargs): + def __init__(self, *, error: Optional["_models.ErrorDetails"] = None, **kwargs: Any) -> None: """ :keyword error: The details of the error. :paramtype error: ~azure.mgmt.consumption.models.ErrorDetails @@ -953,14 +1069,14 @@ class Events(_serialization.Model): "next_link": {"key": "nextLink", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.value = None - self.next_link = None + self.value: Optional[List["_models.EventSummary"]] = None + self.next_link: Optional[str] = None -class EventSummary(ProxyResource): # pylint: disable=too-many-instance-attributes +class EventSummary(ProxyResource): """An event summary resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -987,10 +1103,21 @@ class EventSummary(ProxyResource): # pylint: disable=too-many-instance-attribut event. :vartype credit_expired: ~azure.mgmt.consumption.models.Amount :ivar charges: The amount of charges for events of type SettleCharges and - PendingEligibleCharges. + PendingEligibleCharges in Lot Currency. :vartype charges: ~azure.mgmt.consumption.models.Amount - :ivar closed_balance: The balance after the event. + :ivar charges_in_lot_currency: The amount of charges for events of type SettleCharges and + PendingEligibleCharges in Lot Currency. + :vartype charges_in_lot_currency: ~azure.mgmt.consumption.models.Amount + :ivar closed_balance: The balance after the event, Note: This will not be returned for + Contributor Organization Type in Multi-Entity consumption commitment. :vartype closed_balance: ~azure.mgmt.consumption.models.Amount + :ivar closed_balance_in_lot_currency: The balance after the event, Note: This will not be + returned for Contributor Organization Type in Multi-Entity consumption commitment. + :vartype closed_balance_in_lot_currency: ~azure.mgmt.consumption.models.Amount + :ivar billing_account_id: Identifier of the billing account. + :vartype billing_account_id: str + :ivar billing_account_display_name: Name of the billing account. + :vartype billing_account_display_name: str :ivar event_type: Identifies the type of the event. Known values are: "SettledCharges", "PendingCharges", "PendingAdjustments", "PendingNewCredit", "PendingExpiredCredit", "UnKnown", "NewCredit", and "CreditExpired". @@ -1030,9 +1157,14 @@ class EventSummary(ProxyResource): # pylint: disable=too-many-instance-attribut :ivar charges_in_billing_currency: The amount of charges for events of type SettleCharges and PendingEligibleCharges in billing currency. :vartype charges_in_billing_currency: ~azure.mgmt.consumption.models.AmountWithExchangeRate - :ivar closed_balance_in_billing_currency: The balance in billing currency after the event. + :ivar closed_balance_in_billing_currency: The balance in billing currency after the event, + Note: This will not be returned for Contributor Organization Type in Multi-Entity consumption + commitment. :vartype closed_balance_in_billing_currency: ~azure.mgmt.consumption.models.AmountWithExchangeRate + :ivar is_estimated_balance: If true, the listed details are based on an estimation and it will + be subjected to change. + :vartype is_estimated_balance: bool :ivar e_tag_properties_e_tag: The eTag for the resource. :vartype e_tag_properties_e_tag: str """ @@ -1047,7 +1179,11 @@ class EventSummary(ProxyResource): # pylint: disable=too-many-instance-attribut "adjustments": {"readonly": True}, "credit_expired": {"readonly": True}, "charges": {"readonly": True}, + "charges_in_lot_currency": {"readonly": True}, "closed_balance": {"readonly": True}, + "closed_balance_in_lot_currency": {"readonly": True}, + "billing_account_id": {"readonly": True}, + "billing_account_display_name": {"readonly": True}, "invoice_number": {"readonly": True}, "billing_profile_id": {"readonly": True}, "billing_profile_display_name": {"readonly": True}, @@ -1062,6 +1198,7 @@ class EventSummary(ProxyResource): # pylint: disable=too-many-instance-attribut "adjustments_in_billing_currency": {"readonly": True}, "charges_in_billing_currency": {"readonly": True}, "closed_balance_in_billing_currency": {"readonly": True}, + "is_estimated_balance": {"readonly": True}, "e_tag_properties_e_tag": {"readonly": True}, } @@ -1076,7 +1213,11 @@ class EventSummary(ProxyResource): # pylint: disable=too-many-instance-attribut "adjustments": {"key": "properties.adjustments", "type": "Amount"}, "credit_expired": {"key": "properties.creditExpired", "type": "Amount"}, "charges": {"key": "properties.charges", "type": "Amount"}, + "charges_in_lot_currency": {"key": "properties.chargesInLotCurrency", "type": "Amount"}, "closed_balance": {"key": "properties.closedBalance", "type": "Amount"}, + "closed_balance_in_lot_currency": {"key": "properties.closedBalanceInLotCurrency", "type": "Amount"}, + "billing_account_id": {"key": "properties.billingAccountId", "type": "str"}, + "billing_account_display_name": {"key": "properties.billingAccountDisplayName", "type": "str"}, "event_type": {"key": "properties.eventType", "type": "str"}, "invoice_number": {"key": "properties.invoiceNumber", "type": "str"}, "billing_profile_id": {"key": "properties.billingProfileId", "type": "str"}, @@ -1104,12 +1245,17 @@ class EventSummary(ProxyResource): # pylint: disable=too-many-instance-attribut "key": "properties.closedBalanceInBillingCurrency", "type": "AmountWithExchangeRate", }, + "is_estimated_balance": {"key": "properties.isEstimatedBalance", "type": "bool"}, "e_tag_properties_e_tag": {"key": "properties.eTag", "type": "str"}, } def __init__( # pylint: disable=too-many-locals - self, *, e_tag: Optional[str] = None, event_type: Optional[Union[str, "_models.EventType"]] = None, **kwargs - ): + self, + *, + e_tag: Optional[str] = None, + event_type: Optional[Union[str, "_models.EventType"]] = None, + **kwargs: Any + ) -> None: """ :keyword e_tag: eTag of the resource. To handle concurrent update scenario, this field will be used to determine whether the user is updating the latest version or not. @@ -1120,29 +1266,34 @@ def __init__( # pylint: disable=too-many-locals :paramtype event_type: str or ~azure.mgmt.consumption.models.EventType """ super().__init__(e_tag=e_tag, **kwargs) - self.transaction_date = None - self.description = None - self.new_credit = None - self.adjustments = None - self.credit_expired = None - self.charges = None - self.closed_balance = None + self.transaction_date: Optional[datetime.datetime] = None + self.description: Optional[str] = None + self.new_credit: Optional["_models.Amount"] = None + self.adjustments: Optional["_models.Amount"] = None + self.credit_expired: Optional["_models.Amount"] = None + self.charges: Optional["_models.Amount"] = None + self.charges_in_lot_currency: Optional["_models.Amount"] = None + self.closed_balance: Optional["_models.Amount"] = None + self.closed_balance_in_lot_currency: Optional["_models.Amount"] = None + self.billing_account_id: Optional[str] = None + self.billing_account_display_name: Optional[str] = None self.event_type = event_type - self.invoice_number = None - self.billing_profile_id = None - self.billing_profile_display_name = None - self.lot_id = None - self.lot_source = None - self.canceled_credit = None - self.credit_currency = None - self.billing_currency = None - self.reseller = None - self.credit_expired_in_billing_currency = None - self.new_credit_in_billing_currency = None - self.adjustments_in_billing_currency = None - self.charges_in_billing_currency = None - self.closed_balance_in_billing_currency = None - self.e_tag_properties_e_tag = None + self.invoice_number: Optional[str] = None + self.billing_profile_id: Optional[str] = None + self.billing_profile_display_name: Optional[str] = None + self.lot_id: Optional[str] = None + self.lot_source: Optional[str] = None + self.canceled_credit: Optional["_models.Amount"] = None + self.credit_currency: Optional[str] = None + self.billing_currency: Optional[str] = None + self.reseller: Optional["_models.Reseller"] = None + self.credit_expired_in_billing_currency: Optional["_models.AmountWithExchangeRate"] = None + self.new_credit_in_billing_currency: Optional["_models.AmountWithExchangeRate"] = None + self.adjustments_in_billing_currency: Optional["_models.AmountWithExchangeRate"] = None + self.charges_in_billing_currency: Optional["_models.AmountWithExchangeRate"] = None + self.closed_balance_in_billing_currency: Optional["_models.AmountWithExchangeRate"] = None + self.is_estimated_balance: Optional[bool] = None + self.e_tag_properties_e_tag: Optional[str] = None class ForecastSpend(_serialization.Model): @@ -1167,11 +1318,11 @@ class ForecastSpend(_serialization.Model): "unit": {"key": "unit", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.amount = None - self.unit = None + self.amount: Optional[float] = None + self.unit: Optional[str] = None class HighCasedErrorDetails(_serialization.Model): @@ -1195,34 +1346,37 @@ class HighCasedErrorDetails(_serialization.Model): "message": {"key": "message", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.code = None - self.message = None + self.code: Optional[str] = None + self.message: Optional[str] = None class HighCasedErrorResponse(_serialization.Model): - """Error response indicates that the service is not able to process the incoming request. The reason is provided in the error message. + """Error response indicates that the service is not able to process the incoming request. The + reason is provided in the error message. Some Error responses: * - 429 TooManyRequests - Request is throttled. Retry after waiting for the time specified in the "x-ms-ratelimit-microsoft.consumption-retry-after" header. + 429 TooManyRequests - Request is throttled. Retry after waiting for the time specified in the + "x-ms-ratelimit-microsoft.consumption-retry-after" header. * - 503 ServiceUnavailable - Service is temporarily unavailable. Retry after waiting for the time specified in the "Retry-After" header. + 503 ServiceUnavailable - Service is temporarily unavailable. Retry after waiting for the time + specified in the "Retry-After" header. - :ivar error: The details of the error. - :vartype error: ~azure.mgmt.consumption.models.HighCasedErrorDetails + :ivar error: The details of the error. + :vartype error: ~azure.mgmt.consumption.models.HighCasedErrorDetails """ _attribute_map = { "error": {"key": "error", "type": "HighCasedErrorDetails"}, } - def __init__(self, *, error: Optional["_models.HighCasedErrorDetails"] = None, **kwargs): + def __init__(self, *, error: Optional["_models.HighCasedErrorDetails"] = None, **kwargs: Any) -> None: """ :keyword error: The details of the error. :paramtype error: ~azure.mgmt.consumption.models.HighCasedErrorDetails @@ -1231,23 +1385,22 @@ def __init__(self, *, error: Optional["_models.HighCasedErrorDetails"] = None, * self.error = error -class LegacyChargeSummary(ChargeSummary): # pylint: disable=too-many-instance-attributes +class LegacyChargeSummary(ChargeSummary): """Legacy charge summary. Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :ivar id: The full qualified ARM ID of an event. + :ivar id: Resource Id. :vartype id: str - :ivar name: The ID that uniquely identifies an event. + :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str - :ivar etag: The etag for the resource. - :vartype etag: str - :ivar tags: Resource tags. - :vartype tags: dict[str, str] + :ivar e_tag: eTag of the resource. To handle concurrent update scenario, this field will be + used to determine whether the user is updating the latest version or not. + :vartype e_tag: str :ivar kind: Specifies the kind of charge summary. Required. Known values are: "legacy" and "modern". :vartype kind: str or ~azure.mgmt.consumption.models.ChargeSummaryKind @@ -1271,8 +1424,6 @@ class LegacyChargeSummary(ChargeSummary): # pylint: disable=too-many-instance-a "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, - "etag": {"readonly": True}, - "tags": {"readonly": True}, "kind": {"required": True}, "billing_period_id": {"readonly": True}, "usage_start": {"readonly": True}, @@ -1287,8 +1438,7 @@ class LegacyChargeSummary(ChargeSummary): # pylint: disable=too-many-instance-a "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, - "etag": {"key": "etag", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, + "e_tag": {"key": "eTag", "type": "str"}, "kind": {"key": "kind", "type": "str"}, "billing_period_id": {"key": "properties.billingPeriodId", "type": "str"}, "usage_start": {"key": "properties.usageStart", "type": "str"}, @@ -1299,17 +1449,21 @@ class LegacyChargeSummary(ChargeSummary): # pylint: disable=too-many-instance-a "currency": {"key": "properties.currency", "type": "str"}, } - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) + def __init__(self, *, e_tag: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword e_tag: eTag of the resource. To handle concurrent update scenario, this field will be + used to determine whether the user is updating the latest version or not. + :paramtype e_tag: str + """ + super().__init__(e_tag=e_tag, **kwargs) self.kind: str = "legacy" - self.billing_period_id = None - self.usage_start = None - self.usage_end = None - self.azure_charges = None - self.charges_billed_separately = None - self.azure_marketplace_charges = None - self.currency = None + self.billing_period_id: Optional[str] = None + self.usage_start: Optional[str] = None + self.usage_end: Optional[str] = None + self.azure_charges: Optional[float] = None + self.charges_billed_separately: Optional[float] = None + self.azure_marketplace_charges: Optional[float] = None + self.currency: Optional[str] = None class ResourceAttributes(_serialization.Model): @@ -1333,11 +1487,11 @@ class ResourceAttributes(_serialization.Model): "sku": {"key": "sku", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.location = None - self.sku = None + self.location: Optional[str] = None + self.sku: Optional[str] = None class ReservationRecommendation(Resource, ResourceAttributes): @@ -1348,7 +1502,7 @@ class ReservationRecommendation(Resource, ResourceAttributes): Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar location: Resource location. :vartype location: str @@ -1393,25 +1547,25 @@ class ReservationRecommendation(Resource, ResourceAttributes): _subtype_map = {"kind": {"legacy": "LegacyReservationRecommendation", "modern": "ModernReservationRecommendation"}} - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.location = None - self.sku = None + self.location: Optional[str] = None + self.sku: Optional[str] = None self.kind: Optional[str] = None - self.id = None - self.name = None - self.type = None - self.etag = None - self.tags = None + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + self.etag: Optional[str] = None + self.tags: Optional[Dict[str, str]] = None -class LegacyReservationRecommendation(ReservationRecommendation): # pylint: disable=too-many-instance-attributes +class LegacyReservationRecommendation(ReservationRecommendation): """Legacy reservation recommendation. Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar location: Resource location. :vartype location: str @@ -1444,7 +1598,7 @@ class LegacyReservationRecommendation(ReservationRecommendation): # pylint: dis :vartype meter_id: str :ivar resource_type: The azure resource type. :vartype resource_type: str - :ivar term: RI recommendations in one or three year terms. + :ivar term: Term period of the reservation. ex: P1M, P1Y or P3Y. :vartype term: str :ivar cost_with_no_reserved_instances: The total amount of cost without reserved instances. :vartype cost_with_no_reserved_instances: float @@ -1460,6 +1614,11 @@ class LegacyReservationRecommendation(ReservationRecommendation): # pylint: dis :vartype scope: str :ivar sku_properties: List of sku properties. :vartype sku_properties: list[~azure.mgmt.consumption.models.SkuProperty] + :ivar last_usage_date: The last usage date used for looking back for computing the + recommendation. + :vartype last_usage_date: ~datetime.datetime + :ivar total_hours: The total hours for which the cost is covered. + :vartype total_hours: int """ _validation = { @@ -1486,6 +1645,8 @@ class LegacyReservationRecommendation(ReservationRecommendation): # pylint: dis "first_usage_date": {"readonly": True}, "scope": {"required": True}, "sku_properties": {"readonly": True}, + "last_usage_date": {"readonly": True}, + "total_hours": {"readonly": True}, } _attribute_map = { @@ -1512,30 +1673,34 @@ class LegacyReservationRecommendation(ReservationRecommendation): # pylint: dis "first_usage_date": {"key": "properties.firstUsageDate", "type": "iso-8601"}, "scope": {"key": "properties.scope", "type": "str"}, "sku_properties": {"key": "properties.skuProperties", "type": "[SkuProperty]"}, + "last_usage_date": {"key": "properties.lastUsageDate", "type": "iso-8601"}, + "total_hours": {"key": "properties.totalHours", "type": "int"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: # pylint: disable=too-many-locals """ """ super().__init__(**kwargs) self.kind: str = "legacy" - self.look_back_period = None - self.instance_flexibility_ratio = None - self.instance_flexibility_group = None - self.normalized_size = None - self.recommended_quantity_normalized = None - self.meter_id = None - self.resource_type = None - self.term = None - self.cost_with_no_reserved_instances = None - self.recommended_quantity = None - self.total_cost_with_reserved_instances = None - self.net_savings = None - self.first_usage_date = None + self.look_back_period: Optional[str] = None + self.instance_flexibility_ratio: Optional[float] = None + self.instance_flexibility_group: Optional[str] = None + self.normalized_size: Optional[str] = None + self.recommended_quantity_normalized: Optional[float] = None + self.meter_id: Optional[str] = None + self.resource_type: Optional[str] = None + self.term: Optional[str] = None + self.cost_with_no_reserved_instances: Optional[float] = None + self.recommended_quantity: Optional[float] = None + self.total_cost_with_reserved_instances: Optional[float] = None + self.net_savings: Optional[float] = None + self.first_usage_date: Optional[datetime.datetime] = None self.scope: str = "legacy" - self.sku_properties = None + self.sku_properties: Optional[List["_models.SkuProperty"]] = None + self.last_usage_date: Optional[datetime.datetime] = None + self.total_hours: Optional[int] = None -class LegacyReservationRecommendationProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes +class LegacyReservationRecommendationProperties(_serialization.Model): # pylint: disable=name-too-long """The properties of the reservation recommendation. You probably want to use the sub-classes and not this class directly. Known sub-classes are: @@ -1544,7 +1709,7 @@ class LegacyReservationRecommendationProperties(_serialization.Model): # pylint Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar look_back_period: The number of days of usage to look back for recommendation. :vartype look_back_period: str @@ -1560,7 +1725,7 @@ class LegacyReservationRecommendationProperties(_serialization.Model): # pylint :vartype meter_id: str :ivar resource_type: The azure resource type. :vartype resource_type: str - :ivar term: RI recommendations in one or three year terms. + :ivar term: Term period of the reservation. ex: P1M, P1Y or P3Y. :vartype term: str :ivar cost_with_no_reserved_instances: The total amount of cost without reserved instances. :vartype cost_with_no_reserved_instances: float @@ -1576,6 +1741,11 @@ class LegacyReservationRecommendationProperties(_serialization.Model): # pylint :vartype scope: str :ivar sku_properties: List of sku properties. :vartype sku_properties: list[~azure.mgmt.consumption.models.SkuProperty] + :ivar last_usage_date: The last usage date used for looking back for computing the + recommendation. + :vartype last_usage_date: ~datetime.datetime + :ivar total_hours: The total hours for which the cost is covered. + :vartype total_hours: int """ _validation = { @@ -1594,6 +1764,8 @@ class LegacyReservationRecommendationProperties(_serialization.Model): # pylint "first_usage_date": {"readonly": True}, "scope": {"required": True}, "sku_properties": {"readonly": True}, + "last_usage_date": {"readonly": True}, + "total_hours": {"readonly": True}, } _attribute_map = { @@ -1612,6 +1784,8 @@ class LegacyReservationRecommendationProperties(_serialization.Model): # pylint "first_usage_date": {"key": "firstUsageDate", "type": "iso-8601"}, "scope": {"key": "scope", "type": "str"}, "sku_properties": {"key": "skuProperties", "type": "[SkuProperty]"}, + "last_usage_date": {"key": "lastUsageDate", "type": "iso-8601"}, + "total_hours": {"key": "totalHours", "type": "int"}, } _subtype_map = { @@ -1621,24 +1795,26 @@ class LegacyReservationRecommendationProperties(_serialization.Model): # pylint } } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.look_back_period = None - self.instance_flexibility_ratio = None - self.instance_flexibility_group = None - self.normalized_size = None - self.recommended_quantity_normalized = None - self.meter_id = None - self.resource_type = None - self.term = None - self.cost_with_no_reserved_instances = None - self.recommended_quantity = None - self.total_cost_with_reserved_instances = None - self.net_savings = None - self.first_usage_date = None + self.look_back_period: Optional[str] = None + self.instance_flexibility_ratio: Optional[float] = None + self.instance_flexibility_group: Optional[str] = None + self.normalized_size: Optional[str] = None + self.recommended_quantity_normalized: Optional[float] = None + self.meter_id: Optional[str] = None + self.resource_type: Optional[str] = None + self.term: Optional[str] = None + self.cost_with_no_reserved_instances: Optional[float] = None + self.recommended_quantity: Optional[float] = None + self.total_cost_with_reserved_instances: Optional[float] = None + self.net_savings: Optional[float] = None + self.first_usage_date: Optional[datetime.datetime] = None self.scope: Optional[str] = None - self.sku_properties = None + self.sku_properties: Optional[List["_models.SkuProperty"]] = None + self.last_usage_date: Optional[datetime.datetime] = None + self.total_hours: Optional[int] = None class ReservationTransactionResource(_serialization.Model): @@ -1670,16 +1846,16 @@ class ReservationTransactionResource(_serialization.Model): "tags": {"key": "tags", "type": "[str]"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.tags = None + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + self.tags: Optional[List[str]] = None -class ReservationTransaction(ReservationTransactionResource): # pylint: disable=too-many-instance-attributes +class ReservationTransaction(ReservationTransactionResource): """Reservation transaction resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -1805,35 +1981,35 @@ class ReservationTransaction(ReservationTransactionResource): # pylint: disable "overage": {"key": "properties.overage", "type": "float"}, } - def __init__(self, **kwargs): # pylint: disable=too-many-locals + def __init__(self, **kwargs: Any) -> None: # pylint: disable=too-many-locals """ """ super().__init__(**kwargs) - self.event_date = None - self.reservation_order_id = None - self.description = None - self.event_type = None - self.quantity = None - self.amount = None - self.currency = None - self.reservation_order_name = None - self.purchasing_enrollment = None - self.purchasing_subscription_guid = None - self.purchasing_subscription_name = None - self.arm_sku_name = None - self.term = None - self.region = None - self.account_name = None - self.account_owner_email = None - self.department_name = None - self.cost_center = None - self.current_enrollment = None - self.billing_frequency = None - self.billing_month = None - self.monetary_commitment = None - self.overage = None - - -class LegacyReservationTransaction(ReservationTransaction): # pylint: disable=too-many-instance-attributes + self.event_date: Optional[datetime.datetime] = None + self.reservation_order_id: Optional[str] = None + self.description: Optional[str] = None + self.event_type: Optional[str] = None + self.quantity: Optional[float] = None + self.amount: Optional[float] = None + self.currency: Optional[str] = None + self.reservation_order_name: Optional[str] = None + self.purchasing_enrollment: Optional[str] = None + self.purchasing_subscription_guid: Optional[str] = None + self.purchasing_subscription_name: Optional[str] = None + self.arm_sku_name: Optional[str] = None + self.term: Optional[str] = None + self.region: Optional[str] = None + self.account_name: Optional[str] = None + self.account_owner_email: Optional[str] = None + self.department_name: Optional[str] = None + self.cost_center: Optional[str] = None + self.current_enrollment: Optional[str] = None + self.billing_frequency: Optional[str] = None + self.billing_month: Optional[int] = None + self.monetary_commitment: Optional[float] = None + self.overage: Optional[float] = None + + +class LegacyReservationTransaction(ReservationTransaction): """Legacy Reservation transaction resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -1899,79 +2075,15 @@ class LegacyReservationTransaction(ReservationTransaction): # pylint: disable=t :vartype overage: float """ - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "tags": {"readonly": True}, - "event_date": {"readonly": True}, - "reservation_order_id": {"readonly": True}, - "description": {"readonly": True}, - "event_type": {"readonly": True}, - "quantity": {"readonly": True}, - "amount": {"readonly": True}, - "currency": {"readonly": True}, - "reservation_order_name": {"readonly": True}, - "purchasing_enrollment": {"readonly": True}, - "purchasing_subscription_guid": {"readonly": True}, - "purchasing_subscription_name": {"readonly": True}, - "arm_sku_name": {"readonly": True}, - "term": {"readonly": True}, - "region": {"readonly": True}, - "account_name": {"readonly": True}, - "account_owner_email": {"readonly": True}, - "department_name": {"readonly": True}, - "cost_center": {"readonly": True}, - "current_enrollment": {"readonly": True}, - "billing_frequency": {"readonly": True}, - "billing_month": {"readonly": True}, - "monetary_commitment": {"readonly": True}, - "overage": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "tags": {"key": "tags", "type": "[str]"}, - "event_date": {"key": "properties.eventDate", "type": "iso-8601"}, - "reservation_order_id": {"key": "properties.reservationOrderId", "type": "str"}, - "description": {"key": "properties.description", "type": "str"}, - "event_type": {"key": "properties.eventType", "type": "str"}, - "quantity": {"key": "properties.quantity", "type": "float"}, - "amount": {"key": "properties.amount", "type": "float"}, - "currency": {"key": "properties.currency", "type": "str"}, - "reservation_order_name": {"key": "properties.reservationOrderName", "type": "str"}, - "purchasing_enrollment": {"key": "properties.purchasingEnrollment", "type": "str"}, - "purchasing_subscription_guid": {"key": "properties.purchasingSubscriptionGuid", "type": "str"}, - "purchasing_subscription_name": {"key": "properties.purchasingSubscriptionName", "type": "str"}, - "arm_sku_name": {"key": "properties.armSkuName", "type": "str"}, - "term": {"key": "properties.term", "type": "str"}, - "region": {"key": "properties.region", "type": "str"}, - "account_name": {"key": "properties.accountName", "type": "str"}, - "account_owner_email": {"key": "properties.accountOwnerEmail", "type": "str"}, - "department_name": {"key": "properties.departmentName", "type": "str"}, - "cost_center": {"key": "properties.costCenter", "type": "str"}, - "current_enrollment": {"key": "properties.currentEnrollment", "type": "str"}, - "billing_frequency": {"key": "properties.billingFrequency", "type": "str"}, - "billing_month": {"key": "properties.billingMonth", "type": "int"}, - "monetary_commitment": {"key": "properties.monetaryCommitment", "type": "float"}, - "overage": {"key": "properties.overage", "type": "float"}, - } - - def __init__(self, **kwargs): # pylint: disable=too-many-locals - """ """ - super().__init__(**kwargs) - class LegacySharedScopeReservationRecommendationProperties( LegacyReservationRecommendationProperties -): # pylint: disable=too-many-instance-attributes +): # pylint: disable=name-too-long """The properties of the legacy reservation recommendation for shared scope. Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar look_back_period: The number of days of usage to look back for recommendation. :vartype look_back_period: str @@ -1987,7 +2099,7 @@ class LegacySharedScopeReservationRecommendationProperties( :vartype meter_id: str :ivar resource_type: The azure resource type. :vartype resource_type: str - :ivar term: RI recommendations in one or three year terms. + :ivar term: Term period of the reservation. ex: P1M, P1Y or P3Y. :vartype term: str :ivar cost_with_no_reserved_instances: The total amount of cost without reserved instances. :vartype cost_with_no_reserved_instances: float @@ -2003,6 +2115,11 @@ class LegacySharedScopeReservationRecommendationProperties( :vartype scope: str :ivar sku_properties: List of sku properties. :vartype sku_properties: list[~azure.mgmt.consumption.models.SkuProperty] + :ivar last_usage_date: The last usage date used for looking back for computing the + recommendation. + :vartype last_usage_date: ~datetime.datetime + :ivar total_hours: The total hours for which the cost is covered. + :vartype total_hours: int """ _validation = { @@ -2021,6 +2138,8 @@ class LegacySharedScopeReservationRecommendationProperties( "first_usage_date": {"readonly": True}, "scope": {"required": True}, "sku_properties": {"readonly": True}, + "last_usage_date": {"readonly": True}, + "total_hours": {"readonly": True}, } _attribute_map = { @@ -2039,9 +2158,11 @@ class LegacySharedScopeReservationRecommendationProperties( "first_usage_date": {"key": "firstUsageDate", "type": "iso-8601"}, "scope": {"key": "scope", "type": "str"}, "sku_properties": {"key": "skuProperties", "type": "[SkuProperty]"}, + "last_usage_date": {"key": "lastUsageDate", "type": "iso-8601"}, + "total_hours": {"key": "totalHours", "type": "int"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.scope: str = "Shared" @@ -2049,12 +2170,12 @@ def __init__(self, **kwargs): class LegacySingleScopeReservationRecommendationProperties( LegacyReservationRecommendationProperties -): # pylint: disable=too-many-instance-attributes +): # pylint: disable=name-too-long """The properties of the legacy reservation recommendation for single scope. Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar look_back_period: The number of days of usage to look back for recommendation. :vartype look_back_period: str @@ -2070,7 +2191,7 @@ class LegacySingleScopeReservationRecommendationProperties( :vartype meter_id: str :ivar resource_type: The azure resource type. :vartype resource_type: str - :ivar term: RI recommendations in one or three year terms. + :ivar term: Term period of the reservation. ex: P1M, P1Y or P3Y. :vartype term: str :ivar cost_with_no_reserved_instances: The total amount of cost without reserved instances. :vartype cost_with_no_reserved_instances: float @@ -2086,6 +2207,11 @@ class LegacySingleScopeReservationRecommendationProperties( :vartype scope: str :ivar sku_properties: List of sku properties. :vartype sku_properties: list[~azure.mgmt.consumption.models.SkuProperty] + :ivar last_usage_date: The last usage date used for looking back for computing the + recommendation. + :vartype last_usage_date: ~datetime.datetime + :ivar total_hours: The total hours for which the cost is covered. + :vartype total_hours: int :ivar subscription_id: Subscription id associated with single scoped recommendation. :vartype subscription_id: str """ @@ -2106,6 +2232,8 @@ class LegacySingleScopeReservationRecommendationProperties( "first_usage_date": {"readonly": True}, "scope": {"required": True}, "sku_properties": {"readonly": True}, + "last_usage_date": {"readonly": True}, + "total_hours": {"readonly": True}, "subscription_id": {"readonly": True}, } @@ -2125,14 +2253,16 @@ class LegacySingleScopeReservationRecommendationProperties( "first_usage_date": {"key": "firstUsageDate", "type": "iso-8601"}, "scope": {"key": "scope", "type": "str"}, "sku_properties": {"key": "skuProperties", "type": "[SkuProperty]"}, + "last_usage_date": {"key": "lastUsageDate", "type": "iso-8601"}, + "total_hours": {"key": "totalHours", "type": "int"}, "subscription_id": {"key": "subscriptionId", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.scope: str = "Single" - self.subscription_id = None + self.subscription_id: Optional[str] = None class UsageDetail(Resource): @@ -2143,7 +2273,7 @@ class UsageDetail(Resource): Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar id: The full qualified ARM ID of an event. :vartype id: str @@ -2180,18 +2310,18 @@ class UsageDetail(Resource): _subtype_map = {"kind": {"legacy": "LegacyUsageDetail", "modern": "ModernUsageDetail"}} - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.kind: Optional[str] = None -class LegacyUsageDetail(UsageDetail): # pylint: disable=too-many-instance-attributes +class LegacyUsageDetail(UsageDetail): """Legacy usage detail. Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar id: The full qualified ARM ID of an event. :vartype id: str @@ -2428,56 +2558,56 @@ class LegacyUsageDetail(UsageDetail): # pylint: disable=too-many-instance-attri "pricing_model": {"key": "properties.pricingModel", "type": "str"}, } - def __init__(self, **kwargs): # pylint: disable=too-many-locals + def __init__(self, **kwargs: Any) -> None: # pylint: disable=too-many-locals """ """ super().__init__(**kwargs) self.kind: str = "legacy" - self.billing_account_id = None - self.billing_account_name = None - self.billing_period_start_date = None - self.billing_period_end_date = None - self.billing_profile_id = None - self.billing_profile_name = None - self.account_owner_id = None - self.account_name = None - self.subscription_id = None - self.subscription_name = None - self.date = None - self.product = None - self.part_number = None - self.meter_id = None - self.meter_details = None - self.quantity = None - self.effective_price = None - self.cost = None - self.unit_price = None - self.billing_currency = None - self.resource_location = None - self.consumed_service = None - self.resource_id = None - self.resource_name = None - self.service_info1 = None - self.service_info2 = None - self.additional_info = None - self.invoice_section = None - self.cost_center = None - self.resource_group = None - self.reservation_id = None - self.reservation_name = None - self.product_order_id = None - self.product_order_name = None - self.offer_id = None - self.is_azure_credit_eligible = None - self.term = None - self.publisher_name = None - self.publisher_type = None - self.plan_name = None - self.charge_type = None - self.frequency = None - self.pay_g_price = None - self.benefit_id = None - self.benefit_name = None - self.pricing_model = None + self.billing_account_id: Optional[str] = None + self.billing_account_name: Optional[str] = None + self.billing_period_start_date: Optional[datetime.datetime] = None + self.billing_period_end_date: Optional[datetime.datetime] = None + self.billing_profile_id: Optional[str] = None + self.billing_profile_name: Optional[str] = None + self.account_owner_id: Optional[str] = None + self.account_name: Optional[str] = None + self.subscription_id: Optional[str] = None + self.subscription_name: Optional[str] = None + self.date: Optional[datetime.datetime] = None + self.product: Optional[str] = None + self.part_number: Optional[str] = None + self.meter_id: Optional[str] = None + self.meter_details: Optional["_models.MeterDetailsResponse"] = None + self.quantity: Optional[float] = None + self.effective_price: Optional[float] = None + self.cost: Optional[float] = None + self.unit_price: Optional[float] = None + self.billing_currency: Optional[str] = None + self.resource_location: Optional[str] = None + self.consumed_service: Optional[str] = None + self.resource_id: Optional[str] = None + self.resource_name: Optional[str] = None + self.service_info1: Optional[str] = None + self.service_info2: Optional[str] = None + self.additional_info: Optional[str] = None + self.invoice_section: Optional[str] = None + self.cost_center: Optional[str] = None + self.resource_group: Optional[str] = None + self.reservation_id: Optional[str] = None + self.reservation_name: Optional[str] = None + self.product_order_id: Optional[str] = None + self.product_order_name: Optional[str] = None + self.offer_id: Optional[str] = None + self.is_azure_credit_eligible: Optional[bool] = None + self.term: Optional[str] = None + self.publisher_name: Optional[str] = None + self.publisher_type: Optional[str] = None + self.plan_name: Optional[str] = None + self.charge_type: Optional[str] = None + self.frequency: Optional[str] = None + self.pay_g_price: Optional[float] = None + self.benefit_id: Optional[str] = None + self.benefit_name: Optional[str] = None + self.pricing_model: Optional[Union[str, "_models.PricingModelType"]] = None class Lots(_serialization.Model): @@ -2501,14 +2631,14 @@ class Lots(_serialization.Model): "next_link": {"key": "nextLink", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.value = None - self.next_link = None + self.value: Optional[List["_models.LotSummary"]] = None + self.next_link: Optional[str] = None -class LotSummary(ProxyResource): # pylint: disable=too-many-instance-attributes +class LotSummary(ProxyResource): """A lot summary resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -2522,7 +2652,8 @@ class LotSummary(ProxyResource): # pylint: disable=too-many-instance-attributes :ivar e_tag: eTag of the resource. To handle concurrent update scenario, this field will be used to determine whether the user is updating the latest version or not. :vartype e_tag: str - :ivar original_amount: The original amount of a lot. + :ivar original_amount: The original amount of a lot, Note: This will not be returned for + Contributor Organization Type in Multi-Entity consumption commitment. :vartype original_amount: ~azure.mgmt.consumption.models.Amount :ivar closed_balance: The balance as of the last invoice. :vartype closed_balance: ~azure.mgmt.consumption.models.Amount @@ -2545,7 +2676,9 @@ class LotSummary(ProxyResource): # pylint: disable=too-many-instance-attributes :vartype credit_currency: str :ivar billing_currency: The billing currency of the lot. :vartype billing_currency: str - :ivar original_amount_in_billing_currency: The original amount of a lot in billing currency. + :ivar original_amount_in_billing_currency: The original amount of a lot in billing currency, + Note: This will not be returned for Contributor Organization Type in Multi-Entity consumption + commitment. :vartype original_amount_in_billing_currency: ~azure.mgmt.consumption.models.AmountWithExchangeRate :ivar closed_balance_in_billing_currency: The balance as of the last invoice in billing @@ -2554,8 +2687,16 @@ class LotSummary(ProxyResource): # pylint: disable=too-many-instance-attributes ~azure.mgmt.consumption.models.AmountWithExchangeRate :ivar reseller: The reseller of the lot. :vartype reseller: ~azure.mgmt.consumption.models.Reseller + :ivar is_estimated_balance: If true, the listed details are based on an estimation and it will + be subjected to change. + :vartype is_estimated_balance: bool :ivar e_tag_properties_e_tag: The eTag for the resource. :vartype e_tag_properties_e_tag: str + :ivar organization_type: The organization type of the lot. Known values are: "Primary" and + "Contributor". + :vartype organization_type: str or ~azure.mgmt.consumption.models.OrganizationType + :ivar used_amount: Amount consumed from the commitment. + :vartype used_amount: ~azure.mgmt.consumption.models.Amount """ _validation = { @@ -2575,7 +2716,10 @@ class LotSummary(ProxyResource): # pylint: disable=too-many-instance-attributes "original_amount_in_billing_currency": {"readonly": True}, "closed_balance_in_billing_currency": {"readonly": True}, "reseller": {"readonly": True}, + "is_estimated_balance": {"readonly": True}, "e_tag_properties_e_tag": {"readonly": True}, + "organization_type": {"readonly": True}, + "used_amount": {"readonly": True}, } _attribute_map = { @@ -2602,33 +2746,39 @@ class LotSummary(ProxyResource): # pylint: disable=too-many-instance-attributes "type": "AmountWithExchangeRate", }, "reseller": {"key": "properties.reseller", "type": "Reseller"}, + "is_estimated_balance": {"key": "properties.isEstimatedBalance", "type": "bool"}, "e_tag_properties_e_tag": {"key": "properties.eTag", "type": "str"}, + "organization_type": {"key": "properties.OrganizationType", "type": "str"}, + "used_amount": {"key": "properties.usedAmount", "type": "Amount"}, } - def __init__(self, *, e_tag: Optional[str] = None, **kwargs): + def __init__(self, *, e_tag: Optional[str] = None, **kwargs: Any) -> None: """ :keyword e_tag: eTag of the resource. To handle concurrent update scenario, this field will be used to determine whether the user is updating the latest version or not. :paramtype e_tag: str """ super().__init__(e_tag=e_tag, **kwargs) - self.original_amount = None - self.closed_balance = None - self.source = None - self.start_date = None - self.expiration_date = None - self.po_number = None - self.purchased_date = None - self.status = None - self.credit_currency = None - self.billing_currency = None - self.original_amount_in_billing_currency = None - self.closed_balance_in_billing_currency = None - self.reseller = None - self.e_tag_properties_e_tag = None - - -class ManagementGroupAggregatedCostResult(Resource): # pylint: disable=too-many-instance-attributes + self.original_amount: Optional["_models.Amount"] = None + self.closed_balance: Optional["_models.Amount"] = None + self.source: Optional[Union[str, "_models.LotSource"]] = None + self.start_date: Optional[datetime.datetime] = None + self.expiration_date: Optional[datetime.datetime] = None + self.po_number: Optional[str] = None + self.purchased_date: Optional[datetime.datetime] = None + self.status: Optional[Union[str, "_models.Status"]] = None + self.credit_currency: Optional[str] = None + self.billing_currency: Optional[str] = None + self.original_amount_in_billing_currency: Optional["_models.AmountWithExchangeRate"] = None + self.closed_balance_in_billing_currency: Optional["_models.AmountWithExchangeRate"] = None + self.reseller: Optional["_models.Reseller"] = None + self.is_estimated_balance: Optional[bool] = None + self.e_tag_properties_e_tag: Optional[str] = None + self.organization_type: Optional[Union[str, "_models.OrganizationType"]] = None + self.used_amount: Optional["_models.Amount"] = None + + +class ManagementGroupAggregatedCostResult(Resource): """A management group aggregated cost resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -2707,8 +2857,8 @@ def __init__( children: Optional[List["_models.ManagementGroupAggregatedCostResult"]] = None, included_subscriptions: Optional[List[str]] = None, excluded_subscriptions: Optional[List[str]] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword children: Children of a management group. :paramtype children: list[~azure.mgmt.consumption.models.ManagementGroupAggregatedCostResult] @@ -2720,19 +2870,19 @@ def __init__( :paramtype excluded_subscriptions: list[str] """ super().__init__(**kwargs) - self.billing_period_id = None - self.usage_start = None - self.usage_end = None - self.azure_charges = None - self.marketplace_charges = None - self.charges_billed_separately = None - self.currency = None + self.billing_period_id: Optional[str] = None + self.usage_start: Optional[datetime.datetime] = None + self.usage_end: Optional[datetime.datetime] = None + self.azure_charges: Optional[float] = None + self.marketplace_charges: Optional[float] = None + self.charges_billed_separately: Optional[float] = None + self.currency: Optional[str] = None self.children = children self.included_subscriptions = included_subscriptions self.excluded_subscriptions = excluded_subscriptions -class Marketplace(Resource): # pylint: disable=too-many-instance-attributes +class Marketplace(Resource): """A marketplace resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -2871,39 +3021,40 @@ class Marketplace(Resource): # pylint: disable=too-many-instance-attributes "is_recurring_charge": {"key": "properties.isRecurringCharge", "type": "bool"}, } - def __init__(self, **kwargs): # pylint: disable=too-many-locals + def __init__(self, **kwargs: Any) -> None: # pylint: disable=too-many-locals """ """ super().__init__(**kwargs) - self.billing_period_id = None - self.usage_start = None - self.usage_end = None - self.resource_rate = None - self.offer_name = None - self.resource_group = None - self.additional_info = None - self.order_number = None - self.instance_name = None - self.instance_id = None - self.currency = None - self.consumed_quantity = None - self.unit_of_measure = None - self.pretax_cost = None - self.is_estimated = None - self.meter_id = None - self.subscription_guid = None - self.subscription_name = None - self.account_name = None - self.department_name = None - self.consumed_service = None - self.cost_center = None - self.additional_properties = None - self.publisher_name = None - self.plan_name = None - self.is_recurring_charge = None + self.billing_period_id: Optional[str] = None + self.usage_start: Optional[datetime.datetime] = None + self.usage_end: Optional[datetime.datetime] = None + self.resource_rate: Optional[float] = None + self.offer_name: Optional[str] = None + self.resource_group: Optional[str] = None + self.additional_info: Optional[str] = None + self.order_number: Optional[str] = None + self.instance_name: Optional[str] = None + self.instance_id: Optional[str] = None + self.currency: Optional[str] = None + self.consumed_quantity: Optional[float] = None + self.unit_of_measure: Optional[str] = None + self.pretax_cost: Optional[float] = None + self.is_estimated: Optional[bool] = None + self.meter_id: Optional[str] = None + self.subscription_guid: Optional[str] = None + self.subscription_name: Optional[str] = None + self.account_name: Optional[str] = None + self.department_name: Optional[str] = None + self.consumed_service: Optional[str] = None + self.cost_center: Optional[str] = None + self.additional_properties: Optional[str] = None + self.publisher_name: Optional[str] = None + self.plan_name: Optional[str] = None + self.is_recurring_charge: Optional[bool] = None class MarketplacesListResult(_serialization.Model): - """Result of listing marketplaces. It contains a list of available marketplaces in reverse chronological order by billing period. + """Result of listing marketplaces. It contains a list of available marketplaces in reverse + chronological order by billing period. Variables are only populated by the server, and will be ignored when sending a request. @@ -2923,11 +3074,11 @@ class MarketplacesListResult(_serialization.Model): "next_link": {"key": "nextLink", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.value = None - self.next_link = None + self.value: Optional[List["_models.Marketplace"]] = None + self.next_link: Optional[str] = None class MeterDetails(_serialization.Model): @@ -2982,18 +3133,18 @@ class MeterDetails(_serialization.Model): "service_tier": {"key": "serviceTier", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.meter_name = None - self.meter_category = None - self.meter_sub_category = None - self.unit = None - self.meter_location = None - self.total_included_quantity = None - self.pretax_standard_rate = None - self.service_name = None - self.service_tier = None + self.meter_name: Optional[str] = None + self.meter_category: Optional[str] = None + self.meter_sub_category: Optional[str] = None + self.unit: Optional[str] = None + self.meter_location: Optional[str] = None + self.total_included_quantity: Optional[float] = None + self.pretax_standard_rate: Optional[float] = None + self.service_name: Optional[str] = None + self.service_tier: Optional[str] = None class MeterDetailsResponse(_serialization.Model): @@ -3032,33 +3183,32 @@ class MeterDetailsResponse(_serialization.Model): "service_family": {"key": "serviceFamily", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.meter_name = None - self.meter_category = None - self.meter_sub_category = None - self.unit_of_measure = None - self.service_family = None + self.meter_name: Optional[str] = None + self.meter_category: Optional[str] = None + self.meter_sub_category: Optional[str] = None + self.unit_of_measure: Optional[str] = None + self.service_family: Optional[str] = None -class ModernChargeSummary(ChargeSummary): # pylint: disable=too-many-instance-attributes +class ModernChargeSummary(ChargeSummary): """Modern charge summary. Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :ivar id: The full qualified ARM ID of an event. + :ivar id: Resource Id. :vartype id: str - :ivar name: The ID that uniquely identifies an event. + :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str - :ivar etag: The etag for the resource. - :vartype etag: str - :ivar tags: Resource tags. - :vartype tags: dict[str, str] + :ivar e_tag: eTag of the resource. To handle concurrent update scenario, this field will be + used to determine whether the user is updating the latest version or not. + :vartype e_tag: str :ivar kind: Specifies the kind of charge summary. Required. Known values are: "legacy" and "modern". :vartype kind: str or ~azure.mgmt.consumption.models.ChargeSummaryKind @@ -3084,14 +3234,14 @@ class ModernChargeSummary(ChargeSummary): # pylint: disable=too-many-instance-a :vartype customer_id: str :ivar is_invoiced: Is charge Invoiced. :vartype is_invoiced: bool + :ivar subscription_id: Subscription guid. + :vartype subscription_id: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, - "etag": {"readonly": True}, - "tags": {"readonly": True}, "kind": {"required": True}, "billing_period_id": {"readonly": True}, "usage_start": {"readonly": True}, @@ -3104,14 +3254,14 @@ class ModernChargeSummary(ChargeSummary): # pylint: disable=too-many-instance-a "invoice_section_id": {"readonly": True}, "customer_id": {"readonly": True}, "is_invoiced": {"readonly": True}, + "subscription_id": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, - "etag": {"key": "etag", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, + "e_tag": {"key": "eTag", "type": "str"}, "kind": {"key": "kind", "type": "str"}, "billing_period_id": {"key": "properties.billingPeriodId", "type": "str"}, "usage_start": {"key": "properties.usageStart", "type": "str"}, @@ -3124,31 +3274,37 @@ class ModernChargeSummary(ChargeSummary): # pylint: disable=too-many-instance-a "invoice_section_id": {"key": "properties.invoiceSectionId", "type": "str"}, "customer_id": {"key": "properties.customerId", "type": "str"}, "is_invoiced": {"key": "properties.isInvoiced", "type": "bool"}, + "subscription_id": {"key": "properties.subscriptionId", "type": "str"}, } - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) + def __init__(self, *, e_tag: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword e_tag: eTag of the resource. To handle concurrent update scenario, this field will be + used to determine whether the user is updating the latest version or not. + :paramtype e_tag: str + """ + super().__init__(e_tag=e_tag, **kwargs) self.kind: str = "modern" - self.billing_period_id = None - self.usage_start = None - self.usage_end = None - self.azure_charges = None - self.charges_billed_separately = None - self.marketplace_charges = None - self.billing_account_id = None - self.billing_profile_id = None - self.invoice_section_id = None - self.customer_id = None - self.is_invoiced = None - - -class ModernReservationRecommendation(ReservationRecommendation): # pylint: disable=too-many-instance-attributes + self.billing_period_id: Optional[str] = None + self.usage_start: Optional[str] = None + self.usage_end: Optional[str] = None + self.azure_charges: Optional["_models.Amount"] = None + self.charges_billed_separately: Optional["_models.Amount"] = None + self.marketplace_charges: Optional["_models.Amount"] = None + self.billing_account_id: Optional[str] = None + self.billing_profile_id: Optional[str] = None + self.invoice_section_id: Optional[str] = None + self.customer_id: Optional[str] = None + self.is_invoiced: Optional[bool] = None + self.subscription_id: Optional[str] = None + + +class ModernReservationRecommendation(ReservationRecommendation): """Modern reservation recommendation. Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar location: Resource location. :vartype location: str @@ -3181,7 +3337,7 @@ class ModernReservationRecommendation(ReservationRecommendation): # pylint: dis :vartype recommended_quantity_normalized: float :ivar meter_id: The meter id (GUID). :vartype meter_id: str - :ivar term: RI recommendations in one or three year terms. + :ivar term: Term period of the reservation. ex: P1M, P1Y or P3Y. :vartype term: str :ivar cost_with_no_reserved_instances: The total amount of cost without reserved instances. :vartype cost_with_no_reserved_instances: ~azure.mgmt.consumption.models.Amount @@ -3201,6 +3357,11 @@ class ModernReservationRecommendation(ReservationRecommendation): # pylint: dis :vartype sku_properties: list[~azure.mgmt.consumption.models.SkuProperty] :ivar sku_name: This is the ARM Sku name. :vartype sku_name: str + :ivar last_usage_date: The last usage date used for looking back for computing the + recommendation. + :vartype last_usage_date: ~datetime.datetime + :ivar total_hours: The total hours for which the cost is covered. + :vartype total_hours: int """ _validation = { @@ -3229,6 +3390,8 @@ class ModernReservationRecommendation(ReservationRecommendation): # pylint: dis "scope": {"required": True}, "sku_properties": {"readonly": True}, "sku_name": {"readonly": True}, + "last_usage_date": {"readonly": True}, + "total_hours": {"readonly": True}, } _attribute_map = { @@ -3257,32 +3420,36 @@ class ModernReservationRecommendation(ReservationRecommendation): # pylint: dis "scope": {"key": "properties.scope", "type": "str"}, "sku_properties": {"key": "properties.skuProperties", "type": "[SkuProperty]"}, "sku_name": {"key": "properties.skuName", "type": "str"}, + "last_usage_date": {"key": "properties.lastUsageDate", "type": "iso-8601"}, + "total_hours": {"key": "properties.totalHours", "type": "int"}, } - def __init__(self, **kwargs): # pylint: disable=too-many-locals + def __init__(self, **kwargs: Any) -> None: # pylint: disable=too-many-locals """ """ super().__init__(**kwargs) self.kind: str = "modern" - self.location_properties_location = None - self.look_back_period = None - self.instance_flexibility_ratio = None - self.instance_flexibility_group = None - self.normalized_size = None - self.recommended_quantity_normalized = None - self.meter_id = None - self.term = None - self.cost_with_no_reserved_instances = None - self.recommended_quantity = None - self.resource_type = None - self.total_cost_with_reserved_instances = None - self.net_savings = None - self.first_usage_date = None + self.location_properties_location: Optional[str] = None + self.look_back_period: Optional[int] = None + self.instance_flexibility_ratio: Optional[float] = None + self.instance_flexibility_group: Optional[str] = None + self.normalized_size: Optional[str] = None + self.recommended_quantity_normalized: Optional[float] = None + self.meter_id: Optional[str] = None + self.term: Optional[str] = None + self.cost_with_no_reserved_instances: Optional["_models.Amount"] = None + self.recommended_quantity: Optional[float] = None + self.resource_type: Optional[str] = None + self.total_cost_with_reserved_instances: Optional["_models.Amount"] = None + self.net_savings: Optional["_models.Amount"] = None + self.first_usage_date: Optional[datetime.datetime] = None self.scope: str = "modern" - self.sku_properties = None - self.sku_name = None + self.sku_properties: Optional[List["_models.SkuProperty"]] = None + self.sku_name: Optional[str] = None + self.last_usage_date: Optional[datetime.datetime] = None + self.total_hours: Optional[int] = None -class ModernReservationRecommendationProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes +class ModernReservationRecommendationProperties(_serialization.Model): # pylint: disable=name-too-long """The properties of the reservation recommendation. You probably want to use the sub-classes and not this class directly. Known sub-classes are: @@ -3291,7 +3458,7 @@ class ModernReservationRecommendationProperties(_serialization.Model): # pylint Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar location: Resource Location. :vartype location: str @@ -3307,7 +3474,7 @@ class ModernReservationRecommendationProperties(_serialization.Model): # pylint :vartype recommended_quantity_normalized: float :ivar meter_id: The meter id (GUID). :vartype meter_id: str - :ivar term: RI recommendations in one or three year terms. + :ivar term: Term period of the reservation. ex: P1M, P1Y or P3Y. :vartype term: str :ivar cost_with_no_reserved_instances: The total amount of cost without reserved instances. :vartype cost_with_no_reserved_instances: ~azure.mgmt.consumption.models.Amount @@ -3327,6 +3494,11 @@ class ModernReservationRecommendationProperties(_serialization.Model): # pylint :vartype sku_properties: list[~azure.mgmt.consumption.models.SkuProperty] :ivar sku_name: This is the ARM Sku name. :vartype sku_name: str + :ivar last_usage_date: The last usage date used for looking back for computing the + recommendation. + :vartype last_usage_date: ~datetime.datetime + :ivar total_hours: The total hours for which the cost is covered. + :vartype total_hours: int """ _validation = { @@ -3347,6 +3519,8 @@ class ModernReservationRecommendationProperties(_serialization.Model): # pylint "scope": {"required": True}, "sku_properties": {"readonly": True}, "sku_name": {"readonly": True}, + "last_usage_date": {"readonly": True}, + "total_hours": {"readonly": True}, } _attribute_map = { @@ -3367,6 +3541,8 @@ class ModernReservationRecommendationProperties(_serialization.Model): # pylint "scope": {"key": "scope", "type": "str"}, "sku_properties": {"key": "skuProperties", "type": "[SkuProperty]"}, "sku_name": {"key": "skuName", "type": "str"}, + "last_usage_date": {"key": "lastUsageDate", "type": "iso-8601"}, + "total_hours": {"key": "totalHours", "type": "int"}, } _subtype_map = { @@ -3376,29 +3552,31 @@ class ModernReservationRecommendationProperties(_serialization.Model): # pylint } } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.location = None - self.look_back_period = None - self.instance_flexibility_ratio = None - self.instance_flexibility_group = None - self.normalized_size = None - self.recommended_quantity_normalized = None - self.meter_id = None - self.term = None - self.cost_with_no_reserved_instances = None - self.recommended_quantity = None - self.resource_type = None - self.total_cost_with_reserved_instances = None - self.net_savings = None - self.first_usage_date = None + self.location: Optional[str] = None + self.look_back_period: Optional[int] = None + self.instance_flexibility_ratio: Optional[float] = None + self.instance_flexibility_group: Optional[str] = None + self.normalized_size: Optional[str] = None + self.recommended_quantity_normalized: Optional[float] = None + self.meter_id: Optional[str] = None + self.term: Optional[str] = None + self.cost_with_no_reserved_instances: Optional["_models.Amount"] = None + self.recommended_quantity: Optional[float] = None + self.resource_type: Optional[str] = None + self.total_cost_with_reserved_instances: Optional["_models.Amount"] = None + self.net_savings: Optional["_models.Amount"] = None + self.first_usage_date: Optional[datetime.datetime] = None self.scope: Optional[str] = None - self.sku_properties = None - self.sku_name = None + self.sku_properties: Optional[List["_models.SkuProperty"]] = None + self.sku_name: Optional[str] = None + self.last_usage_date: Optional[datetime.datetime] = None + self.total_hours: Optional[int] = None -class ModernReservationTransaction(ReservationTransactionResource): # pylint: disable=too-many-instance-attributes +class ModernReservationTransaction(ReservationTransactionResource): """Modern Reservation transaction resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -3511,29 +3689,29 @@ class ModernReservationTransaction(ReservationTransactionResource): # pylint: d "term": {"key": "properties.term", "type": "str"}, } - def __init__(self, **kwargs): # pylint: disable=too-many-locals + def __init__(self, **kwargs: Any) -> None: # pylint: disable=too-many-locals """ """ super().__init__(**kwargs) - self.amount = None - self.arm_sku_name = None - self.billing_frequency = None - self.billing_profile_id = None - self.billing_profile_name = None - self.currency = None - self.description = None - self.event_date = None - self.event_type = None - self.invoice = None - self.invoice_id = None - self.invoice_section_id = None - self.invoice_section_name = None - self.purchasing_subscription_guid = None - self.purchasing_subscription_name = None - self.quantity = None - self.region = None - self.reservation_order_id = None - self.reservation_order_name = None - self.term = None + self.amount: Optional[float] = None + self.arm_sku_name: Optional[str] = None + self.billing_frequency: Optional[str] = None + self.billing_profile_id: Optional[str] = None + self.billing_profile_name: Optional[str] = None + self.currency: Optional[str] = None + self.description: Optional[str] = None + self.event_date: Optional[datetime.datetime] = None + self.event_type: Optional[str] = None + self.invoice: Optional[str] = None + self.invoice_id: Optional[str] = None + self.invoice_section_id: Optional[str] = None + self.invoice_section_name: Optional[str] = None + self.purchasing_subscription_guid: Optional[str] = None + self.purchasing_subscription_name: Optional[str] = None + self.quantity: Optional[float] = None + self.region: Optional[str] = None + self.reservation_order_id: Optional[str] = None + self.reservation_order_name: Optional[str] = None + self.term: Optional[str] = None class ModernReservationTransactionsListResult(_serialization.Model): @@ -3557,21 +3735,21 @@ class ModernReservationTransactionsListResult(_serialization.Model): "next_link": {"key": "nextLink", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.value = None - self.next_link = None + self.value: Optional[List["_models.ModernReservationTransaction"]] = None + self.next_link: Optional[str] = None class ModernSharedScopeReservationRecommendationProperties( ModernReservationRecommendationProperties -): # pylint: disable=too-many-instance-attributes +): # pylint: disable=name-too-long """The properties of the modern reservation recommendation for shared scope. Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar location: Resource Location. :vartype location: str @@ -3587,7 +3765,7 @@ class ModernSharedScopeReservationRecommendationProperties( :vartype recommended_quantity_normalized: float :ivar meter_id: The meter id (GUID). :vartype meter_id: str - :ivar term: RI recommendations in one or three year terms. + :ivar term: Term period of the reservation. ex: P1M, P1Y or P3Y. :vartype term: str :ivar cost_with_no_reserved_instances: The total amount of cost without reserved instances. :vartype cost_with_no_reserved_instances: ~azure.mgmt.consumption.models.Amount @@ -3607,6 +3785,11 @@ class ModernSharedScopeReservationRecommendationProperties( :vartype sku_properties: list[~azure.mgmt.consumption.models.SkuProperty] :ivar sku_name: This is the ARM Sku name. :vartype sku_name: str + :ivar last_usage_date: The last usage date used for looking back for computing the + recommendation. + :vartype last_usage_date: ~datetime.datetime + :ivar total_hours: The total hours for which the cost is covered. + :vartype total_hours: int """ _validation = { @@ -3627,6 +3810,8 @@ class ModernSharedScopeReservationRecommendationProperties( "scope": {"required": True}, "sku_properties": {"readonly": True}, "sku_name": {"readonly": True}, + "last_usage_date": {"readonly": True}, + "total_hours": {"readonly": True}, } _attribute_map = { @@ -3647,9 +3832,11 @@ class ModernSharedScopeReservationRecommendationProperties( "scope": {"key": "scope", "type": "str"}, "sku_properties": {"key": "skuProperties", "type": "[SkuProperty]"}, "sku_name": {"key": "skuName", "type": "str"}, + "last_usage_date": {"key": "lastUsageDate", "type": "iso-8601"}, + "total_hours": {"key": "totalHours", "type": "int"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.scope: str = "Shared" @@ -3657,12 +3844,12 @@ def __init__(self, **kwargs): class ModernSingleScopeReservationRecommendationProperties( ModernReservationRecommendationProperties -): # pylint: disable=too-many-instance-attributes +): # pylint: disable=name-too-long """The properties of the modern reservation recommendation for single scope. Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar location: Resource Location. :vartype location: str @@ -3678,7 +3865,7 @@ class ModernSingleScopeReservationRecommendationProperties( :vartype recommended_quantity_normalized: float :ivar meter_id: The meter id (GUID). :vartype meter_id: str - :ivar term: RI recommendations in one or three year terms. + :ivar term: Term period of the reservation. ex: P1M, P1Y or P3Y. :vartype term: str :ivar cost_with_no_reserved_instances: The total amount of cost without reserved instances. :vartype cost_with_no_reserved_instances: ~azure.mgmt.consumption.models.Amount @@ -3698,6 +3885,11 @@ class ModernSingleScopeReservationRecommendationProperties( :vartype sku_properties: list[~azure.mgmt.consumption.models.SkuProperty] :ivar sku_name: This is the ARM Sku name. :vartype sku_name: str + :ivar last_usage_date: The last usage date used for looking back for computing the + recommendation. + :vartype last_usage_date: ~datetime.datetime + :ivar total_hours: The total hours for which the cost is covered. + :vartype total_hours: int :ivar subscription_id: Subscription ID associated with single scoped recommendation. :vartype subscription_id: str """ @@ -3720,6 +3912,8 @@ class ModernSingleScopeReservationRecommendationProperties( "scope": {"required": True}, "sku_properties": {"readonly": True}, "sku_name": {"readonly": True}, + "last_usage_date": {"readonly": True}, + "total_hours": {"readonly": True}, "subscription_id": {"readonly": True}, } @@ -3741,22 +3935,24 @@ class ModernSingleScopeReservationRecommendationProperties( "scope": {"key": "scope", "type": "str"}, "sku_properties": {"key": "skuProperties", "type": "[SkuProperty]"}, "sku_name": {"key": "skuName", "type": "str"}, + "last_usage_date": {"key": "lastUsageDate", "type": "iso-8601"}, + "total_hours": {"key": "totalHours", "type": "int"}, "subscription_id": {"key": "subscriptionId", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.scope: str = "Single" - self.subscription_id = None + self.subscription_id: Optional[str] = None -class ModernUsageDetail(UsageDetail): # pylint: disable=too-many-instance-attributes +class ModernUsageDetail(UsageDetail): """Modern usage detail. Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar id: The full qualified ARM ID of an event. :vartype id: str @@ -4126,88 +4322,88 @@ class ModernUsageDetail(UsageDetail): # pylint: disable=too-many-instance-attri "cost_allocation_rule_name": {"key": "properties.costAllocationRuleName", "type": "str"}, } - def __init__(self, **kwargs): # pylint: disable=too-many-locals + def __init__(self, **kwargs: Any) -> None: # pylint: disable=too-many-locals """ """ super().__init__(**kwargs) self.kind: str = "modern" - self.billing_account_id = None - self.effective_price = None - self.pricing_model = None - self.billing_account_name = None - self.billing_period_start_date = None - self.billing_period_end_date = None - self.billing_profile_id = None - self.billing_profile_name = None - self.subscription_guid = None - self.subscription_name = None - self.date = None - self.product = None - self.meter_id = None - self.meter_name = None - self.meter_region = None - self.meter_category = None - self.meter_sub_category = None - self.service_family = None - self.quantity = None - self.unit_of_measure = None - self.instance_name = None - self.cost_in_usd = None - self.unit_price = None - self.billing_currency_code = None - self.resource_location = None - self.consumed_service = None - self.service_info1 = None - self.service_info2 = None - self.additional_info = None - self.invoice_section_id = None - self.invoice_section_name = None - self.cost_center = None - self.resource_group = None - self.reservation_id = None - self.reservation_name = None - self.product_order_id = None - self.product_order_name = None - self.is_azure_credit_eligible = None - self.term = None - self.publisher_name = None - self.publisher_type = None - self.charge_type = None - self.frequency = None - self.cost_in_billing_currency = None - self.cost_in_pricing_currency = None - self.exchange_rate = None - self.exchange_rate_date = None - self.invoice_id = None - self.previous_invoice_id = None - self.pricing_currency_code = None - self.product_identifier = None - self.resource_location_normalized = None - self.service_period_start_date = None - self.service_period_end_date = None - self.customer_tenant_id = None - self.customer_name = None - self.partner_tenant_id = None - self.partner_name = None - self.reseller_mpn_id = None - self.reseller_name = None - self.publisher_id = None - self.market_price = None - self.exchange_rate_pricing_to_billing = None - self.payg_cost_in_billing_currency = None - self.payg_cost_in_usd = None - self.partner_earned_credit_rate = None - self.partner_earned_credit_applied = None - self.pay_g_price = None - self.benefit_id = None - self.benefit_name = None - self.provider = None - self.cost_allocation_rule_name = None + self.billing_account_id: Optional[str] = None + self.effective_price: Optional[float] = None + self.pricing_model: Optional[Union[str, "_models.PricingModelType"]] = None + self.billing_account_name: Optional[str] = None + self.billing_period_start_date: Optional[datetime.datetime] = None + self.billing_period_end_date: Optional[datetime.datetime] = None + self.billing_profile_id: Optional[str] = None + self.billing_profile_name: Optional[str] = None + self.subscription_guid: Optional[str] = None + self.subscription_name: Optional[str] = None + self.date: Optional[datetime.datetime] = None + self.product: Optional[str] = None + self.meter_id: Optional[str] = None + self.meter_name: Optional[str] = None + self.meter_region: Optional[str] = None + self.meter_category: Optional[str] = None + self.meter_sub_category: Optional[str] = None + self.service_family: Optional[str] = None + self.quantity: Optional[float] = None + self.unit_of_measure: Optional[str] = None + self.instance_name: Optional[str] = None + self.cost_in_usd: Optional[float] = None + self.unit_price: Optional[float] = None + self.billing_currency_code: Optional[str] = None + self.resource_location: Optional[str] = None + self.consumed_service: Optional[str] = None + self.service_info1: Optional[str] = None + self.service_info2: Optional[str] = None + self.additional_info: Optional[str] = None + self.invoice_section_id: Optional[str] = None + self.invoice_section_name: Optional[str] = None + self.cost_center: Optional[str] = None + self.resource_group: Optional[str] = None + self.reservation_id: Optional[str] = None + self.reservation_name: Optional[str] = None + self.product_order_id: Optional[str] = None + self.product_order_name: Optional[str] = None + self.is_azure_credit_eligible: Optional[bool] = None + self.term: Optional[str] = None + self.publisher_name: Optional[str] = None + self.publisher_type: Optional[str] = None + self.charge_type: Optional[str] = None + self.frequency: Optional[str] = None + self.cost_in_billing_currency: Optional[float] = None + self.cost_in_pricing_currency: Optional[float] = None + self.exchange_rate: Optional[str] = None + self.exchange_rate_date: Optional[datetime.datetime] = None + self.invoice_id: Optional[str] = None + self.previous_invoice_id: Optional[str] = None + self.pricing_currency_code: Optional[str] = None + self.product_identifier: Optional[str] = None + self.resource_location_normalized: Optional[str] = None + self.service_period_start_date: Optional[datetime.datetime] = None + self.service_period_end_date: Optional[datetime.datetime] = None + self.customer_tenant_id: Optional[str] = None + self.customer_name: Optional[str] = None + self.partner_tenant_id: Optional[str] = None + self.partner_name: Optional[str] = None + self.reseller_mpn_id: Optional[str] = None + self.reseller_name: Optional[str] = None + self.publisher_id: Optional[str] = None + self.market_price: Optional[float] = None + self.exchange_rate_pricing_to_billing: Optional[float] = None + self.payg_cost_in_billing_currency: Optional[float] = None + self.payg_cost_in_usd: Optional[float] = None + self.partner_earned_credit_rate: Optional[float] = None + self.partner_earned_credit_applied: Optional[str] = None + self.pay_g_price: Optional[float] = None + self.benefit_id: Optional[str] = None + self.benefit_name: Optional[str] = None + self.provider: Optional[str] = None + self.cost_allocation_rule_name: Optional[str] = None class Notification(_serialization.Model): """The notification associated with a budget. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar enabled: The notification is enabled or not. Required. :vartype enabled: bool @@ -4268,8 +4464,8 @@ def __init__( contact_groups: Optional[List[str]] = None, threshold_type: Union[str, "_models.ThresholdType"] = "Actual", locale: Optional[Union[str, "_models.CultureCode"]] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword enabled: The notification is enabled or not. Required. :paramtype enabled: bool @@ -4335,14 +4531,14 @@ class Operation(_serialization.Model): "display": {"key": "display", "type": "OperationDisplay"}, } - def __init__(self, *, display: Optional["_models.OperationDisplay"] = None, **kwargs): + def __init__(self, *, display: Optional["_models.OperationDisplay"] = None, **kwargs: Any) -> None: """ :keyword display: The object that represents the operation. :paramtype display: ~azure.mgmt.consumption.models.OperationDisplay """ super().__init__(**kwargs) - self.id = None - self.name = None + self.id: Optional[str] = None + self.name: Optional[str] = None self.display = display @@ -4375,17 +4571,18 @@ class OperationDisplay(_serialization.Model): "description": {"key": "description", "type": "str"}, } - def __init__(self, **kwargs): + 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): - """Result of listing consumption operations. It contains a list of operations and a URL link to get the next set of results. + """Result of listing consumption operations. It contains a list of operations and a URL link to + get the next set of results. Variables are only populated by the server, and will be ignored when sending a request. @@ -4406,11 +4603,48 @@ class OperationListResult(_serialization.Model): "next_link": {"key": "nextLink", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.value = None - self.next_link = None + self.value: Optional[List["_models.Operation"]] = None + self.next_link: Optional[str] = None + + +class OperationStatus(_serialization.Model): + """The status of the long running operation. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar status: The status of the long running operation. Known values are: "Running", + "Completed", and "Failed". + :vartype status: str or ~azure.mgmt.consumption.models.OperationStatusType + :ivar download_url: The link (url) to download the pricesheet. + :vartype download_url: str + :ivar valid_till: Download link validity. + :vartype valid_till: ~datetime.datetime + """ + + _validation = { + "download_url": {"readonly": True}, + "valid_till": {"readonly": True}, + } + + _attribute_map = { + "status": {"key": "status", "type": "str"}, + "download_url": {"key": "properties.downloadUrl", "type": "str"}, + "valid_till": {"key": "properties.validTill", "type": "iso-8601"}, + } + + def __init__(self, *, status: Optional[Union[str, "_models.OperationStatusType"]] = None, **kwargs: Any) -> None: + """ + :keyword status: The status of the long running operation. Known values are: "Running", + "Completed", and "Failed". + :paramtype status: str or ~azure.mgmt.consumption.models.OperationStatusType + """ + super().__init__(**kwargs) + self.status = status + self.download_url: Optional[str] = None + self.valid_till: Optional[datetime.datetime] = None class PriceSheetProperties(_serialization.Model): @@ -4437,6 +4671,8 @@ class PriceSheetProperties(_serialization.Model): :vartype currency_code: str :ivar offer_id: Offer Id. :vartype offer_id: str + :ivar savings_plan: SavingsPlan Details. + :vartype savings_plan: ~azure.mgmt.consumption.models.SavingsPlan """ _validation = { @@ -4449,6 +4685,7 @@ class PriceSheetProperties(_serialization.Model): "unit_price": {"readonly": True}, "currency_code": {"readonly": True}, "offer_id": {"readonly": True}, + "savings_plan": {"readonly": True}, } _attribute_map = { @@ -4461,20 +4698,22 @@ class PriceSheetProperties(_serialization.Model): "unit_price": {"key": "unitPrice", "type": "float"}, "currency_code": {"key": "currencyCode", "type": "str"}, "offer_id": {"key": "offerId", "type": "str"}, + "savings_plan": {"key": "savingsPlan", "type": "SavingsPlan"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.billing_period_id = None - self.meter_id = None - self.meter_details = None - self.unit_of_measure = None - self.included_quantity = None - self.part_number = None - self.unit_price = None - self.currency_code = None - self.offer_id = None + self.billing_period_id: Optional[str] = None + self.meter_id: Optional[str] = None + self.meter_details: Optional["_models.MeterDetails"] = None + self.unit_of_measure: Optional[str] = None + self.included_quantity: Optional[float] = None + self.part_number: Optional[str] = None + self.unit_price: Optional[float] = None + self.currency_code: Optional[str] = None + self.offer_id: Optional[str] = None + self.savings_plan: Optional["_models.SavingsPlan"] = None class PriceSheetResult(Resource): @@ -4522,12 +4761,12 @@ class PriceSheetResult(Resource): "download": {"key": "properties.download", "type": "MeterDetails"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.pricesheets = None - self.next_link = None - self.download = None + self.pricesheets: Optional[List["_models.PriceSheetProperties"]] = None + self.next_link: Optional[str] = None + self.download: Optional["_models.MeterDetails"] = None class Reseller(_serialization.Model): @@ -4551,14 +4790,14 @@ class Reseller(_serialization.Model): "reseller_description": {"key": "resellerDescription", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.reseller_id = None - self.reseller_description = None + self.reseller_id: Optional[str] = None + self.reseller_description: Optional[str] = None -class ReservationDetail(Resource): # pylint: disable=too-many-instance-attributes +class ReservationDetail(Resource): """reservation detail resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -4645,20 +4884,20 @@ class ReservationDetail(Resource): # pylint: disable=too-many-instance-attribut "kind": {"key": "properties.kind", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.reservation_order_id = None - self.instance_flexibility_ratio = None - self.instance_flexibility_group = None - self.reservation_id = None - self.sku_name = None - self.reserved_hours = None - self.usage_date = None - self.used_hours = None - self.instance_id = None - self.total_reserved_quantity = None - self.kind = None + self.reservation_order_id: Optional[str] = None + self.instance_flexibility_ratio: Optional[str] = None + self.instance_flexibility_group: Optional[str] = None + self.reservation_id: Optional[str] = None + self.sku_name: Optional[str] = None + self.reserved_hours: Optional[float] = None + self.usage_date: Optional[datetime.datetime] = None + self.used_hours: Optional[float] = None + self.instance_id: Optional[str] = None + self.total_reserved_quantity: Optional[float] = None + self.kind: Optional[str] = None class ReservationDetailsListResult(_serialization.Model): @@ -4682,14 +4921,16 @@ class ReservationDetailsListResult(_serialization.Model): "next_link": {"key": "nextLink", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.value = None - self.next_link = None + self.value: Optional[List["_models.ReservationDetail"]] = None + self.next_link: Optional[str] = None -class ReservationRecommendationDetailsCalculatedSavingsProperties(_serialization.Model): +class ReservationRecommendationDetailsCalculatedSavingsProperties( + _serialization.Model +): # pylint: disable=name-too-long """Details of estimated savings. The costs and savings are estimated for the term. Variables are only populated by the server, and will be ignored when sending a request. @@ -4732,23 +4973,23 @@ class ReservationRecommendationDetailsCalculatedSavingsProperties(_serialization "savings": {"key": "savings", "type": "float"}, } - def __init__(self, *, reserved_unit_count: Optional[float] = None, **kwargs): + def __init__(self, *, reserved_unit_count: Optional[float] = None, **kwargs: Any) -> None: """ :keyword reserved_unit_count: The number of reserved units used to calculate savings. Always 1 for virtual machines. :paramtype reserved_unit_count: float """ super().__init__(**kwargs) - self.on_demand_cost = None - self.overage_cost = None - self.quantity = None - self.reservation_cost = None - self.total_reservation_cost = None + self.on_demand_cost: Optional[float] = None + self.overage_cost: Optional[float] = None + self.quantity: Optional[float] = None + self.reservation_cost: Optional[float] = None + self.total_reservation_cost: Optional[float] = None self.reserved_unit_count = reserved_unit_count - self.savings = None + self.savings: Optional[float] = None -class ReservationRecommendationDetailsModel(Resource): # pylint: disable=too-many-instance-attributes +class ReservationRecommendationDetailsModel(Resource): """Reservation recommendation details. Variables are only populated by the server, and will be ignored when sending a request. @@ -4813,7 +5054,7 @@ class ReservationRecommendationDetailsModel(Resource): # pylint: disable=too-ma "usage": {"key": "properties.usage", "type": "ReservationRecommendationDetailsUsageProperties"}, } - def __init__(self, *, location: Optional[str] = None, sku: Optional[str] = None, **kwargs): + def __init__(self, *, location: Optional[str] = None, sku: Optional[str] = None, **kwargs: Any) -> None: """ :keyword location: Resource Location. :paramtype location: str @@ -4823,15 +5064,15 @@ def __init__(self, *, location: Optional[str] = None, sku: Optional[str] = None, super().__init__(**kwargs) self.location = location self.sku = sku - self.currency = None - self.resource = None - self.resource_group = None - self.savings = None - self.scope = None - self.usage = None + self.currency: Optional[str] = None + self.resource: Optional["_models.ReservationRecommendationDetailsResourceProperties"] = None + self.resource_group: Optional[str] = None + self.savings: Optional["_models.ReservationRecommendationDetailsSavingsProperties"] = None + self.scope: Optional[str] = None + self.usage: Optional["_models.ReservationRecommendationDetailsUsageProperties"] = None -class ReservationRecommendationDetailsResourceProperties(_serialization.Model): +class ReservationRecommendationDetailsResourceProperties(_serialization.Model): # pylint: disable=name-too-long """Details of the resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -4869,18 +5110,18 @@ class ReservationRecommendationDetailsResourceProperties(_serialization.Model): "resource_type": {"key": "resourceType", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.applied_scopes = None - self.on_demand_rate = None - self.product = None - self.region = None - self.reservation_rate = None - self.resource_type = None + self.applied_scopes: Optional[List[str]] = None + self.on_demand_rate: Optional[float] = None + self.product: Optional[str] = None + self.region: Optional[str] = None + self.reservation_rate: Optional[float] = None + self.resource_type: Optional[str] = None -class ReservationRecommendationDetailsSavingsProperties(_serialization.Model): +class ReservationRecommendationDetailsSavingsProperties(_serialization.Model): # pylint: disable=name-too-long """Details of the estimated savings. Variables are only populated by the server, and will be ignored when sending a request. @@ -4893,7 +5134,7 @@ class ReservationRecommendationDetailsSavingsProperties(_serialization.Model): :vartype look_back_period: int :ivar recommended_quantity: Number of recommended units of the resource. :vartype recommended_quantity: float - :ivar reservation_order_term: Term period of the reservation, ex: P1Y or P3Y. + :ivar reservation_order_term: Term period of the reservation. ex: P1M, P1Y or P3Y. :vartype reservation_order_term: str :ivar savings_type: Type of savings, ex: instance. :vartype savings_type: str @@ -4927,8 +5168,8 @@ def __init__( calculated_savings: Optional[ List["_models.ReservationRecommendationDetailsCalculatedSavingsProperties"] ] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword calculated_savings: List of calculated savings. :paramtype calculated_savings: @@ -4936,14 +5177,14 @@ def __init__( """ super().__init__(**kwargs) self.calculated_savings = calculated_savings - self.look_back_period = None - self.recommended_quantity = None - self.reservation_order_term = None - self.savings_type = None - self.unit_of_measure = None + self.look_back_period: Optional[int] = None + self.recommended_quantity: Optional[float] = None + self.reservation_order_term: Optional[str] = None + self.savings_type: Optional[str] = None + self.unit_of_measure: Optional[str] = None -class ReservationRecommendationDetailsUsageProperties(_serialization.Model): +class ReservationRecommendationDetailsUsageProperties(_serialization.Model): # pylint: disable=name-too-long """Details about historical usage data that has been used for computing the recommendation. Variables are only populated by the server, and will be ignored when sending a request. @@ -4979,14 +5220,14 @@ class ReservationRecommendationDetailsUsageProperties(_serialization.Model): "usage_grain": {"key": "usageGrain", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.first_consumption_date = None - self.last_consumption_date = None - self.look_back_unit_type = None - self.usage_data = None - self.usage_grain = None + self.first_consumption_date: Optional[str] = None + self.last_consumption_date: Optional[str] = None + self.look_back_unit_type: Optional[str] = None + self.usage_data: Optional[List[float]] = None + self.usage_grain: Optional[str] = None class ReservationRecommendationsListResult(_serialization.Model): @@ -5014,12 +5255,12 @@ class ReservationRecommendationsListResult(_serialization.Model): "previous_link": {"key": "previousLink", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.value = None - self.next_link = None - self.previous_link = None + self.value: Optional[List["_models.ReservationRecommendation"]] = None + self.next_link: Optional[str] = None + self.previous_link: Optional[str] = None class ReservationSummariesListResult(_serialization.Model): @@ -5043,14 +5284,14 @@ class ReservationSummariesListResult(_serialization.Model): "next_link": {"key": "nextLink", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.value = None - self.next_link = None + self.value: Optional[List["_models.ReservationSummary"]] = None + self.next_link: Optional[str] = None -class ReservationSummary(Resource): # pylint: disable=too-many-instance-attributes +class ReservationSummary(Resource): """reservation summary resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -5157,24 +5398,24 @@ class ReservationSummary(Resource): # pylint: disable=too-many-instance-attribu "utilized_percentage": {"key": "properties.utilizedPercentage", "type": "float"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.reservation_order_id = None - self.reservation_id = None - self.sku_name = None - self.reserved_hours = None - self.usage_date = None - self.used_hours = None - self.min_utilization_percentage = None - self.avg_utilization_percentage = None - self.max_utilization_percentage = None - self.kind = None - self.purchased_quantity = None - self.remaining_quantity = None - self.total_reserved_quantity = None - self.used_quantity = None - self.utilized_percentage = None + self.reservation_order_id: Optional[str] = None + self.reservation_id: Optional[str] = None + self.sku_name: Optional[str] = None + self.reserved_hours: Optional[float] = None + self.usage_date: Optional[datetime.datetime] = None + self.used_hours: Optional[float] = None + self.min_utilization_percentage: Optional[float] = None + self.avg_utilization_percentage: Optional[float] = None + self.max_utilization_percentage: Optional[float] = None + self.kind: Optional[str] = None + self.purchased_quantity: Optional[float] = None + self.remaining_quantity: Optional[float] = None + self.total_reserved_quantity: Optional[float] = None + self.used_quantity: Optional[float] = None + self.utilized_percentage: Optional[float] = None class ReservationTransactionsListResult(_serialization.Model): @@ -5198,11 +5439,44 @@ class ReservationTransactionsListResult(_serialization.Model): "next_link": {"key": "nextLink", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value: Optional[List["_models.ReservationTransaction"]] = None + self.next_link: Optional[str] = None + + +class SavingsPlan(_serialization.Model): + """The properties of the SavingsPlan. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar term: SavingsPlan term. + :vartype term: str + :ivar market_price: SavingsPlan Market Price. + :vartype market_price: float + :ivar effective_price: SavingsPlan Effective Price. + :vartype effective_price: float + """ + + _validation = { + "term": {"readonly": True}, + "market_price": {"readonly": True}, + "effective_price": {"readonly": True}, + } + + _attribute_map = { + "term": {"key": "term", "type": "str"}, + "market_price": {"key": "marketPrice", "type": "float"}, + "effective_price": {"key": "effectivePrice", "type": "float"}, + } + + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.value = None - self.next_link = None + self.term: Optional[str] = None + self.market_price: Optional[float] = None + self.effective_price: Optional[float] = None class SkuProperty(_serialization.Model): @@ -5226,11 +5500,11 @@ class SkuProperty(_serialization.Model): "value": {"key": "value", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.name = None - self.value = None + self.name: Optional[str] = None + self.value: Optional[str] = None class Tag(_serialization.Model): @@ -5247,7 +5521,7 @@ class Tag(_serialization.Model): "value": {"key": "value", "type": "[str]"}, } - def __init__(self, *, key: Optional[str] = None, value: Optional[List[str]] = None, **kwargs): + def __init__(self, *, key: Optional[str] = None, value: Optional[List[str]] = None, **kwargs: Any) -> None: """ :keyword key: Tag key. :paramtype key: str @@ -5299,7 +5573,9 @@ class TagsResult(ProxyResource): "previous_link": {"key": "properties.previousLink", "type": "str"}, } - def __init__(self, *, e_tag: Optional[str] = None, tags: Optional[List["_models.Tag"]] = None, **kwargs): + def __init__( + self, *, e_tag: Optional[str] = None, tags: Optional[List["_models.Tag"]] = None, **kwargs: Any + ) -> None: """ :keyword e_tag: eTag of the resource. To handle concurrent update scenario, this field will be used to determine whether the user is updating the latest version or not. @@ -5309,12 +5585,13 @@ def __init__(self, *, e_tag: Optional[str] = None, tags: Optional[List["_models. """ super().__init__(e_tag=e_tag, **kwargs) self.tags = tags - self.next_link = None - self.previous_link = None + self.next_link: Optional[str] = None + self.previous_link: Optional[str] = None class UsageDetailsListResult(_serialization.Model): - """Result of listing usage details. It contains a list of available usage details in reverse chronological order by billing period. + """Result of listing usage details. It contains a list of available usage details in reverse + chronological order by billing period. Variables are only populated by the server, and will be ignored when sending a request. @@ -5334,8 +5611,8 @@ class UsageDetailsListResult(_serialization.Model): "next_link": {"key": "nextLink", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.value = None - self.next_link = None + self.value: Optional[List["_models.UsageDetail"]] = None + self.next_link: Optional[str] = None diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/__init__.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/__init__.py index 33de5eb645bc..42a8462b32ee 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/__init__.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/__init__.py @@ -5,30 +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 ._usage_details_operations import UsageDetailsOperations -from ._marketplaces_operations import MarketplacesOperations -from ._budgets_operations import BudgetsOperations -from ._tags_operations import TagsOperations -from ._charges_operations import ChargesOperations -from ._balances_operations import BalancesOperations -from ._reservations_summaries_operations import ReservationsSummariesOperations -from ._reservations_details_operations import ReservationsDetailsOperations -from ._reservation_recommendations_operations import ReservationRecommendationsOperations -from ._reservation_recommendation_details_operations import ReservationRecommendationDetailsOperations -from ._reservation_transactions_operations import ReservationTransactionsOperations -from ._price_sheet_operations import PriceSheetOperations -from ._operations import Operations -from ._aggregated_cost_operations import AggregatedCostOperations -from ._events_operations import EventsOperations -from ._lots_operations import LotsOperations -from ._credits_operations import CreditsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._price_sheet_operations import PriceSheetOperations # type: ignore +from ._usage_details_operations import UsageDetailsOperations # type: ignore +from ._marketplaces_operations import MarketplacesOperations # type: ignore +from ._budgets_operations import BudgetsOperations # type: ignore +from ._tags_operations import TagsOperations # type: ignore +from ._charges_operations import ChargesOperations # type: ignore +from ._balances_operations import BalancesOperations # type: ignore +from ._reservations_summaries_operations import ReservationsSummariesOperations # type: ignore +from ._reservations_details_operations import ReservationsDetailsOperations # type: ignore +from ._reservation_recommendations_operations import ReservationRecommendationsOperations # type: ignore +from ._reservation_recommendation_details_operations import ReservationRecommendationDetailsOperations # type: ignore +from ._reservation_transactions_operations import ReservationTransactionsOperations # type: ignore +from ._operations import Operations # type: ignore +from ._aggregated_cost_operations import AggregatedCostOperations # type: ignore +from ._events_operations import EventsOperations # type: ignore +from ._lots_operations import LotsOperations # type: ignore +from ._credits_operations import CreditsOperations # 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__ = [ + "PriceSheetOperations", "UsageDetailsOperations", "MarketplacesOperations", "BudgetsOperations", @@ -40,12 +47,11 @@ "ReservationRecommendationsOperations", "ReservationRecommendationDetailsOperations", "ReservationTransactionsOperations", - "PriceSheetOperations", "Operations", "AggregatedCostOperations", "EventsOperations", "LotsOperations", "CreditsOperations", ] -__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/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_aggregated_cost_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_aggregated_cost_operations.py index 9c2f27dc3073..6d0b77787b30 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_aggregated_cost_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_aggregated_cost_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# 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 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, _format_url_section +from .._configuration import ConsumptionManagementClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -45,19 +41,19 @@ def build_get_by_management_group_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Consumption/aggregatedcost", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -70,26 +66,26 @@ def build_get_by_management_group_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_get_for_billing_period_by_management_group_request( +def build_get_for_billing_period_by_management_group_request( # pylint: disable=name-too-long management_group_id: str, billing_period_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/aggregatedCost", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), "billingPeriodName": _SERIALIZER.url("billing_period_name", billing_period_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -114,10 +110,12 @@ class AggregatedCostOperations: 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: ConsumptionManagementClientConfiguration = ( + 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_by_management_group( @@ -126,6 +124,9 @@ def get_by_management_group( """Provides the aggregate cost of a management group and all child management groups by current billing period. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param management_group_id: Azure Management Group ID. Required. :type management_group_id: str :param filter: May be used to filter aggregated cost by properties/usageStart (Utc time), @@ -133,12 +134,11 @@ def get_by_management_group( does not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair string where key and value is separated by a colon (:). Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ManagementGroupAggregatedCostResult or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.ManagementGroupAggregatedCostResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -149,61 +149,56 @@ def get_by_management_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ManagementGroupAggregatedCostResult] = kwargs.pop("cls", None) - request = build_get_by_management_group_request( + _request = build_get_by_management_group_request( management_group_id=management_group_id, filter=filter, api_version=api_version, - template_url=self.get_by_management_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ManagementGroupAggregatedCostResult", pipeline_response) + deserialized = self._deserialize("ManagementGroupAggregatedCostResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - get_by_management_group.metadata = { - "url": "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Consumption/aggregatedcost" - } + return deserialized # type: ignore @distributed_trace - def get_for_billing_period_by_management_group( + def get_for_billing_period_by_management_group( # pylint: disable=name-too-long self, management_group_id: str, billing_period_name: str, **kwargs: Any ) -> _models.ManagementGroupAggregatedCostResult: """Provides the aggregate cost of a management group and all child management groups by specified billing period. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param management_group_id: Azure Management Group ID. Required. :type management_group_id: str :param billing_period_name: Billing Period Name. Required. :type billing_period_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ManagementGroupAggregatedCostResult or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.ManagementGroupAggregatedCostResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -214,40 +209,33 @@ def get_for_billing_period_by_management_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ManagementGroupAggregatedCostResult] = kwargs.pop("cls", None) - request = build_get_for_billing_period_by_management_group_request( + _request = build_get_for_billing_period_by_management_group_request( management_group_id=management_group_id, billing_period_name=billing_period_name, api_version=api_version, - template_url=self.get_for_billing_period_by_management_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ManagementGroupAggregatedCostResult", pipeline_response) + deserialized = self._deserialize("ManagementGroupAggregatedCostResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - get_for_billing_period_by_management_group.metadata = { - "url": "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/aggregatedCost" - } + return deserialized # type: ignore diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_balances_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_balances_operations.py index 2120804fedc2..088b0a0d7b30 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_balances_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_balances_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# 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 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, _format_url_section +from .._configuration import ConsumptionManagementClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -43,19 +39,19 @@ def build_get_by_billing_account_request(billing_account_id: str, **kwargs: Any) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/balances", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -66,26 +62,26 @@ def build_get_by_billing_account_request(billing_account_id: str, **kwargs: Any) return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_get_for_billing_period_by_billing_account_request( +def build_get_for_billing_period_by_billing_account_request( # pylint: disable=name-too-long billing_account_id: str, billing_period_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/balances", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), "billingPeriodName": _SERIALIZER.url("billing_period_name", billing_period_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -110,24 +106,28 @@ class BalancesOperations: 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: ConsumptionManagementClientConfiguration = ( + 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_by_billing_account(self, billing_account_id: str, **kwargs: Any) -> _models.Balance: """Gets the balances for a scope by billingAccountId. Balances are available via this API only for May 1, 2014 or later. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Balance or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.Balance :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -138,60 +138,55 @@ def get_by_billing_account(self, billing_account_id: str, **kwargs: Any) -> _mod _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Balance] = kwargs.pop("cls", None) - request = build_get_by_billing_account_request( + _request = build_get_by_billing_account_request( billing_account_id=billing_account_id, api_version=api_version, - template_url=self.get_by_billing_account.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Balance", pipeline_response) + deserialized = self._deserialize("Balance", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - get_by_billing_account.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/balances" - } + return deserialized # type: ignore @distributed_trace - def get_for_billing_period_by_billing_account( + def get_for_billing_period_by_billing_account( # pylint: disable=name-too-long self, billing_account_id: str, billing_period_name: str, **kwargs: Any ) -> _models.Balance: """Gets the balances for a scope by billing period and billingAccountId. Balances are available via this API only for May 1, 2014 or later. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str :param billing_period_name: Billing Period Name. Required. :type billing_period_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Balance or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.Balance :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -202,40 +197,33 @@ def get_for_billing_period_by_billing_account( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Balance] = kwargs.pop("cls", None) - request = build_get_for_billing_period_by_billing_account_request( + _request = build_get_for_billing_period_by_billing_account_request( billing_account_id=billing_account_id, billing_period_name=billing_period_name, api_version=api_version, - template_url=self.get_for_billing_period_by_billing_account.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Balance", pipeline_response) + deserialized = self._deserialize("Balance", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - get_for_billing_period_by_billing_account.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/balances" - } + return deserialized # type: ignore diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_budgets_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_budgets_operations.py index f8731081cab6..c8e9877ad870 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_budgets_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_budgets_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +5,12 @@ # 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 collections.abc import MutableMapping +from io import IOBase from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -20,20 +21,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, _format_url_section +from .._configuration import ConsumptionManagementClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -45,7 +41,7 @@ def build_list_request(scope: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -54,7 +50,7 @@ def build_list_request(scope: str, **kwargs: Any) -> HttpRequest: "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -69,7 +65,7 @@ def build_get_request(scope: str, budget_name: str, **kwargs: Any) -> HttpReques _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -79,7 +75,7 @@ def build_get_request(scope: str, budget_name: str, **kwargs: Any) -> HttpReques "budgetName": _SERIALIZER.url("budget_name", budget_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -94,7 +90,7 @@ def build_create_or_update_request(scope: str, budget_name: str, **kwargs: Any) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -105,7 +101,7 @@ def build_create_or_update_request(scope: str, budget_name: str, **kwargs: Any) "budgetName": _SERIALIZER.url("budget_name", budget_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -122,7 +118,7 @@ def build_delete_request(scope: str, budget_name: str, **kwargs: Any) -> HttpReq _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -132,7 +128,7 @@ def build_delete_request(scope: str, budget_name: str, **kwargs: Any) -> HttpReq "budgetName": _SERIALIZER.url("budget_name", budget_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -157,15 +153,20 @@ class BudgetsOperations: 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: ConsumptionManagementClientConfiguration = ( + 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, scope: str, **kwargs: Any) -> Iterable["_models.Budget"]: """Lists all budgets for the defined scope. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param scope: The scope associated with budget operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, @@ -178,10 +179,9 @@ def list(self, scope: str, **kwargs: Any) -> Iterable["_models.Budget"]: scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' for billingProfile scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope. Required. :type scope: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Budget or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.Budget] :raises ~azure.core.exceptions.HttpResponseError: @@ -189,12 +189,10 @@ def list(self, scope: str, **kwargs: Any) -> Iterable["_models.Budget"]: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BudgetsListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -205,15 +203,13 @@ def list(self, scope: str, **kwargs: Any) -> Iterable["_models.Budget"]: def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( scope=scope, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -225,13 +221,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("BudgetsListResult", pipeline_response) @@ -241,28 +236,30 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) - list.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/budgets"} - @distributed_trace def get(self, scope: str, budget_name: str, **kwargs: Any) -> _models.Budget: """Gets the budget for the scope by budget name. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param scope: The scope associated with budget operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, @@ -275,17 +272,16 @@ def get(self, scope: str, budget_name: str, **kwargs: Any) -> _models.Budget: scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' for billingProfile scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope. Required. :type scope: str :param budget_name: Budget Name. Required. :type budget_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Budget or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.Budget :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -296,41 +292,36 @@ def get(self, scope: str, budget_name: str, **kwargs: Any) -> _models.Budget: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Budget] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( scope=scope, budget_name=budget_name, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Budget", pipeline_response) + deserialized = self._deserialize("Budget", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/budgets/{budgetName}"} + return deserialized # type: ignore @overload def create_or_update( @@ -346,6 +337,9 @@ def create_or_update( form of concurrency control. To obtain the latest eTag for a given budget, perform a get operation prior to your put operation. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param scope: The scope associated with budget operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, @@ -358,7 +352,7 @@ def create_or_update( scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' for billingProfile scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope. Required. :type scope: str :param budget_name: Budget Name. Required. @@ -368,7 +362,6 @@ def create_or_update( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Budget or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.Budget :raises ~azure.core.exceptions.HttpResponseError: @@ -376,12 +369,21 @@ def create_or_update( @overload def create_or_update( - self, scope: str, budget_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, + scope: str, + budget_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models.Budget: """The operation to create or update a budget. You can optionally provide an eTag if desired as a form of concurrency control. To obtain the latest eTag for a given budget, perform a get operation prior to your put operation. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param scope: The scope associated with budget operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, @@ -394,17 +396,16 @@ def create_or_update( scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' for billingProfile scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope. Required. :type scope: str :param budget_name: Budget Name. Required. :type budget_name: str :param parameters: Parameters supplied to the Create Budget operation. Required. - :type parameters: IO + :type parameters: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Budget or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.Budget :raises ~azure.core.exceptions.HttpResponseError: @@ -412,12 +413,15 @@ def create_or_update( @distributed_trace def create_or_update( - self, scope: str, budget_name: str, parameters: Union[_models.Budget, IO], **kwargs: Any + self, scope: str, budget_name: str, parameters: Union[_models.Budget, IO[bytes]], **kwargs: Any ) -> _models.Budget: """The operation to create or update a budget. You can optionally provide an eTag if desired as a form of concurrency control. To obtain the latest eTag for a given budget, perform a get operation prior to your put operation. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param scope: The scope associated with budget operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, @@ -430,23 +434,19 @@ def create_or_update( scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' for billingProfile scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope. Required. :type scope: str :param budget_name: Budget Name. Required. :type budget_name: str - :param parameters: Parameters supplied to the Create Budget operation. Is either a model type - or a IO type. Required. - :type parameters: ~azure.mgmt.consumption.models.Budget or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + :param parameters: Parameters supplied to the Create Budget operation. Is either a Budget type + or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.consumption.models.Budget or IO[bytes] :return: Budget or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.Budget :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -457,64 +457,58 @@ def create_or_update( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + 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.Budget] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(parameters, (IO, bytes)): + if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "Budget") - request = build_create_or_update_request( + _request = build_create_or_update_request( scope=scope, budget_name=budget_name, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.create_or_update.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("Budget", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("Budget", pipeline_response) + deserialized = self._deserialize("Budget", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/budgets/{budgetName}"} - @distributed_trace def delete( # pylint: disable=inconsistent-return-statements self, scope: str, budget_name: str, **kwargs: Any ) -> None: """The operation to delete a budget. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param scope: The scope associated with budget operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, @@ -527,17 +521,16 @@ def delete( # pylint: disable=inconsistent-return-statements scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' for billingProfile scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope. Required. :type scope: str :param budget_name: Budget Name. Required. :type budget_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -548,34 +541,29 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( scope=scope, budget_name=budget_name, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/budgets/{budgetName}"} + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_charges_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_charges_operations.py index e471dfe96028..2fbf30495007 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_charges_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_charges_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# 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 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, _format_url_section +from .._configuration import ConsumptionManagementClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -51,7 +47,7 @@ def build_list_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -60,7 +56,7 @@ def build_list_request( "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -93,10 +89,12 @@ class ChargesOperations: 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: ConsumptionManagementClientConfiguration = ( + 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( @@ -110,6 +108,9 @@ def list( ) -> _models.ChargesListResult: """Lists the charges based for the defined scope. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param scope: The scope associated with charges operations. This includes '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for Department scope, and @@ -122,9 +123,9 @@ def list( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' for billingProfile scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' specific for partners. Required. :type scope: str :param start_date: Start date. Default value is None. @@ -141,12 +142,11 @@ def list( Partner Led), or for billingProfile scope by properties/invoiceSectionId. Default value is None. :type apply: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ChargesListResult or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.ChargesListResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -157,41 +157,36 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ChargesListResult] = kwargs.pop("cls", None) - request = build_list_request( + _request = build_list_request( scope=scope, start_date=start_date, end_date=end_date, filter=filter, apply=apply, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ChargesListResult", pipeline_response) + deserialized = self._deserialize("ChargesListResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - list.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/charges"} + return deserialized # type: ignore diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_credits_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_credits_operations.py index 530dbf701b32..e991b0d04cd9 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_credits_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_credits_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# 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 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, _format_url_section +from .._configuration import ConsumptionManagementClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -43,20 +39,20 @@ def build_get_request(billing_account_id: str, billing_profile_id: str, **kwargs _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/credits/balanceSummary", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), "billingProfileId": _SERIALIZER.url("billing_profile_id", billing_profile_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -81,25 +77,29 @@ class CreditsOperations: 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: ConsumptionManagementClientConfiguration = ( + 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, billing_account_id: str, billing_profile_id: str, **kwargs: Any) -> Optional[_models.CreditSummary]: """The credit summary by billingAccountId and billingProfileId. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str :param billing_profile_id: Azure Billing Profile ID. Required. :type billing_profile_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: CreditSummary or None or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.CreditSummary or None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -110,42 +110,35 @@ def get(self, billing_account_id: str, billing_profile_id: str, **kwargs: Any) - _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[Optional[_models.CreditSummary]] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( billing_account_id=billing_account_id, billing_profile_id=billing_profile_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize("CreditSummary", pipeline_response) + deserialized = self._deserialize("CreditSummary", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - get.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/credits/balanceSummary" - } + return deserialized # type: ignore diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_events_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_events_operations.py index a9f78867dcfb..f01ac5dceba1 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_events_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_events_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +6,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 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 +21,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, _format_url_section +from .._configuration import ConsumptionManagementClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -47,20 +43,20 @@ def build_list_by_billing_profile_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/events", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), "billingProfileId": _SERIALIZER.url("billing_profile_id", billing_profile_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -79,19 +75,19 @@ def build_list_by_billing_account_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/events", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -118,10 +114,12 @@ class EventsOperations: 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: ConsumptionManagementClientConfiguration = ( + 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_by_billing_profile( @@ -130,6 +128,9 @@ def list_by_billing_profile( """Lists the events that decrements Azure credits or Microsoft Azure consumption commitment for a billing account or a billing profile for a given start and end date. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str :param billing_profile_id: Azure Billing Profile ID. Required. @@ -138,7 +139,6 @@ def list_by_billing_profile( :type start_date: str :param end_date: End date. Required. :type end_date: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either EventSummary or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.EventSummary] :raises ~azure.core.exceptions.HttpResponseError: @@ -146,12 +146,10 @@ def list_by_billing_profile( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Events] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -162,18 +160,16 @@ def list_by_billing_profile( def prepare_request(next_link=None): if not next_link: - request = build_list_by_billing_profile_request( + _request = build_list_by_billing_profile_request( billing_account_id=billing_account_id, billing_profile_id=billing_profile_id, start_date=start_date, end_date=end_date, api_version=api_version, - template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -185,13 +181,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("Events", pipeline_response) @@ -201,26 +196,23 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) - list_by_billing_profile.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/events" - } - @distributed_trace def list_by_billing_account( self, billing_account_id: str, filter: Optional[str] = None, **kwargs: Any @@ -228,6 +220,9 @@ def list_by_billing_account( """Lists the events that decrements Azure credits or Microsoft Azure consumption commitment for a billing account or a billing profile for a given start and end date. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str :param filter: May be used to filter the events by lotId, lotSource etc. The filter supports @@ -235,7 +230,6 @@ def list_by_billing_account( Tag filter is a key value pair string where key and value is separated by a colon (:). Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either EventSummary or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.EventSummary] :raises ~azure.core.exceptions.HttpResponseError: @@ -243,12 +237,10 @@ def list_by_billing_account( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Events] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -259,16 +251,14 @@ def list_by_billing_account( def prepare_request(next_link=None): if not next_link: - request = build_list_by_billing_account_request( + _request = build_list_by_billing_account_request( billing_account_id=billing_account_id, filter=filter, api_version=api_version, - template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -280,13 +270,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("Events", pipeline_response) @@ -296,22 +285,19 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) - - list_by_billing_account.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/events" - } diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_lots_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_lots_operations.py index cd94ed0583b9..d99c2b2f4fe4 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_lots_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_lots_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +6,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 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 +21,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, _format_url_section +from .._configuration import ConsumptionManagementClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -47,20 +43,20 @@ def build_list_by_billing_profile_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/lots", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), "billingProfileId": _SERIALIZER.url("billing_profile_id", billing_profile_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -77,19 +73,19 @@ def build_list_by_billing_account_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/lots", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -108,20 +104,20 @@ def build_list_by_customer_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}/providers/Microsoft.Consumption/lots", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), "customerId": _SERIALIZER.url("customer_id", customer_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -148,10 +144,12 @@ class LotsOperations: 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: ConsumptionManagementClientConfiguration = ( + 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_by_billing_profile( @@ -160,11 +158,13 @@ def list_by_billing_profile( """Lists all Azure credits for a billing account or a billing profile. The API is only supported for Microsoft Customer Agreements (MCA) billing accounts. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str :param billing_profile_id: Azure Billing Profile ID. Required. :type billing_profile_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either LotSummary or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.LotSummary] :raises ~azure.core.exceptions.HttpResponseError: @@ -172,12 +172,10 @@ def list_by_billing_profile( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Lots] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -188,16 +186,14 @@ def list_by_billing_profile( def prepare_request(next_link=None): if not next_link: - request = build_list_by_billing_profile_request( + _request = build_list_by_billing_profile_request( billing_account_id=billing_account_id, billing_profile_id=billing_profile_id, api_version=api_version, - template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -209,13 +205,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("Lots", pipeline_response) @@ -225,26 +220,23 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) - list_by_billing_profile.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/lots" - } - @distributed_trace def list_by_billing_account( self, billing_account_id: str, filter: Optional[str] = None, **kwargs: Any @@ -253,6 +245,9 @@ def list_by_billing_account( supported for Microsoft Customer Agreements (MCA) and Direct Enterprise Agreement (EA) billing accounts. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str :param filter: May be used to filter the lots by Status, Source etc. The filter supports 'eq', @@ -260,7 +255,6 @@ def list_by_billing_account( filter is a key value pair string where key and value is separated by a colon (:). Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either LotSummary or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.LotSummary] :raises ~azure.core.exceptions.HttpResponseError: @@ -268,12 +262,10 @@ def list_by_billing_account( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Lots] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -284,16 +276,14 @@ def list_by_billing_account( def prepare_request(next_link=None): if not next_link: - request = build_list_by_billing_account_request( + _request = build_list_by_billing_account_request( billing_account_id=billing_account_id, filter=filter, api_version=api_version, - template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -305,13 +295,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("Lots", pipeline_response) @@ -321,26 +310,23 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) - list_by_billing_account.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/lots" - } - @distributed_trace def list_by_customer( self, billing_account_id: str, customer_id: str, filter: Optional[str] = None, **kwargs: Any @@ -348,6 +334,9 @@ def list_by_customer( """Lists all Azure credits for a customer. The API is only supported for Microsoft Partner Agreements (MPA) billing accounts. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str :param customer_id: Customer ID. Required. @@ -356,7 +345,6 @@ def list_by_customer( 'lt', 'gt', 'le', 'ge', and 'and'. Tag filter is a key value pair string where key and value is separated by a colon (:). Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either LotSummary or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.LotSummary] :raises ~azure.core.exceptions.HttpResponseError: @@ -364,12 +352,10 @@ def list_by_customer( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Lots] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -380,17 +366,15 @@ def list_by_customer( def prepare_request(next_link=None): if not next_link: - request = build_list_by_customer_request( + _request = build_list_by_customer_request( billing_account_id=billing_account_id, customer_id=customer_id, filter=filter, api_version=api_version, - template_url=self.list_by_customer.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -402,13 +386,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("Lots", pipeline_response) @@ -418,22 +401,19 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) - - list_by_customer.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}/providers/Microsoft.Consumption/lots" - } diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_marketplaces_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_marketplaces_operations.py index 36cc085b75d9..19947995c3a1 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_marketplaces_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_marketplaces_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +6,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 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 +21,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, _format_url_section +from .._configuration import ConsumptionManagementClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -52,7 +48,7 @@ def build_list_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -61,7 +57,7 @@ def build_list_request( "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters if filter is not None: @@ -92,10 +88,12 @@ class MarketplacesOperations: 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: ConsumptionManagementClientConfiguration = ( + 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( @@ -109,6 +107,9 @@ def list( """Lists the marketplaces for a scope at the defined scope. Marketplaces are available via this API only for May 1, 2014 or later. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param scope: The scope associated with marketplace operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, @@ -135,7 +136,6 @@ def list( a skiptoken parameter that specifies a starting point to use for subsequent calls. Default value is None. :type skiptoken: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Marketplace or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.Marketplace] :raises ~azure.core.exceptions.HttpResponseError: @@ -143,12 +143,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.MarketplacesListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -159,18 +157,16 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( scope=scope, filter=filter, top=top, skiptoken=skiptoken, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -182,13 +178,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("MarketplacesListResult", pipeline_response) @@ -198,20 +193,19 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/marketplaces"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_operations.py index 5dd6eb4d602c..ae89ee906f43 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # 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 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 ConsumptionManagementClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -45,7 +40,7 @@ def build_list_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -74,16 +69,17 @@ 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: ConsumptionManagementClientConfiguration = ( + 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"]: """Lists all of the available consumption REST API operations. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Operation or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.Operation] :raises ~azure.core.exceptions.HttpResponseError: @@ -91,12 +87,10 @@ def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -107,14 +101,12 @@ def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -126,13 +118,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) @@ -142,20 +133,19 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/providers/Microsoft.Consumption/operations"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_price_sheet_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_price_sheet_operations.py index 971a66821334..f98c7abd37ec 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_price_sheet_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_price_sheet_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,32 +6,32 @@ # 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, TypeVar +from collections.abc import MutableMapping +from typing import Any, Callable, Dict, Iterator, Optional, TypeVar, Union, cast +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.rest import HttpRequest +from azure.core.polling import LROPoller, NoPolling, PollingMethod +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, _format_url_section +from .._configuration import ConsumptionManagementClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -39,6 +39,36 @@ _SERIALIZER.client_side_validation = False +def build_download_by_billing_account_period_request( # pylint: disable=name-too-long + billing_account_id: str, billing_period_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", "2025-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/pricesheets/download", + ) + path_format_arguments = { + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + "billingPeriodName": _SERIALIZER.url("billing_period_name", billing_period_name, "str", pattern=r"^[0-9]*$"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + def build_get_request( subscription_id: str, *, @@ -50,7 +80,7 @@ def build_get_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -61,7 +91,7 @@ def build_get_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters if expand is not None: @@ -90,20 +120,20 @@ def build_get_by_billing_period_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/pricesheets/default", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), "billingPeriodName": _SERIALIZER.url("billing_period_name", billing_period_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters if expand is not None: @@ -134,10 +164,132 @@ class PriceSheetOperations: 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: ConsumptionManagementClientConfiguration = ( + 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") + + def _download_by_billing_account_period_initial( # pylint: disable=name-too-long + self, billing_account_id: str, billing_period_name: str, **kwargs: Any + ) -> Iterator[bytes]: + 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[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_download_by_billing_account_period_request( + billing_account_id=billing_account_id, + billing_period_name=billing_period_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + 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, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_download_by_billing_account_period( + self, billing_account_id: str, billing_period_name: str, **kwargs: Any + ) -> LROPoller[_models.OperationStatus]: + """Generates the pricesheet for the provided billing period asynchronously based on the enrollment + id. + + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + + :param billing_account_id: BillingAccount ID. Required. + :type billing_account_id: str + :param billing_period_name: Billing Period Name. Required. + :type billing_period_name: str + :return: An instance of LROPoller that returns either OperationStatus or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.consumption.models.OperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _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.OperationStatus] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._download_by_billing_account_period_initial( + billing_account_id=billing_account_id, + billing_period_name=billing_period_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + 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("OperationStatus", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.OperationStatus].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.OperationStatus]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) @distributed_trace def get( @@ -146,6 +298,9 @@ def get( """Gets the price sheet for a subscription. Price sheet is available via this API only for May 1, 2014 or later. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param expand: May be used to expand the properties/meterDetails within a price sheet. By default, these fields are not included when returning price sheet. Default value is None. :type expand: str @@ -157,12 +312,11 @@ def get( :param top: May be used to limit the number of results to the top N results. Default value is None. :type top: int - :keyword callable cls: A custom type or function that will be passed the direct response :return: PriceSheetResult or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.PriceSheetResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -173,43 +327,38 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.PriceSheetResult] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( subscription_id=self._config.subscription_id, expand=expand, skiptoken=skiptoken, top=top, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("PriceSheetResult", pipeline_response) + deserialized = self._deserialize("PriceSheetResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Consumption/pricesheets/default"} + return deserialized # type: ignore @distributed_trace def get_by_billing_period( @@ -223,6 +372,9 @@ def get_by_billing_period( """Get the price sheet for a scope by subscriptionId and billing period. Price sheet is available via this API only for May 1, 2014 or later. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param billing_period_name: Billing Period Name. Required. :type billing_period_name: str :param expand: May be used to expand the properties/meterDetails within a price sheet. By @@ -236,12 +388,11 @@ def get_by_billing_period( :param top: May be used to limit the number of results to the top N results. Default value is None. :type top: int - :keyword callable cls: A custom type or function that will be passed the direct response :return: PriceSheetResult or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.PriceSheetResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -252,43 +403,36 @@ def get_by_billing_period( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.PriceSheetResult] = kwargs.pop("cls", None) - request = build_get_by_billing_period_request( + _request = build_get_by_billing_period_request( billing_period_name=billing_period_name, subscription_id=self._config.subscription_id, expand=expand, skiptoken=skiptoken, top=top, api_version=api_version, - template_url=self.get_by_billing_period.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("PriceSheetResult", pipeline_response) + deserialized = self._deserialize("PriceSheetResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - get_by_billing_period.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/pricesheets/default" - } + return deserialized # type: ignore diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservation_recommendation_details_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservation_recommendation_details_operations.py index 7e44d960f078..10b4e4b2f9e0 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservation_recommendation_details_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservation_recommendation_details_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,9 +5,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 collections.abc import MutableMapping from typing import Any, Callable, Dict, Optional, TypeVar, Union +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -18,20 +18,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, _format_url_section +from .._configuration import ConsumptionManagementClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -47,12 +42,13 @@ def build_get_request( term: Union[str, _models.Term], look_back_period: Union[str, _models.LookBackPeriod], product: str, + filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -63,7 +59,7 @@ def build_get_request( "resourceScope": _SERIALIZER.url("resource_scope", resource_scope, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -72,6 +68,8 @@ def build_get_request( _params["term"] = _SERIALIZER.query("term", term, "str") _params["lookBackPeriod"] = _SERIALIZER.query("look_back_period", look_back_period, "str") _params["product"] = _SERIALIZER.query("product", product, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -79,7 +77,7 @@ def build_get_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -class ReservationRecommendationDetailsOperations: +class ReservationRecommendationDetailsOperations: # pylint: disable=name-too-long """ .. warning:: **DO NOT** instantiate this class directly. @@ -93,10 +91,12 @@ class ReservationRecommendationDetailsOperations: 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: ConsumptionManagementClientConfiguration = ( + 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( @@ -107,10 +107,14 @@ def get( term: Union[str, _models.Term], look_back_period: Union[str, _models.LookBackPeriod], product: str, + filter: Optional[str] = None, **kwargs: Any ) -> Optional[_models.ReservationRecommendationDetailsModel]: """Details of a reservation recommendation for what-if analysis of reserved instances. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param resource_scope: The scope associated with reservation recommendation details operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resource group scope, @@ -122,8 +126,8 @@ def get( :type scope: str or ~azure.mgmt.consumption.models.Scope :param region: Used to select the region the recommendation should be generated for. Required. :type region: str - :param term: Specify length of reservation recommendation term. Known values are: "P1Y" and - "P3Y". Required. + :param term: Specify length of reservation recommendation term. Known values are: "P1M", "P1Y", + and "P3Y". Required. :type term: str or ~azure.mgmt.consumption.models.Term :param look_back_period: Filter the time period on which reservation recommendation results are based. Known values are: "Last7Days", "Last30Days", and "Last60Days". Required. @@ -132,12 +136,14 @@ def get( Examples: Standard_DS1_v2 (for VM), Premium_SSD_Managed_Disks_P30 (for Managed Disks). Required. :type product: str - :keyword callable cls: A custom type or function that will be passed the direct response + :param filter: Used to filter reservation recommendation details by: properties/subscriptionId + can be specified for billing account and billing profile paths. Default value is None. + :type filter: str :return: ReservationRecommendationDetailsModel or None or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.ReservationRecommendationDetailsModel or None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -148,28 +154,26 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[Optional[_models.ReservationRecommendationDetailsModel]] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_scope=resource_scope, scope=scope, region=region, term=term, look_back_period=look_back_period, product=product, + filter=filter, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -181,11 +185,9 @@ def get( deserialized = None if response.status_code == 200: - deserialized = self._deserialize("ReservationRecommendationDetailsModel", pipeline_response) + deserialized = self._deserialize("ReservationRecommendationDetailsModel", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = {"url": "/{resourceScope}/providers/Microsoft.Consumption/reservationRecommendationDetails"} + return deserialized # type: ignore diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservation_recommendations_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservation_recommendations_operations.py index 5f8707a5a5af..e76ac27f8a83 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservation_recommendations_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservation_recommendations_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # 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 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, _format_url_section +from .._configuration import ConsumptionManagementClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -45,7 +40,7 @@ def build_list_request(resource_scope: str, *, filter: Optional[str] = None, **k _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -54,7 +49,7 @@ def build_list_request(resource_scope: str, *, filter: Optional[str] = None, **k "resourceScope": _SERIALIZER.url("resource_scope", resource_scope, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters if filter is not None: @@ -81,10 +76,12 @@ class ReservationRecommendationsOperations: 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: ConsumptionManagementClientConfiguration = ( + 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( @@ -92,6 +89,9 @@ def list( ) -> Iterable["_models.ReservationRecommendation"]: """List of recommendations for purchasing reserved instances. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param resource_scope: The scope associated with reservation recommendations operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resource group scope, @@ -107,7 +107,6 @@ def list( properties/lookBackPeriod with allowed values ['Last7Days', 'Last30Days', 'Last60Days'] and default value 'Last7Days'. Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ReservationRecommendation or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationRecommendation] @@ -116,12 +115,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ReservationRecommendationsListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -132,16 +129,14 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_scope=resource_scope, filter=filter, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -153,13 +148,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ReservationRecommendationsListResult", pipeline_response) @@ -169,20 +163,19 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{resourceScope}/providers/Microsoft.Consumption/reservationRecommendations"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservation_transactions_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservation_transactions_operations.py index ec4582467374..ea6162175940 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservation_transactions_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservation_transactions_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +6,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 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 +21,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, _format_url_section +from .._configuration import ConsumptionManagementClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -41,28 +37,41 @@ _SERIALIZER.client_side_validation = False -def build_list_request(billing_account_id: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: +def build_list_request( + billing_account_id: str, + *, + filter: Optional[str] = None, + use_markup_if_partner: Optional[bool] = None, + preview_markup_percentage: Optional[float] = None, + **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/reservationTransactions", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters if filter is not None: _params["$filter"] = _SERIALIZER.query("filter", filter, "str") _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if use_markup_if_partner is not None: + _params["useMarkupIfPartner"] = _SERIALIZER.query("use_markup_if_partner", use_markup_if_partner, "bool") + if preview_markup_percentage is not None: + _params["previewMarkupPercentage"] = _SERIALIZER.query( + "preview_markup_percentage", preview_markup_percentage, "float" + ) # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -76,20 +85,20 @@ def build_list_by_billing_profile_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/reservationTransactions", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), "billingProfileId": _SERIALIZER.url("billing_profile_id", billing_profile_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters if filter is not None: @@ -116,20 +125,32 @@ class ReservationTransactionsOperations: 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: ConsumptionManagementClientConfiguration = ( + 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, billing_account_id: str, filter: Optional[str] = None, **kwargs: Any + self, + billing_account_id: str, + filter: Optional[str] = None, + use_markup_if_partner: Optional[bool] = None, + preview_markup_percentage: Optional[float] = None, + **kwargs: Any ) -> Iterable["_models.ReservationTransaction"]: """List of transactions for reserved instances on billing account scope. Note: The refund transactions are posted along with its purchase transaction (i.e. in the purchase billing month). For example, The refund is requested in May 2021. This refund transaction will have event date as May 2021 but the billing month as April 2020 when the reservation purchase was - made. + made. Note: ARM has a payload size limit of 12MB, so currently callers get 400 when the + response size exceeds the ARM limit. In such cases, API call should be made with smaller date + ranges. + + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str @@ -140,7 +161,12 @@ def list( the entire December 2020 month (i.e. will contain records for dates December 30 and 31). Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response + :param use_markup_if_partner: Applies mark up to the transactions if the caller is a partner. + Default value is None. + :type use_markup_if_partner: bool + :param preview_markup_percentage: Preview markup percentage to be applied. Default value is + None. + :type preview_markup_percentage: float :return: An iterator like instance of either ReservationTransaction or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationTransaction] @@ -149,12 +175,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ReservationTransactionsListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -165,16 +189,16 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( billing_account_id=billing_account_id, filter=filter, + use_markup_if_partner=use_markup_if_partner, + preview_markup_percentage=preview_markup_percentage, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -186,13 +210,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ReservationTransactionsListResult", pipeline_response) @@ -202,26 +225,23 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) - list.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/reservationTransactions" - } - @distributed_trace def list_by_billing_profile( self, billing_account_id: str, billing_profile_id: str, filter: Optional[str] = None, **kwargs: Any @@ -229,7 +249,12 @@ def list_by_billing_profile( """List of transactions for reserved instances on billing profile scope. The refund transactions are posted along with its purchase transaction (i.e. in the purchase billing month). For example, The refund is requested in May 2021. This refund transaction will have event date as - May 2021 but the billing month as April 2020 when the reservation purchase was made. + May 2021 but the billing month as April 2020 when the reservation purchase was made. Note: ARM + has a payload size limit of 12MB, so currently callers get 400 when the response size exceeds + the ARM limit. In such cases, API call should be made with smaller date ranges. + + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str @@ -242,7 +267,6 @@ def list_by_billing_profile( entire December 2020 month (i.e. will contain records for dates December 30 and 31). Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ModernReservationTransaction or the result of cls(response) :rtype: @@ -252,12 +276,10 @@ def list_by_billing_profile( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ModernReservationTransactionsListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -268,17 +290,15 @@ def list_by_billing_profile( def prepare_request(next_link=None): if not next_link: - request = build_list_by_billing_profile_request( + _request = build_list_by_billing_profile_request( billing_account_id=billing_account_id, billing_profile_id=billing_profile_id, filter=filter, api_version=api_version, - template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -290,13 +310,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ModernReservationTransactionsListResult", pipeline_response) @@ -306,22 +325,19 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) - - list_by_billing_profile.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/reservationTransactions" - } diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservations_details_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservations_details_operations.py index f4fb83276110..8ceb6e5abd15 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservations_details_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservations_details_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +6,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 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 +21,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, _format_url_section +from .._configuration import ConsumptionManagementClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -45,19 +41,19 @@ def build_list_by_reservation_order_request(reservation_order_id: str, *, filter _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/providers/Microsoft.Consumption/reservationDetails", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["$filter"] = _SERIALIZER.query("filter", filter, "str") @@ -69,26 +65,26 @@ def build_list_by_reservation_order_request(reservation_order_id: str, *, filter return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_list_by_reservation_order_and_reservation_request( +def build_list_by_reservation_order_and_reservation_request( # pylint: disable=name-too-long reservation_order_id: str, reservation_id: str, *, filter: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/reservations/{reservationId}/providers/Microsoft.Consumption/reservationDetails", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), "reservationId": _SERIALIZER.url("reservation_id", reservation_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["$filter"] = _SERIALIZER.query("filter", filter, "str") @@ -113,7 +109,7 @@ def build_list_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -122,7 +118,7 @@ def build_list_request( "resourceScope": _SERIALIZER.url("resource_scope", resource_scope, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters if start_date is not None: @@ -157,25 +153,32 @@ class ReservationsDetailsOperations: 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: ConsumptionManagementClientConfiguration = ( + 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_by_reservation_order( self, reservation_order_id: str, filter: str, **kwargs: Any ) -> Iterable["_models.ReservationDetail"]: """Lists the reservations details for provided date range. Note: ARM has a payload size limit of - 12MB, so currently callers get 502 when the response size exceeds the ARM limit. In such cases, - API call should be made with smaller date ranges. + 12MB, so currently callers get 400 when the response size exceeds the ARM limit. If the data + size is too large, customers may also get 504 as the API timed out preparing the data. In such + cases, API call should be made with smaller date ranges or a call to Generate Reservation + Details Report API should be made as it is asynchronous and will not run into response size + time outs. + + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str :param filter: Filter reservation details by date range. The properties/UsageDate for start date and end date. The filter supports 'le' and 'ge'. Required. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ReservationDetail or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationDetail] :raises ~azure.core.exceptions.HttpResponseError: @@ -183,12 +186,10 @@ def list_by_reservation_order( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ReservationDetailsListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -199,16 +200,14 @@ def list_by_reservation_order( def prepare_request(next_link=None): if not next_link: - request = build_list_by_reservation_order_request( + _request = build_list_by_reservation_order_request( reservation_order_id=reservation_order_id, filter=filter, api_version=api_version, - template_url=self.list_by_reservation_order.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -220,13 +219,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ReservationDetailsListResult", pipeline_response) @@ -236,33 +234,36 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) - list_by_reservation_order.metadata = { - "url": "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/providers/Microsoft.Consumption/reservationDetails" - } - @distributed_trace - def list_by_reservation_order_and_reservation( + def list_by_reservation_order_and_reservation( # pylint: disable=name-too-long self, reservation_order_id: str, reservation_id: str, filter: str, **kwargs: Any ) -> Iterable["_models.ReservationDetail"]: """Lists the reservations details for provided date range. Note: ARM has a payload size limit of - 12MB, so currently callers get 502 when the response size exceeds the ARM limit. In such cases, - API call should be made with smaller date ranges. + 12MB, so currently callers get 400 when the response size exceeds the ARM limit. If the data + size is too large, customers may also get 504 as the API timed out preparing the data. In such + cases, API call should be made with smaller date ranges or a call to Generate Reservation + Details Report API should be made as it is asynchronous and will not run into response size + time outs. + + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str @@ -271,7 +272,6 @@ def list_by_reservation_order_and_reservation( :param filter: Filter reservation details by date range. The properties/UsageDate for start date and end date. The filter supports 'le' and 'ge'. Required. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ReservationDetail or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationDetail] :raises ~azure.core.exceptions.HttpResponseError: @@ -279,12 +279,10 @@ def list_by_reservation_order_and_reservation( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ReservationDetailsListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -295,17 +293,15 @@ def list_by_reservation_order_and_reservation( def prepare_request(next_link=None): if not next_link: - request = build_list_by_reservation_order_and_reservation_request( + _request = build_list_by_reservation_order_and_reservation_request( reservation_order_id=reservation_order_id, reservation_id=reservation_id, filter=filter, api_version=api_version, - template_url=self.list_by_reservation_order_and_reservation.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -317,13 +313,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ReservationDetailsListResult", pipeline_response) @@ -333,26 +328,23 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) - list_by_reservation_order_and_reservation.metadata = { - "url": "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/reservations/{reservationId}/providers/Microsoft.Consumption/reservationDetails" - } - @distributed_trace def list( self, @@ -364,9 +356,15 @@ def list( reservation_order_id: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.ReservationDetail"]: - """Lists the reservations details for the defined scope and provided date range. Note: ARM has a - payload size limit of 12MB, so currently callers get 502 when the response size exceeds the ARM - limit. In such cases, API call should be made with smaller date ranges. + """Lists the reservations details for provided date range. Note: ARM has a payload size limit of + 12MB, so currently callers get 400 when the response size exceeds the ARM limit. If the data + size is too large, customers may also get 504 as the API timed out preparing the data. In such + cases, API call should be made with smaller date ranges or a call to Generate Reservation + Details Report API should be made as it is asynchronous and will not run into response size + time outs. + + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ :param resource_scope: The scope associated with reservations details operations. This includes '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for BillingAccount scope @@ -390,7 +388,6 @@ def list( :param reservation_order_id: Reservation Order Id GUID. Required if reservationId is provided. Filter to a specific reservation order. Default value is None. :type reservation_order_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ReservationDetail or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationDetail] :raises ~azure.core.exceptions.HttpResponseError: @@ -398,12 +395,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ReservationDetailsListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -414,7 +409,7 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_scope=resource_scope, start_date=start_date, end_date=end_date, @@ -422,12 +417,10 @@ def prepare_request(next_link=None): reservation_id=reservation_id, reservation_order_id=reservation_order_id, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -439,13 +432,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ReservationDetailsListResult", pipeline_response) @@ -455,20 +447,19 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{resourceScope}/providers/Microsoft.Consumption/reservationDetails"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservations_summaries_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservations_summaries_operations.py index d76164bcc81e..96307b664ff4 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservations_summaries_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservations_summaries_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +6,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 collections.abc import MutableMapping from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union import urllib.parse +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -20,20 +21,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, _format_url_section +from .._configuration import ConsumptionManagementClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -47,19 +43,19 @@ def build_list_by_reservation_order_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/providers/Microsoft.Consumption/reservationSummaries", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["grain"] = _SERIALIZER.query("grain", grain, "str") @@ -73,7 +69,7 @@ def build_list_by_reservation_order_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_list_by_reservation_order_and_reservation_request( +def build_list_by_reservation_order_and_reservation_request( # pylint: disable=name-too-long reservation_order_id: str, reservation_id: str, *, @@ -84,20 +80,20 @@ def build_list_by_reservation_order_and_reservation_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/reservations/{reservationId}/providers/Microsoft.Consumption/reservationSummaries", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), "reservationId": _SERIALIZER.url("reservation_id", reservation_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["grain"] = _SERIALIZER.query("grain", grain, "str") @@ -125,7 +121,7 @@ def build_list_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -134,7 +130,7 @@ def build_list_request( "resourceScope": _SERIALIZER.url("resource_scope", resource_scope, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["grain"] = _SERIALIZER.query("grain", grain, "str") @@ -170,10 +166,12 @@ class ReservationsSummariesOperations: 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: ConsumptionManagementClientConfiguration = ( + 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_by_reservation_order( @@ -183,7 +181,12 @@ def list_by_reservation_order( filter: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.ReservationSummary"]: - """Lists the reservations summaries for daily or monthly grain. + """Lists the reservations summaries for daily or monthly grain. Note: ARM has a payload size limit + of 12MB, so currently callers get 400 when the response size exceeds the ARM limit. In such + cases, API call should be made with smaller date ranges. + + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str @@ -192,7 +195,6 @@ def list_by_reservation_order( :param filter: Required only for daily grain. The properties/UsageDate for start date and end date. The filter supports 'le' and 'ge'. Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ReservationSummary or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationSummary] :raises ~azure.core.exceptions.HttpResponseError: @@ -200,12 +202,10 @@ def list_by_reservation_order( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ReservationSummariesListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -216,17 +216,15 @@ def list_by_reservation_order( def prepare_request(next_link=None): if not next_link: - request = build_list_by_reservation_order_request( + _request = build_list_by_reservation_order_request( reservation_order_id=reservation_order_id, grain=grain, filter=filter, api_version=api_version, - template_url=self.list_by_reservation_order.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -238,13 +236,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ReservationSummariesListResult", pipeline_response) @@ -254,28 +251,25 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) - list_by_reservation_order.metadata = { - "url": "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/providers/Microsoft.Consumption/reservationSummaries" - } - @distributed_trace - def list_by_reservation_order_and_reservation( + def list_by_reservation_order_and_reservation( # pylint: disable=name-too-long self, reservation_order_id: str, reservation_id: str, @@ -283,7 +277,12 @@ def list_by_reservation_order_and_reservation( filter: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.ReservationSummary"]: - """Lists the reservations summaries for daily or monthly grain. + """Lists the reservations summaries for daily or monthly grain. Note: ARM has a payload size limit + of 12MB, so currently callers get 400 when the response size exceeds the ARM limit. In such + cases, API call should be made with smaller date ranges. + + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str @@ -294,7 +293,6 @@ def list_by_reservation_order_and_reservation( :param filter: Required only for daily grain. The properties/UsageDate for start date and end date. The filter supports 'le' and 'ge'. Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ReservationSummary or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationSummary] :raises ~azure.core.exceptions.HttpResponseError: @@ -302,12 +300,10 @@ def list_by_reservation_order_and_reservation( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ReservationSummariesListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -318,18 +314,16 @@ def list_by_reservation_order_and_reservation( def prepare_request(next_link=None): if not next_link: - request = build_list_by_reservation_order_and_reservation_request( + _request = build_list_by_reservation_order_and_reservation_request( reservation_order_id=reservation_order_id, reservation_id=reservation_id, grain=grain, filter=filter, api_version=api_version, - template_url=self.list_by_reservation_order_and_reservation.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -341,13 +335,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ReservationSummariesListResult", pipeline_response) @@ -357,26 +350,23 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) - list_by_reservation_order_and_reservation.metadata = { - "url": "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/reservations/{reservationId}/providers/Microsoft.Consumption/reservationSummaries" - } - @distributed_trace def list( self, @@ -389,7 +379,12 @@ def list( reservation_order_id: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.ReservationSummary"]: - """Lists the reservations summaries for the defined scope daily or monthly grain. + """Lists the reservations summaries for the defined scope daily or monthly grain. Note: ARM has a + payload size limit of 12MB, so currently callers get 400 when the response size exceeds the ARM + limit. In such cases, API call should be made with smaller date ranges. + + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ :param resource_scope: The scope associated with reservations summaries operations. This includes '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for BillingAccount @@ -415,7 +410,6 @@ def list( :param reservation_order_id: Reservation Order Id GUID. Required if reservationId is provided. Filter to a specific reservation order. Default value is None. :type reservation_order_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ReservationSummary or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationSummary] :raises ~azure.core.exceptions.HttpResponseError: @@ -423,12 +417,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ReservationSummariesListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -439,7 +431,7 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_scope=resource_scope, grain=grain, start_date=start_date, @@ -448,12 +440,10 @@ def prepare_request(next_link=None): reservation_id=reservation_id, reservation_order_id=reservation_order_id, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -465,13 +455,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ReservationSummariesListResult", pipeline_response) @@ -481,20 +470,19 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{resourceScope}/providers/Microsoft.Consumption/reservationSummaries"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_tags_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_tags_operations.py index cef15e36ba0c..a35cbb1f3880 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_tags_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_tags_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,9 +5,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 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 +18,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, _format_url_section +from .._configuration import ConsumptionManagementClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -43,7 +38,7 @@ def build_get_request(scope: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -52,7 +47,7 @@ def build_get_request(scope: str, **kwargs: Any) -> HttpRequest: "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -77,15 +72,20 @@ class TagsOperations: 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: ConsumptionManagementClientConfiguration = ( + 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, **kwargs: Any) -> Optional[_models.TagsResult]: """Get all available tag keys for the defined scope. + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param scope: The scope associated with tags operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, @@ -97,12 +97,11 @@ def get(self, scope: str, **kwargs: Any) -> Optional[_models.TagsResult]: '/providers/Microsoft.Management/managementGroups/{managementGroupId}' for Management Group scope.. Required. :type scope: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: TagsResult or None or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.TagsResult or None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -113,39 +112,34 @@ def get(self, scope: str, **kwargs: Any) -> Optional[_models.TagsResult]: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[Optional[_models.TagsResult]] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( scope=scope, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize("TagsResult", pipeline_response) + deserialized = self._deserialize("TagsResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/tags"} + return deserialized # type: ignore diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_usage_details_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_usage_details_operations.py index 687fc9e04261..fe50afa3ad2a 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_usage_details_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_usage_details_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +6,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 collections.abc import MutableMapping from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union import urllib.parse +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -20,20 +21,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, _format_url_section +from .._configuration import ConsumptionManagementClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -54,7 +50,7 @@ def build_list_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -63,7 +59,7 @@ def build_list_request( "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters if expand is not None: @@ -98,10 +94,12 @@ class UsageDetailsOperations: 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: ConsumptionManagementClientConfiguration = ( + 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( @@ -117,6 +115,16 @@ def list( """Lists the usage details for the defined scope. Usage details are available via this API only for May 1, 2014 or later. + **Note:Microsoft will be retiring the Consumption Usage Details API at some point in the + future. We do not recommend that you take a new dependency on this API. Please use the Cost + Details API instead. We will notify customers once a date for retirement has been + determined.For Learn more,see `Generate Cost Details Report - Create Operation + `_\\ + **. + + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/consumption/ + :param scope: The scope associated with usage details operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, @@ -132,9 +140,9 @@ def list( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' for billingProfile scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' specific for partners. Required. :type scope: str :param expand: May be used to expand the properties/additionalInfo or properties/meterDetails @@ -160,7 +168,6 @@ def list( :param metric: Allows to select different type of cost/usage records. Known values are: "actualcost", "amortizedcost", and "usage". Default value is None. :type metric: str or ~azure.mgmt.consumption.models.Metrictype - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either UsageDetail or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.UsageDetail] :raises ~azure.core.exceptions.HttpResponseError: @@ -168,12 +175,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.UsageDetailsListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -184,7 +189,7 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( scope=scope, expand=expand, filter=filter, @@ -192,12 +197,10 @@ def prepare_request(next_link=None): top=top, metric=metric, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -209,13 +212,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("UsageDetailsListResult", pipeline_response) @@ -225,20 +227,19 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/usageDetails"} diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/aggregated_cost_by_management_group.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/aggregated_cost_by_management_group.py index 3620ba064233..16794fcd7923 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/aggregated_cost_by_management_group.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/aggregated_cost_by_management_group.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -35,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/AggregatedCostByManagementGroup.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/AggregatedCostByManagementGroup.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/aggregated_cost_by_management_group_filter_by_date.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/aggregated_cost_by_management_group_filter_by_date.py index 35594a0f8f15..de021d7ab539 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/aggregated_cost_by_management_group_filter_by_date.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/aggregated_cost_by_management_group_filter_by_date.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -35,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/AggregatedCostByManagementGroupFilterByDate.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/AggregatedCostByManagementGroupFilterByDate.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/aggregated_cost_for_billing_period_by_management_group.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/aggregated_cost_for_billing_period_by_management_group.py index 03f35dd50ae3..673f741dc9b6 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/aggregated_cost_for_billing_period_by_management_group.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/aggregated_cost_for_billing_period_by_management_group.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/AggregatedCostForBillingPeriodByManagementGroup.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/AggregatedCostForBillingPeriodByManagementGroup.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/balances_by_billing_account.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/balances_by_billing_account.py index cb29ed39ea58..0ca5f94b08d2 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/balances_by_billing_account.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/balances_by_billing_account.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -35,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/BalancesByBillingAccount.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/BalancesByBillingAccount.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/balances_by_billing_account_for_billing_period.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/balances_by_billing_account_for_billing_period.py index 149d33469f55..e7f601c6418f 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/balances_by_billing_account_for_billing_period.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/balances_by_billing_account_for_billing_period.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/BalancesByBillingAccountForBillingPeriod.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/BalancesByBillingAccountForBillingPeriod.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/budget.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/budget.py index 3d72c42e5a07..84338c06fda2 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/budget.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/budget.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/Budget.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/Budget.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/budgets_list.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/budgets_list.py index a07166094b71..e55862db928c 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/budgets_list.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/budgets_list.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/BudgetsList.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/BudgetsList.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_for_billing_period_by_department.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_for_billing_period_by_department.py index 2ce887e2d9f9..a91f6d4a61bc 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_for_billing_period_by_department.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_for_billing_period_by_department.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -35,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesForBillingPeriodByDepartment.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ChargesForBillingPeriodByDepartment.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_for_billing_period_by_enrollment_account.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_for_billing_period_by_enrollment_account.py index c91466879da1..953d57520f41 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_for_billing_period_by_enrollment_account.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_for_billing_period_by_enrollment_account.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -35,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesForBillingPeriodByEnrollmentAccount.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ChargesForBillingPeriodByEnrollmentAccount.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account.py index c48bb008f4ac..54cd4ef0b864 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -35,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListByModernBillingAccount.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ChargesListByModernBillingAccount.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account_group_by_billing_profile_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account_group_by_billing_profile_id.py index efd41b7b098a..eaf05b2d0647 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account_group_by_billing_profile_id.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account_group_by_billing_profile_id.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -35,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListByModernBillingAccountGroupByBillingProfileId.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ChargesListByModernBillingAccountGroupByBillingProfileId.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account_group_by_customer_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account_group_by_customer_id.py index 04b0cbddbc9f..c61420bccfca 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account_group_by_customer_id.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account_group_by_customer_id.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -35,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListByModernBillingAccountGroupByCustomerId.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ChargesListByModernBillingAccountGroupByCustomerId.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account_group_by_invoice_section_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account_group_by_invoice_section_id.py index 7035f89b7016..d7c5f2244ae2 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account_group_by_invoice_section_id.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account_group_by_invoice_section_id.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -35,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListByModernBillingAccountGroupByInvoiceSectionId.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ChargesListByModernBillingAccountGroupByInvoiceSectionId.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_profile.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_profile.py index 067b57bb7844..3994a4517803 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_profile.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_profile.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -35,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListByModernBillingProfile.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ChargesListByModernBillingProfile.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_profile_group_by_invoice_section_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_profile_group_by_invoice_section_id.py index 1ae82b37718a..e4212d61b3fa 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_profile_group_by_invoice_section_id.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_profile_group_by_invoice_section_id.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -35,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListByModernBillingProfileGroupByInvoiceSectionId.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ChargesListByModernBillingProfileGroupByInvoiceSectionId.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_profile_invoice_section.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_profile_invoice_section.py index 613175dbc5a0..f676bc43d78e 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_profile_invoice_section.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_profile_invoice_section.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -35,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListByModernBillingProfileInvoiceSection.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ChargesListByModernBillingProfileInvoiceSection.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_customer.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_customer.py index 43c9070e4881..0f7f9e170c9d 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_customer.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_customer.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -35,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListByModernCustomer.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ChargesListByModernCustomer.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_invoice_section_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_invoice_section_id.py index 2a373da5182b..c4a65cfd2250 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_invoice_section_id.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_invoice_section_id.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -35,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListByModernInvoiceSectionId.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ChargesListByModernInvoiceSectionId.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_for_department_filter_by_start_end_date.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_for_department_filter_by_start_end_date.py index 5f000f461b71..8743836ef3d0 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_for_department_filter_by_start_end_date.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_for_department_filter_by_start_end_date.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -35,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListForDepartmentFilterByStartEndDate.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ChargesListForDepartmentFilterByStartEndDate.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_for_enrollment_account_filter_by_start_end_date.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_for_enrollment_account_filter_by_start_end_date.py index 36be9fec7917..ab41757dd7b1 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_for_enrollment_account_filter_by_start_end_date.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_for_enrollment_account_filter_by_start_end_date.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -35,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListForEnrollmentAccountFilterByStartEndDate.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ChargesListForEnrollmentAccountFilterByStartEndDate.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/create_or_update_budget.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/create_or_update_budget.py index 979f6ed0c2b4..171c36b197ae 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/create_or_update_budget.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/create_or_update_budget.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -75,6 +77,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/CreateOrUpdateBudget.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/CreateOrUpdateBudget.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/credit_summary_by_billing_profile.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/credit_summary_by_billing_profile.py index e28aa54c136a..0be813845393 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/credit_summary_by_billing_profile.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/credit_summary_by_billing_profile.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/CreditSummaryByBillingProfile.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/CreditSummaryByBillingProfile.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/delete_budget.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/delete_budget.py index b8f8189f1e45..d61f3c9dcf9e 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/delete_budget.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/delete_budget.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -29,13 +31,12 @@ def main(): subscription_id="00000000-0000-0000-0000-000000000000", ) - response = client.budgets.delete( + client.budgets.delete( scope="subscriptions/00000000-0000-0000-0000-000000000000", budget_name="TestBudget", ) - print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/DeleteBudget.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/DeleteBudget.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/ea_price_sheet_for_billing_period.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/ea_price_sheet_for_billing_period.py new file mode 100644 index 000000000000..a94475459523 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/ea_price_sheet_for_billing_period.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python ea_price_sheet_for_billing_period.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 = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.price_sheet.begin_download_by_billing_account_period( + billing_account_id="0000000", + billing_period_name="202305", + ).result() + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/EAPriceSheetForBillingPeriod.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account.py index 654c39418ad4..7400b12b46df 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/EventsGetByBillingAccount.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/EventsGetByBillingAccount.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_contributor.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_contributor.py new file mode 100644 index 000000000000..105f22d3fd00 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_contributor.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python events_get_by_billing_account_contributor.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 = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.events.list_by_billing_account( + billing_account_id="1234:5678", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/EventsGetByBillingAccount-Contributor.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_primary.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_primary.py new file mode 100644 index 000000000000..2a612e034886 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_primary.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python events_get_by_billing_account_primary.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 = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.events.list_by_billing_account( + billing_account_id="1234:5678", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/EventsGetByBillingAccount-Primary.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_with_filters.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_with_filters.py index 727edac86858..0afdbb56326e 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_with_filters.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_with_filters.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/EventsGetByBillingAccountWithFilters.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/EventsGetByBillingAccountWithFilters.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_with_filters_contributor.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_with_filters_contributor.py new file mode 100644 index 000000000000..7e18a0e4e02a --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_with_filters_contributor.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python events_get_by_billing_account_with_filters_contributor.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 = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.events.list_by_billing_account( + billing_account_id="1234:5678", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/EventsGetByBillingAccountWithFilters-Contributor.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_with_filters_primary.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_with_filters_primary.py new file mode 100644 index 000000000000..f0dcd9657dc8 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_with_filters_primary.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python events_get_by_billing_account_with_filters_primary.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 = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.events.list_by_billing_account( + billing_account_id="1234:5678", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/EventsGetByBillingAccountWithFilters-Primary.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/events_list_by_billing_profile.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/events_list_by_billing_profile.py index f84a0cec1ec3..9b77bfeb8689 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/events_list_by_billing_profile.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/events_list_by_billing_profile.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -39,6 +41,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/EventsListByBillingProfile.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/EventsListByBillingProfile.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account.py index e63cf0b91405..6d494a4e2ba9 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/LotsListByBillingAccount.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/LotsListByBillingAccount.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_contributor.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_contributor.py new file mode 100644 index 000000000000..fd6d885d52b2 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_contributor.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python lots_list_by_billing_account_contributor.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 = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.lots.list_by_billing_account( + billing_account_id="1234:5678", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/LotsListByBillingAccount-Contributor.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_primary.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_primary.py new file mode 100644 index 000000000000..77f59856a15b --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_primary.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python lots_list_by_billing_account_primary.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 = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.lots.list_by_billing_account( + billing_account_id="1234:5678", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/LotsListByBillingAccount-Primary.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_with_filters.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_with_filters.py index 76381e1425e0..dd0a8860c1cf 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_with_filters.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_with_filters.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/LotsListByBillingAccountWithFilters.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/LotsListByBillingAccountWithFilters.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_with_filters_contributor.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_with_filters_contributor.py new file mode 100644 index 000000000000..8d6d97cd53b0 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_with_filters_contributor.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python lots_list_by_billing_account_with_filters_contributor.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 = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.lots.list_by_billing_account( + billing_account_id="1234:5678", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/LotsListByBillingAccountWithFilters-Contributor.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_with_filters_primary.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_with_filters_primary.py new file mode 100644 index 000000000000..f34d61a0740a --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_with_filters_primary.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python lots_list_by_billing_account_with_filters_primary.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 = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.lots.list_by_billing_account( + billing_account_id="1234:5678", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/LotsListByBillingAccountWithFilters-Primary.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_profile.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_profile.py index fe3344c1b346..7fff0b3dd65e 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_profile.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_profile.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -37,6 +39,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/LotsListByBillingProfile.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/LotsListByBillingProfile.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_customer.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_customer.py index f5bb3322ebe5..87c78abd347b 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_customer.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_customer.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -37,6 +39,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/LotsListByCustomer.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/LotsListByCustomer.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_customer_with_filters.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_customer_with_filters.py index 74e95d98f92c..67ab94bc522f 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_customer_with_filters.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_customer_with_filters.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -37,6 +39,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/LotsListByCustomerWithFilters.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/LotsListByCustomerWithFilters.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_billing_account_list.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_billing_account_list.py index 85fe45b1a08c..4e0790c7aa49 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_billing_account_list.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_billing_account_list.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesByBillingAccountList.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/MarketplacesByBillingAccountList.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_billing_account_list_for_billing_period.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_billing_account_list_for_billing_period.py index ff44044a915e..b9355b0c6e55 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_billing_account_list_for_billing_period.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_billing_account_list_for_billing_period.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesByBillingAccountListForBillingPeriod.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/MarketplacesByBillingAccountListForBillingPeriod.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_department_list.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_department_list.py index 022527d5f93e..aeb84f347416 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_department_list.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_department_list.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesByDepartmentList.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/MarketplacesByDepartmentList.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_department_list_by_billing_period.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_department_list_by_billing_period.py index 21aacd1cec54..697dcb4cc652 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_department_list_by_billing_period.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_department_list_by_billing_period.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesByDepartment_ListByBillingPeriod.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/MarketplacesByDepartment_ListByBillingPeriod.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_enrollment_account_list.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_enrollment_account_list.py index 6ca5344dc699..d11c55f3b857 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_enrollment_account_list.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_enrollment_account_list.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesByEnrollmentAccountList.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/MarketplacesByEnrollmentAccountList.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_enrollment_accounts_list_by_billing_period.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_enrollment_accounts_list_by_billing_period.py index a8db1c7722ab..317cf4d0696a 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_enrollment_accounts_list_by_billing_period.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_enrollment_accounts_list_by_billing_period.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesByEnrollmentAccounts_ListByBillingPeriod.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/MarketplacesByEnrollmentAccounts_ListByBillingPeriod.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_management_group_list.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_management_group_list.py index 4ee9b750a604..edae6e28aea1 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_management_group_list.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_management_group_list.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesByManagementGroupList.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/MarketplacesByManagementGroupList.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_management_group_list_for_billing_period.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_management_group_list_for_billing_period.py index 1418bb34ebde..d7f90d119856 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_management_group_list_for_billing_period.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_management_group_list_for_billing_period.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesByManagementGroup_ListForBillingPeriod.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/MarketplacesByManagementGroup_ListForBillingPeriod.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_list.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_list.py index 8db7d43c202b..71081ddac69e 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_list.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_list.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesList.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/MarketplacesList.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_list_for_billing_period.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_list_for_billing_period.py index cd0a50fb3de2..25527f7052f5 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_list_for_billing_period.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_list_for_billing_period.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesListForBillingPeriod.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/MarketplacesListForBillingPeriod.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/operation_list.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/operation_list.py index 0aa0424ba67f..308bf0668d40 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/operation_list.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/operation_list.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -34,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/OperationList.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/OperationList.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/price_sheet.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/price_sheet.py index 50f503ce57fa..bc755f80edf5 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/price_sheet.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/price_sheet.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -33,6 +35,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/PriceSheet.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/PriceSheet.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/price_sheet_expand.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/price_sheet_expand.py index bb0b296619c5..f4a5af47c051 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/price_sheet_expand.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/price_sheet_expand.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -35,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/PriceSheetExpand.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/PriceSheetExpand.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/price_sheet_for_billing_period.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/price_sheet_for_billing_period.py index f0fc2a5d6a78..ed97a30448e5 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/price_sheet_for_billing_period.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/price_sheet_for_billing_period.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -35,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/PriceSheetForBillingPeriod.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/PriceSheetForBillingPeriod.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details.py index 305bb208f4f7..c69a489ea749 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -37,6 +39,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationDetails.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ReservationDetails.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_by_billing_account_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_by_billing_account_id.py index ad1a1e3d3a2e..e1e5194b4ad0 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_by_billing_account_id.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_by_billing_account_id.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationDetailsByBillingAccountId.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ReservationDetailsByBillingAccountId.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_by_billing_profile_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_by_billing_profile_id.py index 868b9badee5a..424e52e255d5 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_by_billing_profile_id.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_by_billing_profile_id.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationDetailsByBillingProfileId.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ReservationDetailsByBillingProfileId.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_by_billing_profile_id_reservation_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_by_billing_profile_id_reservation_id.py index 5e2576af19e9..800b7bac0ef2 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_by_billing_profile_id_reservation_id.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_by_billing_profile_id_reservation_id.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationDetailsByBillingProfileIdReservationId.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ReservationDetailsByBillingProfileIdReservationId.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_with_reservation_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_with_reservation_id.py index 648185c1e6d3..c8f84557c79f 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_with_reservation_id.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_with_reservation_id.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -38,6 +40,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationDetailsWithReservationId.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ReservationDetailsWithReservationId.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_billing_account.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_billing_account.py index b568ac4ebc9a..095e6f0f77da 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_billing_account.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_billing_account.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -30,7 +32,7 @@ def main(): ) response = client.reservation_recommendation_details.get( - resource_scope="providers/Microsoft.Billing/billingAccounts/000000", + resource_scope="providers/Microsoft.Billing/billingAccounts/00000000", scope="Shared", region="eastus", term="P1Y", @@ -40,6 +42,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationRecommendationDetailsByBillingAccount.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ReservationRecommendationDetailsByBillingAccount.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_billing_profile.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_billing_profile.py index baadc975b913..af3cb65e3e8e 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_billing_profile.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_billing_profile.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -40,6 +42,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationRecommendationDetailsByBillingProfile.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ReservationRecommendationDetailsByBillingProfile.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_resource_group.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_resource_group.py index 24db1707a9eb..b6a6594b631a 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_resource_group.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_resource_group.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -40,6 +42,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationRecommendationDetailsByResourceGroup.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ReservationRecommendationDetailsByResourceGroup.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_subscription.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_subscription.py index 00fd41c3e879..de53cf276d01 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_subscription.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_subscription.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -40,6 +42,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationRecommendationDetailsBySubscription.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ReservationRecommendationDetailsBySubscription.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_billing_account.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_billing_account.py index b6e75bdc45ba..f9974b4b3548 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_billing_account.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_billing_account.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationRecommendationsByBillingAccount.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ReservationRecommendationsByBillingAccount.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_billing_account_filter_by_scope.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_billing_account_filter_by_scope.py new file mode 100644 index 000000000000..24007ecfb410 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_billing_account_filter_by_scope.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python reservation_recommendations_by_billing_account_filter_by_scope.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 = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.reservation_recommendations.list( + resource_scope="providers/Microsoft.Billing/billingAccounts/123456", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ReservationRecommendationsByBillingAccountFilterByScope.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_billing_profile.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_billing_profile.py index 34c18444bb67..272e35d2a14b 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_billing_profile.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_billing_profile.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationRecommendationsByBillingProfile.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ReservationRecommendationsByBillingProfile.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_resource_group.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_resource_group.py index 38c93cb12b72..a0b08ab99736 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_resource_group.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_resource_group.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationRecommendationsByResourceGroup.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ReservationRecommendationsByResourceGroup.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_subscription.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_subscription.py index 6f3953bfafe0..1694078dd110 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_subscription.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_subscription.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationRecommendationsBySubscription.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ReservationRecommendationsBySubscription.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_filter_by_subscription_for_scope_look_back_period.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_filter_by_subscription_for_scope_look_back_period.py index b1eb8f1d440f..fc8957baf466 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_filter_by_subscription_for_scope_look_back_period.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_filter_by_subscription_for_scope_look_back_period.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationRecommendationsFilterBySubscriptionForScopeLookBackPeriod.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ReservationRecommendationsFilterBySubscriptionForScopeLookBackPeriod.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily.py index 483c4cc28fdc..394295788804 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -37,6 +39,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationSummariesDaily.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ReservationSummariesDaily.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily_with_billing_account_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily_with_billing_account_id.py index c8cb54c7f501..87b446804e9b 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily_with_billing_account_id.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily_with_billing_account_id.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -37,6 +39,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationSummariesDailyWithBillingAccountId.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ReservationSummariesDailyWithBillingAccountId.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily_with_billing_profile_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily_with_billing_profile_id.py index 026c74b73209..93a09bc5dc7a 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily_with_billing_profile_id.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily_with_billing_profile_id.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -37,6 +39,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationSummariesDailyWithBillingProfileId.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ReservationSummariesDailyWithBillingProfileId.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily_with_reservation_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily_with_reservation_id.py index fef5c801ffd3..638970bff687 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily_with_reservation_id.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily_with_reservation_id.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -38,6 +40,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationSummariesDailyWithReservationId.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ReservationSummariesDailyWithReservationId.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly.py index d422a0e92546..90e71a9f7a3f 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -37,6 +39,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationSummariesMonthly.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ReservationSummariesMonthly.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_billing_account_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_billing_account_id.py index 5364f59a6cdc..de56aa661009 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_billing_account_id.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_billing_account_id.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -37,6 +39,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationSummariesMonthlyWithBillingAccountId.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ReservationSummariesMonthlyWithBillingAccountId.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_billing_profile_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_billing_profile_id.py index 26e7ace88c0e..a33334f7e09c 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_billing_profile_id.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_billing_profile_id.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -37,6 +39,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationSummariesMonthlyWithBillingProfileId.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ReservationSummariesMonthlyWithBillingProfileId.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_billing_profile_id_reservation_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_billing_profile_id_reservation_id.py index ecce4ed58421..68860d59c1c3 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_billing_profile_id_reservation_id.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_billing_profile_id_reservation_id.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -37,6 +39,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationSummariesMonthlyWithBillingProfileIdReservationId.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ReservationSummariesMonthlyWithBillingProfileIdReservationId.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_reservation_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_reservation_id.py index 5d568bf216d2..b00822dabdf0 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_reservation_id.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_reservation_id.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -38,6 +40,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationSummariesMonthlyWithReservationId.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ReservationSummariesMonthlyWithReservationId.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_transactions_list_by_billing_profile_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_transactions_list_by_billing_profile_id.py index 47ad9d5fefe6..39f0cb592d66 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_transactions_list_by_billing_profile_id.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_transactions_list_by_billing_profile_id.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -37,6 +39,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationTransactionsListByBillingProfileId.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ReservationTransactionsListByBillingProfileId.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_transactions_list_by_enrollment_number.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_transactions_list_by_enrollment_number.py index e981da502b4c..81e17a390197 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_transactions_list_by_enrollment_number.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_transactions_list_by_enrollment_number.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationTransactionsListByEnrollmentNumber.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/ReservationTransactionsListByEnrollmentNumber.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/tags.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/tags.py index d1687eeaea60..d59c5155382a 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/tags.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/tags.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -35,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/Tags.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/Tags.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_expand.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_expand.py index 1bd9e81a704a..0cb82759b9b4 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_expand.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_expand.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsExpand.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/UsageDetailsExpand.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list.py index 629b97dd45a8..a090914ca56c 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsList.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/UsageDetailsList.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_billing_account.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_billing_account.py index b7670a59ed04..3c7bfe87c8b8 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_billing_account.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_billing_account.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByBillingAccount.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/UsageDetailsListByBillingAccount.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_department.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_department.py index 1ae750575929..3a3f206deae5 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_department.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_department.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByDepartment.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/UsageDetailsListByDepartment.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_enrollment_account.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_enrollment_account.py index b30348d97760..25bdabd37d95 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_enrollment_account.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_enrollment_account.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByEnrollmentAccount.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/UsageDetailsListByEnrollmentAccount.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_management_group.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_management_group.py index bea5ad73b412..82eb09f04e18 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_management_group.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_management_group.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByManagementGroup.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/UsageDetailsListByManagementGroup.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_billing_account.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_billing_account.py index fa5ce256e80a..c839ec5bcda3 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_billing_account.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_billing_account.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByMCABillingAccount.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/UsageDetailsListByMCABillingAccount.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_billing_profile.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_billing_profile.py index 26898092a093..2235ac84c03f 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_billing_profile.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_billing_profile.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByMCABillingProfile.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/UsageDetailsListByMCABillingProfile.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_customer.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_customer.py index 9dc99a6b98a5..b9bb5b74f4de 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_customer.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_customer.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByMCACustomer.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/UsageDetailsListByMCACustomer.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_invoice_section.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_invoice_section.py index 31956a23ef8d..858e401d1c47 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_invoice_section.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_invoice_section.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByMCAInvoiceSection.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/UsageDetailsListByMCAInvoiceSection.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_metric_actual_cost.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_metric_actual_cost.py index 74a175954cb5..22c536fa3892 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_metric_actual_cost.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_metric_actual_cost.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByMetricActualCost.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/UsageDetailsListByMetricActualCost.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_metric_amortized_cost.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_metric_amortized_cost.py index 8f8e9287f20e..99674e585f5a 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_metric_amortized_cost.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_metric_amortized_cost.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByMetricAmortizedCost.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/UsageDetailsListByMetricAmortizedCost.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_metric_usage.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_metric_usage.py index 5fd433c0db0e..3de90e241353 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_metric_usage.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_metric_usage.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByMetricUsage.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/UsageDetailsListByMetricUsage.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_filter_by_tag.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_filter_by_tag.py index 0f46035be369..2eab2b833a6f 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_filter_by_tag.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_filter_by_tag.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListFilterByTag.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/UsageDetailsListFilterByTag.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period.py index 2bc29d159630..96f90fdea081 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListForBillingPeriod.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/UsageDetailsListForBillingPeriod.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_billing_account.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_billing_account.py index 2f72f2a0cfb0..fdfeb77f617a 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_billing_account.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_billing_account.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListForBillingPeriodByBillingAccount.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/UsageDetailsListForBillingPeriodByBillingAccount.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_department.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_department.py index 462999a9dc8a..aac0829f478c 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_department.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_department.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListForBillingPeriodByDepartment.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/UsageDetailsListForBillingPeriodByDepartment.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_enrollment_account.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_enrollment_account.py index ffec807c47c5..6061c51871eb 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_enrollment_account.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_enrollment_account.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListForBillingPeriodByEnrollmentAccount.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/UsageDetailsListForBillingPeriodByEnrollmentAccount.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_management_group.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_management_group.py index dce956c8dbd4..3ca7fa995fd1 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_management_group.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_management_group.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.consumption import ConsumptionManagementClient """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListForBillingPeriodByManagementGroup.json +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2025-04-01/examples/UsageDetailsListForBillingPeriodByManagementGroup.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/conftest.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/conftest.py new file mode 100644 index 000000000000..cfbe7724cefe --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/conftest.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +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): + consumptionmanagement_subscription_id = os.environ.get( + "AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000" + ) + consumptionmanagement_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + consumptionmanagement_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + consumptionmanagement_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer( + regex=consumptionmanagement_subscription_id, value="00000000-0000-0000-0000-000000000000" + ) + add_general_regex_sanitizer(regex=consumptionmanagement_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=consumptionmanagement_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=consumptionmanagement_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/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_aggregated_cost_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_aggregated_cost_operations.py new file mode 100644 index 000000000000..9ca9bb9d8af7 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_aggregated_cost_operations.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption import ConsumptionManagementClient + +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 TestConsumptionManagementAggregatedCostOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_aggregated_cost_get_by_management_group(self, resource_group): + response = self.client.aggregated_cost.get_by_management_group( + management_group_id="str", + api_version="2025-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_aggregated_cost_get_for_billing_period_by_management_group(self, resource_group): + response = self.client.aggregated_cost.get_for_billing_period_by_management_group( + management_group_id="str", + billing_period_name="str", + api_version="2025-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_aggregated_cost_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_aggregated_cost_operations_async.py new file mode 100644 index 000000000000..1e963cdcb7f6 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_aggregated_cost_operations_async.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption.aio import ConsumptionManagementClient + +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 TestConsumptionManagementAggregatedCostOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_aggregated_cost_get_by_management_group(self, resource_group): + response = await self.client.aggregated_cost.get_by_management_group( + management_group_id="str", + api_version="2025-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_aggregated_cost_get_for_billing_period_by_management_group(self, resource_group): + response = await self.client.aggregated_cost.get_for_billing_period_by_management_group( + management_group_id="str", + billing_period_name="str", + api_version="2025-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_balances_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_balances_operations.py new file mode 100644 index 000000000000..2127a0bfcca0 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_balances_operations.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption import ConsumptionManagementClient + +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 TestConsumptionManagementBalancesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_balances_get_by_billing_account(self, resource_group): + response = self.client.balances.get_by_billing_account( + billing_account_id="str", + api_version="2025-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_balances_get_for_billing_period_by_billing_account(self, resource_group): + response = self.client.balances.get_for_billing_period_by_billing_account( + billing_account_id="str", + billing_period_name="str", + api_version="2025-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_balances_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_balances_operations_async.py new file mode 100644 index 000000000000..5a85b8137788 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_balances_operations_async.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption.aio import ConsumptionManagementClient + +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 TestConsumptionManagementBalancesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_balances_get_by_billing_account(self, resource_group): + response = await self.client.balances.get_by_billing_account( + billing_account_id="str", + api_version="2025-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_balances_get_for_billing_period_by_billing_account(self, resource_group): + response = await self.client.balances.get_for_billing_period_by_billing_account( + billing_account_id="str", + billing_period_name="str", + api_version="2025-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_budgets_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_budgets_operations.py new file mode 100644 index 000000000000..cfae55f16974 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_budgets_operations.py @@ -0,0 +1,100 @@ +# 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.consumption import ConsumptionManagementClient + +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 TestConsumptionManagementBudgetsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_budgets_list(self, resource_group): + response = self.client.budgets.list( + scope="str", + api_version="2025-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_budgets_get(self, resource_group): + response = self.client.budgets.get( + scope="str", + budget_name="str", + api_version="2025-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_budgets_create_or_update(self, resource_group): + response = self.client.budgets.create_or_update( + scope="str", + budget_name="str", + parameters={ + "amount": 0.0, + "category": "str", + "currentSpend": {"amount": 0.0, "unit": "str"}, + "eTag": "str", + "filter": { + "and": [ + { + "dimensions": {"name": "str", "operator": "str", "values": ["str"]}, + "tags": {"name": "str", "operator": "str", "values": ["str"]}, + } + ], + "dimensions": {"name": "str", "operator": "str", "values": ["str"]}, + "tags": {"name": "str", "operator": "str", "values": ["str"]}, + }, + "forecastSpend": {"amount": 0.0, "unit": "str"}, + "id": "str", + "name": "str", + "notifications": { + "str": { + "contactEmails": ["str"], + "enabled": bool, + "operator": "str", + "threshold": 0.0, + "contactGroups": ["str"], + "contactRoles": ["str"], + "locale": "str", + "thresholdType": "Actual", + } + }, + "timeGrain": "str", + "timePeriod": {"startDate": "2020-02-20 00:00:00", "endDate": "2020-02-20 00:00:00"}, + "type": "str", + }, + api_version="2025-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_budgets_delete(self, resource_group): + response = self.client.budgets.delete( + scope="str", + budget_name="str", + api_version="2025-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_budgets_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_budgets_operations_async.py new file mode 100644 index 000000000000..a703e987624c --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_budgets_operations_async.py @@ -0,0 +1,101 @@ +# 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.consumption.aio import ConsumptionManagementClient + +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 TestConsumptionManagementBudgetsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_budgets_list(self, resource_group): + response = self.client.budgets.list( + scope="str", + api_version="2025-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_budgets_get(self, resource_group): + response = await self.client.budgets.get( + scope="str", + budget_name="str", + api_version="2025-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_budgets_create_or_update(self, resource_group): + response = await self.client.budgets.create_or_update( + scope="str", + budget_name="str", + parameters={ + "amount": 0.0, + "category": "str", + "currentSpend": {"amount": 0.0, "unit": "str"}, + "eTag": "str", + "filter": { + "and": [ + { + "dimensions": {"name": "str", "operator": "str", "values": ["str"]}, + "tags": {"name": "str", "operator": "str", "values": ["str"]}, + } + ], + "dimensions": {"name": "str", "operator": "str", "values": ["str"]}, + "tags": {"name": "str", "operator": "str", "values": ["str"]}, + }, + "forecastSpend": {"amount": 0.0, "unit": "str"}, + "id": "str", + "name": "str", + "notifications": { + "str": { + "contactEmails": ["str"], + "enabled": bool, + "operator": "str", + "threshold": 0.0, + "contactGroups": ["str"], + "contactRoles": ["str"], + "locale": "str", + "thresholdType": "Actual", + } + }, + "timeGrain": "str", + "timePeriod": {"startDate": "2020-02-20 00:00:00", "endDate": "2020-02-20 00:00:00"}, + "type": "str", + }, + api_version="2025-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_budgets_delete(self, resource_group): + response = await self.client.budgets.delete( + scope="str", + budget_name="str", + api_version="2025-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_charges_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_charges_operations.py new file mode 100644 index 000000000000..3d1ef0874030 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_charges_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.consumption import ConsumptionManagementClient + +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 TestConsumptionManagementChargesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_charges_list(self, resource_group): + response = self.client.charges.list( + scope="str", + api_version="2025-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_charges_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_charges_operations_async.py new file mode 100644 index 000000000000..31cab21d770b --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_charges_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.consumption.aio import ConsumptionManagementClient + +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 TestConsumptionManagementChargesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_charges_list(self, resource_group): + response = await self.client.charges.list( + scope="str", + api_version="2025-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_credits_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_credits_operations.py new file mode 100644 index 000000000000..aa9e5dc991a8 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_credits_operations.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.consumption import ConsumptionManagementClient + +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 TestConsumptionManagementCreditsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_credits_get(self, resource_group): + response = self.client.credits.get( + billing_account_id="str", + billing_profile_id="str", + api_version="2025-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_credits_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_credits_operations_async.py new file mode 100644 index 000000000000..a4ee5f9dd69a --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_credits_operations_async.py @@ -0,0 +1,32 @@ +# 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.consumption.aio import ConsumptionManagementClient + +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 TestConsumptionManagementCreditsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_credits_get(self, resource_group): + response = await self.client.credits.get( + billing_account_id="str", + billing_profile_id="str", + api_version="2025-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_events_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_events_operations.py new file mode 100644 index 000000000000..41c2440889c1 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_events_operations.py @@ -0,0 +1,44 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption import ConsumptionManagementClient + +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 TestConsumptionManagementEventsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_events_list_by_billing_profile(self, resource_group): + response = self.client.events.list_by_billing_profile( + billing_account_id="str", + billing_profile_id="str", + start_date="str", + end_date="str", + api_version="2025-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_events_list_by_billing_account(self, resource_group): + response = self.client.events.list_by_billing_account( + billing_account_id="str", + api_version="2025-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_events_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_events_operations_async.py new file mode 100644 index 000000000000..ef2405b174ad --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_events_operations_async.py @@ -0,0 +1,45 @@ +# 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.consumption.aio import ConsumptionManagementClient + +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 TestConsumptionManagementEventsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_events_list_by_billing_profile(self, resource_group): + response = self.client.events.list_by_billing_profile( + billing_account_id="str", + billing_profile_id="str", + start_date="str", + end_date="str", + api_version="2025-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_events_list_by_billing_account(self, resource_group): + response = self.client.events.list_by_billing_account( + billing_account_id="str", + api_version="2025-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_lots_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_lots_operations.py new file mode 100644 index 000000000000..07672fccc80f --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_lots_operations.py @@ -0,0 +1,54 @@ +# 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.consumption import ConsumptionManagementClient + +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 TestConsumptionManagementLotsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_lots_list_by_billing_profile(self, resource_group): + response = self.client.lots.list_by_billing_profile( + billing_account_id="str", + billing_profile_id="str", + api_version="2025-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_lots_list_by_billing_account(self, resource_group): + response = self.client.lots.list_by_billing_account( + billing_account_id="str", + api_version="2025-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_lots_list_by_customer(self, resource_group): + response = self.client.lots.list_by_customer( + billing_account_id="str", + customer_id="str", + api_version="2025-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_lots_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_lots_operations_async.py new file mode 100644 index 000000000000..3a0bc226d7fe --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_lots_operations_async.py @@ -0,0 +1,55 @@ +# 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.consumption.aio import ConsumptionManagementClient + +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 TestConsumptionManagementLotsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_lots_list_by_billing_profile(self, resource_group): + response = self.client.lots.list_by_billing_profile( + billing_account_id="str", + billing_profile_id="str", + api_version="2025-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_lots_list_by_billing_account(self, resource_group): + response = self.client.lots.list_by_billing_account( + billing_account_id="str", + api_version="2025-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_lots_list_by_customer(self, resource_group): + response = self.client.lots.list_by_customer( + billing_account_id="str", + customer_id="str", + api_version="2025-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_marketplaces_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_marketplaces_operations.py new file mode 100644 index 000000000000..81c0aeb77094 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_marketplaces_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.consumption import ConsumptionManagementClient + +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 TestConsumptionManagementMarketplacesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_marketplaces_list(self, resource_group): + response = self.client.marketplaces.list( + scope="str", + api_version="2025-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_marketplaces_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_marketplaces_operations_async.py new file mode 100644 index 000000000000..1c65461bd61d --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_marketplaces_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.consumption.aio import ConsumptionManagementClient + +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 TestConsumptionManagementMarketplacesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_marketplaces_list(self, resource_group): + response = self.client.marketplaces.list( + scope="str", + api_version="2025-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_operations.py new file mode 100644 index 000000000000..b8f1b264c16e --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_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.consumption import ConsumptionManagementClient + +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 TestConsumptionManagementOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_operations_list(self, resource_group): + response = self.client.operations.list( + api_version="2025-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_operations_async.py new file mode 100644 index 000000000000..b2334326e2d2 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_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.consumption.aio import ConsumptionManagementClient + +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 TestConsumptionManagementOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, 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="2025-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_price_sheet_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_price_sheet_operations.py new file mode 100644 index 000000000000..666c503d9caa --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_price_sheet_operations.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.consumption import ConsumptionManagementClient + +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 TestConsumptionManagementPriceSheetOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_price_sheet_begin_download_by_billing_account_period(self, resource_group): + response = self.client.price_sheet.begin_download_by_billing_account_period( + billing_account_id="str", + billing_period_name="str", + api_version="2025-04-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_price_sheet_get(self, resource_group): + response = self.client.price_sheet.get( + api_version="2025-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_price_sheet_get_by_billing_period(self, resource_group): + response = self.client.price_sheet.get_by_billing_period( + billing_period_name="str", + api_version="2025-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_price_sheet_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_price_sheet_operations_async.py new file mode 100644 index 000000000000..5f42eb32ce0d --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_price_sheet_operations_async.py @@ -0,0 +1,55 @@ +# 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.consumption.aio import ConsumptionManagementClient + +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 TestConsumptionManagementPriceSheetOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_price_sheet_begin_download_by_billing_account_period(self, resource_group): + response = await ( + await self.client.price_sheet.begin_download_by_billing_account_period( + billing_account_id="str", + billing_period_name="str", + api_version="2025-04-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_price_sheet_get(self, resource_group): + response = await self.client.price_sheet.get( + api_version="2025-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_price_sheet_get_by_billing_period(self, resource_group): + response = await self.client.price_sheet.get_by_billing_period( + billing_period_name="str", + api_version="2025-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_recommendation_details_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_recommendation_details_operations.py new file mode 100644 index 000000000000..2d7e722f53d7 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_recommendation_details_operations.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 pytest +from azure.mgmt.consumption import ConsumptionManagementClient + +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 TestConsumptionManagementReservationRecommendationDetailsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservation_recommendation_details_get(self, resource_group): + response = self.client.reservation_recommendation_details.get( + resource_scope="str", + scope="str", + region="str", + term="str", + look_back_period="str", + product="str", + api_version="2025-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_recommendation_details_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_recommendation_details_operations_async.py new file mode 100644 index 000000000000..43c1dca19570 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_recommendation_details_operations_async.py @@ -0,0 +1,36 @@ +# 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.consumption.aio import ConsumptionManagementClient + +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 TestConsumptionManagementReservationRecommendationDetailsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservation_recommendation_details_get(self, resource_group): + response = await self.client.reservation_recommendation_details.get( + resource_scope="str", + scope="str", + region="str", + term="str", + look_back_period="str", + product="str", + api_version="2025-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_recommendations_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_recommendations_operations.py new file mode 100644 index 000000000000..a809c6c55eeb --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_recommendations_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.consumption import ConsumptionManagementClient + +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 TestConsumptionManagementReservationRecommendationsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservation_recommendations_list(self, resource_group): + response = self.client.reservation_recommendations.list( + resource_scope="str", + api_version="2025-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_recommendations_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_recommendations_operations_async.py new file mode 100644 index 000000000000..0201b0252e9a --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_recommendations_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.consumption.aio import ConsumptionManagementClient + +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 TestConsumptionManagementReservationRecommendationsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservation_recommendations_list(self, resource_group): + response = self.client.reservation_recommendations.list( + resource_scope="str", + api_version="2025-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_transactions_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_transactions_operations.py new file mode 100644 index 000000000000..636912677dbc --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_transactions_operations.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption import ConsumptionManagementClient + +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 TestConsumptionManagementReservationTransactionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservation_transactions_list(self, resource_group): + response = self.client.reservation_transactions.list( + billing_account_id="str", + api_version="2025-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservation_transactions_list_by_billing_profile(self, resource_group): + response = self.client.reservation_transactions.list_by_billing_profile( + billing_account_id="str", + billing_profile_id="str", + api_version="2025-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_transactions_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_transactions_operations_async.py new file mode 100644 index 000000000000..5961f49401c3 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_transactions_operations_async.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption.aio import ConsumptionManagementClient + +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 TestConsumptionManagementReservationTransactionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservation_transactions_list(self, resource_group): + response = self.client.reservation_transactions.list( + billing_account_id="str", + api_version="2025-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservation_transactions_list_by_billing_profile(self, resource_group): + response = self.client.reservation_transactions.list_by_billing_profile( + billing_account_id="str", + billing_profile_id="str", + api_version="2025-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservations_details_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservations_details_operations.py new file mode 100644 index 000000000000..7d56b5bc78ca --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservations_details_operations.py @@ -0,0 +1,55 @@ +# 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.consumption import ConsumptionManagementClient + +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 TestConsumptionManagementReservationsDetailsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservations_details_list_by_reservation_order(self, resource_group): + response = self.client.reservations_details.list_by_reservation_order( + reservation_order_id="str", + filter="str", + api_version="2025-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservations_details_list_by_reservation_order_and_reservation(self, resource_group): + response = self.client.reservations_details.list_by_reservation_order_and_reservation( + reservation_order_id="str", + reservation_id="str", + filter="str", + api_version="2025-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservations_details_list(self, resource_group): + response = self.client.reservations_details.list( + resource_scope="str", + api_version="2025-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservations_details_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservations_details_operations_async.py new file mode 100644 index 000000000000..0b9f1d1a1f25 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservations_details_operations_async.py @@ -0,0 +1,56 @@ +# 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.consumption.aio import ConsumptionManagementClient + +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 TestConsumptionManagementReservationsDetailsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservations_details_list_by_reservation_order(self, resource_group): + response = self.client.reservations_details.list_by_reservation_order( + reservation_order_id="str", + filter="str", + api_version="2025-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservations_details_list_by_reservation_order_and_reservation(self, resource_group): + response = self.client.reservations_details.list_by_reservation_order_and_reservation( + reservation_order_id="str", + reservation_id="str", + filter="str", + api_version="2025-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservations_details_list(self, resource_group): + response = self.client.reservations_details.list( + resource_scope="str", + api_version="2025-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservations_summaries_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservations_summaries_operations.py new file mode 100644 index 000000000000..1c73bcc8b4ba --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservations_summaries_operations.py @@ -0,0 +1,56 @@ +# 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.consumption import ConsumptionManagementClient + +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 TestConsumptionManagementReservationsSummariesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservations_summaries_list_by_reservation_order(self, resource_group): + response = self.client.reservations_summaries.list_by_reservation_order( + reservation_order_id="str", + grain="str", + api_version="2025-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservations_summaries_list_by_reservation_order_and_reservation(self, resource_group): + response = self.client.reservations_summaries.list_by_reservation_order_and_reservation( + reservation_order_id="str", + reservation_id="str", + grain="str", + api_version="2025-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservations_summaries_list(self, resource_group): + response = self.client.reservations_summaries.list( + resource_scope="str", + grain="str", + api_version="2025-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservations_summaries_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservations_summaries_operations_async.py new file mode 100644 index 000000000000..8427535ffe57 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservations_summaries_operations_async.py @@ -0,0 +1,57 @@ +# 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.consumption.aio import ConsumptionManagementClient + +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 TestConsumptionManagementReservationsSummariesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservations_summaries_list_by_reservation_order(self, resource_group): + response = self.client.reservations_summaries.list_by_reservation_order( + reservation_order_id="str", + grain="str", + api_version="2025-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservations_summaries_list_by_reservation_order_and_reservation(self, resource_group): + response = self.client.reservations_summaries.list_by_reservation_order_and_reservation( + reservation_order_id="str", + reservation_id="str", + grain="str", + api_version="2025-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservations_summaries_list(self, resource_group): + response = self.client.reservations_summaries.list( + resource_scope="str", + grain="str", + api_version="2025-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_tags_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_tags_operations.py new file mode 100644 index 000000000000..c14d0e3c0e96 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_tags_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.consumption import ConsumptionManagementClient + +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 TestConsumptionManagementTagsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_tags_get(self, resource_group): + response = self.client.tags.get( + scope="str", + api_version="2025-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_tags_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_tags_operations_async.py new file mode 100644 index 000000000000..21460502a628 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_tags_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.consumption.aio import ConsumptionManagementClient + +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 TestConsumptionManagementTagsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_tags_get(self, resource_group): + response = await self.client.tags.get( + scope="str", + api_version="2025-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_usage_details_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_usage_details_operations.py new file mode 100644 index 000000000000..cbd3be426eb6 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_usage_details_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.consumption import ConsumptionManagementClient + +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 TestConsumptionManagementUsageDetailsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_usage_details_list(self, resource_group): + response = self.client.usage_details.list( + scope="str", + api_version="2025-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_usage_details_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_usage_details_operations_async.py new file mode 100644 index 000000000000..83308bc7e14c --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_usage_details_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.consumption.aio import ConsumptionManagementClient + +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 TestConsumptionManagementUsageDetailsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_usage_details_list(self, resource_group): + response = self.client.usage_details.list( + scope="str", + api_version="2025-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/sdk_packaging.toml b/sdk/consumption/azure-mgmt-consumption/sdk_packaging.toml index 17190cce32d8..4b8d1561f551 100644 --- a/sdk/consumption/azure-mgmt-consumption/sdk_packaging.toml +++ b/sdk/consumption/azure-mgmt-consumption/sdk_packaging.toml @@ -3,7 +3,7 @@ package_name = "azure-mgmt-consumption" package_nspkg = "azure-mgmt-nspkg" package_pprint_name = "Consumption" package_doc_id = "consumption" -is_stable = false +is_stable = true is_arm = true sample_link = "" title = "ConsumptionManagementClient" diff --git a/sdk/consumption/azure-mgmt-consumption/setup.py b/sdk/consumption/azure-mgmt-consumption/setup.py index 58c2d0310b71..2fd945c35b76 100644 --- a/sdk/consumption/azure-mgmt-consumption/setup.py +++ b/sdk/consumption/azure-mgmt-consumption/setup.py @@ -1,10 +1,10 @@ #!/usr/bin/env python -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. -#-------------------------------------------------------------------------- +# -------------------------------------------------------------------------- import re import os.path @@ -16,64 +16,67 @@ PACKAGE_PPRINT_NAME = "Consumption" # a-b-c => a/b/c -package_folder_path = PACKAGE_NAME.replace('-', '/') +package_folder_path = PACKAGE_NAME.replace("-", "/") # a-b-c => a.b.c -namespace_name = PACKAGE_NAME.replace('-', '.') +namespace_name = PACKAGE_NAME.replace("-", ".") # Version extraction inspired from 'requests' -with open(os.path.join(package_folder_path, 'version.py') - if os.path.exists(os.path.join(package_folder_path, 'version.py')) - else os.path.join(package_folder_path, '_version.py'), 'r') as fd: - version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', - fd.read(), re.MULTILINE).group(1) +with open( + os.path.join(package_folder_path, "version.py") + if os.path.exists(os.path.join(package_folder_path, "version.py")) + else os.path.join(package_folder_path, "_version.py"), + "r", +) as fd: + version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: - raise RuntimeError('Cannot find version information') + raise RuntimeError("Cannot find version information") -with open('README.md', encoding='utf-8') as f: +with open("README.md", encoding="utf-8") as f: readme = f.read() -with open('CHANGELOG.md', encoding='utf-8') as f: +with open("CHANGELOG.md", encoding="utf-8") as f: changelog = f.read() setup( name=PACKAGE_NAME, version=version, - description='Microsoft Azure {} Client Library for Python'.format(PACKAGE_PPRINT_NAME), - long_description=readme + '\n\n' + changelog, - long_description_content_type='text/markdown', - license='MIT License', - author='Microsoft Corporation', - author_email='azpysdkhelp@microsoft.com', - url='https://github.com/Azure/azure-sdk-for-python', + description="Microsoft Azure {} Client Library for Python".format(PACKAGE_PPRINT_NAME), + long_description=readme + "\n\n" + changelog, + long_description_content_type="text/markdown", + license="MIT License", + author="Microsoft Corporation", + author_email="azpysdkhelp@microsoft.com", + url="https://github.com/Azure/azure-sdk-for-python", keywords="azure, azure sdk", # update with search keywords relevant to the azure service / product classifiers=[ - 'Development Status :: 4 - Beta', - 'Programming Language :: Python', - 'Programming Language :: Python :: 3 :: Only', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Programming Language :: Python :: 3.10', - 'Programming Language :: Python :: 3.11', - 'License :: OSI Approved :: MIT License', + "Development Status :: 5 - Production/Stable", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "License :: OSI Approved :: MIT License", ], zip_safe=False, - packages=find_packages(exclude=[ - 'tests', - # Exclude packages that will be covered by PEP420 or nspkg - 'azure', - 'azure.mgmt', - ]), + packages=find_packages( + exclude=[ + "tests", + # Exclude packages that will be covered by PEP420 or nspkg + "azure", + "azure.mgmt", + ] + ), include_package_data=True, package_data={ - 'pytyped': ['py.typed'], + "pytyped": ["py.typed"], }, install_requires=[ - "msrest>=0.7.1", - "azure-common~=1.1", - "azure-mgmt-core>=1.3.2,<2.0.0", - "typing-extensions>=4.3.0; python_version<'3.8.0'", + "isodate>=0.6.1", + "typing-extensions>=4.6.0", + "azure-common>=1.1", + "azure-mgmt-core>=1.5.0", ], - python_requires=">=3.7" + python_requires=">=3.9", )