diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/CHANGELOG.md b/sdk/costmanagement/azure-mgmt-costmanagement/CHANGELOG.md index 119b38ef45a5..8cbeba3021f3 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/CHANGELOG.md +++ b/sdk/costmanagement/azure-mgmt-costmanagement/CHANGELOG.md @@ -1,5 +1,153 @@ # Release History +## 5.0.0b1 (2025-03-25) + +### Features Added + + - Client `CostManagementClient` added operation group `cost_allocation_rules` + - Client `CostManagementClient` added operation group `generate_benefit_utilization_summaries_report` + - Client `CostManagementClient` added operation group `budgets` + - Client `CostManagementClient` added operation group `settings` + - Model `CommonExportProperties` added property `data_overwrite_behavior` + - Model `CommonExportProperties` added property `compression_mode` + - Model `CommonExportProperties` added property `export_description` + - Model `CommonExportProperties` added property `system_suspension_context` + - Model `Export` added property `identity` + - Model `Export` added property `location` + - Model `Export` added property `data_overwrite_behavior` + - Model `Export` added property `compression_mode` + - Model `Export` added property `export_description` + - Model `Export` added property `system_suspension_context` + - Model `ExportDatasetConfiguration` added property `data_version` + - Model `ExportDatasetConfiguration` added property `filters` + - Model `ExportDeliveryDestination` added property `type` + - Model `ExportDeliveryDestination` added property `microsoft_fabric_settings` + - Model `ExportProperties` added property `data_overwrite_behavior` + - Model `ExportProperties` added property `compression_mode` + - Model `ExportProperties` added property `export_description` + - Model `ExportProperties` added property `system_suspension_context` + - Model `ExportRun` added property `start_date` + - Model `ExportRun` added property `end_date` + - Model `ExportRun` added property `manifest_file` + - Enum `ExportType` added member `FOCUS_COST` + - Enum `ExportType` added member `PRICE_SHEET` + - Enum `ExportType` added member `RESERVATION_DETAILS` + - Enum `ExportType` added member `RESERVATION_RECOMMENDATIONS` + - Enum `ExportType` added member `RESERVATION_TRANSACTIONS` + - Enum `FormatType` added member `DELTA` + - Enum `FormatType` added member `PARQUET` + - Enum `GranularityType` added member `MONTHLY` + - Enum `OperationStatusType` added member `COMPLETE` + - Enum `StatusType` added member `SYSTEM_SUSPENDED` + - Enum `TimeframeType` added member `THE_CURRENT_MONTH` + - Added model `AsyncOperationStatusProperties` + - Added model `BenefitUtilizationSummariesOperationStatus` + - Added model `BenefitUtilizationSummariesRequest` + - Added enum `BenefitUtilizationSummaryReportSchema` + - Added model `Budget` + - Added model `BudgetComparisonExpression` + - Added model `BudgetFilter` + - Added model `BudgetFilterProperties` + - Added enum `BudgetNotificationOperatorType` + - Added enum `BudgetOperatorType` + - Added model `BudgetTimePeriod` + - Added model `BudgetsListResult` + - Added enum `CategoryType` + - Added enum `CompressionModeType` + - Added enum `CostAllocationPolicyType` + - Added model `CostAllocationProportion` + - Added model `CostAllocationResource` + - Added enum `CostAllocationResourceType` + - Added model `CostAllocationRuleCheckNameAvailabilityRequest` + - Added model `CostAllocationRuleCheckNameAvailabilityResponse` + - Added model `CostAllocationRuleDefinition` + - Added model `CostAllocationRuleDetails` + - Added model `CostAllocationRuleList` + - Added model `CostAllocationRuleProperties` + - Added enum `CultureCode` + - Added model `CurrentSpend` + - Added enum `DataOverwriteBehaviorType` + - Added enum `DestinationType` + - Added model `EAPriceSheetProperties` + - Added model `ErrorAdditionalInfo` + - Added model `ErrorDetail` + - Added model `ErrorDetailAutoGenerated` + - Added model `ErrorResponseAutoGenerated` + - Added model `ErrorResponseAutoGenerated2` + - Added model `ExportRunRequest` + - Added model `ExportSuspensionContext` + - Added model `FabricLakehouse` + - Added model `FabricWorkspace` + - Added enum `FilterItemNames` + - Added model `FilterItems` + - Added model `ForecastSpend` + - Added enum `Frequency` + - Added model `MCAPriceSheetProperties` + - Added model `MicrosoftFabricDestinationSettings` + - Added model `Notification` + - Added model `OperationStatusAutoGenerated` + - Added model `PricesheetDownloadProperties` + - Added enum `Reason` + - Added enum `RuleStatus` + - Added model `Setting` + - Added enum `SettingType` + - Added enum `SettingsKind` + - Added model `SettingsListResult` + - Added model `SourceCostAllocationResource` + - Added model `SystemAssignedServiceIdentity` + - Added enum `SystemAssignedServiceIdentityType` + - Added model `TagInheritanceProperties` + - Added model `TagInheritanceSetting` + - Added model `TargetCostAllocationResource` + - Added enum `ThresholdType` + - Added enum `TimeGrainType` + - Model `PriceSheetOperations` added method `begin_download_by_billing_account` + - Model `PriceSheetOperations` added method `begin_download_by_invoice` + - Added model `BudgetsOperations` + - Added model `CostAllocationRulesOperations` + - Added model `GenerateBenefitUtilizationSummariesReportOperations` + - Added model `SettingsOperations` + - Method `AlertsOperations.dismiss` has a new overload `def dismiss(self: None, scope: str, alert_id: str, parameters: IO[bytes], content_type: str)` + - Method `ExportsOperations.create_or_update` has a new overload `def create_or_update(self: None, scope: str, export_name: str, parameters: IO[bytes], content_type: str)` + - Method `ExportsOperations.execute` has a new overload `def execute(self: None, scope: str, export_name: str, parameters: Optional[ExportRunRequest], content_type: str)` + - Method `ExportsOperations.execute` has a new overload `def execute(self: None, scope: str, export_name: str, parameters: Optional[IO[bytes]], content_type: str)` + - Method `ForecastOperations.external_cloud_provider_usage` has a new overload `def external_cloud_provider_usage(self: None, external_cloud_provider_type: Union[str, ExternalCloudProviderType], external_cloud_provider_id: str, parameters: IO[bytes], filter: Optional[str], content_type: str)` + - Method `ForecastOperations.usage` has a new overload `def usage(self: None, scope: str, parameters: IO[bytes], filter: Optional[str], content_type: str)` + - Method `GenerateCostDetailsReportOperations.begin_create_operation` has a new overload `def begin_create_operation(self: None, scope: str, parameters: IO[bytes], content_type: str)` + - Method `GenerateDetailedCostReportOperations.begin_create_operation` has a new overload `def begin_create_operation(self: None, scope: str, parameters: IO[bytes], content_type: str)` + - Method `QueryOperations.usage` has a new overload `def usage(self: None, scope: str, parameters: IO[bytes], content_type: str)` + - Method `QueryOperations.usage_by_external_cloud_provider_type` has a new overload `def usage_by_external_cloud_provider_type(self: None, external_cloud_provider_type: Union[str, ExternalCloudProviderType], external_cloud_provider_id: str, parameters: IO[bytes], content_type: str)` + - Method `ScheduledActionsOperations.check_name_availability` has a new overload `def check_name_availability(self: None, check_name_availability_request: IO[bytes], content_type: str)` + - Method `ScheduledActionsOperations.check_name_availability_by_scope` has a new overload `def check_name_availability_by_scope(self: None, scope: str, check_name_availability_request: IO[bytes], content_type: str)` + - Method `ScheduledActionsOperations.create_or_update` has a new overload `def create_or_update(self: None, name: str, scheduled_action: IO[bytes], if_match: Optional[str], content_type: str)` + - Method `ScheduledActionsOperations.create_or_update_by_scope` has a new overload `def create_or_update_by_scope(self: None, scope: str, name: str, scheduled_action: IO[bytes], if_match: Optional[str], content_type: str)` + - Method `ViewsOperations.create_or_update` has a new overload `def create_or_update(self: None, view_name: str, parameters: IO[bytes], content_type: str)` + - Method `ViewsOperations.create_or_update_by_scope` has a new overload `def create_or_update_by_scope(self: None, scope: str, view_name: str, parameters: IO[bytes], content_type: str)` + - 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)` + - Method `CostAllocationRulesOperations.check_name_availability` has a new overload `def check_name_availability(self: None, billing_account_id: str, cost_allocation_rule_check_name_availability_request: CostAllocationRuleCheckNameAvailabilityRequest, content_type: str)` + - Method `CostAllocationRulesOperations.check_name_availability` has a new overload `def check_name_availability(self: None, billing_account_id: str, cost_allocation_rule_check_name_availability_request: IO[bytes], content_type: str)` + - Method `CostAllocationRulesOperations.create_or_update` has a new overload `def create_or_update(self: None, billing_account_id: str, rule_name: str, cost_allocation_rule: CostAllocationRuleDefinition, content_type: str)` + - Method `CostAllocationRulesOperations.create_or_update` has a new overload `def create_or_update(self: None, billing_account_id: str, rule_name: str, cost_allocation_rule: IO[bytes], content_type: str)` + - Method `GenerateBenefitUtilizationSummariesReportOperations.begin_generate_by_billing_account` has a new overload `def begin_generate_by_billing_account(self: None, billing_account_id: str, benefit_utilization_summaries_request: BenefitUtilizationSummariesRequest, content_type: str)` + - Method `GenerateBenefitUtilizationSummariesReportOperations.begin_generate_by_billing_account` has a new overload `def begin_generate_by_billing_account(self: None, billing_account_id: str, benefit_utilization_summaries_request: IO[bytes], content_type: str)` + - Method `GenerateBenefitUtilizationSummariesReportOperations.begin_generate_by_billing_profile` has a new overload `def begin_generate_by_billing_profile(self: None, billing_account_id: str, billing_profile_id: str, benefit_utilization_summaries_request: BenefitUtilizationSummariesRequest, content_type: str)` + - Method `GenerateBenefitUtilizationSummariesReportOperations.begin_generate_by_billing_profile` has a new overload `def begin_generate_by_billing_profile(self: None, billing_account_id: str, billing_profile_id: str, benefit_utilization_summaries_request: IO[bytes], content_type: str)` + - Method `GenerateBenefitUtilizationSummariesReportOperations.begin_generate_by_reservation_id` has a new overload `def begin_generate_by_reservation_id(self: None, reservation_order_id: str, reservation_id: str, benefit_utilization_summaries_request: BenefitUtilizationSummariesRequest, content_type: str)` + - Method `GenerateBenefitUtilizationSummariesReportOperations.begin_generate_by_reservation_id` has a new overload `def begin_generate_by_reservation_id(self: None, reservation_order_id: str, reservation_id: str, benefit_utilization_summaries_request: IO[bytes], content_type: str)` + - Method `GenerateBenefitUtilizationSummariesReportOperations.begin_generate_by_reservation_order_id` has a new overload `def begin_generate_by_reservation_order_id(self: None, reservation_order_id: str, benefit_utilization_summaries_request: BenefitUtilizationSummariesRequest, content_type: str)` + - Method `GenerateBenefitUtilizationSummariesReportOperations.begin_generate_by_reservation_order_id` has a new overload `def begin_generate_by_reservation_order_id(self: None, reservation_order_id: str, benefit_utilization_summaries_request: IO[bytes], content_type: str)` + - Method `GenerateBenefitUtilizationSummariesReportOperations.begin_generate_by_savings_plan_id` has a new overload `def begin_generate_by_savings_plan_id(self: None, savings_plan_order_id: str, savings_plan_id: str, benefit_utilization_summaries_request: BenefitUtilizationSummariesRequest, content_type: str)` + - Method `GenerateBenefitUtilizationSummariesReportOperations.begin_generate_by_savings_plan_id` has a new overload `def begin_generate_by_savings_plan_id(self: None, savings_plan_order_id: str, savings_plan_id: str, benefit_utilization_summaries_request: IO[bytes], content_type: str)` + - Method `GenerateBenefitUtilizationSummariesReportOperations.begin_generate_by_savings_plan_order_id` has a new overload `def begin_generate_by_savings_plan_order_id(self: None, savings_plan_order_id: str, benefit_utilization_summaries_request: BenefitUtilizationSummariesRequest, content_type: str)` + - Method `GenerateBenefitUtilizationSummariesReportOperations.begin_generate_by_savings_plan_order_id` has a new overload `def begin_generate_by_savings_plan_order_id(self: None, savings_plan_order_id: str, benefit_utilization_summaries_request: IO[bytes], content_type: str)` + - Method `SettingsOperations.create_or_update_by_scope` has a new overload `def create_or_update_by_scope(self: None, scope: str, type: Union[str, SettingType], setting: Setting, content_type: str)` + - Method `SettingsOperations.create_or_update_by_scope` has a new overload `def create_or_update_by_scope(self: None, scope: str, type: Union[str, SettingType], setting: IO[bytes], content_type: str)` + +### Breaking Changes + + - Deleted or renamed method `PriceSheetOperations.begin_download` + ## 4.0.1 (2023-07-19) ### Bugs Fixed diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/README.md b/sdk/costmanagement/azure-mgmt-costmanagement/README.md index deec30aa11e0..74ca3d56fb6b 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/README.md +++ b/sdk/costmanagement/azure-mgmt-costmanagement/README.md @@ -1,7 +1,7 @@ # Microsoft Azure SDK for Python This is the Microsoft Azure Cost Management Client Library. -This package has been tested with Python 3.7+. +This package has been tested with Python 3.8+. For a more complete view of Azure libraries, see the [azure sdk python release](https://aka.ms/azsdk/python/all). ## _Disclaimer_ @@ -12,7 +12,7 @@ _Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For ### Prerequisites -- Python 3.7+ is required to use this package. +- Python 3.8+ is required to use this package. - [Azure subscription](https://azure.microsoft.com/free/) ### Install the package @@ -55,6 +55,3 @@ Code samples for this package can be found at: 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/costmanagement/azure-mgmt-costmanagement/_meta.json b/sdk/costmanagement/azure-mgmt-costmanagement/_meta.json index 7c83f312205c..44158c7104f0 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/_meta.json +++ b/sdk/costmanagement/azure-mgmt-costmanagement/_meta.json @@ -1,11 +1,11 @@ { - "commit": "493aa7224fd65fe1e5b4cff59bcae5c6cdf4525e", + "commit": "ba3631957859da5ce2ddbabddac35a5d05bde224", "repository_url": "https://github.com/Azure/azure-rest-api-specs", - "autorest": "3.9.2", + "autorest": "3.10.2", "use": [ - "@autorest/python@6.6.0", - "@autorest/modelerfour@4.24.3" + "@autorest/python@6.27.4", + "@autorest/modelerfour@4.27.0" ], - "autorest_command": "autorest specification/cost-management/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 --tag=package-2022-10 --use=@autorest/python@6.6.0 --use=@autorest/modelerfour@4.24.3 --version=3.9.2 --version-tolerant=False", + "autorest_command": "autorest specification/cost-management/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.27.4 --use=@autorest/modelerfour@4.27.0 --version=3.10.2 --version-tolerant=False", "readme": "specification/cost-management/resource-manager/readme.md" } \ No newline at end of file diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/__init__.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/__init__.py index 327688c9882a..cb3da220a6b5 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/__init__.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/__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 ._cost_management_client import CostManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._cost_management_client import CostManagementClient # 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__ = [ "CostManagementClient", ] -__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/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_configuration.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_configuration.py index 8087ca9f9c1f..80d1d26201c4 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_configuration.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_configuration.py @@ -8,18 +8,16 @@ 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 TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class CostManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class CostManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for CostManagementClient. Note that all parameters used to create this instance are saved as instance @@ -27,14 +25,13 @@ class CostManagementClientConfiguration(Configuration): # pylint: disable=too-m :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :keyword api_version: Api Version. Default value is "2022-10-01". Note that overriding this - default value may result in unsupported behavior. + :keyword api_version: Api Version. Default value is "2024-10-01-preview". Note that overriding + this default value may result in unsupported behavior. :paramtype api_version: str """ def __init__(self, credential: "TokenCredential", **kwargs: Any) -> None: - super(CostManagementClientConfiguration, self).__init__(**kwargs) - api_version: str = kwargs.pop("api_version", "2022-10-01") + api_version: str = kwargs.pop("api_version", "2024-10-01-preview") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -43,6 +40,7 @@ def __init__(self, credential: "TokenCredential", **kwargs: Any) -> None: self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-costmanagement/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -51,9 +49,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/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_cost_management_client.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_cost_management_client.py index 0e26e2fa3291..b7f92f990015 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_cost_management_client.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_cost_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from ._configuration import CostManagementClientConfiguration @@ -19,9 +22,12 @@ AlertsOperations, BenefitRecommendationsOperations, BenefitUtilizationSummariesOperations, + BudgetsOperations, + CostAllocationRulesOperations, DimensionsOperations, ExportsOperations, ForecastOperations, + GenerateBenefitUtilizationSummariesReportOperations, GenerateCostDetailsReportOperations, GenerateDetailedCostReportOperationResultsOperations, GenerateDetailedCostReportOperationStatusOperations, @@ -31,34 +37,35 @@ PriceSheetOperations, QueryOperations, ScheduledActionsOperations, + SettingsOperations, ViewsOperations, ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class CostManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes +class CostManagementClient: # pylint: disable=too-many-instance-attributes """CostManagement management client provides access to CostManagement resources for Azure Enterprise Subscriptions. :ivar operations: Operations operations :vartype operations: azure.mgmt.costmanagement.operations.Operations - :ivar views: ViewsOperations operations - :vartype views: azure.mgmt.costmanagement.operations.ViewsOperations - :ivar alerts: AlertsOperations operations - :vartype alerts: azure.mgmt.costmanagement.operations.AlertsOperations - :ivar forecast: ForecastOperations operations - :vartype forecast: azure.mgmt.costmanagement.operations.ForecastOperations - :ivar dimensions: DimensionsOperations operations - :vartype dimensions: azure.mgmt.costmanagement.operations.DimensionsOperations - :ivar query: QueryOperations operations - :vartype query: azure.mgmt.costmanagement.operations.QueryOperations - :ivar generate_reservation_details_report: GenerateReservationDetailsReportOperations - operations - :vartype generate_reservation_details_report: - azure.mgmt.costmanagement.operations.GenerateReservationDetailsReportOperations + :ivar cost_allocation_rules: CostAllocationRulesOperations operations + :vartype cost_allocation_rules: + azure.mgmt.costmanagement.operations.CostAllocationRulesOperations + :ivar benefit_recommendations: BenefitRecommendationsOperations operations + :vartype benefit_recommendations: + azure.mgmt.costmanagement.operations.BenefitRecommendationsOperations + :ivar benefit_utilization_summaries: BenefitUtilizationSummariesOperations operations + :vartype benefit_utilization_summaries: + azure.mgmt.costmanagement.operations.BenefitUtilizationSummariesOperations + :ivar generate_benefit_utilization_summaries_report: + GenerateBenefitUtilizationSummariesReportOperations operations + :vartype generate_benefit_utilization_summaries_report: + azure.mgmt.costmanagement.operations.GenerateBenefitUtilizationSummariesReportOperations + :ivar budgets: BudgetsOperations operations + :vartype budgets: azure.mgmt.costmanagement.operations.BudgetsOperations :ivar exports: ExportsOperations operations :vartype exports: azure.mgmt.costmanagement.operations.ExportsOperations :ivar generate_cost_details_report: GenerateCostDetailsReportOperations operations @@ -75,22 +82,32 @@ class CostManagementClient: # pylint: disable=client-accepts-api-version-keywor GenerateDetailedCostReportOperationStatusOperations operations :vartype generate_detailed_cost_report_operation_status: azure.mgmt.costmanagement.operations.GenerateDetailedCostReportOperationStatusOperations + :ivar views: ViewsOperations operations + :vartype views: azure.mgmt.costmanagement.operations.ViewsOperations + :ivar alerts: AlertsOperations operations + :vartype alerts: azure.mgmt.costmanagement.operations.AlertsOperations + :ivar forecast: ForecastOperations operations + :vartype forecast: azure.mgmt.costmanagement.operations.ForecastOperations + :ivar dimensions: DimensionsOperations operations + :vartype dimensions: azure.mgmt.costmanagement.operations.DimensionsOperations + :ivar query: QueryOperations operations + :vartype query: azure.mgmt.costmanagement.operations.QueryOperations + :ivar generate_reservation_details_report: GenerateReservationDetailsReportOperations + operations + :vartype generate_reservation_details_report: + azure.mgmt.costmanagement.operations.GenerateReservationDetailsReportOperations :ivar price_sheet: PriceSheetOperations operations :vartype price_sheet: azure.mgmt.costmanagement.operations.PriceSheetOperations :ivar scheduled_actions: ScheduledActionsOperations operations :vartype scheduled_actions: azure.mgmt.costmanagement.operations.ScheduledActionsOperations - :ivar benefit_recommendations: BenefitRecommendationsOperations operations - :vartype benefit_recommendations: - azure.mgmt.costmanagement.operations.BenefitRecommendationsOperations - :ivar benefit_utilization_summaries: BenefitUtilizationSummariesOperations operations - :vartype benefit_utilization_summaries: - azure.mgmt.costmanagement.operations.BenefitUtilizationSummariesOperations + :ivar settings: SettingsOperations operations + :vartype settings: azure.mgmt.costmanagement.operations.SettingsOperations :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str - :keyword api_version: Api Version. Default value is "2022-10-01". Note that overriding this - default value may result in unsupported behavior. + :keyword api_version: Api Version. Default value is "2024-10-01-preview". 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. @@ -100,21 +117,44 @@ def __init__( self, credential: "TokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = CostManagementClientConfiguration(credential=credential, **kwargs) - self._client: ARMPipelineClient = 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=base_url, policies=_policies, **kwargs) client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) - self.views = ViewsOperations(self._client, self._config, self._serialize, self._deserialize) - self.alerts = AlertsOperations(self._client, self._config, self._serialize, self._deserialize) - self.forecast = ForecastOperations(self._client, self._config, self._serialize, self._deserialize) - self.dimensions = DimensionsOperations(self._client, self._config, self._serialize, self._deserialize) - self.query = QueryOperations(self._client, self._config, self._serialize, self._deserialize) - self.generate_reservation_details_report = GenerateReservationDetailsReportOperations( + self.cost_allocation_rules = CostAllocationRulesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.benefit_recommendations = BenefitRecommendationsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.benefit_utilization_summaries = BenefitUtilizationSummariesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.generate_benefit_utilization_summaries_report = GenerateBenefitUtilizationSummariesReportOperations( self._client, self._config, self._serialize, self._deserialize ) + self.budgets = BudgetsOperations(self._client, self._config, self._serialize, self._deserialize) self.exports = ExportsOperations(self._client, self._config, self._serialize, self._deserialize) self.generate_cost_details_report = GenerateCostDetailsReportOperations( self._client, self._config, self._serialize, self._deserialize @@ -128,18 +168,21 @@ def __init__( self.generate_detailed_cost_report_operation_status = GenerateDetailedCostReportOperationStatusOperations( self._client, self._config, self._serialize, self._deserialize ) - self.price_sheet = PriceSheetOperations(self._client, self._config, self._serialize, self._deserialize) - self.scheduled_actions = ScheduledActionsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.benefit_recommendations = BenefitRecommendationsOperations( + self.views = ViewsOperations(self._client, self._config, self._serialize, self._deserialize) + self.alerts = AlertsOperations(self._client, self._config, self._serialize, self._deserialize) + self.forecast = ForecastOperations(self._client, self._config, self._serialize, self._deserialize) + self.dimensions = DimensionsOperations(self._client, self._config, self._serialize, self._deserialize) + self.query = QueryOperations(self._client, self._config, self._serialize, self._deserialize) + self.generate_reservation_details_report = GenerateReservationDetailsReportOperations( self._client, self._config, self._serialize, self._deserialize ) - self.benefit_utilization_summaries = BenefitUtilizationSummariesOperations( + self.price_sheet = PriceSheetOperations(self._client, self._config, self._serialize, self._deserialize) + self.scheduled_actions = ScheduledActionsOperations( self._client, self._config, self._serialize, self._deserialize ) + self.settings = SettingsOperations(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 @@ -159,12 +202,12 @@ 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) -> "CostManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_serialization.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_serialization.py index 842ae727fbbc..b24ab2885450 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_serialization.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_serialization.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # # Copyright (c) Microsoft Corporation. All rights reserved. @@ -24,7 +25,6 @@ # # -------------------------------------------------------------------------- -# pylint: skip-file # pyright: reportUnnecessaryTypeIgnoreComment=false from base64 import b64decode, b64encode @@ -52,7 +52,6 @@ MutableMapping, Type, List, - Mapping, ) try: @@ -63,8 +62,8 @@ import isodate # type: ignore -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback -from azure.core.serialization import NULL as AzureCoreNull +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") @@ -91,6 +90,8 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: :param data: Input, could be bytes or stream (will be decoded with UTF8) or text :type data: str or bytes or IO :param str content_type: The content type. + :return: The deserialized data. + :rtype: object """ if hasattr(data, "read"): # Assume a stream @@ -112,7 +113,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: @@ -124,7 +125,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 @@ -143,7 +144,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 @@ -153,6 +156,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 @@ -170,13 +178,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: @@ -189,15 +190,30 @@ class UTC(datetime.tzinfo): """Time Zone info for handling UTC""" def utcoffset(self, dt): - """UTF offset for UTC is 0.""" + """UTF offset for UTC is 0. + + :param datetime.datetime dt: The datetime + :returns: The offset + :rtype: datetime.timedelta + """ return datetime.timedelta(0) def tzname(self, dt): - """Timestamp representation.""" + """Timestamp representation. + + :param datetime.datetime dt: The datetime + :returns: The timestamp representation + :rtype: str + """ return "Z" def dst(self, dt): - """No daylight saving for UTC.""" + """No daylight saving for UTC. + + :param datetime.datetime dt: The datetime + :returns: The daylight saving time + :rtype: datetime.timedelta + """ return datetime.timedelta(hours=1) @@ -211,7 +227,7 @@ class _FixedOffset(datetime.tzinfo): # type: ignore :param datetime.timedelta offset: offset in timedelta format """ - def __init__(self, offset): + def __init__(self, offset) -> None: self.__offset = offset def utcoffset(self, dt): @@ -240,24 +256,26 @@ def __getinitargs__(self): _FLATTEN = re.compile(r"(? None: - self.additional_properties: Dict[str, Any] = {} - for k in kwargs: + 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): @@ -305,13 +330,23 @@ def __init__(self, **kwargs: Any) -> None: setattr(self, k, kwargs[k]) def __eq__(self, other: Any) -> bool: - """Compare objects by comparing all attributes.""" + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ return False def __ne__(self, other: Any) -> bool: - """Compare objects by comparing all attributes.""" + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ return not self.__eq__(other) def __str__(self) -> str: @@ -331,7 +366,11 @@ def is_xml_model(cls) -> bool: @classmethod def _create_xml_node(cls): - """Create XML node.""" + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ try: xml_map = cls._xml_map # type: ignore except AttributeError: @@ -340,7 +379,7 @@ 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: bool = False, **kwargs: Any) -> JSON: - """Return the JSON that would be sent to azure from this model. + """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)`. @@ -351,7 +390,9 @@ def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) def as_dict( self, @@ -385,12 +426,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): @@ -400,7 +444,7 @@ 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 @@ -413,9 +457,10 @@ def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = N :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model :raises: DeserializationError if something went wrong + :rtype: ModelType """ 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( @@ -431,9 +476,11 @@ def from_dict( and last_rest_key_case_insensitive_extractor) :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model :raises: DeserializationError if something went wrong + :rtype: ModelType """ deserializer = Deserializer(cls._infer_class_models()) deserializer.key_extractors = ( # type: ignore @@ -445,7 +492,7 @@ def from_dict( if key_extractors is None else key_extractors ) - return deserializer(cls.__name__, data, content_type=content_type) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod def _flatten_subtype(cls, key, objects): @@ -453,21 +500,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: @@ -506,11 +557,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"} @@ -545,7 +598,7 @@ class Serializer(object): "multiple": lambda x, y: x % y != 0, } - def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.serialize_type = { "iso-8601": Serializer.serialize_iso, "rfc-1123": Serializer.serialize_rfc, @@ -561,17 +614,20 @@ def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): "[]": self.serialize_iter, "{}": self.serialize_dict, } - self.dependencies: Dict[str, Type[ModelType]] = 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. + :returns: The serialized data. """ key_transformer = kwargs.get("key_transformer", self.key_transformer) keep_readonly = kwargs.get("keep_readonly", False) @@ -597,12 +653,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"] == "": @@ -638,7 +696,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 @@ -649,7 +708,7 @@ 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 @@ -662,23 +721,24 @@ 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 + :returns: The serialized request body """ # Just in case this is a dict @@ -707,18 +767,20 @@ 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 + :returns: The serialized URL path :raises: TypeError if serialization fails. :raises: ValueError if data is None """ @@ -729,30 +791,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 + :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) @@ -762,19 +824,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 + :returns: The serialized header """ try: if data_type in ["[str]"]: @@ -783,32 +846,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. + :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 AzureCoreNull: + 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 @@ -823,12 +885,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 @@ -844,23 +905,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 @@ -874,8 +938,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. @@ -885,13 +948,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.") @@ -903,9 +966,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) @@ -941,16 +1009,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: @@ -965,7 +1034,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 @@ -973,6 +1042,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 @@ -983,7 +1053,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) @@ -997,7 +1067,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: @@ -1028,56 +1098,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) @@ -1085,11 +1160,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) @@ -1099,30 +1175,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. + :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], @@ -1135,12 +1213,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. + :return: serialized iso """ if isinstance(attr, str): attr = isodate.parse_datetime(attr) @@ -1160,19 +1239,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 + :return: serialied unix """ if isinstance(attr, int): return attr @@ -1180,11 +1260,11 @@ def serialize_unix(attr, **kwargs): if not attr.tzinfo: _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc -def rest_key_extractor(attr, attr_desc, data): +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument key = attr_desc["key"] working_data = data @@ -1199,14 +1279,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 @@ -1220,7 +1301,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:]) @@ -1228,17 +1308,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) @@ -1275,7 +1367,7 @@ def _extract_name_from_internal_type(internal_type): return xml_name -def xml_key_extractor(attr, attr_desc, data): +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements if isinstance(data, dict): return None @@ -1327,22 +1419,21 @@ def xml_key_extractor(attr, attr_desc, data): if is_iter_type: if is_wrapped: return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list + return [] # not wrapped, assume empty list return None # Assume it's not there, maybe an optional node. # If is_iter_type and not wrapped, return all found children if is_iter_type: if not is_wrapped: return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) + # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( # pylint: disable=line-too-long + xml_name ) - return list(children[0]) # Might be empty list and that's ok. + ) + return list(children[0]) # Might be empty list and that's ok. # Here it's not a itertype, we should have found one element only or empty if len(children) > 1: @@ -1350,7 +1441,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. @@ -1359,9 +1450,9 @@ class Deserializer(object): basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.deserialize_type = { "iso-8601": Deserializer.deserialize_iso, "rfc-1123": Deserializer.deserialize_rfc, @@ -1381,7 +1472,7 @@ def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): "duration": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } - self.dependencies: Dict[str, Type[ModelType]] = 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 @@ -1399,11 +1490,12 @@ def __call__(self, target_obj, response_data, content_type=None): :param str content_type: Swagger "produces" if available. :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 @@ -1412,12 +1504,13 @@ def _deserialize(self, target_obj, data): :param object data: Object to deserialize. :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) @@ -1434,15 +1527,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"... @@ -1471,10 +1564,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: @@ -1501,18 +1593,20 @@ def _classify_target(self, target, data): :param str target: The target object type to deserialize to. :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple """ if target is None: return None, None - 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__ # type: ignore @@ -1527,10 +1621,12 @@ def failsafe_deserialize(self, target_obj, data, content_type=None): :param str target_obj: The target object type to deserialize to. :param str/dict data: The response data to deserialize. :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object """ try: return self(target_obj, data, content_type=content_type) - except: + except: # pylint: disable=bare-except _LOGGER.debug( "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True ) @@ -1548,10 +1644,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", {}) @@ -1568,31 +1666,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(): @@ -1601,15 +1710,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. :return: Deserialized object. + :rtype: object """ if data is None: return data @@ -1623,7 +1733,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) @@ -1642,15 +1756,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: @@ -1667,6 +1781,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): @@ -1677,11 +1792,12 @@ 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. """ @@ -1690,7 +1806,7 @@ def deserialize_object(self, attr, **kwargs): if isinstance(attr, ET.Element): # Do no recurse on XML, just return the tree as-is return attr - if isinstance(attr, basestring): + if isinstance(attr, str): return self.deserialize_basic(attr, "str") obj_type = type(attr) if obj_type in self.basic_types: @@ -1716,11 +1832,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 @@ -1728,6 +1843,7 @@ 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. """ @@ -1739,24 +1855,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): @@ -1764,6 +1879,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, @@ -1777,8 +1893,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): @@ -1790,6 +1905,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: @@ -1798,12 +1914,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: @@ -1819,6 +1934,7 @@ 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. """ @@ -1831,6 +1947,7 @@ 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. """ @@ -1846,22 +1963,24 @@ def deserialize_decimal(attr): """Deserialize string into Decimal object. :param str attr: response string to be deserialized. - :rtype: Decimal + :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. """ @@ -1874,6 +1993,7 @@ 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. """ @@ -1883,15 +2003,15 @@ 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. """ @@ -1900,13 +2020,14 @@ def deserialize_date(attr): 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. """ @@ -1921,6 +2042,7 @@ 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. """ @@ -1935,15 +2057,15 @@ def deserialize_rfc(attr): date_obj = date_obj.astimezone(tz=TZ_UTC) except ValueError as err: msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - 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. """ @@ -1972,9 +2094,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): @@ -1982,15 +2103,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 """ 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/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_vendor.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -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: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_version.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_version.py index f4674910a502..c2a9243ac0cd 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_version.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "4.0.1" +VERSION = "5.0.0b1" diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/__init__.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/__init__.py index e631aab7dc99..8170fcf87d3a 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/__init__.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/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 ._cost_management_client import CostManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._cost_management_client import CostManagementClient # 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__ = [ "CostManagementClient", ] -__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/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_configuration.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_configuration.py index 55e6f4190aa5..e8e85c8fdbdd 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_configuration.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_configuration.py @@ -8,18 +8,16 @@ 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 TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class CostManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class CostManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for CostManagementClient. Note that all parameters used to create this instance are saved as instance @@ -27,14 +25,13 @@ class CostManagementClientConfiguration(Configuration): # pylint: disable=too-m :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :keyword api_version: Api Version. Default value is "2022-10-01". Note that overriding this - default value may result in unsupported behavior. + :keyword api_version: Api Version. Default value is "2024-10-01-preview". Note that overriding + this default value may result in unsupported behavior. :paramtype api_version: str """ def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None: - super(CostManagementClientConfiguration, self).__init__(**kwargs) - api_version: str = kwargs.pop("api_version", "2022-10-01") + api_version: str = kwargs.pop("api_version", "2024-10-01-preview") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -43,6 +40,7 @@ def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None: self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-costmanagement/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -51,9 +49,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/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_cost_management_client.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_cost_management_client.py index daa9e01ede33..b3b897230e54 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_cost_management_client.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_cost_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from .._serialization import Deserializer, Serializer @@ -19,9 +22,12 @@ AlertsOperations, BenefitRecommendationsOperations, BenefitUtilizationSummariesOperations, + BudgetsOperations, + CostAllocationRulesOperations, DimensionsOperations, ExportsOperations, ForecastOperations, + GenerateBenefitUtilizationSummariesReportOperations, GenerateCostDetailsReportOperations, GenerateDetailedCostReportOperationResultsOperations, GenerateDetailedCostReportOperationStatusOperations, @@ -31,34 +37,35 @@ PriceSheetOperations, QueryOperations, ScheduledActionsOperations, + SettingsOperations, ViewsOperations, ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class CostManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes +class CostManagementClient: # pylint: disable=too-many-instance-attributes """CostManagement management client provides access to CostManagement resources for Azure Enterprise Subscriptions. :ivar operations: Operations operations :vartype operations: azure.mgmt.costmanagement.aio.operations.Operations - :ivar views: ViewsOperations operations - :vartype views: azure.mgmt.costmanagement.aio.operations.ViewsOperations - :ivar alerts: AlertsOperations operations - :vartype alerts: azure.mgmt.costmanagement.aio.operations.AlertsOperations - :ivar forecast: ForecastOperations operations - :vartype forecast: azure.mgmt.costmanagement.aio.operations.ForecastOperations - :ivar dimensions: DimensionsOperations operations - :vartype dimensions: azure.mgmt.costmanagement.aio.operations.DimensionsOperations - :ivar query: QueryOperations operations - :vartype query: azure.mgmt.costmanagement.aio.operations.QueryOperations - :ivar generate_reservation_details_report: GenerateReservationDetailsReportOperations - operations - :vartype generate_reservation_details_report: - azure.mgmt.costmanagement.aio.operations.GenerateReservationDetailsReportOperations + :ivar cost_allocation_rules: CostAllocationRulesOperations operations + :vartype cost_allocation_rules: + azure.mgmt.costmanagement.aio.operations.CostAllocationRulesOperations + :ivar benefit_recommendations: BenefitRecommendationsOperations operations + :vartype benefit_recommendations: + azure.mgmt.costmanagement.aio.operations.BenefitRecommendationsOperations + :ivar benefit_utilization_summaries: BenefitUtilizationSummariesOperations operations + :vartype benefit_utilization_summaries: + azure.mgmt.costmanagement.aio.operations.BenefitUtilizationSummariesOperations + :ivar generate_benefit_utilization_summaries_report: + GenerateBenefitUtilizationSummariesReportOperations operations + :vartype generate_benefit_utilization_summaries_report: + azure.mgmt.costmanagement.aio.operations.GenerateBenefitUtilizationSummariesReportOperations + :ivar budgets: BudgetsOperations operations + :vartype budgets: azure.mgmt.costmanagement.aio.operations.BudgetsOperations :ivar exports: ExportsOperations operations :vartype exports: azure.mgmt.costmanagement.aio.operations.ExportsOperations :ivar generate_cost_details_report: GenerateCostDetailsReportOperations operations @@ -75,22 +82,32 @@ class CostManagementClient: # pylint: disable=client-accepts-api-version-keywor GenerateDetailedCostReportOperationStatusOperations operations :vartype generate_detailed_cost_report_operation_status: azure.mgmt.costmanagement.aio.operations.GenerateDetailedCostReportOperationStatusOperations + :ivar views: ViewsOperations operations + :vartype views: azure.mgmt.costmanagement.aio.operations.ViewsOperations + :ivar alerts: AlertsOperations operations + :vartype alerts: azure.mgmt.costmanagement.aio.operations.AlertsOperations + :ivar forecast: ForecastOperations operations + :vartype forecast: azure.mgmt.costmanagement.aio.operations.ForecastOperations + :ivar dimensions: DimensionsOperations operations + :vartype dimensions: azure.mgmt.costmanagement.aio.operations.DimensionsOperations + :ivar query: QueryOperations operations + :vartype query: azure.mgmt.costmanagement.aio.operations.QueryOperations + :ivar generate_reservation_details_report: GenerateReservationDetailsReportOperations + operations + :vartype generate_reservation_details_report: + azure.mgmt.costmanagement.aio.operations.GenerateReservationDetailsReportOperations :ivar price_sheet: PriceSheetOperations operations :vartype price_sheet: azure.mgmt.costmanagement.aio.operations.PriceSheetOperations :ivar scheduled_actions: ScheduledActionsOperations operations :vartype scheduled_actions: azure.mgmt.costmanagement.aio.operations.ScheduledActionsOperations - :ivar benefit_recommendations: BenefitRecommendationsOperations operations - :vartype benefit_recommendations: - azure.mgmt.costmanagement.aio.operations.BenefitRecommendationsOperations - :ivar benefit_utilization_summaries: BenefitUtilizationSummariesOperations operations - :vartype benefit_utilization_summaries: - azure.mgmt.costmanagement.aio.operations.BenefitUtilizationSummariesOperations + :ivar settings: SettingsOperations operations + :vartype settings: azure.mgmt.costmanagement.aio.operations.SettingsOperations :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str - :keyword api_version: Api Version. Default value is "2022-10-01". Note that overriding this - default value may result in unsupported behavior. + :keyword api_version: Api Version. Default value is "2024-10-01-preview". 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. @@ -100,21 +117,44 @@ def __init__( self, credential: "AsyncTokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = CostManagementClientConfiguration(credential=credential, **kwargs) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(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), + AsyncARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, policies=_policies, **kwargs) client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) - self.views = ViewsOperations(self._client, self._config, self._serialize, self._deserialize) - self.alerts = AlertsOperations(self._client, self._config, self._serialize, self._deserialize) - self.forecast = ForecastOperations(self._client, self._config, self._serialize, self._deserialize) - self.dimensions = DimensionsOperations(self._client, self._config, self._serialize, self._deserialize) - self.query = QueryOperations(self._client, self._config, self._serialize, self._deserialize) - self.generate_reservation_details_report = GenerateReservationDetailsReportOperations( + self.cost_allocation_rules = CostAllocationRulesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.benefit_recommendations = BenefitRecommendationsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.benefit_utilization_summaries = BenefitUtilizationSummariesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.generate_benefit_utilization_summaries_report = GenerateBenefitUtilizationSummariesReportOperations( self._client, self._config, self._serialize, self._deserialize ) + self.budgets = BudgetsOperations(self._client, self._config, self._serialize, self._deserialize) self.exports = ExportsOperations(self._client, self._config, self._serialize, self._deserialize) self.generate_cost_details_report = GenerateCostDetailsReportOperations( self._client, self._config, self._serialize, self._deserialize @@ -128,18 +168,23 @@ def __init__( self.generate_detailed_cost_report_operation_status = GenerateDetailedCostReportOperationStatusOperations( self._client, self._config, self._serialize, self._deserialize ) - self.price_sheet = PriceSheetOperations(self._client, self._config, self._serialize, self._deserialize) - self.scheduled_actions = ScheduledActionsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.benefit_recommendations = BenefitRecommendationsOperations( + self.views = ViewsOperations(self._client, self._config, self._serialize, self._deserialize) + self.alerts = AlertsOperations(self._client, self._config, self._serialize, self._deserialize) + self.forecast = ForecastOperations(self._client, self._config, self._serialize, self._deserialize) + self.dimensions = DimensionsOperations(self._client, self._config, self._serialize, self._deserialize) + self.query = QueryOperations(self._client, self._config, self._serialize, self._deserialize) + self.generate_reservation_details_report = GenerateReservationDetailsReportOperations( self._client, self._config, self._serialize, self._deserialize ) - self.benefit_utilization_summaries = BenefitUtilizationSummariesOperations( + self.price_sheet = PriceSheetOperations(self._client, self._config, self._serialize, self._deserialize) + self.scheduled_actions = ScheduledActionsOperations( self._client, self._config, self._serialize, self._deserialize ) + self.settings = SettingsOperations(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 @@ -159,12 +204,12 @@ 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) -> "CostManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/__init__.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/__init__.py index ba3f6355c103..abdd1e06a664 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/__init__.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/__init__.py @@ -5,49 +5,59 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._operations import Operations -from ._views_operations import ViewsOperations -from ._alerts_operations import AlertsOperations -from ._forecast_operations import ForecastOperations -from ._dimensions_operations import DimensionsOperations -from ._query_operations import QueryOperations -from ._generate_reservation_details_report_operations import GenerateReservationDetailsReportOperations -from ._exports_operations import ExportsOperations -from ._generate_cost_details_report_operations import GenerateCostDetailsReportOperations -from ._generate_detailed_cost_report_operations import GenerateDetailedCostReportOperations -from ._generate_detailed_cost_report_operation_results_operations import ( - GenerateDetailedCostReportOperationResultsOperations, -) -from ._generate_detailed_cost_report_operation_status_operations import ( - GenerateDetailedCostReportOperationStatusOperations, -) -from ._price_sheet_operations import PriceSheetOperations -from ._scheduled_actions_operations import ScheduledActionsOperations -from ._benefit_recommendations_operations import BenefitRecommendationsOperations -from ._benefit_utilization_summaries_operations import BenefitUtilizationSummariesOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import Operations # type: ignore +from ._cost_allocation_rules_operations import CostAllocationRulesOperations # type: ignore +from ._benefit_recommendations_operations import BenefitRecommendationsOperations # type: ignore +from ._benefit_utilization_summaries_operations import BenefitUtilizationSummariesOperations # type: ignore +from ._generate_benefit_utilization_summaries_report_operations import GenerateBenefitUtilizationSummariesReportOperations # type: ignore +from ._budgets_operations import BudgetsOperations # type: ignore +from ._exports_operations import ExportsOperations # type: ignore +from ._generate_cost_details_report_operations import GenerateCostDetailsReportOperations # type: ignore +from ._generate_detailed_cost_report_operations import GenerateDetailedCostReportOperations # type: ignore +from ._generate_detailed_cost_report_operation_results_operations import GenerateDetailedCostReportOperationResultsOperations # type: ignore +from ._generate_detailed_cost_report_operation_status_operations import GenerateDetailedCostReportOperationStatusOperations # type: ignore +from ._views_operations import ViewsOperations # type: ignore +from ._alerts_operations import AlertsOperations # type: ignore +from ._forecast_operations import ForecastOperations # type: ignore +from ._dimensions_operations import DimensionsOperations # type: ignore +from ._query_operations import QueryOperations # type: ignore +from ._generate_reservation_details_report_operations import GenerateReservationDetailsReportOperations # type: ignore +from ._price_sheet_operations import PriceSheetOperations # type: ignore +from ._scheduled_actions_operations import ScheduledActionsOperations # type: ignore +from ._settings_operations import SettingsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "Operations", + "CostAllocationRulesOperations", + "BenefitRecommendationsOperations", + "BenefitUtilizationSummariesOperations", + "GenerateBenefitUtilizationSummariesReportOperations", + "BudgetsOperations", + "ExportsOperations", + "GenerateCostDetailsReportOperations", + "GenerateDetailedCostReportOperations", + "GenerateDetailedCostReportOperationResultsOperations", + "GenerateDetailedCostReportOperationStatusOperations", "ViewsOperations", "AlertsOperations", "ForecastOperations", "DimensionsOperations", "QueryOperations", "GenerateReservationDetailsReportOperations", - "ExportsOperations", - "GenerateCostDetailsReportOperations", - "GenerateDetailedCostReportOperations", - "GenerateDetailedCostReportOperationResultsOperations", - "GenerateDetailedCostReportOperationStatusOperations", "PriceSheetOperations", "ScheduledActionsOperations", - "BenefitRecommendationsOperations", - "BenefitUtilizationSummariesOperations", + "SettingsOperations", ] -__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/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_alerts_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_alerts_operations.py index aac3086e4d30..89445f95eebe 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_alerts_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_alerts_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( @@ -18,14 +18,12 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request from ...operations._alerts_operations import ( build_dismiss_request, build_get_request, @@ -33,6 +31,10 @@ build_list_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -58,6 +60,7 @@ def __init__(self, *args, **kwargs) -> None: @distributed_trace_async async def list(self, scope: str, **kwargs: Any) -> _models.AlertsResult: + # pylint: disable=line-too-long """Lists the alerts for scope defined. .. seealso:: @@ -80,12 +83,11 @@ async def list(self, scope: str, **kwargs: Any) -> _models.AlertsResult: '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' specific for partners. Required. :type scope: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AlertsResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.AlertsResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -99,19 +101,17 @@ async def list(self, scope: str, **kwargs: Any) -> _models.AlertsResult: api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.AlertsResult] = kwargs.pop("cls", None) - 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -121,17 +121,16 @@ async def list(self, scope: str, **kwargs: Any) -> _models.AlertsResult: error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AlertsResult", pipeline_response) + deserialized = self._deserialize("AlertsResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - list.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/alerts"} + return deserialized # type: ignore @distributed_trace_async async def get(self, scope: str, alert_id: str, **kwargs: Any) -> _models.Alert: + # pylint: disable=line-too-long """Gets the alert for the scope by alert ID. .. seealso:: @@ -156,12 +155,11 @@ async def get(self, scope: str, alert_id: str, **kwargs: Any) -> _models.Alert: :type scope: str :param alert_id: Alert ID. Required. :type alert_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Alert or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Alert :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -175,20 +173,18 @@ async def get(self, scope: str, alert_id: str, **kwargs: Any) -> _models.Alert: api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Alert] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( scope=scope, alert_id=alert_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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -198,14 +194,12 @@ async def get(self, scope: str, alert_id: str, **kwargs: Any) -> _models.Alert: error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Alert", pipeline_response) + deserialized = self._deserialize("Alert", 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.CostManagement/alerts/{alertId}"} + return deserialized # type: ignore @overload async def dismiss( @@ -217,6 +211,7 @@ async def dismiss( content_type: str = "application/json", **kwargs: Any ) -> _models.Alert: + # pylint: disable=line-too-long """Dismisses the specified alert. .. seealso:: @@ -246,7 +241,6 @@ async def dismiss( :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: Alert or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Alert :raises ~azure.core.exceptions.HttpResponseError: @@ -254,8 +248,9 @@ async def dismiss( @overload async def dismiss( - self, scope: str, alert_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, scope: str, alert_id: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.Alert: + # pylint: disable=line-too-long """Dismisses the specified alert. .. seealso:: @@ -281,11 +276,10 @@ async def dismiss( :param alert_id: Alert ID. Required. :type alert_id: str :param parameters: Parameters supplied to the Dismiss Alert 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: Alert or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Alert :raises ~azure.core.exceptions.HttpResponseError: @@ -293,8 +287,9 @@ async def dismiss( @distributed_trace_async async def dismiss( - self, scope: str, alert_id: str, parameters: Union[_models.DismissAlertPayload, IO], **kwargs: Any + self, scope: str, alert_id: str, parameters: Union[_models.DismissAlertPayload, IO[bytes]], **kwargs: Any ) -> _models.Alert: + # pylint: disable=line-too-long """Dismisses the specified alert. .. seealso:: @@ -320,17 +315,13 @@ async def dismiss( :param alert_id: Alert ID. Required. :type alert_id: str :param parameters: Parameters supplied to the Dismiss Alert operation. Is either a - DismissAlertPayload type or a IO type. Required. - :type parameters: ~azure.mgmt.costmanagement.models.DismissAlertPayload 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 + DismissAlertPayload type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.DismissAlertPayload or IO[bytes] :return: Alert or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Alert :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -353,23 +344,21 @@ async def dismiss( else: _json = self._serialize.body(parameters, "DismissAlertPayload") - request = build_dismiss_request( + _request = build_dismiss_request( scope=scope, alert_id=alert_id, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.dismiss.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -379,14 +368,12 @@ async def dismiss( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Alert", pipeline_response) + deserialized = self._deserialize("Alert", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - dismiss.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/alerts/{alertId}"} + return deserialized # type: ignore @distributed_trace_async async def list_external( @@ -410,12 +397,11 @@ async def list_external( '{externalBillingAccountId}' for consolidated account used with dimension/query operations. Required. :type external_cloud_provider_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AlertsResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.AlertsResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -429,20 +415,18 @@ async def list_external( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.AlertsResult] = kwargs.pop("cls", None) - request = build_list_external_request( + _request = build_list_external_request( external_cloud_provider_type=external_cloud_provider_type, external_cloud_provider_id=external_cloud_provider_id, api_version=api_version, - template_url=self.list_external.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -452,13 +436,9 @@ async def list_external( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AlertsResult", pipeline_response) + deserialized = self._deserialize("AlertsResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - list_external.metadata = { - "url": "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/alerts" - } + return deserialized # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_benefit_recommendations_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_benefit_recommendations_operations.py index cafa32b3d00d..565df7402423 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_benefit_recommendations_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_benefit_recommendations_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar import urllib.parse @@ -19,16 +19,18 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request from ...operations._benefit_recommendations_operations import build_list_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -87,7 +89,6 @@ def list( :param expand: May be used to expand the properties by: properties/usage, properties/allRecommendationDetails. Default value is None. :type expand: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BenefitRecommendationModel or the result of cls(response) :rtype: @@ -100,7 +101,7 @@ def list( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BenefitRecommendationsListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -111,18 +112,16 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( billing_scope=billing_scope, filter=filter, orderby=orderby, expand=expand, 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 @@ -134,13 +133,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("BenefitRecommendationsListResult", pipeline_response) @@ -150,11 +148,11 @@ 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -166,5 +164,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{billingScope}/providers/Microsoft.CostManagement/benefitRecommendations"} diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_benefit_utilization_summaries_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_benefit_utilization_summaries_operations.py index 81caf0cefc6f..d3440bec1c2f 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_benefit_utilization_summaries_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_benefit_utilization_summaries_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union import urllib.parse @@ -19,14 +19,12 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request from ...operations._benefit_utilization_summaries_operations import ( build_list_by_billing_account_id_request, build_list_by_billing_profile_id_request, @@ -34,6 +32,10 @@ build_list_by_savings_plan_order_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -79,7 +81,6 @@ def list_by_billing_account_id( :param filter: Supports filtering by properties/benefitId, properties/benefitOrderId and properties/usageDate. 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 BenefitUtilizationSummary or the result of cls(response) :rtype: @@ -92,7 +93,7 @@ def list_by_billing_account_id( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BenefitUtilizationSummariesListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -103,17 +104,15 @@ def list_by_billing_account_id( def prepare_request(next_link=None): if not next_link: - request = build_list_by_billing_account_id_request( + _request = build_list_by_billing_account_id_request( billing_account_id=billing_account_id, grain_parameter=grain_parameter, filter=filter, api_version=api_version, - template_url=self.list_by_billing_account_id.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 +124,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("BenefitUtilizationSummariesListResult", pipeline_response) @@ -141,11 +139,11 @@ 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -158,10 +156,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_billing_account_id.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/benefitUtilizationSummaries" - } - @distributed_trace def list_by_billing_profile_id( self, @@ -187,7 +181,6 @@ def list_by_billing_profile_id( :param filter: Supports filtering by properties/benefitId, properties/benefitOrderId and properties/usageDate. 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 BenefitUtilizationSummary or the result of cls(response) :rtype: @@ -200,7 +193,7 @@ def list_by_billing_profile_id( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BenefitUtilizationSummariesListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -211,18 +204,16 @@ def list_by_billing_profile_id( def prepare_request(next_link=None): if not next_link: - request = build_list_by_billing_profile_id_request( + _request = build_list_by_billing_profile_id_request( billing_account_id=billing_account_id, billing_profile_id=billing_profile_id, grain_parameter=grain_parameter, filter=filter, api_version=api_version, - template_url=self.list_by_billing_profile_id.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 @@ -234,13 +225,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("BenefitUtilizationSummariesListResult", pipeline_response) @@ -250,11 +240,11 @@ 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -267,10 +257,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_billing_profile_id.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.CostManagement/benefitUtilizationSummaries" - } - @distributed_trace def list_by_savings_plan_order( self, @@ -291,7 +277,6 @@ def list_by_savings_plan_order( :param grain_parameter: Grain. Known values are: "Hourly", "Daily", and "Monthly". Default value is None. :type grain_parameter: str or ~azure.mgmt.costmanagement.models.GrainParameter - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BenefitUtilizationSummary or the result of cls(response) :rtype: @@ -304,7 +289,7 @@ def list_by_savings_plan_order( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BenefitUtilizationSummariesListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -315,17 +300,15 @@ def list_by_savings_plan_order( def prepare_request(next_link=None): if not next_link: - request = build_list_by_savings_plan_order_request( + _request = build_list_by_savings_plan_order_request( savings_plan_order_id=savings_plan_order_id, filter=filter, grain_parameter=grain_parameter, api_version=api_version, - template_url=self.list_by_savings_plan_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 @@ -337,13 +320,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("BenefitUtilizationSummariesListResult", pipeline_response) @@ -353,11 +335,11 @@ 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -370,10 +352,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_savings_plan_order.metadata = { - "url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/providers/Microsoft.CostManagement/benefitUtilizationSummaries" - } - @distributed_trace def list_by_savings_plan_id( self, @@ -397,7 +375,6 @@ def list_by_savings_plan_id( :param grain_parameter: Grain. Known values are: "Hourly", "Daily", and "Monthly". Default value is None. :type grain_parameter: str or ~azure.mgmt.costmanagement.models.GrainParameter - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BenefitUtilizationSummary or the result of cls(response) :rtype: @@ -410,7 +387,7 @@ def list_by_savings_plan_id( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BenefitUtilizationSummariesListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -421,18 +398,16 @@ def list_by_savings_plan_id( def prepare_request(next_link=None): if not next_link: - request = build_list_by_savings_plan_id_request( + _request = build_list_by_savings_plan_id_request( savings_plan_order_id=savings_plan_order_id, savings_plan_id=savings_plan_id, filter=filter, grain_parameter=grain_parameter, api_version=api_version, - template_url=self.list_by_savings_plan_id.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 @@ -444,13 +419,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("BenefitUtilizationSummariesListResult", pipeline_response) @@ -460,11 +434,11 @@ 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -476,7 +450,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list_by_savings_plan_id.metadata = { - "url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans/{savingsPlanId}/providers/Microsoft.CostManagement/benefitUtilizationSummaries" - } diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_budgets_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_budgets_operations.py new file mode 100644 index 000000000000..9aed8847f8ef --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_budgets_operations.py @@ -0,0 +1,700 @@ +# 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 io import IOBase +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +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 ...operations._budgets_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class BudgetsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s + :attr:`budgets` attribute. + """ + + models = _models + + 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") + + @distributed_trace + def list(self, scope: str, filter: Optional[str] = None, **kwargs: Any) -> AsyncIterable["_models.Budget"]: + # pylint: disable=line-too-long + """Lists all budgets for the defined scope. + + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/CostManagement/ + + :param scope: The scope associated with budget operations. + + Supported scopes for **CategoryType: Cost** + + Azure RBAC Scopes: + + + * '/subscriptions/{subscriptionId}/' for subscription scope + * '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope + * + '/providers/Microsoft.Management/managementGroups/{managementGroupId}' for Management Group + scope + + EA (Enterprise Agreement) Scopes: + + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope + + MCA (Modern Customer Agreement) Scopes: + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' for + customer scope (CSP only) + + Supported scopes for **CategoryType: ReservationUtilization** + + EA (Enterprise Agreement) Scopes: + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account Scope + + MCA (Modern Customer Agreement) Scopes: + + + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope (non-CSP only) + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' for + customer scope (CSP only). Required. + :type scope: str + :param filter: OData filter option. May be used to filter budgets by properties/category. The + filter supports 'eq' only. Default value is None. + :type filter: str + :return: An iterator like instance of either Budget or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.Budget] + :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.BudgetsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + scope=scope, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _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) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get(self, scope: str, budget_name: str, **kwargs: Any) -> _models.Budget: + # pylint: disable=line-too-long + """Gets the budget for the scope by budget name. + + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/CostManagement/ + + :param scope: The scope associated with budget operations. + + Supported scopes for **CategoryType: Cost** + + Azure RBAC Scopes: + + + * '/subscriptions/{subscriptionId}/' for subscription scope + * '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope + * + '/providers/Microsoft.Management/managementGroups/{managementGroupId}' for Management Group + scope + + EA (Enterprise Agreement) Scopes: + + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope + + MCA (Modern Customer Agreement) Scopes: + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' for + customer scope (CSP only) + + Supported scopes for **CategoryType: ReservationUtilization** + + EA (Enterprise Agreement) Scopes: + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account Scope + + MCA (Modern Customer Agreement) Scopes: + + + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope (non-CSP only) + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' for + customer scope (CSP only). Required. + :type scope: str + :param budget_name: Budget Name. Required. + :type budget_name: str + :return: Budget or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Budget + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.Budget] = kwargs.pop("cls", None) + + _request = build_get_request( + scope=scope, + budget_name=budget_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Budget", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_or_update( + self, + scope: str, + budget_name: str, + parameters: _models.Budget, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Budget: + # pylint: disable=line-too-long + """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/CostManagement/ + + :param scope: The scope associated with budget operations. + + Supported scopes for **CategoryType: Cost** + + Azure RBAC Scopes: + + + * '/subscriptions/{subscriptionId}/' for subscription scope + * '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope + * + '/providers/Microsoft.Management/managementGroups/{managementGroupId}' for Management Group + scope + + EA (Enterprise Agreement) Scopes: + + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope + + MCA (Modern Customer Agreement) Scopes: + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' for + customer scope (CSP only) + + Supported scopes for **CategoryType: ReservationUtilization** + + EA (Enterprise Agreement) Scopes: + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account Scope + + MCA (Modern Customer Agreement) Scopes: + + + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope (non-CSP only) + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' for + customer scope (CSP only). 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: ~azure.mgmt.costmanagement.models.Budget + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Budget or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Budget + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + scope: str, + budget_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Budget: + # pylint: disable=line-too-long + """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/CostManagement/ + + :param scope: The scope associated with budget operations. + + Supported scopes for **CategoryType: Cost** + + Azure RBAC Scopes: + + + * '/subscriptions/{subscriptionId}/' for subscription scope + * '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope + * + '/providers/Microsoft.Management/managementGroups/{managementGroupId}' for Management Group + scope + + EA (Enterprise Agreement) Scopes: + + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope + + MCA (Modern Customer Agreement) Scopes: + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' for + customer scope (CSP only) + + Supported scopes for **CategoryType: ReservationUtilization** + + EA (Enterprise Agreement) Scopes: + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account Scope + + MCA (Modern Customer Agreement) Scopes: + + + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope (non-CSP only) + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' for + customer scope (CSP only). 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[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Budget or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Budget + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, scope: str, budget_name: str, parameters: Union[_models.Budget, IO[bytes]], **kwargs: Any + ) -> _models.Budget: + # pylint: disable=line-too-long + """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/CostManagement/ + + :param scope: The scope associated with budget operations. + + Supported scopes for **CategoryType: Cost** + + Azure RBAC Scopes: + + + * '/subscriptions/{subscriptionId}/' for subscription scope + * '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope + * + '/providers/Microsoft.Management/managementGroups/{managementGroupId}' for Management Group + scope + + EA (Enterprise Agreement) Scopes: + + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope + + MCA (Modern Customer Agreement) Scopes: + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' for + customer scope (CSP only) + + Supported scopes for **CategoryType: ReservationUtilization** + + EA (Enterprise Agreement) Scopes: + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account Scope + + MCA (Modern Customer Agreement) Scopes: + + + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope (non-CSP only) + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' for + customer scope (CSP only). 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 Budget type + or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.Budget or IO[bytes] + :return: Budget or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Budget + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = 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", 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, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Budget") + + _request = build_create_or_update_request( + scope=scope, + budget_name=budget_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Budget", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete(self, scope: str, budget_name: str, **kwargs: Any) -> None: + # pylint: disable=line-too-long + """The operation to delete a budget. + + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/CostManagement/ + + :param scope: The scope associated with budget operations. + + Supported scopes for **CategoryType: Cost** + + Azure RBAC Scopes: + + + * '/subscriptions/{subscriptionId}/' for subscription scope + * '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope + * + '/providers/Microsoft.Management/managementGroups/{managementGroupId}' for Management Group + scope + + EA (Enterprise Agreement) Scopes: + + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope + + MCA (Modern Customer Agreement) Scopes: + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' for + customer scope (CSP only) + + Supported scopes for **CategoryType: ReservationUtilization** + + EA (Enterprise Agreement) Scopes: + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account Scope + + MCA (Modern Customer Agreement) Scopes: + + + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope (non-CSP only) + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' for + customer scope (CSP only). Required. + :type scope: str + :param budget_name: Budget Name. Required. + :type budget_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_delete_request( + scope=scope, + budget_name=budget_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_cost_allocation_rules_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_cost_allocation_rules_operations.py new file mode 100644 index 000000000000..485db8cb8f3d --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_cost_allocation_rules_operations.py @@ -0,0 +1,510 @@ +# 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 io import IOBase +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +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 ...operations._cost_allocation_rules_operations import ( + build_check_name_availability_request, + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class CostAllocationRulesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s + :attr:`cost_allocation_rules` attribute. + """ + + models = _models + + 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") + + @distributed_trace + def list(self, billing_account_id: str, **kwargs: Any) -> AsyncIterable["_models.CostAllocationRuleDefinition"]: + """Get the list of all cost allocation rules for a billing account or enterprise enrollment. + + :param billing_account_id: BillingAccount ID. Required. + :type billing_account_id: str + :return: An iterator like instance of either CostAllocationRuleDefinition or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.CostAllocationRuleDefinition] + :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.CostAllocationRuleList] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + billing_account_id=billing_account_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("CostAllocationRuleList", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @overload + async def check_name_availability( + self, + billing_account_id: str, + cost_allocation_rule_check_name_availability_request: _models.CostAllocationRuleCheckNameAvailabilityRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CostAllocationRuleCheckNameAvailabilityResponse: + """Checks availability and correctness of a name for a cost allocation rule. + + :param billing_account_id: BillingAccount ID. Required. + :type billing_account_id: str + :param cost_allocation_rule_check_name_availability_request: Cost allocation rule to be created + or updated. Required. + :type cost_allocation_rule_check_name_availability_request: + ~azure.mgmt.costmanagement.models.CostAllocationRuleCheckNameAvailabilityRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: CostAllocationRuleCheckNameAvailabilityResponse or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.CostAllocationRuleCheckNameAvailabilityResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def check_name_availability( + self, + billing_account_id: str, + cost_allocation_rule_check_name_availability_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CostAllocationRuleCheckNameAvailabilityResponse: + """Checks availability and correctness of a name for a cost allocation rule. + + :param billing_account_id: BillingAccount ID. Required. + :type billing_account_id: str + :param cost_allocation_rule_check_name_availability_request: Cost allocation rule to be created + or updated. Required. + :type cost_allocation_rule_check_name_availability_request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: CostAllocationRuleCheckNameAvailabilityResponse or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.CostAllocationRuleCheckNameAvailabilityResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def check_name_availability( + self, + billing_account_id: str, + cost_allocation_rule_check_name_availability_request: Union[ + _models.CostAllocationRuleCheckNameAvailabilityRequest, IO[bytes] + ], + **kwargs: Any + ) -> _models.CostAllocationRuleCheckNameAvailabilityResponse: + """Checks availability and correctness of a name for a cost allocation rule. + + :param billing_account_id: BillingAccount ID. Required. + :type billing_account_id: str + :param cost_allocation_rule_check_name_availability_request: Cost allocation rule to be created + or updated. Is either a CostAllocationRuleCheckNameAvailabilityRequest type or a IO[bytes] + type. Required. + :type cost_allocation_rule_check_name_availability_request: + ~azure.mgmt.costmanagement.models.CostAllocationRuleCheckNameAvailabilityRequest or IO[bytes] + :return: CostAllocationRuleCheckNameAvailabilityResponse or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.CostAllocationRuleCheckNameAvailabilityResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = 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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CostAllocationRuleCheckNameAvailabilityResponse] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(cost_allocation_rule_check_name_availability_request, (IOBase, bytes)): + _content = cost_allocation_rule_check_name_availability_request + else: + _json = self._serialize.body( + cost_allocation_rule_check_name_availability_request, "CostAllocationRuleCheckNameAvailabilityRequest" + ) + + _request = build_check_name_availability_request( + billing_account_id=billing_account_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize( + "CostAllocationRuleCheckNameAvailabilityResponse", pipeline_response.http_response + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get(self, billing_account_id: str, rule_name: str, **kwargs: Any) -> _models.CostAllocationRuleDefinition: + """Get a cost allocation rule by rule name and billing account or enterprise enrollment. + + :param billing_account_id: BillingAccount ID. Required. + :type billing_account_id: str + :param rule_name: Cost allocation rule name. The name cannot include spaces or any non + alphanumeric characters other than '_' and '-'. The max length is 260 characters. Required. + :type rule_name: str + :return: CostAllocationRuleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.CostAllocationRuleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.CostAllocationRuleDefinition] = kwargs.pop("cls", None) + + _request = build_get_request( + billing_account_id=billing_account_id, + rule_name=rule_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("CostAllocationRuleDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_or_update( + self, + billing_account_id: str, + rule_name: str, + cost_allocation_rule: _models.CostAllocationRuleDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CostAllocationRuleDefinition: + """Create/Update a rule to allocate cost between different resources within a billing account or + enterprise enrollment. + + :param billing_account_id: BillingAccount ID. Required. + :type billing_account_id: str + :param rule_name: Cost allocation rule name. The name cannot include spaces or any non + alphanumeric characters other than '_' and '-'. The max length is 260 characters. Required. + :type rule_name: str + :param cost_allocation_rule: Cost allocation rule to be created or updated. Required. + :type cost_allocation_rule: ~azure.mgmt.costmanagement.models.CostAllocationRuleDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: CostAllocationRuleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.CostAllocationRuleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + billing_account_id: str, + rule_name: str, + cost_allocation_rule: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CostAllocationRuleDefinition: + """Create/Update a rule to allocate cost between different resources within a billing account or + enterprise enrollment. + + :param billing_account_id: BillingAccount ID. Required. + :type billing_account_id: str + :param rule_name: Cost allocation rule name. The name cannot include spaces or any non + alphanumeric characters other than '_' and '-'. The max length is 260 characters. Required. + :type rule_name: str + :param cost_allocation_rule: Cost allocation rule to be created or updated. Required. + :type cost_allocation_rule: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: CostAllocationRuleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.CostAllocationRuleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + billing_account_id: str, + rule_name: str, + cost_allocation_rule: Union[_models.CostAllocationRuleDefinition, IO[bytes]], + **kwargs: Any + ) -> _models.CostAllocationRuleDefinition: + """Create/Update a rule to allocate cost between different resources within a billing account or + enterprise enrollment. + + :param billing_account_id: BillingAccount ID. Required. + :type billing_account_id: str + :param rule_name: Cost allocation rule name. The name cannot include spaces or any non + alphanumeric characters other than '_' and '-'. The max length is 260 characters. Required. + :type rule_name: str + :param cost_allocation_rule: Cost allocation rule to be created or updated. Is either a + CostAllocationRuleDefinition type or a IO[bytes] type. Required. + :type cost_allocation_rule: ~azure.mgmt.costmanagement.models.CostAllocationRuleDefinition or + IO[bytes] + :return: CostAllocationRuleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.CostAllocationRuleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = 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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CostAllocationRuleDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(cost_allocation_rule, (IOBase, bytes)): + _content = cost_allocation_rule + else: + _json = self._serialize.body(cost_allocation_rule, "CostAllocationRuleDefinition") + + _request = build_create_or_update_request( + billing_account_id=billing_account_id, + rule_name=rule_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("CostAllocationRuleDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete(self, billing_account_id: str, rule_name: str, **kwargs: Any) -> None: + """Delete cost allocation rule for billing account or enterprise enrollment. + + :param billing_account_id: BillingAccount ID. Required. + :type billing_account_id: str + :param rule_name: Cost allocation rule name. The name cannot include spaces or any non + alphanumeric characters other than '_' and '-'. The max length is 260 characters. Required. + :type rule_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_delete_request( + billing_account_id=billing_account_id, + rule_name=rule_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_dimensions_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_dimensions_operations.py index 1f64b263a6b0..04613de609fb 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_dimensions_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_dimensions_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union import urllib.parse @@ -19,16 +19,18 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request from ...operations._dimensions_operations import build_by_external_cloud_provider_type_request, build_list_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -62,6 +64,7 @@ def list( top: Optional[int] = None, **kwargs: Any ) -> AsyncIterable["_models.Dimension"]: + # pylint: disable=line-too-long """Lists the dimensions by the defined scope. .. seealso:: @@ -99,7 +102,6 @@ def list( :param top: May be used to limit the number of results to the most recent N dimension data. Default value is None. :type top: int - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Dimension or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.Dimension] :raises ~azure.core.exceptions.HttpResponseError: @@ -110,7 +112,7 @@ def list( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.DimensionsListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -121,19 +123,17 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( scope=scope, filter=filter, expand=expand, skiptoken=skiptoken, top=top, 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 @@ -145,13 +145,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("DimensionsListResult", pipeline_response) @@ -161,11 +160,11 @@ async def extract_data(pipeline_response): return 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -178,8 +177,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/dimensions"} - @distributed_trace def by_external_cloud_provider_type( self, @@ -221,7 +218,6 @@ def by_external_cloud_provider_type( :param top: May be used to limit the number of results to the most recent N dimension data. Default value is None. :type top: int - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Dimension or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.Dimension] :raises ~azure.core.exceptions.HttpResponseError: @@ -232,7 +228,7 @@ def by_external_cloud_provider_type( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.DimensionsListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -243,7 +239,7 @@ def by_external_cloud_provider_type( def prepare_request(next_link=None): if not next_link: - request = build_by_external_cloud_provider_type_request( + _request = build_by_external_cloud_provider_type_request( external_cloud_provider_type=external_cloud_provider_type, external_cloud_provider_id=external_cloud_provider_id, filter=filter, @@ -251,12 +247,10 @@ def prepare_request(next_link=None): skiptoken=skiptoken, top=top, api_version=api_version, - template_url=self.by_external_cloud_provider_type.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 @@ -268,13 +262,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("DimensionsListResult", pipeline_response) @@ -284,11 +277,11 @@ async def extract_data(pipeline_response): return 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -300,7 +293,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - by_external_cloud_provider_type.metadata = { - "url": "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/dimensions" - } diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_exports_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_exports_operations.py index bfa77ebf03d9..78b645b53f53 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_exports_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_exports_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( @@ -18,14 +18,12 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request from ...operations._exports_operations import ( build_create_or_update_request, build_delete_request, @@ -35,6 +33,10 @@ build_list_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -60,6 +62,7 @@ def __init__(self, *args, **kwargs) -> None: @distributed_trace_async async def list(self, scope: str, expand: Optional[str] = None, **kwargs: Any) -> _models.ExportListResult: + # pylint: disable=line-too-long """The operation to list all exports at the given scope. .. seealso:: @@ -86,12 +89,11 @@ async def list(self, scope: str, expand: Optional[str] = None, **kwargs: Any) -> 'runHistory' is supported and will return information for the last run of each export. Default value is None. :type expand: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ExportListResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ExportListResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -105,20 +107,18 @@ async def list(self, scope: str, expand: Optional[str] = None, **kwargs: Any) -> api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ExportListResult] = kwargs.pop("cls", None) - request = build_list_request( + _request = build_list_request( scope=scope, expand=expand, 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -128,17 +128,16 @@ async def list(self, scope: str, expand: Optional[str] = None, **kwargs: Any) -> error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ExportListResult", pipeline_response) + deserialized = self._deserialize("ExportListResult", 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.CostManagement/exports"} + return deserialized # type: ignore @distributed_trace_async async def get(self, scope: str, export_name: str, expand: Optional[str] = None, **kwargs: Any) -> _models.Export: + # pylint: disable=line-too-long """The operation to get the export for the defined scope by export name. .. seealso:: @@ -167,12 +166,11 @@ async def get(self, scope: str, export_name: str, expand: Optional[str] = None, 'runHistory' is supported and will return information for the last 10 runs of the export. Default value is None. :type expand: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Export or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Export :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -186,21 +184,19 @@ async def get(self, scope: str, export_name: str, expand: Optional[str] = None, api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Export] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( scope=scope, export_name=export_name, expand=expand, 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -210,14 +206,12 @@ async def get(self, scope: str, export_name: str, expand: Optional[str] = None, error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Export", pipeline_response) + deserialized = self._deserialize("Export", 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.CostManagement/exports/{exportName}"} + return deserialized # type: ignore @overload async def create_or_update( @@ -229,6 +223,7 @@ async def create_or_update( content_type: str = "application/json", **kwargs: Any ) -> _models.Export: + # pylint: disable=line-too-long """The operation to create or update a export. Update operation requires latest eTag to be set in the request. You may obtain the latest eTag by performing a get operation. Create operation does not require eTag. @@ -260,7 +255,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: Export or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Export :raises ~azure.core.exceptions.HttpResponseError: @@ -268,8 +262,15 @@ async def create_or_update( @overload async def create_or_update( - self, scope: str, export_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, + scope: str, + export_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models.Export: + # pylint: disable=line-too-long """The operation to create or update a export. Update operation requires latest eTag to be set in the request. You may obtain the latest eTag by performing a get operation. Create operation does not require eTag. @@ -297,11 +298,10 @@ async def create_or_update( :param export_name: Export Name. Required. :type export_name: str :param parameters: Parameters supplied to the CreateOrUpdate Export 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: Export or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Export :raises ~azure.core.exceptions.HttpResponseError: @@ -309,8 +309,9 @@ async def create_or_update( @distributed_trace_async async def create_or_update( - self, scope: str, export_name: str, parameters: Union[_models.Export, IO], **kwargs: Any + self, scope: str, export_name: str, parameters: Union[_models.Export, IO[bytes]], **kwargs: Any ) -> _models.Export: + # pylint: disable=line-too-long """The operation to create or update a export. Update operation requires latest eTag to be set in the request. You may obtain the latest eTag by performing a get operation. Create operation does not require eTag. @@ -338,17 +339,13 @@ async def create_or_update( :param export_name: Export Name. Required. :type export_name: str :param parameters: Parameters supplied to the CreateOrUpdate Export operation. Is either a - Export type or a IO type. Required. - :type parameters: ~azure.mgmt.costmanagement.models.Export 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 + Export type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.Export or IO[bytes] :return: Export or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Export :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -371,23 +368,21 @@ async def create_or_update( else: _json = self._serialize.body(parameters, "Export") - request = build_create_or_update_request( + _request = build_create_or_update_request( scope=scope, export_name=export_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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -397,23 +392,16 @@ async def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("Export", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("Export", pipeline_response) + deserialized = self._deserialize("Export", 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.CostManagement/exports/{exportName}"} - @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, scope: str, export_name: str, **kwargs: Any - ) -> None: + async def delete(self, scope: str, export_name: str, **kwargs: Any) -> None: + # pylint: disable=line-too-long """The operation to delete a export. .. seealso:: @@ -438,12 +426,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type scope: str :param export_name: Export Name. Required. :type export_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, @@ -457,20 +444,18 @@ async def delete( # pylint: disable=inconsistent-return-statements 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, export_name=export_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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -481,14 +466,109 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore + + @overload + async def execute( + self, + scope: str, + export_name: str, + parameters: Optional[_models.ExportRunRequest] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + # pylint: disable=line-too-long + """The operation to run an export. + + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/costmanagement/ + + :param scope: The scope associated with export operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param export_name: Export Name. Required. + :type export_name: str + :param parameters: Parameters supplied to the CreateOrUpdate Export operation. Default value is + None. + :type parameters: ~azure.mgmt.costmanagement.models.ExportRunRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def execute( + self, + scope: str, + export_name: str, + parameters: Optional[IO[bytes]] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + # pylint: disable=line-too-long + """The operation to run an export. - delete.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}"} + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/costmanagement/ + + :param scope: The scope associated with export operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param export_name: Export Name. Required. + :type export_name: str + :param parameters: Parameters supplied to the CreateOrUpdate Export operation. Default value is + None. + :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 + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async - async def execute( # pylint: disable=inconsistent-return-statements - self, scope: str, export_name: str, **kwargs: Any + async def execute( + self, + scope: str, + export_name: str, + parameters: Optional[Union[_models.ExportRunRequest, IO[bytes]]] = None, + **kwargs: Any ) -> None: + # pylint: disable=line-too-long """The operation to run an export. .. seealso:: @@ -513,12 +593,14 @@ async def execute( # pylint: disable=inconsistent-return-statements :type scope: str :param export_name: Export Name. Required. :type export_name: str - :keyword callable cls: A custom type or function that will be passed the direct response + :param parameters: Parameters supplied to the CreateOrUpdate Export operation. Is either a + ExportRunRequest type or a IO[bytes] type. Default value is None. + :type parameters: ~azure.mgmt.costmanagement.models.ExportRunRequest or IO[bytes] :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, @@ -526,26 +608,39 @@ async def execute( # pylint: disable=inconsistent-return-statements } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_execute_request( + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + if parameters is not None: + _json = self._serialize.body(parameters, "ExportRunRequest") + else: + _json = None + + _request = build_execute_request( scope=scope, export_name=export_name, api_version=api_version, - template_url=self.execute.metadata["url"], + content_type=content_type, + json=_json, + content=_content, 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -556,14 +651,13 @@ async def execute( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - execute.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}/run"} + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async async def get_execution_history( self, scope: str, export_name: str, **kwargs: Any ) -> _models.ExportExecutionListResult: + # pylint: disable=line-too-long """The operation to get the run history of an export for the defined scope and export name. .. seealso:: @@ -588,12 +682,11 @@ async def get_execution_history( :type scope: str :param export_name: Export Name. Required. :type export_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ExportExecutionListResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ExportExecutionListResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -607,20 +700,18 @@ async def get_execution_history( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ExportExecutionListResult] = kwargs.pop("cls", None) - request = build_get_execution_history_request( + _request = build_get_execution_history_request( scope=scope, export_name=export_name, api_version=api_version, - template_url=self.get_execution_history.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -630,13 +721,9 @@ async def get_execution_history( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ExportExecutionListResult", pipeline_response) + deserialized = self._deserialize("ExportExecutionListResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_execution_history.metadata = { - "url": "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}/runHistory" - } + return deserialized # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_forecast_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_forecast_operations.py index 45ae7f6285bc..e32dd8751404 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_forecast_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_forecast_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( @@ -18,16 +18,18 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request from ...operations._forecast_operations import build_external_cloud_provider_usage_request, build_usage_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -61,6 +63,7 @@ async def usage( content_type: str = "application/json", **kwargs: Any ) -> Optional[_models.ForecastResult]: + # pylint: disable=line-too-long """Lists the forecast charges for scope defined. .. seealso:: @@ -93,7 +96,6 @@ async def usage( :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: ForecastResult or None or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ForecastResult or None :raises ~azure.core.exceptions.HttpResponseError: @@ -103,12 +105,13 @@ async def usage( async def usage( self, scope: str, - parameters: IO, + parameters: IO[bytes], filter: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> Optional[_models.ForecastResult]: + # pylint: disable=line-too-long """Lists the forecast charges for scope defined. .. seealso:: @@ -133,7 +136,7 @@ async def usage( :type scope: str :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. Required. - :type parameters: IO + :type parameters: IO[bytes] :param filter: May be used to filter forecasts by properties/usageDate (Utc time), properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. @@ -141,7 +144,6 @@ async def usage( :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: ForecastResult or None or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ForecastResult or None :raises ~azure.core.exceptions.HttpResponseError: @@ -149,8 +151,13 @@ async def usage( @distributed_trace_async async def usage( - self, scope: str, parameters: Union[_models.ForecastDefinition, IO], filter: Optional[str] = None, **kwargs: Any + self, + scope: str, + parameters: Union[_models.ForecastDefinition, IO[bytes]], + filter: Optional[str] = None, + **kwargs: Any ) -> Optional[_models.ForecastResult]: + # pylint: disable=line-too-long """Lists the forecast charges for scope defined. .. seealso:: @@ -174,21 +181,17 @@ async def usage( specific for partners. Required. :type scope: str :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. Is - either a ForecastDefinition type or a IO type. Required. - :type parameters: ~azure.mgmt.costmanagement.models.ForecastDefinition or IO + either a ForecastDefinition type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.ForecastDefinition or IO[bytes] :param filter: May be used to filter forecasts by properties/usageDate (Utc time), properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. :type filter: str - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ForecastResult or None or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ForecastResult or None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -211,23 +214,21 @@ async def usage( else: _json = self._serialize.body(parameters, "ForecastDefinition") - request = build_usage_request( + _request = build_usage_request( scope=scope, filter=filter, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.usage.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -239,14 +240,12 @@ async def usage( deserialized = None if response.status_code == 200: - deserialized = self._deserialize("ForecastResult", pipeline_response) + deserialized = self._deserialize("ForecastResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - usage.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/forecast"} + return deserialized # type: ignore @overload async def external_cloud_provider_usage( @@ -284,7 +283,6 @@ async def external_cloud_provider_usage( :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: ForecastResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ForecastResult :raises ~azure.core.exceptions.HttpResponseError: @@ -295,7 +293,7 @@ async def external_cloud_provider_usage( self, external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], external_cloud_provider_id: str, - parameters: IO, + parameters: IO[bytes], filter: Optional[str] = None, *, content_type: str = "application/json", @@ -318,7 +316,7 @@ async def external_cloud_provider_usage( :type external_cloud_provider_id: str :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. Required. - :type parameters: IO + :type parameters: IO[bytes] :param filter: May be used to filter forecasts by properties/usageDate (Utc time), properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. @@ -326,7 +324,6 @@ async def external_cloud_provider_usage( :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: ForecastResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ForecastResult :raises ~azure.core.exceptions.HttpResponseError: @@ -337,7 +334,7 @@ async def external_cloud_provider_usage( self, external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], external_cloud_provider_id: str, - parameters: Union[_models.ForecastDefinition, IO], + parameters: Union[_models.ForecastDefinition, IO[bytes]], filter: Optional[str] = None, **kwargs: Any ) -> _models.ForecastResult: @@ -357,21 +354,17 @@ async def external_cloud_provider_usage( Required. :type external_cloud_provider_id: str :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. Is - either a ForecastDefinition type or a IO type. Required. - :type parameters: ~azure.mgmt.costmanagement.models.ForecastDefinition or IO + either a ForecastDefinition type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.ForecastDefinition or IO[bytes] :param filter: May be used to filter forecasts by properties/usageDate (Utc time), properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. :type filter: str - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ForecastResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ForecastResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -394,7 +387,7 @@ async def external_cloud_provider_usage( else: _json = self._serialize.body(parameters, "ForecastDefinition") - request = build_external_cloud_provider_usage_request( + _request = build_external_cloud_provider_usage_request( external_cloud_provider_type=external_cloud_provider_type, external_cloud_provider_id=external_cloud_provider_id, filter=filter, @@ -402,16 +395,14 @@ async def external_cloud_provider_usage( content_type=content_type, json=_json, content=_content, - template_url=self.external_cloud_provider_usage.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -421,13 +412,9 @@ async def external_cloud_provider_usage( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ForecastResult", pipeline_response) + deserialized = self._deserialize("ForecastResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - external_cloud_provider_usage.metadata = { - "url": "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/forecast" - } + return deserialized # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_benefit_utilization_summaries_report_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_benefit_utilization_summaries_report_operations.py new file mode 100644 index 000000000000..2138616e21a4 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_benefit_utilization_summaries_report_operations.py @@ -0,0 +1,1344 @@ +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, AsyncIterator, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +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 ...operations._generate_benefit_utilization_summaries_report_operations import ( + build_generate_by_billing_account_request, + build_generate_by_billing_profile_request, + build_generate_by_reservation_id_request, + build_generate_by_reservation_order_id_request, + build_generate_by_savings_plan_id_request, + build_generate_by_savings_plan_order_id_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class GenerateBenefitUtilizationSummariesReportOperations: # pylint: disable=name-too-long + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s + :attr:`generate_benefit_utilization_summaries_report` attribute. + """ + + models = _models + + 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") + + async def _generate_by_billing_account_initial( + self, + billing_account_id: str, + benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(benefit_utilization_summaries_request, (IOBase, bytes)): + _content = benefit_utilization_summaries_request + else: + _json = self._serialize.body(benefit_utilization_summaries_request, "BenefitUtilizationSummariesRequest") + + _request = build_generate_by_billing_account_request( + billing_account_id=billing_account_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + 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.ErrorResponseAutoGenerated, 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 + + @overload + async def begin_generate_by_billing_account( + self, + billing_account_id: str, + benefit_utilization_summaries_request: _models.BenefitUtilizationSummariesRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + # pylint: disable=line-too-long + """Triggers generation of a benefit utilization summaries report for the provided billing account. + This API supports only enrollment accounts. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param billing_account_id: Billing account ID. Required. + :type billing_account_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Required. + :type benefit_utilization_summaries_request: + ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_generate_by_billing_account( + self, + billing_account_id: str, + benefit_utilization_summaries_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + # pylint: disable=line-too-long + """Triggers generation of a benefit utilization summaries report for the provided billing account. + This API supports only enrollment accounts. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param billing_account_id: Billing account ID. Required. + :type billing_account_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Required. + :type benefit_utilization_summaries_request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_generate_by_billing_account( + self, + billing_account_id: str, + benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + # pylint: disable=line-too-long + """Triggers generation of a benefit utilization summaries report for the provided billing account. + This API supports only enrollment accounts. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param billing_account_id: Billing account ID. Required. + :type billing_account_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Is either a BenefitUtilizationSummariesRequest type or a IO[bytes] type. Required. + :type benefit_utilization_summaries_request: + ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest or IO[bytes] + :return: An instance of AsyncLROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.BenefitUtilizationSummariesOperationStatus] = 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._generate_by_billing_account_initial( + billing_account_id=billing_account_id, + benefit_utilization_summaries_request=benefit_utilization_summaries_request, + api_version=api_version, + content_type=content_type, + 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( + "BenefitUtilizationSummariesOperationStatus", 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.BenefitUtilizationSummariesOperationStatus].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _generate_by_billing_profile_initial( + self, + billing_account_id: str, + billing_profile_id: str, + benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(benefit_utilization_summaries_request, (IOBase, bytes)): + _content = benefit_utilization_summaries_request + else: + _json = self._serialize.body(benefit_utilization_summaries_request, "BenefitUtilizationSummariesRequest") + + _request = build_generate_by_billing_profile_request( + billing_account_id=billing_account_id, + billing_profile_id=billing_profile_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + 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.ErrorResponseAutoGenerated, 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 + + @overload + async def begin_generate_by_billing_profile( + self, + billing_account_id: str, + billing_profile_id: str, + benefit_utilization_summaries_request: _models.BenefitUtilizationSummariesRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + # pylint: disable=line-too-long + """Triggers generation of a benefit utilization summaries report for the provided billing account + and billing profile. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param billing_account_id: Billing account ID. Required. + :type billing_account_id: str + :param billing_profile_id: Billing profile ID. Required. + :type billing_profile_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Required. + :type benefit_utilization_summaries_request: + ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_generate_by_billing_profile( + self, + billing_account_id: str, + billing_profile_id: str, + benefit_utilization_summaries_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + # pylint: disable=line-too-long + """Triggers generation of a benefit utilization summaries report for the provided billing account + and billing profile. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param billing_account_id: Billing account ID. Required. + :type billing_account_id: str + :param billing_profile_id: Billing profile ID. Required. + :type billing_profile_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Required. + :type benefit_utilization_summaries_request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_generate_by_billing_profile( + self, + billing_account_id: str, + billing_profile_id: str, + benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + # pylint: disable=line-too-long + """Triggers generation of a benefit utilization summaries report for the provided billing account + and billing profile. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param billing_account_id: Billing account ID. Required. + :type billing_account_id: str + :param billing_profile_id: Billing profile ID. Required. + :type billing_profile_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Is either a BenefitUtilizationSummariesRequest type or a IO[bytes] type. Required. + :type benefit_utilization_summaries_request: + ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest or IO[bytes] + :return: An instance of AsyncLROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.BenefitUtilizationSummariesOperationStatus] = 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._generate_by_billing_profile_initial( + billing_account_id=billing_account_id, + billing_profile_id=billing_profile_id, + benefit_utilization_summaries_request=benefit_utilization_summaries_request, + api_version=api_version, + content_type=content_type, + 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( + "BenefitUtilizationSummariesOperationStatus", 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.BenefitUtilizationSummariesOperationStatus].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _generate_by_reservation_order_id_initial( # pylint: disable=name-too-long + self, + reservation_order_id: str, + benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(benefit_utilization_summaries_request, (IOBase, bytes)): + _content = benefit_utilization_summaries_request + else: + _json = self._serialize.body(benefit_utilization_summaries_request, "BenefitUtilizationSummariesRequest") + + _request = build_generate_by_reservation_order_id_request( + reservation_order_id=reservation_order_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + 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.ErrorResponseAutoGenerated, 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 + + @overload + async def begin_generate_by_reservation_order_id( + self, + reservation_order_id: str, + benefit_utilization_summaries_request: _models.BenefitUtilizationSummariesRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + # pylint: disable=line-too-long + """Triggers generation of a benefit utilization summaries report for the provided reservation + order. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param reservation_order_id: Reservation Order ID. Required. + :type reservation_order_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Required. + :type benefit_utilization_summaries_request: + ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_generate_by_reservation_order_id( + self, + reservation_order_id: str, + benefit_utilization_summaries_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + # pylint: disable=line-too-long + """Triggers generation of a benefit utilization summaries report for the provided reservation + order. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param reservation_order_id: Reservation Order ID. Required. + :type reservation_order_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Required. + :type benefit_utilization_summaries_request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_generate_by_reservation_order_id( + self, + reservation_order_id: str, + benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + # pylint: disable=line-too-long + """Triggers generation of a benefit utilization summaries report for the provided reservation + order. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param reservation_order_id: Reservation Order ID. Required. + :type reservation_order_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Is either a BenefitUtilizationSummariesRequest type or a IO[bytes] type. Required. + :type benefit_utilization_summaries_request: + ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest or IO[bytes] + :return: An instance of AsyncLROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.BenefitUtilizationSummariesOperationStatus] = 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._generate_by_reservation_order_id_initial( + reservation_order_id=reservation_order_id, + benefit_utilization_summaries_request=benefit_utilization_summaries_request, + api_version=api_version, + content_type=content_type, + 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( + "BenefitUtilizationSummariesOperationStatus", 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.BenefitUtilizationSummariesOperationStatus].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _generate_by_reservation_id_initial( + self, + reservation_order_id: str, + reservation_id: str, + benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(benefit_utilization_summaries_request, (IOBase, bytes)): + _content = benefit_utilization_summaries_request + else: + _json = self._serialize.body(benefit_utilization_summaries_request, "BenefitUtilizationSummariesRequest") + + _request = build_generate_by_reservation_id_request( + reservation_order_id=reservation_order_id, + reservation_id=reservation_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + 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.ErrorResponseAutoGenerated, 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 + + @overload + async def begin_generate_by_reservation_id( + self, + reservation_order_id: str, + reservation_id: str, + benefit_utilization_summaries_request: _models.BenefitUtilizationSummariesRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + # pylint: disable=line-too-long + """Triggers generation of a benefit utilization summaries report for the provided reservation. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param reservation_order_id: Reservation Order ID. Required. + :type reservation_order_id: str + :param reservation_id: Reservation ID. Required. + :type reservation_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Required. + :type benefit_utilization_summaries_request: + ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_generate_by_reservation_id( + self, + reservation_order_id: str, + reservation_id: str, + benefit_utilization_summaries_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + # pylint: disable=line-too-long + """Triggers generation of a benefit utilization summaries report for the provided reservation. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param reservation_order_id: Reservation Order ID. Required. + :type reservation_order_id: str + :param reservation_id: Reservation ID. Required. + :type reservation_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Required. + :type benefit_utilization_summaries_request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_generate_by_reservation_id( + self, + reservation_order_id: str, + reservation_id: str, + benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + # pylint: disable=line-too-long + """Triggers generation of a benefit utilization summaries report for the provided reservation. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param reservation_order_id: Reservation Order ID. Required. + :type reservation_order_id: str + :param reservation_id: Reservation ID. Required. + :type reservation_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Is either a BenefitUtilizationSummariesRequest type or a IO[bytes] type. Required. + :type benefit_utilization_summaries_request: + ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest or IO[bytes] + :return: An instance of AsyncLROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.BenefitUtilizationSummariesOperationStatus] = 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._generate_by_reservation_id_initial( + reservation_order_id=reservation_order_id, + reservation_id=reservation_id, + benefit_utilization_summaries_request=benefit_utilization_summaries_request, + api_version=api_version, + content_type=content_type, + 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( + "BenefitUtilizationSummariesOperationStatus", 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.BenefitUtilizationSummariesOperationStatus].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _generate_by_savings_plan_order_id_initial( # pylint: disable=name-too-long + self, + savings_plan_order_id: str, + benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(benefit_utilization_summaries_request, (IOBase, bytes)): + _content = benefit_utilization_summaries_request + else: + _json = self._serialize.body(benefit_utilization_summaries_request, "BenefitUtilizationSummariesRequest") + + _request = build_generate_by_savings_plan_order_id_request( + savings_plan_order_id=savings_plan_order_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + 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.ErrorResponseAutoGenerated, 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 + + @overload + async def begin_generate_by_savings_plan_order_id( + self, + savings_plan_order_id: str, + benefit_utilization_summaries_request: _models.BenefitUtilizationSummariesRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + # pylint: disable=line-too-long + """Triggers generation of a benefit utilization summaries report for the provided savings plan + order. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param savings_plan_order_id: Savings plan order ID. Required. + :type savings_plan_order_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Required. + :type benefit_utilization_summaries_request: + ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_generate_by_savings_plan_order_id( + self, + savings_plan_order_id: str, + benefit_utilization_summaries_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + # pylint: disable=line-too-long + """Triggers generation of a benefit utilization summaries report for the provided savings plan + order. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param savings_plan_order_id: Savings plan order ID. Required. + :type savings_plan_order_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Required. + :type benefit_utilization_summaries_request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_generate_by_savings_plan_order_id( + self, + savings_plan_order_id: str, + benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + # pylint: disable=line-too-long + """Triggers generation of a benefit utilization summaries report for the provided savings plan + order. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param savings_plan_order_id: Savings plan order ID. Required. + :type savings_plan_order_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Is either a BenefitUtilizationSummariesRequest type or a IO[bytes] type. Required. + :type benefit_utilization_summaries_request: + ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest or IO[bytes] + :return: An instance of AsyncLROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.BenefitUtilizationSummariesOperationStatus] = 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._generate_by_savings_plan_order_id_initial( + savings_plan_order_id=savings_plan_order_id, + benefit_utilization_summaries_request=benefit_utilization_summaries_request, + api_version=api_version, + content_type=content_type, + 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( + "BenefitUtilizationSummariesOperationStatus", 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.BenefitUtilizationSummariesOperationStatus].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _generate_by_savings_plan_id_initial( + self, + savings_plan_order_id: str, + savings_plan_id: str, + benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(benefit_utilization_summaries_request, (IOBase, bytes)): + _content = benefit_utilization_summaries_request + else: + _json = self._serialize.body(benefit_utilization_summaries_request, "BenefitUtilizationSummariesRequest") + + _request = build_generate_by_savings_plan_id_request( + savings_plan_order_id=savings_plan_order_id, + savings_plan_id=savings_plan_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + 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.ErrorResponseAutoGenerated, 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 + + @overload + async def begin_generate_by_savings_plan_id( + self, + savings_plan_order_id: str, + savings_plan_id: str, + benefit_utilization_summaries_request: _models.BenefitUtilizationSummariesRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + # pylint: disable=line-too-long + """Triggers generation of a benefit utilization summaries report for the provided savings plan. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param savings_plan_order_id: Savings plan order ID. Required. + :type savings_plan_order_id: str + :param savings_plan_id: Savings plan ID. Required. + :type savings_plan_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Required. + :type benefit_utilization_summaries_request: + ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_generate_by_savings_plan_id( + self, + savings_plan_order_id: str, + savings_plan_id: str, + benefit_utilization_summaries_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + # pylint: disable=line-too-long + """Triggers generation of a benefit utilization summaries report for the provided savings plan. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param savings_plan_order_id: Savings plan order ID. Required. + :type savings_plan_order_id: str + :param savings_plan_id: Savings plan ID. Required. + :type savings_plan_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Required. + :type benefit_utilization_summaries_request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_generate_by_savings_plan_id( + self, + savings_plan_order_id: str, + savings_plan_id: str, + benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + # pylint: disable=line-too-long + """Triggers generation of a benefit utilization summaries report for the provided savings plan. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param savings_plan_order_id: Savings plan order ID. Required. + :type savings_plan_order_id: str + :param savings_plan_id: Savings plan ID. Required. + :type savings_plan_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Is either a BenefitUtilizationSummariesRequest type or a IO[bytes] type. Required. + :type benefit_utilization_summaries_request: + ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest or IO[bytes] + :return: An instance of AsyncLROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.BenefitUtilizationSummariesOperationStatus] = 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._generate_by_savings_plan_id_initial( + savings_plan_order_id=savings_plan_order_id, + savings_plan_id=savings_plan_id, + benefit_utilization_summaries_request=benefit_utilization_summaries_request, + api_version=api_version, + content_type=content_type, + 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( + "BenefitUtilizationSummariesOperationStatus", 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.BenefitUtilizationSummariesOperationStatus].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_cost_details_report_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_cost_details_report_operations.py index 0c905cc94df4..d9722bebcd84 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_cost_details_report_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_cost_details_report_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,7 +6,8 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from io import IOBase -from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import sys +from typing import Any, AsyncIterator, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload from azure.core.exceptions import ( ClientAuthenticationError, @@ -15,24 +15,28 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models -from ..._vendor import _convert_request from ...operations._generate_cost_details_report_operations import ( build_create_operation_request, build_get_operation_results_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -57,9 +61,12 @@ def __init__(self, *args, **kwargs) -> None: self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") async def _create_operation_initial( - self, scope: str, parameters: Union[_models.GenerateCostDetailsReportRequestDefinition, IO], **kwargs: Any - ) -> Optional[_models.CostDetailsOperationResults]: - error_map = { + self, + scope: str, + parameters: Union[_models.GenerateCostDetailsReportRequestDefinition, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -72,7 +79,7 @@ async def _create_operation_initial( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.CostDetailsOperationResults]] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None @@ -82,50 +89,47 @@ async def _create_operation_initial( else: _json = self._serialize.body(parameters, "GenerateCostDetailsReportRequestDefinition") - request = build_create_operation_request( + _request = build_create_operation_request( scope=scope, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self._create_operation_initial.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 + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize( _models.GenerateCostDetailsReportErrorResponse, pipeline_response ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("CostDetailsOperationResults", pipeline_response) - 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")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _create_operation_initial.metadata = { - "url": "/{scope}/providers/Microsoft.CostManagement/generateCostDetailsReport" - } + return deserialized # type: ignore @overload async def begin_create_operation( @@ -147,27 +151,20 @@ async def begin_create_operation( response along with details on the report blob(s) that are available for download. The details on the file(s) available for download will be available in the polling response body. To Understand cost details (formerly known as usage details) fields found in files ,see - https://learn.microsoft.com/azure/cost-management-billing/automate/understand-usage-details-fields. + https://learn.microsoft.com/en-us/azure/cost-management-billing/automate/understand-usage-details-fields. .. seealso:: - https://docs.microsoft.com/en-us/rest/api/costmanagement/ - :param scope: The ARM Resource ID for subscription, resource group, billing account, or other - billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. + :param scope: The ARM Resource ID for subscription, billing account, or other billing + scopes.Currently Resource Group and Management Group are not supported. For details, see + https://aka.ms/costmgmt/scopes. Required. :type scope: str :param parameters: Parameters supplied to the Create cost details operation. Required. :type parameters: ~azure.mgmt.costmanagement.models.GenerateCostDetailsReportRequestDefinition :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either CostDetailsOperationResults or the result of cls(response) :rtype: @@ -177,7 +174,7 @@ async def begin_create_operation( @overload async def begin_create_operation( - self, scope: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, scope: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.CostDetailsOperationResults]: """This API is the replacement for all previously release Usage Details APIs. Request to generate a cost details report for the provided date range, billing period (Only enterprise customers) @@ -190,27 +187,20 @@ async def begin_create_operation( response along with details on the report blob(s) that are available for download. The details on the file(s) available for download will be available in the polling response body. To Understand cost details (formerly known as usage details) fields found in files ,see - https://learn.microsoft.com/azure/cost-management-billing/automate/understand-usage-details-fields. + https://learn.microsoft.com/en-us/azure/cost-management-billing/automate/understand-usage-details-fields. .. seealso:: - https://docs.microsoft.com/en-us/rest/api/costmanagement/ - :param scope: The ARM Resource ID for subscription, resource group, billing account, or other - billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. + :param scope: The ARM Resource ID for subscription, billing account, or other billing + scopes.Currently Resource Group and Management Group are not supported. For details, see + https://aka.ms/costmgmt/scopes. Required. :type scope: str :param parameters: Parameters supplied to the Create cost details 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 - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either CostDetailsOperationResults or the result of cls(response) :rtype: @@ -220,7 +210,10 @@ async def begin_create_operation( @distributed_trace_async async def begin_create_operation( - self, scope: str, parameters: Union[_models.GenerateCostDetailsReportRequestDefinition, IO], **kwargs: Any + self, + scope: str, + parameters: Union[_models.GenerateCostDetailsReportRequestDefinition, IO[bytes]], + **kwargs: Any ) -> AsyncLROPoller[_models.CostDetailsOperationResults]: """This API is the replacement for all previously release Usage Details APIs. Request to generate a cost details report for the provided date range, billing period (Only enterprise customers) @@ -233,29 +226,19 @@ async def begin_create_operation( response along with details on the report blob(s) that are available for download. The details on the file(s) available for download will be available in the polling response body. To Understand cost details (formerly known as usage details) fields found in files ,see - https://learn.microsoft.com/azure/cost-management-billing/automate/understand-usage-details-fields. + https://learn.microsoft.com/en-us/azure/cost-management-billing/automate/understand-usage-details-fields. .. seealso:: - https://docs.microsoft.com/en-us/rest/api/costmanagement/ - :param scope: The ARM Resource ID for subscription, resource group, billing account, or other - billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. + :param scope: The ARM Resource ID for subscription, billing account, or other billing + scopes.Currently Resource Group and Management Group are not supported. For details, see + https://aka.ms/costmgmt/scopes. Required. :type scope: str :param parameters: Parameters supplied to the Create cost details operation. Is either a - GenerateCostDetailsReportRequestDefinition type or a IO type. Required. + GenerateCostDetailsReportRequestDefinition type or a IO[bytes] type. Required. :type parameters: ~azure.mgmt.costmanagement.models.GenerateCostDetailsReportRequestDefinition - 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 - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + or IO[bytes] :return: An instance of AsyncLROPoller that returns either CostDetailsOperationResults or the result of cls(response) :rtype: @@ -282,12 +265,13 @@ async def begin_create_operation( 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("CostDetailsOperationResults", pipeline_response) + deserialized = self._deserialize("CostDetailsOperationResults", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -299,20 +283,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.CostDetailsOperationResults].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_operation.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/generateCostDetailsReport"} + return AsyncLROPoller[_models.CostDetailsOperationResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) async def _get_operation_results_initial( self, scope: str, operation_id: str, **kwargs: Any - ) -> Optional[_models.CostDetailsOperationResults]: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -324,43 +308,40 @@ async def _get_operation_results_initial( _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[Optional[_models.CostDetailsOperationResults]] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - request = build_get_operation_results_request( + _request = build_get_operation_results_request( scope=scope, operation_id=operation_id, api_version=api_version, - template_url=self._get_operation_results_initial.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 + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _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) - deserialized = None - if response.status_code == 200: - deserialized = self._deserialize("CostDetailsOperationResults", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - _get_operation_results_initial.metadata = { - "url": "/{scope}/providers/Microsoft.CostManagement/costDetailsOperationResults/{operationId}" - } + return deserialized # type: ignore @distributed_trace_async async def begin_get_operation_results( @@ -369,19 +350,12 @@ async def begin_get_operation_results( """Get the result of the specified operation. This link is provided in the CostDetails creation request response Location header. - :param scope: The ARM Resource ID for subscription, resource group, billing account, or other - billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. + :param scope: The ARM Resource ID for subscription, billing account, or other billing + scopes.Currently Resource Group and Management Group are not supported. For details, see + https://aka.ms/costmgmt/scopes. Required. :type scope: str :param operation_id: The target operation Id. Required. :type operation_id: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either CostDetailsOperationResults or the result of cls(response) :rtype: @@ -406,12 +380,13 @@ async def begin_get_operation_results( 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("CostDetailsOperationResults", pipeline_response) + deserialized = self._deserialize("CostDetailsOperationResults", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -423,14 +398,12 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.CostDetailsOperationResults].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_get_operation_results.metadata = { - "url": "/{scope}/providers/Microsoft.CostManagement/costDetailsOperationResults/{operationId}" - } + return AsyncLROPoller[_models.CostDetailsOperationResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operation_results_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operation_results_operations.py index f1fa361658d2..0bd2ae01b898 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operation_results_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operation_results_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Optional, TypeVar, Union, cast +import sys +from typing import Any, AsyncIterator, Callable, Dict, Optional, TypeVar, Union, cast from azure.core.exceptions import ( ClientAuthenticationError, @@ -14,26 +14,30 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models -from ..._vendor import _convert_request from ...operations._generate_detailed_cost_report_operation_results_operations import build_get_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class GenerateDetailedCostReportOperationResultsOperations: +class GenerateDetailedCostReportOperationResultsOperations: # pylint: disable=name-too-long """ .. warning:: **DO NOT** instantiate this class directly. @@ -52,10 +56,8 @@ def __init__(self, *args, **kwargs) -> None: 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") - async def _get_initial( - self, operation_id: str, scope: str, **kwargs: Any - ) -> Optional[_models.GenerateDetailedCostReportOperationResult]: - error_map = { + async def _get_initial(self, operation_id: str, scope: str, **kwargs: Any) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -67,41 +69,40 @@ async def _get_initial( _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[Optional[_models.GenerateDetailedCostReportOperationResult]] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( operation_id=operation_id, scope=scope, api_version=api_version, - template_url=self._get_initial.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 + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _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) - deserialized = None - if response.status_code == 200: - deserialized = self._deserialize("GenerateDetailedCostReportOperationResult", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - _get_initial.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/operationResults/{operationId}"} + return deserialized # type: ignore @distributed_trace_async async def begin_get( @@ -115,14 +116,6 @@ async def begin_get( :param scope: The ARM Resource ID for subscription, resource group, billing account, or other billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. :type scope: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either GenerateDetailedCostReportOperationResult or the result of cls(response) :rtype: @@ -147,12 +140,15 @@ async def begin_get( 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("GenerateDetailedCostReportOperationResult", pipeline_response) + deserialized = self._deserialize( + "GenerateDetailedCostReportOperationResult", pipeline_response.http_response + ) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -162,12 +158,12 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.GenerateDetailedCostReportOperationResult].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_get.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/operationResults/{operationId}"} + return AsyncLROPoller[_models.GenerateDetailedCostReportOperationResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operation_status_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operation_status_operations.py index 241b5a5598cf..5d78036cf862 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operation_status_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operation_status_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # 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 azure.core.exceptions import ( @@ -17,21 +17,23 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request from ...operations._generate_detailed_cost_report_operation_status_operations import build_get_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class GenerateDetailedCostReportOperationStatusOperations: +class GenerateDetailedCostReportOperationStatusOperations: # pylint: disable=name-too-long """ .. warning:: **DO NOT** instantiate this class directly. @@ -62,12 +64,11 @@ async def get( :param scope: The ARM Resource ID for subscription, resource group, billing account, or other billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. :type scope: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: GenerateDetailedCostReportOperationStatuses or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportOperationStatuses :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -81,20 +82,18 @@ async def get( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.GenerateDetailedCostReportOperationStatuses] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( operation_id=operation_id, 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -104,11 +103,9 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("GenerateDetailedCostReportOperationStatuses", pipeline_response) + deserialized = self._deserialize("GenerateDetailedCostReportOperationStatuses", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - get.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/operationStatus/{operationId}"} + return deserialized # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operations.py index 407343cd8e4b..d11a94448fb2 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,7 +6,8 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from io import IOBase -from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import sys +from typing import Any, AsyncIterator, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload from azure.core.exceptions import ( ClientAuthenticationError, @@ -15,21 +15,25 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models -from ..._vendor import _convert_request from ...operations._generate_detailed_cost_report_operations import build_create_operation_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -54,9 +58,9 @@ def __init__(self, *args, **kwargs) -> None: self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") async def _create_operation_initial( - self, scope: str, parameters: Union[_models.GenerateDetailedCostReportDefinition, IO], **kwargs: Any - ) -> Optional[_models.GenerateDetailedCostReportOperationResult]: - error_map = { + self, scope: str, parameters: Union[_models.GenerateDetailedCostReportDefinition, IO[bytes]], **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -69,7 +73,7 @@ async def _create_operation_initial( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.GenerateDetailedCostReportOperationResult]] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None @@ -79,38 +83,37 @@ async def _create_operation_initial( else: _json = self._serialize.body(parameters, "GenerateDetailedCostReportDefinition") - request = build_create_operation_request( + _request = build_create_operation_request( scope=scope, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self._create_operation_initial.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 + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _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.GenerateDetailedCostReportErrorResponse, pipeline_response ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("GenerateDetailedCostReportOperationResult", pipeline_response) - if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Azure-Consumption-AsyncOperation"] = self._deserialize( @@ -121,14 +124,12 @@ async def _create_operation_initial( ) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _create_operation_initial.metadata = { - "url": "/{scope}/providers/Microsoft.CostManagement/generateDetailedCostReport" - } + return deserialized # type: ignore @overload async def begin_create_operation( @@ -156,14 +157,6 @@ async def begin_create_operation( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either GenerateDetailedCostReportOperationResult or the result of cls(response) :rtype: @@ -173,7 +166,7 @@ async def begin_create_operation( @overload async def begin_create_operation( - self, scope: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, scope: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.GenerateDetailedCostReportOperationResult]: """Generates the detailed cost report for provided date range, billing period(only enterprise customers) or Invoice ID asynchronously at a certain scope. Call returns a 202 with header @@ -188,18 +181,10 @@ async def begin_create_operation( billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. :type scope: str :param parameters: Parameters supplied to the Create detailed cost report 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 - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either GenerateDetailedCostReportOperationResult or the result of cls(response) :rtype: @@ -209,7 +194,7 @@ async def begin_create_operation( @distributed_trace_async async def begin_create_operation( - self, scope: str, parameters: Union[_models.GenerateDetailedCostReportDefinition, IO], **kwargs: Any + self, scope: str, parameters: Union[_models.GenerateDetailedCostReportDefinition, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.GenerateDetailedCostReportOperationResult]: """Generates the detailed cost report for provided date range, billing period(only enterprise customers) or Invoice ID asynchronously at a certain scope. Call returns a 202 with header @@ -224,19 +209,9 @@ async def begin_create_operation( billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. :type scope: str :param parameters: Parameters supplied to the Create detailed cost report operation. Is either - a GenerateDetailedCostReportDefinition type or a IO type. Required. - :type parameters: ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportDefinition 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 - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + a GenerateDetailedCostReportDefinition type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportDefinition or + IO[bytes] :return: An instance of AsyncLROPoller that returns either GenerateDetailedCostReportOperationResult or the result of cls(response) :rtype: @@ -263,12 +238,15 @@ async def begin_create_operation( 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("GenerateDetailedCostReportOperationResult", pipeline_response) + deserialized = self._deserialize( + "GenerateDetailedCostReportOperationResult", pipeline_response.http_response + ) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -280,12 +258,12 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.GenerateDetailedCostReportOperationResult].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_operation.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/generateDetailedCostReport"} + return AsyncLROPoller[_models.GenerateDetailedCostReportOperationResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_reservation_details_report_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_reservation_details_report_operations.py index f9da4d617b6a..0aa389f7b920 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_reservation_details_report_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_reservation_details_report_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Optional, TypeVar, Union, cast +import sys +from typing import Any, AsyncIterator, Callable, Dict, Optional, TypeVar, Union, cast from azure.core.exceptions import ( ClientAuthenticationError, @@ -14,29 +14,33 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models -from ..._vendor import _convert_request from ...operations._generate_reservation_details_report_operations import ( build_by_billing_account_id_request, build_by_billing_profile_id_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class GenerateReservationDetailsReportOperations: +class GenerateReservationDetailsReportOperations: # pylint: disable=name-too-long """ .. warning:: **DO NOT** instantiate this class directly. @@ -57,8 +61,8 @@ def __init__(self, *args, **kwargs) -> None: async def _by_billing_account_id_initial( self, billing_account_id: str, start_date: str, end_date: str, **kwargs: Any - ) -> Optional[_models.OperationStatus]: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -70,49 +74,46 @@ async def _by_billing_account_id_initial( _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[Optional[_models.OperationStatus]] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - request = build_by_billing_account_id_request( + _request = build_by_billing_account_id_request( billing_account_id=billing_account_id, start_date=start_date, end_date=end_date, api_version=api_version, - template_url=self._by_billing_account_id_initial.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 + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _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) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("OperationStatus", pipeline_response) - 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")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _by_billing_account_id_initial.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/generateReservationDetailsReport" - } + return deserialized # type: ignore @distributed_trace_async async def begin_by_billing_account_id( @@ -121,7 +122,7 @@ async def begin_by_billing_account_id( """Generates the reservations details report for provided date range asynchronously based on enrollment id. The Reservation usage details can be viewed only by certain enterprise roles. For more details on the roles see, - https://docs.microsoft.com/azure/cost-management-billing/manage/understand-ea-roles#usage-and-costs-access-by-role. + https://docs.microsoft.com/en-us/azure/cost-management-billing/manage/understand-ea-roles#usage-and-costs-access-by-role. .. seealso:: - https://docs.microsoft.com/en-us/rest/api/costmanagement/ @@ -132,14 +133,6 @@ async def begin_by_billing_account_id( :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 - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either OperationStatus or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.OperationStatus] @@ -164,12 +157,13 @@ async def begin_by_billing_account_id( 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) + deserialized = self._deserialize("OperationStatus", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -181,22 +175,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_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(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_by_billing_account_id.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/generateReservationDetailsReport" - } + return AsyncLROPoller[_models.OperationStatus]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) async def _by_billing_profile_id_initial( self, billing_account_id: str, billing_profile_id: str, start_date: str, end_date: str, **kwargs: Any - ) -> Optional[_models.OperationStatus]: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -208,50 +200,47 @@ async def _by_billing_profile_id_initial( _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[Optional[_models.OperationStatus]] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - request = build_by_billing_profile_id_request( + _request = build_by_billing_profile_id_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._by_billing_profile_id_initial.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 + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _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) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("OperationStatus", pipeline_response) - 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")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _by_billing_profile_id_initial.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.CostManagement/generateReservationDetailsReport" - } + return deserialized # type: ignore @distributed_trace_async async def begin_by_billing_profile_id( @@ -260,7 +249,7 @@ async def begin_by_billing_profile_id( """Generates the reservations details report for provided date range asynchronously by billing profile. The Reservation usage details can be viewed by only certain enterprise roles by default. For more details on the roles see, - https://docs.microsoft.com/azure/cost-management-billing/reservations/reservation-utilization#view-utilization-in-the-azure-portal-with-azure-rbac-access. + https://docs.microsoft.com/en-us/azure/cost-management-billing/reservations/reservation-utilization#view-utilization-in-the-azure-portal-with-azure-rbac-access. .. seealso:: - https://docs.microsoft.com/en-us/rest/api/costmanagement/ @@ -273,14 +262,6 @@ async def begin_by_billing_profile_id( :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 - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either OperationStatus or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.OperationStatus] @@ -306,12 +287,13 @@ async def begin_by_billing_profile_id( 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) + deserialized = self._deserialize("OperationStatus", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -323,14 +305,12 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_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(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_by_billing_profile_id.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.CostManagement/generateReservationDetailsReport" - } + return AsyncLROPoller[_models.OperationStatus]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_operations.py index 9ea97535fb12..a093786dcb9b 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar import urllib.parse @@ -19,16 +19,18 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request from ...operations._operations import build_list_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -56,7 +58,6 @@ def __init__(self, *args, **kwargs) -> None: def list(self, **kwargs: Any) -> AsyncIterable["_models.CostManagementOperation"]: """Lists all of the available cost management REST API operations. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either CostManagementOperation or the result of cls(response) :rtype: @@ -69,7 +70,7 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.CostManagementOperation" 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, @@ -80,14 +81,12 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.CostManagementOperation" 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 @@ -99,13 +98,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) @@ -115,11 +113,11 @@ 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -131,5 +129,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/providers/Microsoft.CostManagement/operations"} diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_price_sheet_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_price_sheet_operations.py index ee61643df312..26f7d56abb80 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_price_sheet_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/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,7 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Optional, TypeVar, Union, cast +import sys +from typing import Any, AsyncIterator, Callable, Dict, Optional, TypeVar, Union, cast from azure.core.exceptions import ( ClientAuthenticationError, @@ -14,21 +14,29 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models -from ..._vendor import _convert_request -from ...operations._price_sheet_operations import build_download_by_billing_profile_request, build_download_request +from ...operations._price_sheet_operations import ( + build_download_by_billing_account_request, + build_download_by_billing_profile_request, + build_download_by_invoice_request, +) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -52,10 +60,10 @@ def __init__(self, *args, **kwargs) -> None: 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") - async def _download_initial( + async def _download_by_invoice_initial( self, billing_account_name: str, billing_profile_name: str, invoice_name: str, **kwargs: Any - ) -> Optional[_models.DownloadURL]: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -67,53 +75,50 @@ async def _download_initial( _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[Optional[_models.DownloadURL]] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - request = build_download_request( + _request = build_download_by_invoice_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_name=invoice_name, api_version=api_version, - template_url=self._download_initial.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 + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _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) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("DownloadURL", pipeline_response) - if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) response_headers["OData-EntityId"] = self._deserialize("str", response.headers.get("OData-EntityId")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _download_initial.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoices/{invoiceName}/providers/Microsoft.CostManagement/pricesheets/default/download" - } + return deserialized # type: ignore @distributed_trace_async - async def begin_download( + async def begin_download_by_invoice( self, billing_account_name: str, billing_profile_name: str, invoice_name: str, **kwargs: Any ) -> AsyncLROPoller[_models.DownloadURL]: """Gets a URL to download the pricesheet for an invoice. The operation is supported for billing @@ -125,14 +130,6 @@ async def begin_download( :type billing_profile_name: str :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either DownloadURL or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.DownloadURL] @@ -147,7 +144,7 @@ async def begin_download( 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_initial( + raw_result = await self._download_by_invoice_initial( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_name=invoice_name, @@ -157,12 +154,13 @@ async def begin_download( 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("DownloadURL", pipeline_response) + deserialized = self._deserialize("DownloadURL", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -174,22 +172,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.DownloadURL].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_download.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoices/{invoiceName}/providers/Microsoft.CostManagement/pricesheets/default/download" - } + return AsyncLROPoller[_models.DownloadURL]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) async def _download_by_billing_profile_initial( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any - ) -> Optional[_models.DownloadURL]: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -201,82 +197,77 @@ async def _download_by_billing_profile_initial( _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[Optional[_models.DownloadURL]] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - request = build_download_by_billing_profile_request( + _request = build_download_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, - template_url=self._download_by_billing_profile_initial.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 + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _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) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("DownloadURL", pipeline_response) - if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) response_headers["OData-EntityId"] = self._deserialize("str", response.headers.get("OData-EntityId")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _download_by_billing_profile_initial.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/providers/Microsoft.CostManagement/pricesheets/default/download" - } + return deserialized # type: ignore @distributed_trace_async async def begin_download_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any - ) -> AsyncLROPoller[_models.DownloadURL]: + ) -> AsyncLROPoller[_models.PricesheetDownloadProperties]: """Gets a URL to download the current month's pricesheet for a billing profile. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft - Customer Agreement.Due to Azure product growth, the Azure price sheet download experience in - this preview version will be updated from a single csv file to a Zip file containing multiple - csv files, each with max 200k records. + Customer Agreement. + + You can use the new 2023-09-01 API version for billing periods January 2023 onwards. Azure + Reserved Instance (RI) pricing is only available through the new version of the API. + + Due to Azure product growth, the Azure price sheet download experience in this preview version + will be updated from a single csv/json file to a Zip file containing multiple csv/json files, + each with max size of 75MB. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either DownloadURL or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.DownloadURL] + :return: An instance of AsyncLROPoller that returns either PricesheetDownloadProperties or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.PricesheetDownloadProperties] :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.DownloadURL] = kwargs.pop("cls", None) + cls: ClsType[_models.PricesheetDownloadProperties] = 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) @@ -290,12 +281,13 @@ async def begin_download_by_billing_profile( 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("DownloadURL", pipeline_response) + deserialized = self._deserialize("PricesheetDownloadProperties", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -307,14 +299,152 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.PricesheetDownloadProperties].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return AsyncLROPoller[_models.PricesheetDownloadProperties]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _download_by_billing_account_initial( + 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_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.ErrorResponseAutoGenerated2, 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("str", 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( + self, billing_account_id: str, billing_period_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.OperationStatusAutoGenerated]: + """Generates the pricesheet for the provided billing period asynchronously based on the Enrollment + ID. This is for Enterprise Agreement customers. + + **Migrate to version 2024-10-01-preview** + + You can use the 2024-10-01-preview API version with the new URI: + + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingPeriods/{billingPeriodName}/providers/Microsoft.CostManagement/pricesheets/default/download' + + With a new schema detailed below, the new version of the price sheet provides additional + information and includes prices for Azure Reserved Instances (RI) for the current billing + period. We recommend downloading an Azure Price Sheet for when entering a new billing period if + you would maintain an ongoing record of past Azure Reserved Instance (RI) pricing. + + The EA Azure price sheet is available for billing periods in the past 13 months. To request a + price sheet for a billing period older than 13 months, please contact support. + + The Azure price sheet download experience has been updated from a single .csv file to a zip + file containing multiple .csv files, each with max size of 75MB. The 2023-11-01 version has + been upgraded to use http POST method; details can be found below. + + All versions of the Microsoft.Consumption Azure Price Sheet - Download by Billing Account + (including 2022-06-01, 2021-10-01, 2020-01-01-preview, 2019-10-01, 2019-05-01) are scheduled to + be retired on 01 June 2026 and will no longer be supported after this date. + + :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 OperationStatusAutoGenerated or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.OperationStatusAutoGenerated] + :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.OperationStatusAutoGenerated] = 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_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) - begin_download_by_billing_profile.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/providers/Microsoft.CostManagement/pricesheets/default/download" - } + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("OperationStatusAutoGenerated", 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.OperationStatusAutoGenerated].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.OperationStatusAutoGenerated]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_query_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_query_operations.py index 21f90c26efe1..6309c4fe8c3e 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_query_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_query_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( @@ -18,16 +18,18 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request from ...operations._query_operations import build_usage_by_external_cloud_provider_type_request, build_usage_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -55,6 +57,7 @@ def __init__(self, *args, **kwargs) -> None: async def usage( self, scope: str, parameters: _models.QueryDefinition, *, content_type: str = "application/json", **kwargs: Any ) -> Optional[_models.QueryResult]: + # pylint: disable=line-too-long """Query the usage data for scope defined. .. seealso:: @@ -82,7 +85,6 @@ async def usage( :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: QueryResult or None or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.QueryResult or None :raises ~azure.core.exceptions.HttpResponseError: @@ -90,8 +92,9 @@ async def usage( @overload async def usage( - self, scope: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, scope: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> Optional[_models.QueryResult]: + # pylint: disable=line-too-long """Query the usage data for scope defined. .. seealso:: @@ -115,11 +118,10 @@ async def usage( specific for partners. Required. :type scope: str :param parameters: Parameters supplied to the CreateOrUpdate Query Config 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: QueryResult or None or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.QueryResult or None :raises ~azure.core.exceptions.HttpResponseError: @@ -127,8 +129,9 @@ async def usage( @distributed_trace_async async def usage( - self, scope: str, parameters: Union[_models.QueryDefinition, IO], **kwargs: Any + self, scope: str, parameters: Union[_models.QueryDefinition, IO[bytes]], **kwargs: Any ) -> Optional[_models.QueryResult]: + # pylint: disable=line-too-long """Query the usage data for scope defined. .. seealso:: @@ -152,17 +155,13 @@ async def usage( specific for partners. Required. :type scope: str :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Is either - a QueryDefinition type or a IO type. Required. - :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition 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 + a QueryDefinition type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition or IO[bytes] :return: QueryResult or None or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.QueryResult or None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -185,22 +184,20 @@ async def usage( else: _json = self._serialize.body(parameters, "QueryDefinition") - request = build_usage_request( + _request = build_usage_request( scope=scope, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.usage.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -212,14 +209,12 @@ async def usage( deserialized = None if response.status_code == 200: - deserialized = self._deserialize("QueryResult", pipeline_response) + deserialized = self._deserialize("QueryResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - usage.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/query"} + return deserialized # type: ignore @overload async def usage_by_external_cloud_provider_type( @@ -251,7 +246,6 @@ async def usage_by_external_cloud_provider_type( :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: QueryResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.QueryResult :raises ~azure.core.exceptions.HttpResponseError: @@ -262,7 +256,7 @@ async def usage_by_external_cloud_provider_type( self, external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], external_cloud_provider_id: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -283,11 +277,10 @@ async def usage_by_external_cloud_provider_type( Required. :type external_cloud_provider_id: str :param parameters: Parameters supplied to the CreateOrUpdate Query Config 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: QueryResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.QueryResult :raises ~azure.core.exceptions.HttpResponseError: @@ -298,7 +291,7 @@ async def usage_by_external_cloud_provider_type( self, external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], external_cloud_provider_id: str, - parameters: Union[_models.QueryDefinition, IO], + parameters: Union[_models.QueryDefinition, IO[bytes]], **kwargs: Any ) -> _models.QueryResult: """Query the usage data for external cloud provider type defined. @@ -317,17 +310,13 @@ async def usage_by_external_cloud_provider_type( Required. :type external_cloud_provider_id: str :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Is either - a QueryDefinition type or a IO type. Required. - :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition 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 + a QueryDefinition type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition or IO[bytes] :return: QueryResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.QueryResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -350,23 +339,21 @@ async def usage_by_external_cloud_provider_type( else: _json = self._serialize.body(parameters, "QueryDefinition") - request = build_usage_by_external_cloud_provider_type_request( + _request = build_usage_by_external_cloud_provider_type_request( external_cloud_provider_type=external_cloud_provider_type, external_cloud_provider_id=external_cloud_provider_id, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.usage_by_external_cloud_provider_type.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -376,13 +363,9 @@ async def usage_by_external_cloud_provider_type( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("QueryResult", pipeline_response) + deserialized = self._deserialize("QueryResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - usage_by_external_cloud_provider_type.metadata = { - "url": "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/query" - } + return deserialized # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_scheduled_actions_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_scheduled_actions_operations.py index 9adf299e0b72..f720adc05325 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_scheduled_actions_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_scheduled_actions_operations.py @@ -7,6 +7,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -20,15 +21,13 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request from ...operations._scheduled_actions_operations import ( build_check_name_availability_by_scope_request, build_check_name_availability_request, @@ -44,6 +43,10 @@ build_run_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -77,7 +80,6 @@ def list(self, filter: Optional[str] = None, **kwargs: Any) -> AsyncIterable["_m :param filter: May be used to filter scheduled actions by properties/viewId. Supported operator is 'eq'. 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 ScheduledAction or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.ScheduledAction] @@ -89,7 +91,7 @@ def list(self, filter: Optional[str] = None, **kwargs: Any) -> AsyncIterable["_m api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ScheduledActionListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -100,15 +102,13 @@ def list(self, filter: Optional[str] = None, **kwargs: Any) -> AsyncIterable["_m def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( 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 @@ -120,13 +120,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("ScheduledActionListResult", pipeline_response) @@ -136,11 +135,11 @@ 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -155,8 +154,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list.metadata = {"url": "/providers/Microsoft.CostManagement/scheduledActions"} - @distributed_trace def list_by_scope( self, scope: str, filter: Optional[str] = None, **kwargs: Any @@ -187,7 +184,6 @@ def list_by_scope( :param filter: May be used to filter scheduled actions by properties/viewId. Supported operator is 'eq'. 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 ScheduledAction or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.ScheduledAction] @@ -199,7 +195,7 @@ def list_by_scope( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ScheduledActionListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -210,16 +206,14 @@ def list_by_scope( def prepare_request(next_link=None): if not next_link: - request = build_list_by_scope_request( + _request = build_list_by_scope_request( scope=scope, filter=filter, api_version=api_version, - template_url=self.list_by_scope.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 @@ -231,13 +225,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("ScheduledActionListResult", pipeline_response) @@ -247,11 +240,11 @@ 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -266,8 +259,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/scheduledActions"} - @overload async def create_or_update( self, @@ -291,7 +282,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: ScheduledAction or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction :raises ~azure.core.exceptions.HttpResponseError: @@ -301,7 +291,7 @@ async def create_or_update( async def create_or_update( self, name: str, - scheduled_action: IO, + scheduled_action: IO[bytes], if_match: Optional[str] = None, *, content_type: str = "application/json", @@ -312,7 +302,7 @@ async def create_or_update( :param name: Scheduled action name. Required. :type name: str :param scheduled_action: Scheduled action to be created or updated. Required. - :type scheduled_action: IO + :type scheduled_action: IO[bytes] :param if_match: ETag of the Entity. Not required when creating an entity. Optional when updating an entity and can be specified to achieve optimistic concurrency. Default value is None. @@ -320,7 +310,6 @@ async def create_or_update( :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: ScheduledAction or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction :raises ~azure.core.exceptions.HttpResponseError: @@ -330,7 +319,7 @@ async def create_or_update( async def create_or_update( self, name: str, - scheduled_action: Union[_models.ScheduledAction, IO], + scheduled_action: Union[_models.ScheduledAction, IO[bytes]], if_match: Optional[str] = None, **kwargs: Any ) -> _models.ScheduledAction: @@ -339,21 +328,17 @@ async def create_or_update( :param name: Scheduled action name. Required. :type name: str :param scheduled_action: Scheduled action to be created or updated. Is either a ScheduledAction - type or a IO type. Required. - :type scheduled_action: ~azure.mgmt.costmanagement.models.ScheduledAction or IO + type or a IO[bytes] type. Required. + :type scheduled_action: ~azure.mgmt.costmanagement.models.ScheduledAction or IO[bytes] :param if_match: ETag of the Entity. Not required when creating an entity. Optional when updating an entity and can be specified to achieve optimistic concurrency. Default value is None. :type if_match: str - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ScheduledAction or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -376,23 +361,21 @@ async def create_or_update( else: _json = self._serialize.body(scheduled_action, "ScheduledAction") - request = build_create_or_update_request( + _request = build_create_or_update_request( name=name, if_match=if_match, 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -402,19 +385,13 @@ async def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseWithNestedDetails, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("ScheduledAction", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ScheduledAction", pipeline_response) + deserialized = self._deserialize("ScheduledAction", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = {"url": "/providers/Microsoft.CostManagement/scheduledActions/{name}"} - @distributed_trace_async async def get(self, name: str, **kwargs: Any) -> _models.ScheduledAction: """Get the private scheduled action by name. @@ -424,12 +401,11 @@ async def get(self, name: str, **kwargs: Any) -> _models.ScheduledAction: :param name: Scheduled action name. Required. :type name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ScheduledAction or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -443,19 +419,17 @@ async def get(self, name: str, **kwargs: Any) -> _models.ScheduledAction: api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ScheduledAction] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( name=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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -465,17 +439,15 @@ async def get(self, name: str, **kwargs: Any) -> _models.ScheduledAction: error = self._deserialize.failsafe_deserialize(_models.ErrorResponseWithNestedDetails, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ScheduledAction", pipeline_response) + deserialized = self._deserialize("ScheduledAction", 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.CostManagement/scheduledActions/{name}"} + return deserialized # type: ignore @distributed_trace_async - async def delete(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + async def delete(self, name: str, **kwargs: Any) -> None: """Delete a private scheduled action. .. seealso:: @@ -483,12 +455,11 @@ async def delete(self, name: str, **kwargs: Any) -> None: # pylint: disable=inc :param name: Scheduled action name. Required. :type 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, @@ -502,19 +473,17 @@ async def delete(self, name: str, **kwargs: Any) -> None: # pylint: disable=inc 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( name=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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -525,9 +494,7 @@ async def delete(self, name: str, **kwargs: Any) -> None: # pylint: disable=inc raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = {"url": "/providers/Microsoft.CostManagement/scheduledActions/{name}"} + return cls(pipeline_response, None, {}) # type: ignore @overload async def create_or_update_by_scope( @@ -571,7 +538,6 @@ async def create_or_update_by_scope( :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: ScheduledAction or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction :raises ~azure.core.exceptions.HttpResponseError: @@ -582,7 +548,7 @@ async def create_or_update_by_scope( self, scope: str, name: str, - scheduled_action: IO, + scheduled_action: IO[bytes], if_match: Optional[str] = None, *, content_type: str = "application/json", @@ -611,7 +577,7 @@ async def create_or_update_by_scope( :param name: Scheduled action name. Required. :type name: str :param scheduled_action: Scheduled action to be created or updated. Required. - :type scheduled_action: IO + :type scheduled_action: IO[bytes] :param if_match: ETag of the Entity. Not required when creating an entity. Optional when updating an entity and can be specified to achieve optimistic concurrency. Default value is None. @@ -619,7 +585,6 @@ async def create_or_update_by_scope( :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: ScheduledAction or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction :raises ~azure.core.exceptions.HttpResponseError: @@ -630,7 +595,7 @@ async def create_or_update_by_scope( self, scope: str, name: str, - scheduled_action: Union[_models.ScheduledAction, IO], + scheduled_action: Union[_models.ScheduledAction, IO[bytes]], if_match: Optional[str] = None, **kwargs: Any ) -> _models.ScheduledAction: @@ -657,21 +622,17 @@ async def create_or_update_by_scope( :param name: Scheduled action name. Required. :type name: str :param scheduled_action: Scheduled action to be created or updated. Is either a ScheduledAction - type or a IO type. Required. - :type scheduled_action: ~azure.mgmt.costmanagement.models.ScheduledAction or IO + type or a IO[bytes] type. Required. + :type scheduled_action: ~azure.mgmt.costmanagement.models.ScheduledAction or IO[bytes] :param if_match: ETag of the Entity. Not required when creating an entity. Optional when updating an entity and can be specified to achieve optimistic concurrency. Default value is None. :type if_match: str - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ScheduledAction or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -694,7 +655,7 @@ async def create_or_update_by_scope( else: _json = self._serialize.body(scheduled_action, "ScheduledAction") - request = build_create_or_update_by_scope_request( + _request = build_create_or_update_by_scope_request( scope=scope, name=name, if_match=if_match, @@ -702,16 +663,14 @@ async def create_or_update_by_scope( content_type=content_type, json=_json, content=_content, - template_url=self.create_or_update_by_scope.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -721,19 +680,13 @@ async def create_or_update_by_scope( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseWithNestedDetails, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("ScheduledAction", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ScheduledAction", pipeline_response) + deserialized = self._deserialize("ScheduledAction", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/scheduledActions/{name}"} - @distributed_trace_async async def get_by_scope(self, scope: str, name: str, **kwargs: Any) -> _models.ScheduledAction: """Get the shared scheduled action from the given scope by name. @@ -761,12 +714,11 @@ async def get_by_scope(self, scope: str, name: str, **kwargs: Any) -> _models.Sc :type scope: str :param name: Scheduled action name. Required. :type name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ScheduledAction or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -780,20 +732,18 @@ async def get_by_scope(self, scope: str, name: str, **kwargs: Any) -> _models.Sc api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ScheduledAction] = kwargs.pop("cls", None) - request = build_get_by_scope_request( + _request = build_get_by_scope_request( scope=scope, name=name, api_version=api_version, - template_url=self.get_by_scope.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -803,19 +753,15 @@ async def get_by_scope(self, scope: str, name: str, **kwargs: Any) -> _models.Sc error = self._deserialize.failsafe_deserialize(_models.ErrorResponseWithNestedDetails, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ScheduledAction", pipeline_response) + deserialized = self._deserialize("ScheduledAction", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/scheduledActions/{name}"} + return deserialized # type: ignore @distributed_trace_async - async def delete_by_scope( # pylint: disable=inconsistent-return-statements - self, scope: str, name: str, **kwargs: Any - ) -> None: + async def delete_by_scope(self, scope: str, name: str, **kwargs: Any) -> None: """Delete a scheduled action within the given scope. .. seealso:: @@ -841,12 +787,11 @@ async def delete_by_scope( # pylint: disable=inconsistent-return-statements :type scope: str :param name: Scheduled action name. Required. :type 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, @@ -860,20 +805,18 @@ async def delete_by_scope( # pylint: disable=inconsistent-return-statements 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_by_scope_request( + _request = build_delete_by_scope_request( scope=scope, name=name, api_version=api_version, - template_url=self.delete_by_scope.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -884,22 +827,19 @@ async def delete_by_scope( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/scheduledActions/{name}"} + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def run(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + async def run(self, name: str, **kwargs: Any) -> None: """Processes a private scheduled action. :param name: Scheduled action name. Required. :type 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, @@ -913,19 +853,17 @@ async def run(self, name: str, **kwargs: Any) -> None: # pylint: disable=incons api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_run_request( + _request = build_run_request( name=name, api_version=api_version, - template_url=self.run.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -936,14 +874,10 @@ async def run(self, name: str, **kwargs: Any) -> None: # pylint: disable=incons raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - run.metadata = {"url": "/providers/Microsoft.CostManagement/scheduledActions/{name}/execute"} + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def run_by_scope( # pylint: disable=inconsistent-return-statements - self, scope: str, name: str, **kwargs: Any - ) -> None: + async def run_by_scope(self, scope: str, name: str, **kwargs: Any) -> None: """Runs a shared scheduled action within the given scope. :param scope: The scope associated with scheduled action operations. This includes @@ -966,12 +900,11 @@ async def run_by_scope( # pylint: disable=inconsistent-return-statements :type scope: str :param name: Scheduled action name. Required. :type 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, @@ -985,20 +918,18 @@ async def run_by_scope( # pylint: disable=inconsistent-return-statements api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_run_by_scope_request( + _request = build_run_by_scope_request( scope=scope, name=name, api_version=api_version, - template_url=self.run_by_scope.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1009,9 +940,7 @@ async def run_by_scope( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - run_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/scheduledActions/{name}/execute"} + return cls(pipeline_response, None, {}) # type: ignore @overload async def check_name_availability( @@ -1029,7 +958,6 @@ async def check_name_availability( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: CheckNameAvailabilityResponse or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse :raises ~azure.core.exceptions.HttpResponseError: @@ -1037,16 +965,15 @@ async def check_name_availability( @overload async def check_name_availability( - self, check_name_availability_request: IO, *, content_type: str = "application/json", **kwargs: Any + self, check_name_availability_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.CheckNameAvailabilityResponse: """Checks availability and correctness of the name for a scheduled action. :param check_name_availability_request: Scheduled action to be created or updated. Required. - :type check_name_availability_request: IO + :type check_name_availability_request: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: CheckNameAvailabilityResponse or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse :raises ~azure.core.exceptions.HttpResponseError: @@ -1054,23 +981,19 @@ async def check_name_availability( @distributed_trace_async async def check_name_availability( - self, check_name_availability_request: Union[_models.CheckNameAvailabilityRequest, IO], **kwargs: Any + self, check_name_availability_request: Union[_models.CheckNameAvailabilityRequest, IO[bytes]], **kwargs: Any ) -> _models.CheckNameAvailabilityResponse: """Checks availability and correctness of the name for a scheduled action. :param check_name_availability_request: Scheduled action to be created or updated. Is either a - CheckNameAvailabilityRequest type or a IO type. Required. + CheckNameAvailabilityRequest type or a IO[bytes] type. Required. :type check_name_availability_request: - ~azure.mgmt.costmanagement.models.CheckNameAvailabilityRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + ~azure.mgmt.costmanagement.models.CheckNameAvailabilityRequest or IO[bytes] :return: CheckNameAvailabilityResponse or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1093,21 +1016,19 @@ async def check_name_availability( else: _json = self._serialize.body(check_name_availability_request, "CheckNameAvailabilityRequest") - request = build_check_name_availability_request( + _request = build_check_name_availability_request( api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.check_name_availability.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1117,14 +1038,12 @@ async def check_name_availability( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseWithNestedDetails, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("CheckNameAvailabilityResponse", pipeline_response) + deserialized = self._deserialize("CheckNameAvailabilityResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - check_name_availability.metadata = {"url": "/providers/Microsoft.CostManagement/checkNameAvailability"} + return deserialized # type: ignore @overload async def check_name_availability_by_scope( @@ -1161,7 +1080,6 @@ async def check_name_availability_by_scope( :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: CheckNameAvailabilityResponse or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse :raises ~azure.core.exceptions.HttpResponseError: @@ -1169,7 +1087,12 @@ async def check_name_availability_by_scope( @overload async def check_name_availability_by_scope( - self, scope: str, check_name_availability_request: IO, *, content_type: str = "application/json", **kwargs: Any + self, + scope: str, + check_name_availability_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models.CheckNameAvailabilityResponse: """Checks availability and correctness of the name for a scheduled action within the given scope. @@ -1192,11 +1115,10 @@ async def check_name_availability_by_scope( Required. :type scope: str :param check_name_availability_request: Scheduled action to be created or updated. Required. - :type check_name_availability_request: IO + :type check_name_availability_request: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: CheckNameAvailabilityResponse or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse :raises ~azure.core.exceptions.HttpResponseError: @@ -1206,7 +1128,7 @@ async def check_name_availability_by_scope( async def check_name_availability_by_scope( self, scope: str, - check_name_availability_request: Union[_models.CheckNameAvailabilityRequest, IO], + check_name_availability_request: Union[_models.CheckNameAvailabilityRequest, IO[bytes]], **kwargs: Any ) -> _models.CheckNameAvailabilityResponse: """Checks availability and correctness of the name for a scheduled action within the given scope. @@ -1230,18 +1152,14 @@ async def check_name_availability_by_scope( Required. :type scope: str :param check_name_availability_request: Scheduled action to be created or updated. Is either a - CheckNameAvailabilityRequest type or a IO type. Required. + CheckNameAvailabilityRequest type or a IO[bytes] type. Required. :type check_name_availability_request: - ~azure.mgmt.costmanagement.models.CheckNameAvailabilityRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + ~azure.mgmt.costmanagement.models.CheckNameAvailabilityRequest or IO[bytes] :return: CheckNameAvailabilityResponse or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1264,22 +1182,20 @@ async def check_name_availability_by_scope( else: _json = self._serialize.body(check_name_availability_request, "CheckNameAvailabilityRequest") - request = build_check_name_availability_by_scope_request( + _request = build_check_name_availability_by_scope_request( scope=scope, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.check_name_availability_by_scope.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1289,13 +1205,9 @@ async def check_name_availability_by_scope( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseWithNestedDetails, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("CheckNameAvailabilityResponse", pipeline_response) + deserialized = self._deserialize("CheckNameAvailabilityResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - check_name_availability_by_scope.metadata = { - "url": "/{scope}/providers/Microsoft.CostManagement/checkNameAvailability" - } + return deserialized # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_settings_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_settings_operations.py new file mode 100644 index 000000000000..bb7a3382564c --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_settings_operations.py @@ -0,0 +1,374 @@ +# 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 io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +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 ...operations._settings_operations import ( + build_create_or_update_by_scope_request, + build_delete_by_scope_request, + build_get_by_scope_request, + build_list_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class SettingsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s + :attr:`settings` attribute. + """ + + models = _models + + 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") + + @distributed_trace_async + async def list(self, scope: str, **kwargs: Any) -> _models.SettingsListResult: + """List all cost management settings in the requested scope. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param scope: The scope associated with this setting. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billing profile scope. Required. + :type scope: str + :return: SettingsListResult or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.SettingsListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SettingsListResult] = kwargs.pop("cls", None) + + _request = build_list_request( + scope=scope, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("SettingsListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_or_update_by_scope( + self, + scope: str, + type: Union[str, _models.SettingType], + setting: _models.Setting, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Setting: + """Create or update a setting within the given scope. + + :param scope: The scope associated with this setting. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billing profile scope. Required. + :type scope: str + :param type: Setting type. "taginheritance" Required. + :type type: str or ~azure.mgmt.costmanagement.models.SettingType + :param setting: Setting to be created or updated. Required. + :type setting: ~azure.mgmt.costmanagement.models.Setting + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Setting or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Setting + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_by_scope( + self, + scope: str, + type: Union[str, _models.SettingType], + setting: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Setting: + """Create or update a setting within the given scope. + + :param scope: The scope associated with this setting. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billing profile scope. Required. + :type scope: str + :param type: Setting type. "taginheritance" Required. + :type type: str or ~azure.mgmt.costmanagement.models.SettingType + :param setting: Setting to be created or updated. Required. + :type setting: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Setting or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Setting + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_by_scope( + self, + scope: str, + type: Union[str, _models.SettingType], + setting: Union[_models.Setting, IO[bytes]], + **kwargs: Any + ) -> _models.Setting: + """Create or update a setting within the given scope. + + :param scope: The scope associated with this setting. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billing profile scope. Required. + :type scope: str + :param type: Setting type. "taginheritance" Required. + :type type: str or ~azure.mgmt.costmanagement.models.SettingType + :param setting: Setting to be created or updated. Is either a Setting type or a IO[bytes] type. + Required. + :type setting: ~azure.mgmt.costmanagement.models.Setting or IO[bytes] + :return: Setting or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Setting + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = 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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Setting] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(setting, (IOBase, bytes)): + _content = setting + else: + _json = self._serialize.body(setting, "Setting") + + _request = build_create_or_update_by_scope_request( + scope=scope, + type=type, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Setting", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_by_scope(self, scope: str, type: Union[str, _models.SettingType], **kwargs: Any) -> _models.Setting: + """Get the setting from the given scope by name. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param scope: The scope associated with this setting. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billing profile scope. Required. + :type scope: str + :param type: Setting type. "taginheritance" Required. + :type type: str or ~azure.mgmt.costmanagement.models.SettingType + :return: Setting or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Setting + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.Setting] = kwargs.pop("cls", None) + + _request = build_get_by_scope_request( + scope=scope, + type=type, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Setting", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete_by_scope(self, scope: str, type: Union[str, _models.SettingType], **kwargs: Any) -> None: + """Delete a setting within the given scope. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param scope: The scope associated with this setting. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billing profile scope. Required. + :type scope: str + :param type: Setting type. "taginheritance" Required. + :type type: str or ~azure.mgmt.costmanagement.models.SettingType + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_delete_by_scope_request( + scope=scope, + type=type, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_views_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_views_operations.py index 28afc176547a..c16ccdaa86ce 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_views_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_views_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -20,15 +20,13 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request from ...operations._views_operations import ( build_create_or_update_by_scope_request, build_create_or_update_request, @@ -40,6 +38,10 @@ build_list_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -70,7 +72,6 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.View"]: .. seealso:: - https://docs.microsoft.com/en-us/rest/api/costmanagement/ - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either View or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.View] :raises ~azure.core.exceptions.HttpResponseError: @@ -81,7 +82,7 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.View"]: api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ViewListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -92,14 +93,12 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.View"]: 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 @@ -111,13 +110,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("ViewListResult", pipeline_response) @@ -127,11 +125,11 @@ 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -144,8 +142,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list.metadata = {"url": "/providers/Microsoft.CostManagement/views"} - @distributed_trace def list_by_scope(self, scope: str, **kwargs: Any) -> AsyncIterable["_models.View"]: """Lists all views at the given scope. @@ -171,7 +167,6 @@ def list_by_scope(self, scope: str, **kwargs: Any) -> AsyncIterable["_models.Vie 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for External Subscription 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 View or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.View] :raises ~azure.core.exceptions.HttpResponseError: @@ -182,7 +177,7 @@ def list_by_scope(self, scope: str, **kwargs: Any) -> AsyncIterable["_models.Vie api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ViewListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -193,15 +188,13 @@ def list_by_scope(self, scope: str, **kwargs: Any) -> AsyncIterable["_models.Vie def prepare_request(next_link=None): if not next_link: - request = build_list_by_scope_request( + _request = build_list_by_scope_request( scope=scope, api_version=api_version, - template_url=self.list_by_scope.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 +206,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("ViewListResult", pipeline_response) @@ -229,11 +221,11 @@ 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -246,8 +238,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/views"} - @distributed_trace_async async def get(self, view_name: str, **kwargs: Any) -> _models.View: """Gets the view by view name. @@ -257,12 +247,11 @@ async def get(self, view_name: str, **kwargs: Any) -> _models.View: :param view_name: View name. Required. :type view_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -276,19 +265,17 @@ async def get(self, view_name: str, **kwargs: Any) -> _models.View: api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.View] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( view_name=view_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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -298,14 +285,12 @@ async def get(self, view_name: str, **kwargs: Any) -> _models.View: error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("View", pipeline_response) + deserialized = self._deserialize("View", 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.CostManagement/views/{viewName}"} + return deserialized # type: ignore @overload async def create_or_update( @@ -325,7 +310,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: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View :raises ~azure.core.exceptions.HttpResponseError: @@ -333,7 +317,7 @@ async def create_or_update( @overload async def create_or_update( - self, view_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, view_name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.View: """The operation to create or update a view. Update operation requires latest eTag to be set in the request. You may obtain the latest eTag by performing a get operation. Create operation @@ -345,11 +329,10 @@ async def create_or_update( :param view_name: View name. Required. :type view_name: str :param parameters: Parameters supplied to the CreateOrUpdate View 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: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View :raises ~azure.core.exceptions.HttpResponseError: @@ -357,7 +340,7 @@ async def create_or_update( @distributed_trace_async async def create_or_update( - self, view_name: str, parameters: Union[_models.View, IO], **kwargs: Any + self, view_name: str, parameters: Union[_models.View, IO[bytes]], **kwargs: Any ) -> _models.View: """The operation to create or update a view. Update operation requires latest eTag to be set in the request. You may obtain the latest eTag by performing a get operation. Create operation @@ -369,17 +352,13 @@ async def create_or_update( :param view_name: View name. Required. :type view_name: str :param parameters: Parameters supplied to the CreateOrUpdate View operation. Is either a View - type or a IO type. Required. - :type parameters: ~azure.mgmt.costmanagement.models.View 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 + type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.View or IO[bytes] :return: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -402,22 +381,20 @@ async def create_or_update( else: _json = self._serialize.body(parameters, "View") - request = build_create_or_update_request( + _request = build_create_or_update_request( view_name=view_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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -427,21 +404,15 @@ async def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("View", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("View", pipeline_response) + deserialized = self._deserialize("View", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = {"url": "/providers/Microsoft.CostManagement/views/{viewName}"} - @distributed_trace_async - async def delete(self, view_name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + async def delete(self, view_name: str, **kwargs: Any) -> None: """The operation to delete a view. .. seealso:: @@ -449,12 +420,11 @@ async def delete(self, view_name: str, **kwargs: Any) -> None: # pylint: disabl :param view_name: View name. Required. :type view_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, @@ -468,19 +438,17 @@ async def delete(self, view_name: str, **kwargs: Any) -> None: # pylint: disabl 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( view_name=view_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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -491,9 +459,7 @@ async def delete(self, view_name: str, **kwargs: Any) -> None: # pylint: disabl raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = {"url": "/providers/Microsoft.CostManagement/views/{viewName}"} + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async async def get_by_scope(self, scope: str, view_name: str, **kwargs: Any) -> _models.View: @@ -522,12 +488,11 @@ async def get_by_scope(self, scope: str, view_name: str, **kwargs: Any) -> _mode :type scope: str :param view_name: View name. Required. :type view_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -541,20 +506,18 @@ async def get_by_scope(self, scope: str, view_name: str, **kwargs: Any) -> _mode api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.View] = kwargs.pop("cls", None) - request = build_get_by_scope_request( + _request = build_get_by_scope_request( scope=scope, view_name=view_name, api_version=api_version, - template_url=self.get_by_scope.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -564,14 +527,12 @@ async def get_by_scope(self, scope: str, view_name: str, **kwargs: Any) -> _mode error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("View", pipeline_response) + deserialized = self._deserialize("View", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/views/{viewName}"} + return deserialized # type: ignore @overload async def create_or_update_by_scope( @@ -615,7 +576,6 @@ async def create_or_update_by_scope( :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: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View :raises ~azure.core.exceptions.HttpResponseError: @@ -623,7 +583,13 @@ async def create_or_update_by_scope( @overload async def create_or_update_by_scope( - self, scope: str, view_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, + scope: str, + view_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models.View: """The operation to create or update a view. Update operation requires latest eTag to be set in the request. You may obtain the latest eTag by performing a get operation. Create operation @@ -653,11 +619,10 @@ async def create_or_update_by_scope( :param view_name: View name. Required. :type view_name: str :param parameters: Parameters supplied to the CreateOrUpdate View 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: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View :raises ~azure.core.exceptions.HttpResponseError: @@ -665,7 +630,7 @@ async def create_or_update_by_scope( @distributed_trace_async async def create_or_update_by_scope( - self, scope: str, view_name: str, parameters: Union[_models.View, IO], **kwargs: Any + self, scope: str, view_name: str, parameters: Union[_models.View, IO[bytes]], **kwargs: Any ) -> _models.View: """The operation to create or update a view. Update operation requires latest eTag to be set in the request. You may obtain the latest eTag by performing a get operation. Create operation @@ -695,17 +660,13 @@ async def create_or_update_by_scope( :param view_name: View name. Required. :type view_name: str :param parameters: Parameters supplied to the CreateOrUpdate View operation. Is either a View - type or a IO type. Required. - :type parameters: ~azure.mgmt.costmanagement.models.View 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 + type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.View or IO[bytes] :return: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -728,23 +689,21 @@ async def create_or_update_by_scope( else: _json = self._serialize.body(parameters, "View") - request = build_create_or_update_by_scope_request( + _request = build_create_or_update_by_scope_request( scope=scope, view_name=view_name, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.create_or_update_by_scope.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -754,23 +713,15 @@ async def create_or_update_by_scope( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("View", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("View", pipeline_response) + deserialized = self._deserialize("View", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/views/{viewName}"} - @distributed_trace_async - async def delete_by_scope( # pylint: disable=inconsistent-return-statements - self, scope: str, view_name: str, **kwargs: Any - ) -> None: + async def delete_by_scope(self, scope: str, view_name: str, **kwargs: Any) -> None: """The operation to delete a view. .. seealso:: @@ -796,12 +747,11 @@ async def delete_by_scope( # pylint: disable=inconsistent-return-statements :type scope: str :param view_name: View name. Required. :type view_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, @@ -815,20 +765,18 @@ async def delete_by_scope( # pylint: disable=inconsistent-return-statements 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_by_scope_request( + _request = build_delete_by_scope_request( scope=scope, view_name=view_name, api_version=api_version, - template_url=self.delete_by_scope.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -839,6 +787,4 @@ async def delete_by_scope( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/views/{viewName}"} + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/__init__.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/__init__.py index be704298e815..1c3a0eee403b 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/__init__.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/__init__.py @@ -5,168 +5,240 @@ # 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 Alert -from ._models_py3 import AlertPropertiesDefinition -from ._models_py3 import AlertPropertiesDetails -from ._models_py3 import AlertsResult -from ._models_py3 import AllSavingsBenefitDetails -from ._models_py3 import AllSavingsList -from ._models_py3 import BenefitRecommendationModel -from ._models_py3 import BenefitRecommendationProperties -from ._models_py3 import BenefitRecommendationsListResult -from ._models_py3 import BenefitResource -from ._models_py3 import BenefitUtilizationSummariesListResult -from ._models_py3 import BenefitUtilizationSummary -from ._models_py3 import BenefitUtilizationSummaryProperties -from ._models_py3 import BlobInfo -from ._models_py3 import CheckNameAvailabilityRequest -from ._models_py3 import CheckNameAvailabilityResponse -from ._models_py3 import CommonExportProperties -from ._models_py3 import CostDetailsOperationResults -from ._models_py3 import CostDetailsTimePeriod -from ._models_py3 import CostManagementOperation -from ._models_py3 import CostManagementProxyResource -from ._models_py3 import CostManagementResource -from ._models_py3 import Dimension -from ._models_py3 import DimensionsListResult -from ._models_py3 import DismissAlertPayload -from ._models_py3 import DownloadURL -from ._models_py3 import ErrorDetails -from ._models_py3 import ErrorDetailsWithNestedDetails -from ._models_py3 import ErrorResponse -from ._models_py3 import ErrorResponseWithNestedDetails -from ._models_py3 import Export -from ._models_py3 import ExportDataset -from ._models_py3 import ExportDatasetConfiguration -from ._models_py3 import ExportDefinition -from ._models_py3 import ExportDeliveryDestination -from ._models_py3 import ExportDeliveryInfo -from ._models_py3 import ExportExecutionListResult -from ._models_py3 import ExportListResult -from ._models_py3 import ExportProperties -from ._models_py3 import ExportRecurrencePeriod -from ._models_py3 import ExportRun -from ._models_py3 import ExportSchedule -from ._models_py3 import ExportTimePeriod -from ._models_py3 import FileDestination -from ._models_py3 import ForecastAggregation -from ._models_py3 import ForecastColumn -from ._models_py3 import ForecastComparisonExpression -from ._models_py3 import ForecastDataset -from ._models_py3 import ForecastDatasetConfiguration -from ._models_py3 import ForecastDefinition -from ._models_py3 import ForecastFilter -from ._models_py3 import ForecastResult -from ._models_py3 import ForecastTimePeriod -from ._models_py3 import GenerateCostDetailsReportErrorResponse -from ._models_py3 import GenerateCostDetailsReportRequestDefinition -from ._models_py3 import GenerateDetailedCostReportDefinition -from ._models_py3 import GenerateDetailedCostReportErrorResponse -from ._models_py3 import GenerateDetailedCostReportOperationResult -from ._models_py3 import GenerateDetailedCostReportOperationStatuses -from ._models_py3 import GenerateDetailedCostReportTimePeriod -from ._models_py3 import IncludedQuantityUtilizationSummary -from ._models_py3 import IncludedQuantityUtilizationSummaryProperties -from ._models_py3 import KpiProperties -from ._models_py3 import NotificationProperties -from ._models_py3 import Operation -from ._models_py3 import OperationDisplay -from ._models_py3 import OperationListResult -from ._models_py3 import OperationStatus -from ._models_py3 import PivotProperties -from ._models_py3 import ProxyResource -from ._models_py3 import QueryAggregation -from ._models_py3 import QueryColumn -from ._models_py3 import QueryComparisonExpression -from ._models_py3 import QueryDataset -from ._models_py3 import QueryDatasetConfiguration -from ._models_py3 import QueryDefinition -from ._models_py3 import QueryFilter -from ._models_py3 import QueryGrouping -from ._models_py3 import QueryResult -from ._models_py3 import QueryTimePeriod -from ._models_py3 import RecommendationUsageDetails -from ._models_py3 import ReportConfigAggregation -from ._models_py3 import ReportConfigComparisonExpression -from ._models_py3 import ReportConfigDataset -from ._models_py3 import ReportConfigDatasetConfiguration -from ._models_py3 import ReportConfigFilter -from ._models_py3 import ReportConfigGrouping -from ._models_py3 import ReportConfigSorting -from ._models_py3 import ReportConfigTimePeriod -from ._models_py3 import Resource -from ._models_py3 import SavingsPlanUtilizationSummary -from ._models_py3 import SavingsPlanUtilizationSummaryProperties -from ._models_py3 import ScheduleProperties -from ._models_py3 import ScheduledAction -from ._models_py3 import ScheduledActionListResult -from ._models_py3 import ScheduledActionProxyResource -from ._models_py3 import SharedScopeBenefitRecommendationProperties -from ._models_py3 import SingleScopeBenefitRecommendationProperties -from ._models_py3 import Status -from ._models_py3 import SystemData -from ._models_py3 import View -from ._models_py3 import ViewListResult +from typing import TYPE_CHECKING -from ._cost_management_client_enums import AccumulatedType -from ._cost_management_client_enums import ActionType -from ._cost_management_client_enums import AlertCategory -from ._cost_management_client_enums import AlertCriteria -from ._cost_management_client_enums import AlertOperator -from ._cost_management_client_enums import AlertSource -from ._cost_management_client_enums import AlertStatus -from ._cost_management_client_enums import AlertTimeGrainType -from ._cost_management_client_enums import AlertType -from ._cost_management_client_enums import BenefitKind -from ._cost_management_client_enums import ChartType -from ._cost_management_client_enums import CheckNameAvailabilityReason -from ._cost_management_client_enums import CostDetailsDataFormat -from ._cost_management_client_enums import CostDetailsMetricType -from ._cost_management_client_enums import CostDetailsStatusType -from ._cost_management_client_enums import CreatedByType -from ._cost_management_client_enums import DaysOfWeek -from ._cost_management_client_enums import ExecutionStatus -from ._cost_management_client_enums import ExecutionType -from ._cost_management_client_enums import ExportType -from ._cost_management_client_enums import ExternalCloudProviderType -from ._cost_management_client_enums import FileFormat -from ._cost_management_client_enums import ForecastOperatorType -from ._cost_management_client_enums import ForecastTimeframe -from ._cost_management_client_enums import ForecastType -from ._cost_management_client_enums import FormatType -from ._cost_management_client_enums import FunctionName -from ._cost_management_client_enums import FunctionType -from ._cost_management_client_enums import GenerateDetailedCostReportMetricType -from ._cost_management_client_enums import Grain -from ._cost_management_client_enums import GrainParameter -from ._cost_management_client_enums import GranularityType -from ._cost_management_client_enums import KpiType -from ._cost_management_client_enums import LookBackPeriod -from ._cost_management_client_enums import MetricType -from ._cost_management_client_enums import OperationStatusType -from ._cost_management_client_enums import OperatorType -from ._cost_management_client_enums import Origin -from ._cost_management_client_enums import PivotType -from ._cost_management_client_enums import QueryColumnType -from ._cost_management_client_enums import QueryOperatorType -from ._cost_management_client_enums import RecurrenceType -from ._cost_management_client_enums import ReportConfigSortingType -from ._cost_management_client_enums import ReportGranularityType -from ._cost_management_client_enums import ReportOperationStatusType -from ._cost_management_client_enums import ReportTimeframeType -from ._cost_management_client_enums import ReportType -from ._cost_management_client_enums import ReservationReportSchema -from ._cost_management_client_enums import ScheduleFrequency -from ._cost_management_client_enums import ScheduledActionKind -from ._cost_management_client_enums import ScheduledActionStatus -from ._cost_management_client_enums import Scope -from ._cost_management_client_enums import StatusType -from ._cost_management_client_enums import Term -from ._cost_management_client_enums import TimeframeType -from ._cost_management_client_enums import WeeksOfMonth +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + Alert, + AlertPropertiesDefinition, + AlertPropertiesDetails, + AlertsResult, + AllSavingsBenefitDetails, + AllSavingsList, + AsyncOperationStatusProperties, + BenefitRecommendationModel, + BenefitRecommendationProperties, + BenefitRecommendationsListResult, + BenefitResource, + BenefitUtilizationSummariesListResult, + BenefitUtilizationSummariesOperationStatus, + BenefitUtilizationSummariesRequest, + BenefitUtilizationSummary, + BenefitUtilizationSummaryProperties, + BlobInfo, + Budget, + BudgetComparisonExpression, + BudgetFilter, + BudgetFilterProperties, + BudgetTimePeriod, + BudgetsListResult, + CheckNameAvailabilityRequest, + CheckNameAvailabilityResponse, + CommonExportProperties, + CostAllocationProportion, + CostAllocationResource, + CostAllocationRuleCheckNameAvailabilityRequest, + CostAllocationRuleCheckNameAvailabilityResponse, + CostAllocationRuleDefinition, + CostAllocationRuleDetails, + CostAllocationRuleList, + CostAllocationRuleProperties, + CostDetailsOperationResults, + CostDetailsTimePeriod, + CostManagementOperation, + CostManagementProxyResource, + CostManagementResource, + CurrentSpend, + Dimension, + DimensionsListResult, + DismissAlertPayload, + DownloadURL, + EAPriceSheetProperties, + ErrorAdditionalInfo, + ErrorDetail, + ErrorDetailAutoGenerated, + ErrorDetails, + ErrorDetailsWithNestedDetails, + ErrorResponse, + ErrorResponseAutoGenerated, + ErrorResponseAutoGenerated2, + ErrorResponseWithNestedDetails, + Export, + ExportDataset, + ExportDatasetConfiguration, + ExportDefinition, + ExportDeliveryDestination, + ExportDeliveryInfo, + ExportExecutionListResult, + ExportListResult, + ExportProperties, + ExportRecurrencePeriod, + ExportRun, + ExportRunRequest, + ExportSchedule, + ExportSuspensionContext, + ExportTimePeriod, + FabricLakehouse, + FabricWorkspace, + FileDestination, + FilterItems, + ForecastAggregation, + ForecastColumn, + ForecastComparisonExpression, + ForecastDataset, + ForecastDatasetConfiguration, + ForecastDefinition, + ForecastFilter, + ForecastResult, + ForecastSpend, + ForecastTimePeriod, + GenerateCostDetailsReportErrorResponse, + GenerateCostDetailsReportRequestDefinition, + GenerateDetailedCostReportDefinition, + GenerateDetailedCostReportErrorResponse, + GenerateDetailedCostReportOperationResult, + GenerateDetailedCostReportOperationStatuses, + GenerateDetailedCostReportTimePeriod, + IncludedQuantityUtilizationSummary, + IncludedQuantityUtilizationSummaryProperties, + KpiProperties, + MCAPriceSheetProperties, + MicrosoftFabricDestinationSettings, + Notification, + NotificationProperties, + Operation, + OperationDisplay, + OperationListResult, + OperationStatus, + OperationStatusAutoGenerated, + PivotProperties, + PricesheetDownloadProperties, + ProxyResource, + QueryAggregation, + QueryColumn, + QueryComparisonExpression, + QueryDataset, + QueryDatasetConfiguration, + QueryDefinition, + QueryFilter, + QueryGrouping, + QueryResult, + QueryTimePeriod, + RecommendationUsageDetails, + ReportConfigAggregation, + ReportConfigComparisonExpression, + ReportConfigDataset, + ReportConfigDatasetConfiguration, + ReportConfigFilter, + ReportConfigGrouping, + ReportConfigSorting, + ReportConfigTimePeriod, + Resource, + SavingsPlanUtilizationSummary, + SavingsPlanUtilizationSummaryProperties, + ScheduleProperties, + ScheduledAction, + ScheduledActionListResult, + ScheduledActionProxyResource, + Setting, + SettingsListResult, + SharedScopeBenefitRecommendationProperties, + SingleScopeBenefitRecommendationProperties, + SourceCostAllocationResource, + Status, + SystemAssignedServiceIdentity, + SystemData, + TagInheritanceProperties, + TagInheritanceSetting, + TargetCostAllocationResource, + View, + ViewListResult, +) + +from ._cost_management_client_enums import ( # type: ignore + AccumulatedType, + ActionType, + AlertCategory, + AlertCriteria, + AlertOperator, + AlertSource, + AlertStatus, + AlertTimeGrainType, + AlertType, + BenefitKind, + BenefitUtilizationSummaryReportSchema, + BudgetNotificationOperatorType, + BudgetOperatorType, + CategoryType, + ChartType, + CheckNameAvailabilityReason, + CompressionModeType, + CostAllocationPolicyType, + CostAllocationResourceType, + CostDetailsDataFormat, + CostDetailsMetricType, + CostDetailsStatusType, + CreatedByType, + CultureCode, + DataOverwriteBehaviorType, + DaysOfWeek, + DestinationType, + ExecutionStatus, + ExecutionType, + ExportType, + ExternalCloudProviderType, + FileFormat, + FilterItemNames, + ForecastOperatorType, + ForecastTimeframe, + ForecastType, + FormatType, + Frequency, + FunctionName, + FunctionType, + GenerateDetailedCostReportMetricType, + Grain, + GrainParameter, + GranularityType, + KpiType, + LookBackPeriod, + MetricType, + OperationStatusType, + OperatorType, + Origin, + PivotType, + QueryColumnType, + QueryOperatorType, + Reason, + RecurrenceType, + ReportConfigSortingType, + ReportGranularityType, + ReportOperationStatusType, + ReportTimeframeType, + ReportType, + ReservationReportSchema, + RuleStatus, + ScheduleFrequency, + ScheduledActionKind, + ScheduledActionStatus, + Scope, + SettingType, + SettingsKind, + StatusType, + SystemAssignedServiceIdentityType, + Term, + ThresholdType, + TimeGrainType, + TimeframeType, + WeeksOfMonth, +) 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__ = [ @@ -176,29 +248,53 @@ "AlertsResult", "AllSavingsBenefitDetails", "AllSavingsList", + "AsyncOperationStatusProperties", "BenefitRecommendationModel", "BenefitRecommendationProperties", "BenefitRecommendationsListResult", "BenefitResource", "BenefitUtilizationSummariesListResult", + "BenefitUtilizationSummariesOperationStatus", + "BenefitUtilizationSummariesRequest", "BenefitUtilizationSummary", "BenefitUtilizationSummaryProperties", "BlobInfo", + "Budget", + "BudgetComparisonExpression", + "BudgetFilter", + "BudgetFilterProperties", + "BudgetTimePeriod", + "BudgetsListResult", "CheckNameAvailabilityRequest", "CheckNameAvailabilityResponse", "CommonExportProperties", + "CostAllocationProportion", + "CostAllocationResource", + "CostAllocationRuleCheckNameAvailabilityRequest", + "CostAllocationRuleCheckNameAvailabilityResponse", + "CostAllocationRuleDefinition", + "CostAllocationRuleDetails", + "CostAllocationRuleList", + "CostAllocationRuleProperties", "CostDetailsOperationResults", "CostDetailsTimePeriod", "CostManagementOperation", "CostManagementProxyResource", "CostManagementResource", + "CurrentSpend", "Dimension", "DimensionsListResult", "DismissAlertPayload", "DownloadURL", + "EAPriceSheetProperties", + "ErrorAdditionalInfo", + "ErrorDetail", + "ErrorDetailAutoGenerated", "ErrorDetails", "ErrorDetailsWithNestedDetails", "ErrorResponse", + "ErrorResponseAutoGenerated", + "ErrorResponseAutoGenerated2", "ErrorResponseWithNestedDetails", "Export", "ExportDataset", @@ -211,9 +307,14 @@ "ExportProperties", "ExportRecurrencePeriod", "ExportRun", + "ExportRunRequest", "ExportSchedule", + "ExportSuspensionContext", "ExportTimePeriod", + "FabricLakehouse", + "FabricWorkspace", "FileDestination", + "FilterItems", "ForecastAggregation", "ForecastColumn", "ForecastComparisonExpression", @@ -222,6 +323,7 @@ "ForecastDefinition", "ForecastFilter", "ForecastResult", + "ForecastSpend", "ForecastTimePeriod", "GenerateCostDetailsReportErrorResponse", "GenerateCostDetailsReportRequestDefinition", @@ -233,12 +335,17 @@ "IncludedQuantityUtilizationSummary", "IncludedQuantityUtilizationSummaryProperties", "KpiProperties", + "MCAPriceSheetProperties", + "MicrosoftFabricDestinationSettings", + "Notification", "NotificationProperties", "Operation", "OperationDisplay", "OperationListResult", "OperationStatus", + "OperationStatusAutoGenerated", "PivotProperties", + "PricesheetDownloadProperties", "ProxyResource", "QueryAggregation", "QueryColumn", @@ -266,10 +373,17 @@ "ScheduledAction", "ScheduledActionListResult", "ScheduledActionProxyResource", + "Setting", + "SettingsListResult", "SharedScopeBenefitRecommendationProperties", "SingleScopeBenefitRecommendationProperties", + "SourceCostAllocationResource", "Status", + "SystemAssignedServiceIdentity", "SystemData", + "TagInheritanceProperties", + "TagInheritanceSetting", + "TargetCostAllocationResource", "View", "ViewListResult", "AccumulatedType", @@ -282,22 +396,34 @@ "AlertTimeGrainType", "AlertType", "BenefitKind", + "BenefitUtilizationSummaryReportSchema", + "BudgetNotificationOperatorType", + "BudgetOperatorType", + "CategoryType", "ChartType", "CheckNameAvailabilityReason", + "CompressionModeType", + "CostAllocationPolicyType", + "CostAllocationResourceType", "CostDetailsDataFormat", "CostDetailsMetricType", "CostDetailsStatusType", "CreatedByType", + "CultureCode", + "DataOverwriteBehaviorType", "DaysOfWeek", + "DestinationType", "ExecutionStatus", "ExecutionType", "ExportType", "ExternalCloudProviderType", "FileFormat", + "FilterItemNames", "ForecastOperatorType", "ForecastTimeframe", "ForecastType", "FormatType", + "Frequency", "FunctionName", "FunctionType", "GenerateDetailedCostReportMetricType", @@ -313,6 +439,7 @@ "PivotType", "QueryColumnType", "QueryOperatorType", + "Reason", "RecurrenceType", "ReportConfigSortingType", "ReportGranularityType", @@ -320,14 +447,20 @@ "ReportTimeframeType", "ReportType", "ReservationReportSchema", + "RuleStatus", "ScheduleFrequency", "ScheduledActionKind", "ScheduledActionStatus", "Scope", + "SettingType", + "SettingsKind", "StatusType", + "SystemAssignedServiceIdentityType", "Term", + "ThresholdType", + "TimeGrainType", "TimeframeType", "WeeksOfMonth", ] -__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/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_cost_management_client_enums.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_cost_management_client_enums.py index 400e59765fb6..3450f4cd2666 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_cost_management_client_enums.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_cost_management_client_enums.py @@ -114,6 +114,87 @@ class BenefitKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Benefit is SavingsPlan.""" +class BenefitUtilizationSummaryReportSchema(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The CSV file from the reportUrl and secondaryReportUrl blob link will consist of the following + columns of benefit utilization data. UtilizedPercentage will be 0 for savings plans reports and + non data bricks reservations. Utilization percentages will be 0 for data bricks reservations. + """ + + KIND = "Kind" + AVG_UTILIZATION_PERCENTAGE = "AvgUtilizationPercentage" + BENEFIT_ORDER_ID = "BenefitOrderId" + BENEFIT_ID = "BenefitId" + BENEFIT_TYPE = "BenefitType" + MAX_UTILIZATION_PERCENTAGE = "MaxUtilizationPercentage" + MIN_UTILIZATION_PERCENTAGE = "MinUtilizationPercentage" + USAGE_DATE = "UsageDate" + UTILIZED_PERCENTAGE = "UtilizedPercentage" + + +class BudgetNotificationOperatorType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The comparison operator. + + Supported for CategoryType(s): Cost, ReservationUtilization. + + Supported operators for **CategoryType: Cost** + + + * GreaterThan + * + GreaterThanOrEqualTo + + Supported operators for **CategoryType: ReservationUtilization** + + * LessThan. + """ + + EQUAL_TO = "EqualTo" + """Notification 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. + + Supported for CategoryType(s): Cost.""" + GREATER_THAN = "GreaterThan" + """Notification will be triggered if the evaluated cost is greater than the threshold value. Note: + This is the recommended OperatorType while configuring Budget Alert. + + Supported for CategoryType(s): Cost.""" + GREATER_THAN_OR_EQUAL_TO = "GreaterThanOrEqualTo" + """Notification will be triggered if the evaluated cost is greater than or equal to the threshold + value. + + Supported for CategoryType(s): Cost.""" + LESS_THAN = "LessThan" + """Notification will be triggered if any Reservations in the scope of the Reservation Utilization + Alert Rule have a utilization less than the threshold percentage. + + Supported for CategoryType(s): ReservationUtilization.""" + + +class BudgetOperatorType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The operator to use for comparison.""" + + IN = "In" + IN_ENUM = "In" + + +class CategoryType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The category of the budget. + + + * 'Cost' defines a Budget. + * 'ReservationUtilization' defines a Reservation Utilization Alert Rule. + """ + + COST = "Cost" + """A Budget that evaluates monetary cost of Azure resources against an amount, and alerts based on + a configured notification threshold.""" + RESERVATION_UTILIZATION = "ReservationUtilization" + """An Alert Rule that evaluates the utilization percentage of Azure Reservations, and alerts based + on a configured notification threshold.""" + + class ChartType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Chart type of the main view in Cost Analysis. Required.""" @@ -131,6 +212,33 @@ class CheckNameAvailabilityReason(str, Enum, metaclass=CaseInsensitiveEnumMeta): ALREADY_EXISTS = "AlreadyExists" +class CompressionModeType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Allow customers to select compress data(gzip) for exports. This setting will enable destination + file compression scheme at runtime. By default set to None. + """ + + GZIP = "gzip" + NONE = "None" + + +class CostAllocationPolicyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Method to use for allocating cost. FixedProportion indicates that cost will be split based on + specified percentage values. + """ + + FIXED_PROPORTION = "FixedProportion" + + +class CostAllocationResourceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Category of resource to use for allocation.""" + + DIMENSION = "Dimension" + """Indicates an Azure dimension such as a subscription id or resource group name is being used for + allocation.""" + TAG = "Tag" + """Allocates cost based on Azure Tag key value pairs.""" + + class CostDetailsDataFormat(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The data format of the report.""" @@ -167,6 +275,45 @@ class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): KEY = "Key" +class CultureCode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Language in which the recipient will receive the notification, + + Supported for CategoryType(s): Cost, ReservationUtilization. + """ + + EN_US = "en-us" + JA_JP = "ja-jp" + ZH_CN = "zh-cn" + DE_DE = "de-de" + ES_ES = "es-es" + FR_FR = "fr-fr" + IT_IT = "it-it" + KO_KR = "ko-kr" + PT_BR = "pt-br" + RU_RU = "ru-ru" + ZH_TW = "zh-tw" + CS_CZ = "cs-cz" + PL_PL = "pl-pl" + TR_TR = "tr-tr" + DA_DK = "da-dk" + EN_GB = "en-gb" + HU_HU = "hu-hu" + NB_NO = "nb-no" + NL_NL = "nl-nl" + PT_PT = "pt-pt" + SV_SE = "sv-se" + + +class DataOverwriteBehaviorType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Allow customers to select overwrite data(OverwritePreviousReport) for exports. This setting + will enable overwrite data for the same month in customer storage account. By default set to + CreateNewReport. + """ + + OVERWRITE_PREVIOUS_REPORT = "OverwritePreviousReport" + CREATE_NEW_REPORT = "CreateNewReport" + + class DaysOfWeek(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Days of Week.""" @@ -179,6 +326,15 @@ class DaysOfWeek(str, Enum, metaclass=CaseInsensitiveEnumMeta): SUNDAY = "Sunday" +class DestinationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The export delivery destination type. Currently only 'AzureBlob' and 'MicrosoftFabric' is + supported. If no value is provided it will default to 'AzureBlob'. + """ + + AZURE_BLOB = "AzureBlob" + MICROSOFT_FABRIC = "MicrosoftFabric" + + class ExecutionStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The last known status of the export run.""" @@ -199,11 +355,18 @@ class ExecutionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): class ExportType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The type of the query.""" + """The type of the export. Note that 'Usage' is equivalent to 'ActualCost' and is applicable to + exports that do not yet provide data for charges or amortization for service reservations. + """ USAGE = "Usage" ACTUAL_COST = "ActualCost" AMORTIZED_COST = "AmortizedCost" + FOCUS_COST = "FocusCost" + PRICE_SHEET = "PriceSheet" + RESERVATION_TRANSACTIONS = "ReservationTransactions" + RESERVATION_RECOMMENDATIONS = "ReservationRecommendations" + RESERVATION_DETAILS = "ReservationDetails" class ExternalCloudProviderType(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -219,6 +382,17 @@ class FileFormat(str, Enum, metaclass=CaseInsensitiveEnumMeta): CSV = "Csv" +class FilterItemNames(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The name of the filter. This is currently only supported for Export Definition type of + ReservationRecommendations. Supported names are ['ReservationScope', 'LookBackPeriod', + 'ResourceType']. + """ + + RESERVATION_SCOPE = "ReservationScope" + RESOURCE_TYPE = "ResourceType" + LOOK_BACK_PERIOD = "LookBackPeriod" + + class ForecastOperatorType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The operator to use for comparison.""" @@ -241,9 +415,31 @@ class ForecastType(str, Enum, metaclass=CaseInsensitiveEnumMeta): class FormatType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The format of the export being delivered. Currently only 'Csv' is supported.""" + """The format of the export being delivered.""" CSV = "Csv" + PARQUET = "Parquet" + DELTA = "Delta" + + +class Frequency(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Frequency of a notification. Represents how long the notification will be silent after + triggering an alert for a threshold breach. If not specified, the frequency will be set by + default based on the timeGrain (Weekly when timeGrain: Last7Days, Monthly when timeGrain: + Last30Days). + + Supported for CategoryType(s): ReservationUtilization. + """ + + DAILY = "Daily" + """After the threshold breaches and an Alert is fired, no further alerts will be sent until the + next calendar day.""" + WEEKLY = "Weekly" + """After the threshold breaches and an Alert is fired, no further alerts will be sent for 7 + calendar days.""" + MONTHLY = "Monthly" + """After the threshold breaches and an Alert is fired, no further alerts will be sent for 30 + calendar days.""" class FunctionName(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -291,9 +487,10 @@ class GrainParameter(str, Enum, metaclass=CaseInsensitiveEnumMeta): class GranularityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The granularity of rows in the forecast.""" + """The granularity of rows in the export. Currently 'Daily' is supported for most cases.""" DAILY = "Daily" + MONTHLY = "Monthly" class KpiType(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -323,11 +520,12 @@ class MetricType(str, Enum, metaclass=CaseInsensitiveEnumMeta): class OperationStatusType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The status of the long running operation.""" + """Enum representing the status of an async operation.""" RUNNING = "Running" - COMPLETED = "Completed" + COMPLETE = "Complete" FAILED = "Failed" + COMPLETED = "Completed" class OperatorType(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -371,6 +569,14 @@ class QueryOperatorType(str, Enum, metaclass=CaseInsensitiveEnumMeta): IN_ENUM = "In" +class Reason(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The reason this name is not available.""" + + INVALID = "Invalid" + ALREADY_EXISTS = "AlreadyExists" + VALID = "Valid" + + class RecurrenceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The schedule recurrence.""" @@ -444,6 +650,18 @@ class ReservationReportSchema(str, Enum, metaclass=CaseInsensitiveEnumMeta): USED_HOURS = "UsedHours" +class RuleStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Current status of the rule.""" + + NOT_ACTIVE = "NotActive" + """Rule is saved but not used to allocate costs.""" + ACTIVE = "Active" + """Rule is saved and impacting cost allocation.""" + PROCESSING = "Processing" + """Rule is saved and cost allocation is being updated. Readonly value that cannot be submitted in + a put request.""" + + class ScheduledActionKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Kind of the scheduled action.""" @@ -451,7 +669,7 @@ class ScheduledActionKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Cost analysis data will be emailed.""" INSIGHT_ALERT = "InsightAlert" """Cost anomaly information will be emailed. Available only on subscription scope at daily - #: frequency. If no anomaly is detected on the resource, an email won't be sent.""" + frequency. If no anomaly is detected on the resource, an email won't be sent.""" class ScheduledActionStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -485,11 +703,35 @@ class Scope(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Shared scope recommendation.""" +class SettingsKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies the kind of settings.""" + + TAGINHERITANCE = "taginheritance" + + +class SettingType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """SettingType.""" + + TAGINHERITANCE = "taginheritance" + """This setting applies billing profile, invoice section, subscription and resource group tags to + current month's usage data of child resources.""" + + class StatusType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The status of the export's schedule. If 'Inactive', the export's schedule is paused.""" + """The status of the export's schedule. If 'Inactive', the export's schedule is paused. + 'SystemSuspended' can only be set by export service. + """ ACTIVE = "Active" INACTIVE = "Inactive" + SYSTEM_SUSPENDED = "SystemSuspended" + + +class SystemAssignedServiceIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of managed service identity (either system assigned, or none).""" + + NONE = "None" + SYSTEM_ASSIGNED = "SystemAssigned" class Term(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -501,8 +743,21 @@ class Term(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Benefit term is 3 years.""" +class ThresholdType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of threshold. + + Supported for CategoryType(s): Cost. + """ + + ACTUAL = "Actual" + """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 TimeframeType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The time frame for pulling data for the query. If custom, then a specific time period must be + """The time frame for pulling data for the export. If custom, then a specific time period must be provided. """ @@ -512,6 +767,70 @@ class TimeframeType(str, Enum, metaclass=CaseInsensitiveEnumMeta): THE_LAST_BILLING_MONTH = "TheLastBillingMonth" WEEK_TO_DATE = "WeekToDate" CUSTOM = "Custom" + THE_CURRENT_MONTH = "TheCurrentMonth" + + +class TimeGrainType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The time covered by a budget. Tracking of the amount will be reset based on the time grain. + + Supported for CategoryType(s): Cost, ReservationUtilization. + + Supported timeGrainTypes for **CategoryType: Cost** + + + * Monthly + * Quarterly + * Annually + * BillingMonth* + * BillingQuarter* + * + BillingAnnual* + + *only supported for Web Direct customers. + + Supported timeGrainTypes for **CategoryType: ReservationUtilization** + + * Last7Days + * + Last30Days + + Required for CategoryType(s): Cost, ReservationUtilization. + """ + + MONTHLY = "Monthly" + """The budget will track costs in the current calendar month against the amount. + + Supported for CategoryType: Cost only.""" + QUARTERLY = "Quarterly" + """The budget will track costs in the current calendar quarter against the amount. + + Supported for CategoryType: Cost only.""" + ANNUALLY = "Annually" + """The budget will track costs in the current calendar year against the amount. + + Supported for CategoryType: Cost only.""" + BILLING_MONTH = "BillingMonth" + """The budget will track costs in the current billing month against the amount. + + Supported for CategoryType: Cost and Web Direct customers only.""" + BILLING_QUARTER = "BillingQuarter" + """The budget will track costs in the current billing quarter against the amount. + + Supported for CategoryType: Cost and Web Direct customers only.""" + BILLING_ANNUAL = "BillingAnnual" + """The budget will track costs in the current billing year against the amount. + + Supported for CategoryType: Cost and Web Direct customers only.""" + LAST7_DAYS = "Last7Days" + """The Reservation Utilization Alert Rule will evaluate reservations based on their 7-Day + utilization percentage. + + Supported for CategoryType: ReservationUtilization only.""" + LAST30_DAYS = "Last30Days" + """The Reservation Utilization Alert Rule will evaluate reservations based on their 30-Day + utilization percentage. + + Supported for CategoryType: ReservationUtilization only.""" class WeeksOfMonth(str, Enum, metaclass=CaseInsensitiveEnumMeta): diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_models_py3.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_models_py3.py index e4bc3e9da52b..ea9f303e1e0c 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_models_py3.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/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. @@ -16,10 +16,9 @@ if sys.version_info >= (3, 9): from collections.abc import MutableMapping else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object @@ -66,7 +65,7 @@ def __init__(self, *, e_tag: Optional[str] = None, **kwargs: Any) -> None: self.e_tag = e_tag -class Alert(CostManagementProxyResource): # pylint: disable=too-many-instance-attributes +class Alert(CostManagementProxyResource): """An individual alert. Variables are only populated by the server, and will be ignored when sending a request. @@ -239,7 +238,7 @@ def __init__( self.criteria = criteria -class AlertPropertiesDetails(_serialization.Model): # pylint: disable=too-many-instance-attributes +class AlertPropertiesDetails(_serialization.Model): """Alert details. :ivar time_grain_type: Type of timegrain cadence. Known values are: "None", "Monthly", @@ -540,13 +539,70 @@ def __init__(self, **kwargs: Any) -> None: self.next_link = None +class AsyncOperationStatusProperties(_serialization.Model): + """Object representing the report url and valid until date of the async report generated. + + :ivar report_url: Sas url to the async benefit utilization summaries report. Will be empty if + the report is in Running or Failed state. Known values are: "Kind", "AvgUtilizationPercentage", + "BenefitOrderId", "BenefitId", "BenefitType", "MaxUtilizationPercentage", + "MinUtilizationPercentage", "UsageDate", and "UtilizedPercentage". + :vartype report_url: str or + ~azure.mgmt.costmanagement.models.BenefitUtilizationSummaryReportSchema + :ivar secondary_report_url: Sas url to async benefit utilization summaries report in secondary + storage in case of primary outage. Will be empty if the report is in Running or Failed state. + Known values are: "Kind", "AvgUtilizationPercentage", "BenefitOrderId", "BenefitId", + "BenefitType", "MaxUtilizationPercentage", "MinUtilizationPercentage", "UsageDate", and + "UtilizedPercentage". + :vartype secondary_report_url: str or + ~azure.mgmt.costmanagement.models.BenefitUtilizationSummaryReportSchema + :ivar valid_until: The date that the sas url provided in reportUrl expires. + :vartype valid_until: ~datetime.datetime + """ + + _attribute_map = { + "report_url": {"key": "reportUrl", "type": "str"}, + "secondary_report_url": {"key": "secondaryReportUrl", "type": "str"}, + "valid_until": {"key": "validUntil", "type": "iso-8601"}, + } + + def __init__( + self, + *, + report_url: Optional[Union[str, "_models.BenefitUtilizationSummaryReportSchema"]] = None, + secondary_report_url: Optional[Union[str, "_models.BenefitUtilizationSummaryReportSchema"]] = None, + valid_until: Optional[datetime.datetime] = None, + **kwargs: Any + ) -> None: + """ + :keyword report_url: Sas url to the async benefit utilization summaries report. Will be empty + if the report is in Running or Failed state. Known values are: "Kind", + "AvgUtilizationPercentage", "BenefitOrderId", "BenefitId", "BenefitType", + "MaxUtilizationPercentage", "MinUtilizationPercentage", "UsageDate", and "UtilizedPercentage". + :paramtype report_url: str or + ~azure.mgmt.costmanagement.models.BenefitUtilizationSummaryReportSchema + :keyword secondary_report_url: Sas url to async benefit utilization summaries report in + secondary storage in case of primary outage. Will be empty if the report is in Running or + Failed state. Known values are: "Kind", "AvgUtilizationPercentage", "BenefitOrderId", + "BenefitId", "BenefitType", "MaxUtilizationPercentage", "MinUtilizationPercentage", + "UsageDate", and "UtilizedPercentage". + :paramtype secondary_report_url: str or + ~azure.mgmt.costmanagement.models.BenefitUtilizationSummaryReportSchema + :keyword valid_until: The date that the sas url provided in reportUrl expires. + :paramtype valid_until: ~datetime.datetime + """ + super().__init__(**kwargs) + self.report_url = report_url + self.secondary_report_url = secondary_report_url + self.valid_until = valid_until + + class Resource(_serialization.Model): """Common fields that are returned in the response for all Azure Resource Manager resources. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -581,7 +637,7 @@ class BenefitResource(Resource): Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -622,7 +678,7 @@ class BenefitRecommendationModel(BenefitResource): Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -668,7 +724,7 @@ def __init__( self.properties = properties -class BenefitRecommendationProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes +class BenefitRecommendationProperties(_serialization.Model): """The properties of the benefit recommendations. You probably want to use the sub-classes and not this class directly. Known sub-classes are: @@ -676,7 +732,7 @@ class BenefitRecommendationProperties(_serialization.Model): # pylint: disable= 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 first_consumption_date: The first usage date used for looking back for computing the recommendations. @@ -848,6 +904,154 @@ def __init__(self, **kwargs: Any) -> None: self.next_link = None +class BenefitUtilizationSummariesOperationStatus(_serialization.Model): # pylint: disable=name-too-long + """Status of a benefit utilization summaries report. Provides Async Benefit Utilization Summaries + Request input, status, and report sas url. + + :ivar input: Input given to create the benefit utilization summaries report. + :vartype input: ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest + :ivar status: The status of the creation of the benefit utilization summaries report. Known + values are: "Running", "Complete", "Failed", and "Completed". + :vartype status: str or ~azure.mgmt.costmanagement.models.OperationStatusType + :ivar properties: Contains sas url to the async benefit utilization summaries report and a date + that the url is valid until. These values will be empty if the report is in a Running or Failed + state. + :vartype properties: ~azure.mgmt.costmanagement.models.AsyncOperationStatusProperties + """ + + _attribute_map = { + "input": {"key": "input", "type": "BenefitUtilizationSummariesRequest"}, + "status": {"key": "status", "type": "str"}, + "properties": {"key": "properties", "type": "AsyncOperationStatusProperties"}, + } + + def __init__( + self, + *, + input: Optional["_models.BenefitUtilizationSummariesRequest"] = None, + status: Optional[Union[str, "_models.OperationStatusType"]] = None, + properties: Optional["_models.AsyncOperationStatusProperties"] = None, + **kwargs: Any + ) -> None: + """ + :keyword input: Input given to create the benefit utilization summaries report. + :paramtype input: ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest + :keyword status: The status of the creation of the benefit utilization summaries report. Known + values are: "Running", "Complete", "Failed", and "Completed". + :paramtype status: str or ~azure.mgmt.costmanagement.models.OperationStatusType + :keyword properties: Contains sas url to the async benefit utilization summaries report and a + date that the url is valid until. These values will be empty if the report is in a Running or + Failed state. + :paramtype properties: ~azure.mgmt.costmanagement.models.AsyncOperationStatusProperties + """ + super().__init__(**kwargs) + self.input = input + self.status = status + self.properties = properties + + +class BenefitUtilizationSummariesRequest(_serialization.Model): + """Properties of an async benefit utilization summaries request. + + All required parameters must be populated in order to send to server. + + :ivar billing_account_id: Billing account the benefit utilization summaries report is for. + Required for billing account and billing profile scopes. Not supported for any benefit scopes. + :vartype billing_account_id: str + :ivar billing_profile_id: Billing profile id the benefit utilization summaries report is for. + Required for billing profile scope. Not supported for billing account or any benefit scopes. + :vartype billing_profile_id: str + :ivar benefit_order_id: Benefit order id the benefit utilization summaries report is for. + Required for benefit order and benefit id scopes. Not supported for any billing scopes. + :vartype benefit_order_id: str + :ivar benefit_id: Benefit id the benefit utilization summaries report is for. Required for + benefit id scope. Not supported for benefit order or any billing scopes. + :vartype benefit_id: str + :ivar grain: The grain the summaries data is served at in the report. Accepted values are + 'Daily' or 'Monthly'. Required. Known values are: "Hourly", "Daily", and "Monthly". + :vartype grain: str or ~azure.mgmt.costmanagement.models.Grain + :ivar start_date: The start date of the summaries data that will be served in the report. + Required. + :vartype start_date: ~datetime.datetime + :ivar end_date: The end date of the summaries data that will be served in the report. Required. + :vartype end_date: ~datetime.datetime + :ivar kind: The type of benefit data requested. Required for billing account and billing + profile scopes. Implied and not to be passed at benefit scopes. Supported values are + Reservation and SavingsPlan. Known values are: "IncludedQuantity", "Reservation", and + "SavingsPlan". + :vartype kind: str or ~azure.mgmt.costmanagement.models.BenefitKind + """ + + _validation = { + "grain": {"required": True}, + "start_date": {"required": True}, + "end_date": {"required": True}, + } + + _attribute_map = { + "billing_account_id": {"key": "billingAccountId", "type": "str"}, + "billing_profile_id": {"key": "billingProfileId", "type": "str"}, + "benefit_order_id": {"key": "benefitOrderId", "type": "str"}, + "benefit_id": {"key": "benefitId", "type": "str"}, + "grain": {"key": "grain", "type": "str"}, + "start_date": {"key": "startDate", "type": "iso-8601"}, + "end_date": {"key": "endDate", "type": "iso-8601"}, + "kind": {"key": "kind", "type": "str"}, + } + + def __init__( + self, + *, + grain: Union[str, "_models.Grain"], + start_date: datetime.datetime, + end_date: datetime.datetime, + billing_account_id: Optional[str] = None, + billing_profile_id: Optional[str] = None, + benefit_order_id: Optional[str] = None, + benefit_id: Optional[str] = None, + kind: Optional[Union[str, "_models.BenefitKind"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword billing_account_id: Billing account the benefit utilization summaries report is for. + Required for billing account and billing profile scopes. Not supported for any benefit scopes. + :paramtype billing_account_id: str + :keyword billing_profile_id: Billing profile id the benefit utilization summaries report is + for. Required for billing profile scope. Not supported for billing account or any benefit + scopes. + :paramtype billing_profile_id: str + :keyword benefit_order_id: Benefit order id the benefit utilization summaries report is for. + Required for benefit order and benefit id scopes. Not supported for any billing scopes. + :paramtype benefit_order_id: str + :keyword benefit_id: Benefit id the benefit utilization summaries report is for. Required for + benefit id scope. Not supported for benefit order or any billing scopes. + :paramtype benefit_id: str + :keyword grain: The grain the summaries data is served at in the report. Accepted values are + 'Daily' or 'Monthly'. Required. Known values are: "Hourly", "Daily", and "Monthly". + :paramtype grain: str or ~azure.mgmt.costmanagement.models.Grain + :keyword start_date: The start date of the summaries data that will be served in the report. + Required. + :paramtype start_date: ~datetime.datetime + :keyword end_date: The end date of the summaries data that will be served in the report. + Required. + :paramtype end_date: ~datetime.datetime + :keyword kind: The type of benefit data requested. Required for billing account and billing + profile scopes. Implied and not to be passed at benefit scopes. Supported values are + Reservation and SavingsPlan. Known values are: "IncludedQuantity", "Reservation", and + "SavingsPlan". + :paramtype kind: str or ~azure.mgmt.costmanagement.models.BenefitKind + """ + super().__init__(**kwargs) + self.billing_account_id = billing_account_id + self.billing_profile_id = billing_profile_id + self.benefit_order_id = benefit_order_id + self.benefit_id = benefit_id + self.grain = grain + self.start_date = start_date + self.end_date = end_date + self.kind = kind + + class BenefitUtilizationSummary(Resource): """Benefit utilization summary resource. @@ -856,10 +1060,10 @@ class BenefitUtilizationSummary(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: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -972,148 +1176,971 @@ def __init__(self, *, blob_link: Optional[str] = None, byte_count: Optional[int] self.byte_count = byte_count -class CheckNameAvailabilityRequest(_serialization.Model): - """The check availability request body. +class Budget(CostManagementProxyResource): + """A budget resource. - :ivar name: The name of the resource for which availability needs to be checked. + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource Id. + :vartype id: str + :ivar name: Resource name. :vartype name: str - :ivar type: The resource type. + :ivar type: Resource type. :vartype type: 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 category: The category of the budget. + + + * 'Cost' defines a Budget. + * 'ReservationUtilization' defines a Reservation Utilization Alert Rule. Known values are: + "Cost" and "ReservationUtilization". + :vartype category: str or ~azure.mgmt.costmanagement.models.CategoryType + :ivar amount: The total amount of cost to track with the budget. + + Supported for CategoryType(s): Cost. + + Required for CategoryType(s): Cost. + :vartype amount: float + :ivar time_grain: The time covered by a budget. Tracking of the amount will be reset based on + the time grain. + + Supported for CategoryType(s): Cost, ReservationUtilization. + + Supported timeGrainTypes for **CategoryType: Cost** + + + * Monthly + * Quarterly + * Annually + * BillingMonth* + * BillingQuarter* + * + BillingAnnual* + + *only supported for Web Direct customers. + + Supported timeGrainTypes for **CategoryType: ReservationUtilization** + + * Last7Days + * + Last30Days + + Required for CategoryType(s): Cost, ReservationUtilization. Known values are: "Monthly", + "Quarterly", "Annually", "BillingMonth", "BillingQuarter", "BillingAnnual", "Last7Days", and + "Last30Days". + :vartype time_grain: str or ~azure.mgmt.costmanagement.models.TimeGrainType + :ivar time_period: The time period that defines the active period of the budget. The budget + will evaluate data on or after the startDate and will expire on the endDate. + + Supported for CategoryType(s): Cost, ReservationUtilization. + + Required for CategoryType(s): Cost, ReservationUtilization. + :vartype time_period: ~azure.mgmt.costmanagement.models.BudgetTimePeriod + :ivar filter: May be used to filter budgets by user-specified dimensions and/or tags. + + Supported for CategoryType(s): Cost, ReservationUtilization. + :vartype filter: ~azure.mgmt.costmanagement.models.BudgetFilter + :ivar current_spend: The current amount of cost which is being tracked for a budget. + + Supported for CategoryType(s): Cost. + :vartype current_spend: ~azure.mgmt.costmanagement.models.CurrentSpend + :ivar notifications: Dictionary of notifications associated with the budget. + + Supported for CategoryType(s): Cost, ReservationUtilization. + + + * Constraints for **CategoryType: Cost** - Budget can have up to 5 notifications with + thresholdType: Actual and 5 notifications with thresholdType: Forecasted. + * Constraints for **CategoryType: ReservationUtilization** - Only one notification allowed. + thresholdType is not applicable. + :vartype notifications: dict[str, ~azure.mgmt.costmanagement.models.Notification] + :ivar forecast_spend: The forecasted cost which is being tracked for a budget. + + Supported for CategoryType(s): Cost. + :vartype forecast_spend: ~azure.mgmt.costmanagement.models.ForecastSpend """ + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "current_spend": {"readonly": True}, + "forecast_spend": {"readonly": True}, + } + _attribute_map = { + "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, + "e_tag": {"key": "eTag", "type": "str"}, + "category": {"key": "properties.category", "type": "str"}, + "amount": {"key": "properties.amount", "type": "float"}, + "time_grain": {"key": "properties.timeGrain", "type": "str"}, + "time_period": {"key": "properties.timePeriod", "type": "BudgetTimePeriod"}, + "filter": {"key": "properties.filter", "type": "BudgetFilter"}, + "current_spend": {"key": "properties.currentSpend", "type": "CurrentSpend"}, + "notifications": {"key": "properties.notifications", "type": "{Notification}"}, + "forecast_spend": {"key": "properties.forecastSpend", "type": "ForecastSpend"}, } - def __init__(self, *, name: Optional[str] = None, type: Optional[str] = None, **kwargs: Any) -> None: + def __init__( + self, + *, + e_tag: Optional[str] = None, + category: Optional[Union[str, "_models.CategoryType"]] = None, + amount: Optional[float] = None, + time_grain: Optional[Union[str, "_models.TimeGrainType"]] = None, + time_period: Optional["_models.BudgetTimePeriod"] = None, + filter: Optional["_models.BudgetFilter"] = None, # pylint: disable=redefined-builtin + notifications: Optional[Dict[str, "_models.Notification"]] = None, + **kwargs: Any + ) -> None: """ - :keyword name: The name of the resource for which availability needs to be checked. + :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 + :keyword category: The category of the budget. + + + * 'Cost' defines a Budget. + * 'ReservationUtilization' defines a Reservation Utilization Alert Rule. Known values are: + "Cost" and "ReservationUtilization". + :paramtype category: str or ~azure.mgmt.costmanagement.models.CategoryType + :keyword amount: The total amount of cost to track with the budget. + + Supported for CategoryType(s): Cost. + + Required for CategoryType(s): Cost. + :paramtype amount: float + :keyword time_grain: The time covered by a budget. Tracking of the amount will be reset based + on the time grain. + + Supported for CategoryType(s): Cost, ReservationUtilization. + + Supported timeGrainTypes for **CategoryType: Cost** + + + * Monthly + * Quarterly + * Annually + * BillingMonth* + * BillingQuarter* + * + BillingAnnual* + + *only supported for Web Direct customers. + + Supported timeGrainTypes for **CategoryType: ReservationUtilization** + + * Last7Days + * + Last30Days + + Required for CategoryType(s): Cost, ReservationUtilization. Known values are: "Monthly", + "Quarterly", "Annually", "BillingMonth", "BillingQuarter", "BillingAnnual", "Last7Days", and + "Last30Days". + :paramtype time_grain: str or ~azure.mgmt.costmanagement.models.TimeGrainType + :keyword time_period: The time period that defines the active period of the budget. The budget + will evaluate data on or after the startDate and will expire on the endDate. + + Supported for CategoryType(s): Cost, ReservationUtilization. + + Required for CategoryType(s): Cost, ReservationUtilization. + :paramtype time_period: ~azure.mgmt.costmanagement.models.BudgetTimePeriod + :keyword filter: May be used to filter budgets by user-specified dimensions and/or tags. + + Supported for CategoryType(s): Cost, ReservationUtilization. + :paramtype filter: ~azure.mgmt.costmanagement.models.BudgetFilter + :keyword notifications: Dictionary of notifications associated with the budget. + + Supported for CategoryType(s): Cost, ReservationUtilization. + + + * Constraints for **CategoryType: Cost** - Budget can have up to 5 notifications with + thresholdType: Actual and 5 notifications with thresholdType: Forecasted. + * Constraints for **CategoryType: ReservationUtilization** - Only one notification allowed. + thresholdType is not applicable. + :paramtype notifications: dict[str, ~azure.mgmt.costmanagement.models.Notification] + """ + super().__init__(e_tag=e_tag, **kwargs) + self.category = category + self.amount = amount + self.time_grain = time_grain + self.time_period = time_period + self.filter = filter + self.current_spend = None + self.notifications = notifications + self.forecast_spend = 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 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. Known values are: "In" and "In". + :vartype operator: str or ~azure.mgmt.costmanagement.models.BudgetOperatorType + :ivar values: Array of values to use for comparison. Required. + :vartype values: list[str] + """ + + _validation = { + "name": {"required": True}, + "operator": {"required": True}, + "values": {"required": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "operator": {"key": "operator", "type": "str"}, + "values": {"key": "values", "type": "[str]"}, + } + + 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 type: The resource type. - :paramtype type: str + :keyword operator: The operator to use for comparison. Required. Known values are: "In" and + "In". + :paramtype operator: str or ~azure.mgmt.costmanagement.models.BudgetOperatorType + :keyword values: Array of values to use for comparison. Required. + :paramtype values: list[str] """ super().__init__(**kwargs) self.name = name - self.type = type + self.operator = operator + self.values = values -class CheckNameAvailabilityResponse(_serialization.Model): - """The check availability result. +class BudgetFilter(_serialization.Model): + """May be used to filter budgets by user-specified dimensions and/or tags. - :ivar name_available: Indicates if the resource name is available. - :vartype name_available: bool - :ivar reason: The reason why the given name is not available. Known values are: "Invalid" and - "AlreadyExists". - :vartype reason: str or ~azure.mgmt.costmanagement.models.CheckNameAvailabilityReason - :ivar message: Detailed reason why the given name is available. - :vartype message: str + Supported for CategoryType(s): Cost, ReservationUtilization. + + :ivar and_property: The logical "AND" expression. Must have at least 2 items. + + Supported for CategoryType(s): Cost. + :vartype and_property: list[~azure.mgmt.costmanagement.models.BudgetFilterProperties] + :ivar dimensions: Has comparison expression for a dimension. + + Supported for CategoryType(s): Cost, ReservationUtilization. + + Supported dimension names for **CategoryType: ReservationUtilization** + + + * ReservationId + * ReservedResourceType. + :vartype dimensions: ~azure.mgmt.costmanagement.models.BudgetComparisonExpression + :ivar tags: Has comparison expression for a tag. + + Supported for CategoryType(s): Cost. + :vartype tags: ~azure.mgmt.costmanagement.models.BudgetComparisonExpression + """ + + _attribute_map = { + "and_property": {"key": "and", "type": "[BudgetFilterProperties]"}, + "dimensions": {"key": "dimensions", "type": "BudgetComparisonExpression"}, + "tags": {"key": "tags", "type": "BudgetComparisonExpression"}, + } + + def __init__( + self, + *, + and_property: Optional[List["_models.BudgetFilterProperties"]] = None, + dimensions: Optional["_models.BudgetComparisonExpression"] = None, + tags: Optional["_models.BudgetComparisonExpression"] = None, + **kwargs: Any + ) -> None: + """ + :keyword and_property: The logical "AND" expression. Must have at least 2 items. + + Supported for CategoryType(s): Cost. + :paramtype and_property: list[~azure.mgmt.costmanagement.models.BudgetFilterProperties] + :keyword dimensions: Has comparison expression for a dimension. + + Supported for CategoryType(s): Cost, ReservationUtilization. + + Supported dimension names for **CategoryType: ReservationUtilization** + + + * ReservationId + * ReservedResourceType. + :paramtype dimensions: ~azure.mgmt.costmanagement.models.BudgetComparisonExpression + :keyword tags: Has comparison expression for a tag. + + Supported for CategoryType(s): Cost. + :paramtype tags: ~azure.mgmt.costmanagement.models.BudgetComparisonExpression + """ + super().__init__(**kwargs) + self.and_property = and_property + self.dimensions = dimensions + self.tags = tags + + +class BudgetFilterProperties(_serialization.Model): + """The Dimensions or Tags to filter a budget by. + + Supported for CategoryType(s): Cost, ReservationUtilization. + + :ivar dimensions: Has comparison expression for a dimension. + + Supported for CategoryType(s): Cost, ReservationUtilization. + + Supported dimension names for **CategoryType: ReservationUtilization** + + + * ReservationId + * ReservedResourceType. + :vartype dimensions: ~azure.mgmt.costmanagement.models.BudgetComparisonExpression + :ivar tags: Has comparison expression for a tag. + + Supported for CategoryType(s): Cost. + :vartype tags: ~azure.mgmt.costmanagement.models.BudgetComparisonExpression """ _attribute_map = { - "name_available": {"key": "nameAvailable", "type": "bool"}, - "reason": {"key": "reason", "type": "str"}, - "message": {"key": "message", "type": "str"}, + "dimensions": {"key": "dimensions", "type": "BudgetComparisonExpression"}, + "tags": {"key": "tags", "type": "BudgetComparisonExpression"}, + } + + def __init__( + self, + *, + dimensions: Optional["_models.BudgetComparisonExpression"] = None, + tags: Optional["_models.BudgetComparisonExpression"] = None, + **kwargs: Any + ) -> None: + """ + :keyword dimensions: Has comparison expression for a dimension. + + Supported for CategoryType(s): Cost, ReservationUtilization. + + Supported dimension names for **CategoryType: ReservationUtilization** + + + * ReservationId + * ReservedResourceType. + :paramtype dimensions: ~azure.mgmt.costmanagement.models.BudgetComparisonExpression + :keyword tags: Has comparison expression for a tag. + + Supported for CategoryType(s): Cost. + :paramtype tags: ~azure.mgmt.costmanagement.models.BudgetComparisonExpression + """ + super().__init__(**kwargs) + self.dimensions = dimensions + self.tags = tags + + +class BudgetsListResult(_serialization.Model): + """Result of listing budgets. It contains a list of available budgets in the scope provided. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: The list of budgets. + :vartype value: list[~azure.mgmt.costmanagement.models.Budget] + :ivar next_link: The link (url) to the next page of results. + It's null for now, added for future use. + :vartype next_link: str + """ + + _validation = { + "value": {"readonly": True}, + "next_link": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[Budget]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + self.next_link = None + + +class BudgetTimePeriod(_serialization.Model): + """The time period that defines the active period of the budget. The budget will evaluate data on + or after the startDate and will expire on the endDate. + + Supported for CategoryType(s): Cost, ReservationUtilization. + + Required for CategoryType(s): Cost, ReservationUtilization. + + All required parameters must be populated in order to send to server. + + :ivar start_date: The start date for the budget. + + + * + Constraints for **CategoryType: Cost** - Must be first of the month and should be less than + the end date. Budget start date must be on or after June 1, 2017. Future start date should not + be more than twelve months. Past start date should be selected within the timegrain period. + + * + Constraints for **CategoryType: ReservationUtilization** - Must be on or after the current + date and less than the end date. Required. + :vartype start_date: ~datetime.datetime + :ivar end_date: The end date for the budget. + + + * + Constraints for **CategoryType: Cost** - No constraints. If not provided, we default this to + 10 years from the start date. + + * + Constraints for **CategoryType: ReservationUtilization** - End date cannot be more than 3 + years after the start date. + :vartype end_date: ~datetime.datetime + """ + + _validation = { + "start_date": {"required": True}, + } + + _attribute_map = { + "start_date": {"key": "startDate", "type": "iso-8601"}, + "end_date": {"key": "endDate", "type": "iso-8601"}, + } + + 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. + + + * + Constraints for **CategoryType: Cost** - Must be first of the month and should be less than + the end date. Budget start date must be on or after June 1, 2017. Future start date should not + be more than twelve months. Past start date should be selected within the timegrain period. + + * + Constraints for **CategoryType: ReservationUtilization** - Must be on or after the current + date and less than the end date. Required. + :paramtype start_date: ~datetime.datetime + :keyword end_date: The end date for the budget. + + + * + Constraints for **CategoryType: Cost** - No constraints. If not provided, we default this to + 10 years from the start date. + + * + Constraints for **CategoryType: ReservationUtilization** - End date cannot be more than 3 + years after the start date. + :paramtype end_date: ~datetime.datetime + """ + super().__init__(**kwargs) + self.start_date = start_date + self.end_date = end_date + + +class CheckNameAvailabilityRequest(_serialization.Model): + """The check availability request body. + + :ivar name: The name of the resource for which availability needs to be checked. + :vartype name: str + :ivar type: The resource type. + :vartype type: str + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, *, name: Optional[str] = None, type: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword name: The name of the resource for which availability needs to be checked. + :paramtype name: str + :keyword type: The resource type. + :paramtype type: str + """ + super().__init__(**kwargs) + self.name = name + self.type = type + + +class CheckNameAvailabilityResponse(_serialization.Model): + """The check availability result. + + :ivar name_available: Indicates if the resource name is available. + :vartype name_available: bool + :ivar reason: The reason why the given name is not available. Known values are: "Invalid" and + "AlreadyExists". + :vartype reason: str or ~azure.mgmt.costmanagement.models.CheckNameAvailabilityReason + :ivar message: Detailed reason why the given name is available. + :vartype message: str + """ + + _attribute_map = { + "name_available": {"key": "nameAvailable", "type": "bool"}, + "reason": {"key": "reason", "type": "str"}, + "message": {"key": "message", "type": "str"}, + } + + def __init__( + self, + *, + name_available: Optional[bool] = None, + reason: Optional[Union[str, "_models.CheckNameAvailabilityReason"]] = None, + message: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword name_available: Indicates if the resource name is available. + :paramtype name_available: bool + :keyword reason: The reason why the given name is not available. Known values are: "Invalid" + and "AlreadyExists". + :paramtype reason: str or ~azure.mgmt.costmanagement.models.CheckNameAvailabilityReason + :keyword message: Detailed reason why the given name is available. + :paramtype message: str + """ + super().__init__(**kwargs) + self.name_available = name_available + self.reason = reason + self.message = message + + +class CommonExportProperties(_serialization.Model): + """The common properties of the export. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar format: The format of the export being delivered. Known values are: "Csv", "Parquet", and + "Delta". + :vartype format: str or ~azure.mgmt.costmanagement.models.FormatType + :ivar delivery_info: Has delivery information for the export. Required. + :vartype delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo + :ivar definition: Has the definition for the export. Required. + :vartype definition: ~azure.mgmt.costmanagement.models.ExportDefinition + :ivar run_history: If requested, has the most recent run history for the export. + :vartype run_history: ~azure.mgmt.costmanagement.models.ExportExecutionListResult + :ivar partition_data: If set to true, exported data will be partitioned by size and placed in a + blob directory together with a manifest file. Note: this option is currently available only for + Microsoft Customer Agreement commerce scopes. + :vartype partition_data: bool + :ivar data_overwrite_behavior: Allow customers to select overwrite + data(OverwritePreviousReport) for exports. This setting will enable overwrite data for the same + month in customer storage account. By default set to CreateNewReport. Known values are: + "OverwritePreviousReport" and "CreateNewReport". + :vartype data_overwrite_behavior: str or + ~azure.mgmt.costmanagement.models.DataOverwriteBehaviorType + :ivar compression_mode: Allow customers to select compress data(gzip) for exports. This setting + will enable destination file compression scheme at runtime. By default set to None. Known + values are: "gzip" and "None". + :vartype compression_mode: str or ~azure.mgmt.costmanagement.models.CompressionModeType + :ivar export_description: The export description set by customer at time of export + creation/update. + :vartype export_description: str + :ivar next_run_time_estimate: If the export has an active schedule, provides an estimate of the + next run time. + :vartype next_run_time_estimate: ~datetime.datetime + :ivar system_suspension_context: The export suspension reason if export is in SystemSuspended + state. + :vartype system_suspension_context: ~azure.mgmt.costmanagement.models.ExportSuspensionContext + """ + + _validation = { + "delivery_info": {"required": True}, + "definition": {"required": True}, + "next_run_time_estimate": {"readonly": True}, + "system_suspension_context": {"readonly": True}, + } + + _attribute_map = { + "format": {"key": "format", "type": "str"}, + "delivery_info": {"key": "deliveryInfo", "type": "ExportDeliveryInfo"}, + "definition": {"key": "definition", "type": "ExportDefinition"}, + "run_history": {"key": "runHistory", "type": "ExportExecutionListResult"}, + "partition_data": {"key": "partitionData", "type": "bool"}, + "data_overwrite_behavior": {"key": "dataOverwriteBehavior", "type": "str"}, + "compression_mode": {"key": "compressionMode", "type": "str"}, + "export_description": {"key": "exportDescription", "type": "str"}, + "next_run_time_estimate": {"key": "nextRunTimeEstimate", "type": "iso-8601"}, + "system_suspension_context": {"key": "systemSuspensionContext", "type": "ExportSuspensionContext"}, + } + + def __init__( + self, + *, + delivery_info: "_models.ExportDeliveryInfo", + definition: "_models.ExportDefinition", + format: Optional[Union[str, "_models.FormatType"]] = None, + run_history: Optional["_models.ExportExecutionListResult"] = None, + partition_data: Optional[bool] = None, + data_overwrite_behavior: Optional[Union[str, "_models.DataOverwriteBehaviorType"]] = None, + compression_mode: Optional[Union[str, "_models.CompressionModeType"]] = None, + export_description: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword format: The format of the export being delivered. Known values are: "Csv", "Parquet", + and "Delta". + :paramtype format: str or ~azure.mgmt.costmanagement.models.FormatType + :keyword delivery_info: Has delivery information for the export. Required. + :paramtype delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo + :keyword definition: Has the definition for the export. Required. + :paramtype definition: ~azure.mgmt.costmanagement.models.ExportDefinition + :keyword run_history: If requested, has the most recent run history for the export. + :paramtype run_history: ~azure.mgmt.costmanagement.models.ExportExecutionListResult + :keyword partition_data: If set to true, exported data will be partitioned by size and placed + in a blob directory together with a manifest file. Note: this option is currently available + only for Microsoft Customer Agreement commerce scopes. + :paramtype partition_data: bool + :keyword data_overwrite_behavior: Allow customers to select overwrite + data(OverwritePreviousReport) for exports. This setting will enable overwrite data for the same + month in customer storage account. By default set to CreateNewReport. Known values are: + "OverwritePreviousReport" and "CreateNewReport". + :paramtype data_overwrite_behavior: str or + ~azure.mgmt.costmanagement.models.DataOverwriteBehaviorType + :keyword compression_mode: Allow customers to select compress data(gzip) for exports. This + setting will enable destination file compression scheme at runtime. By default set to None. + Known values are: "gzip" and "None". + :paramtype compression_mode: str or ~azure.mgmt.costmanagement.models.CompressionModeType + :keyword export_description: The export description set by customer at time of export + creation/update. + :paramtype export_description: str + """ + super().__init__(**kwargs) + self.format = format + self.delivery_info = delivery_info + self.definition = definition + self.run_history = run_history + self.partition_data = partition_data + self.data_overwrite_behavior = data_overwrite_behavior + self.compression_mode = compression_mode + self.export_description = export_description + self.next_run_time_estimate = None + self.system_suspension_context = None + + +class CostAllocationProportion(_serialization.Model): + """Target resources and allocation. + + All required parameters must be populated in order to send to server. + + :ivar name: Target resource for cost allocation. Required. + :vartype name: str + :ivar percentage: Percentage of source cost to allocate to this resource. This value can be + specified to two decimal places and the total percentage of all resources in this rule must sum + to 100.00. Required. + :vartype percentage: float + """ + + _validation = { + "name": {"required": True}, + "percentage": {"required": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "percentage": {"key": "percentage", "type": "float"}, + } + + def __init__(self, *, name: str, percentage: float, **kwargs: Any) -> None: + """ + :keyword name: Target resource for cost allocation. Required. + :paramtype name: str + :keyword percentage: Percentage of source cost to allocate to this resource. This value can be + specified to two decimal places and the total percentage of all resources in this rule must sum + to 100.00. Required. + :paramtype percentage: float + """ + super().__init__(**kwargs) + self.name = name + self.percentage = percentage + + +class CostAllocationResource(_serialization.Model): + """Common values for resources for cost allocation. + + All required parameters must be populated in order to send to server. + + :ivar resource_type: Type of resources contained in this cost allocation rule. Required. Known + values are: "Dimension" and "Tag". + :vartype resource_type: str or ~azure.mgmt.costmanagement.models.CostAllocationResourceType + :ivar name: If resource type is dimension, this must be either ResourceGroupName or + SubscriptionId. If resource type is tag, this must be a valid Azure tag. Required. + :vartype name: str + """ + + _validation = { + "resource_type": {"required": True}, + "name": {"required": True}, + } + + _attribute_map = { + "resource_type": {"key": "resourceType", "type": "str"}, + "name": {"key": "name", "type": "str"}, + } + + def __init__( + self, *, resource_type: Union[str, "_models.CostAllocationResourceType"], name: str, **kwargs: Any + ) -> None: + """ + :keyword resource_type: Type of resources contained in this cost allocation rule. Required. + Known values are: "Dimension" and "Tag". + :paramtype resource_type: str or ~azure.mgmt.costmanagement.models.CostAllocationResourceType + :keyword name: If resource type is dimension, this must be either ResourceGroupName or + SubscriptionId. If resource type is tag, this must be a valid Azure tag. Required. + :paramtype name: str + """ + super().__init__(**kwargs) + self.resource_type = resource_type + self.name = name + + +class CostAllocationRuleCheckNameAvailabilityRequest(_serialization.Model): # pylint: disable=name-too-long + """The cost allocation rule check name availability request. + + :ivar name: Rule name. + :vartype name: str + :ivar type: Resource type. This is expected to be Microsoft.CostManagement/costAllocationRules. + :vartype type: str + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, *, name: Optional[str] = None, type: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword name: Rule name. + :paramtype name: str + :keyword type: Resource type. This is expected to be + Microsoft.CostManagement/costAllocationRules. + :paramtype type: str + """ + super().__init__(**kwargs) + self.name = name + self.type = type + + +class CostAllocationRuleCheckNameAvailabilityResponse(_serialization.Model): # pylint: disable=name-too-long + """The cost allocation rule check name availability response. + + :ivar name_available: Whether this rule name is available. + :vartype name_available: bool + :ivar reason: The reason this name is not available. Known values are: "Invalid", + "AlreadyExists", and "Valid". + :vartype reason: str or ~azure.mgmt.costmanagement.models.Reason + :ivar message: Error message if the name is not available. + :vartype message: str + """ + + _attribute_map = { + "name_available": {"key": "nameAvailable", "type": "bool"}, + "reason": {"key": "reason", "type": "str"}, + "message": {"key": "message", "type": "str"}, + } + + def __init__( + self, + *, + name_available: Optional[bool] = None, + reason: Optional[Union[str, "_models.Reason"]] = None, + message: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword name_available: Whether this rule name is available. + :paramtype name_available: bool + :keyword reason: The reason this name is not available. Known values are: "Invalid", + "AlreadyExists", and "Valid". + :paramtype reason: str or ~azure.mgmt.costmanagement.models.Reason + :keyword message: Error message if the name is not available. + :paramtype message: str + """ + super().__init__(**kwargs) + self.name_available = name_available + self.reason = reason + self.message = message + + +class CostAllocationRuleDefinition(_serialization.Model): + """The cost allocation rule model definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Azure Resource Manager Id for the rule. This is a read ony value. + :vartype id: str + :ivar name: Name of the rule. This is a read only value. + :vartype name: str + :ivar type: Resource type of the rule. This is a read only value of + Microsoft.CostManagement/CostAllocationRule. + :vartype type: str + :ivar properties: Cost allocation rule properties. + :vartype properties: ~azure.mgmt.costmanagement.models.CostAllocationRuleProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "properties": {"key": "properties", "type": "CostAllocationRuleProperties"}, + } + + def __init__(self, *, properties: Optional["_models.CostAllocationRuleProperties"] = None, **kwargs: Any) -> None: + """ + :keyword properties: Cost allocation rule properties. + :paramtype properties: ~azure.mgmt.costmanagement.models.CostAllocationRuleProperties + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.properties = properties + + +class CostAllocationRuleDetails(_serialization.Model): + """Resource details of the cost allocation rule. + + :ivar source_resources: Source resources for cost allocation. At this time, this list can + contain no more than one element. + :vartype source_resources: list[~azure.mgmt.costmanagement.models.SourceCostAllocationResource] + :ivar target_resources: Target resources for cost allocation. At this time, this list can + contain no more than one element. + :vartype target_resources: list[~azure.mgmt.costmanagement.models.TargetCostAllocationResource] + """ + + _attribute_map = { + "source_resources": {"key": "sourceResources", "type": "[SourceCostAllocationResource]"}, + "target_resources": {"key": "targetResources", "type": "[TargetCostAllocationResource]"}, + } + + def __init__( + self, + *, + source_resources: Optional[List["_models.SourceCostAllocationResource"]] = None, + target_resources: Optional[List["_models.TargetCostAllocationResource"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword source_resources: Source resources for cost allocation. At this time, this list can + contain no more than one element. + :paramtype source_resources: + list[~azure.mgmt.costmanagement.models.SourceCostAllocationResource] + :keyword target_resources: Target resources for cost allocation. At this time, this list can + contain no more than one element. + :paramtype target_resources: + list[~azure.mgmt.costmanagement.models.TargetCostAllocationResource] + """ + super().__init__(**kwargs) + self.source_resources = source_resources + self.target_resources = target_resources + + +class CostAllocationRuleList(_serialization.Model): + """Result of listing cost allocation rules. It contains a list of available rules in the billing + account or enterprise enrollment provided. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: The list of cost allocation rules. + :vartype value: list[~azure.mgmt.costmanagement.models.CostAllocationRuleDefinition] + :ivar next_link: URL to get the next set of rule list results if there are any. + :vartype next_link: str + """ + + _validation = { + "next_link": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[CostAllocationRuleDefinition]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - *, - name_available: Optional[bool] = None, - reason: Optional[Union[str, "_models.CheckNameAvailabilityReason"]] = None, - message: Optional[str] = None, - **kwargs: Any - ) -> None: + def __init__(self, *, value: Optional[List["_models.CostAllocationRuleDefinition"]] = None, **kwargs: Any) -> None: """ - :keyword name_available: Indicates if the resource name is available. - :paramtype name_available: bool - :keyword reason: The reason why the given name is not available. Known values are: "Invalid" - and "AlreadyExists". - :paramtype reason: str or ~azure.mgmt.costmanagement.models.CheckNameAvailabilityReason - :keyword message: Detailed reason why the given name is available. - :paramtype message: str + :keyword value: The list of cost allocation rules. + :paramtype value: list[~azure.mgmt.costmanagement.models.CostAllocationRuleDefinition] """ super().__init__(**kwargs) - self.name_available = name_available - self.reason = reason - self.message = message + self.value = value + self.next_link = None -class CommonExportProperties(_serialization.Model): - """The common properties of the export. +class CostAllocationRuleProperties(_serialization.Model): + """The properties of a cost allocation rule. 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 format: The format of the export being delivered. Currently only 'Csv' is supported. - "Csv" - :vartype format: str or ~azure.mgmt.costmanagement.models.FormatType - :ivar delivery_info: Has delivery information for the export. Required. - :vartype delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo - :ivar definition: Has the definition for the export. Required. - :vartype definition: ~azure.mgmt.costmanagement.models.ExportDefinition - :ivar run_history: If requested, has the most recent run history for the export. - :vartype run_history: ~azure.mgmt.costmanagement.models.ExportExecutionListResult - :ivar partition_data: If set to true, exported data will be partitioned by size and placed in a - blob directory together with a manifest file. Note: this option is currently available only for - Microsoft Customer Agreement commerce scopes. - :vartype partition_data: bool - :ivar next_run_time_estimate: If the export has an active schedule, provides an estimate of the - next run time. - :vartype next_run_time_estimate: ~datetime.datetime + :ivar description: Description of a cost allocation rule. + :vartype description: str + :ivar details: Resource information for the cost allocation rule. Required. + :vartype details: ~azure.mgmt.costmanagement.models.CostAllocationRuleDetails + :ivar status: Status of the rule. Required. Known values are: "NotActive", "Active", and + "Processing". + :vartype status: str or ~azure.mgmt.costmanagement.models.RuleStatus + :ivar created_date: Time at which the rule was created. Rules that change cost for the same + resource are applied in order of creation. + :vartype created_date: ~datetime.datetime + :ivar updated_date: Time at which the rule was last updated. + :vartype updated_date: ~datetime.datetime """ _validation = { - "delivery_info": {"required": True}, - "definition": {"required": True}, - "next_run_time_estimate": {"readonly": True}, + "details": {"required": True}, + "status": {"required": True}, + "created_date": {"readonly": True}, + "updated_date": {"readonly": True}, } _attribute_map = { - "format": {"key": "format", "type": "str"}, - "delivery_info": {"key": "deliveryInfo", "type": "ExportDeliveryInfo"}, - "definition": {"key": "definition", "type": "ExportDefinition"}, - "run_history": {"key": "runHistory", "type": "ExportExecutionListResult"}, - "partition_data": {"key": "partitionData", "type": "bool"}, - "next_run_time_estimate": {"key": "nextRunTimeEstimate", "type": "iso-8601"}, + "description": {"key": "description", "type": "str"}, + "details": {"key": "details", "type": "CostAllocationRuleDetails"}, + "status": {"key": "status", "type": "str"}, + "created_date": {"key": "createdDate", "type": "iso-8601"}, + "updated_date": {"key": "updatedDate", "type": "iso-8601"}, } def __init__( self, *, - delivery_info: "_models.ExportDeliveryInfo", - definition: "_models.ExportDefinition", - format: Optional[Union[str, "_models.FormatType"]] = None, - run_history: Optional["_models.ExportExecutionListResult"] = None, - partition_data: Optional[bool] = None, + details: "_models.CostAllocationRuleDetails", + status: Union[str, "_models.RuleStatus"], + description: Optional[str] = None, **kwargs: Any ) -> None: """ - :keyword format: The format of the export being delivered. Currently only 'Csv' is supported. - "Csv" - :paramtype format: str or ~azure.mgmt.costmanagement.models.FormatType - :keyword delivery_info: Has delivery information for the export. Required. - :paramtype delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo - :keyword definition: Has the definition for the export. Required. - :paramtype definition: ~azure.mgmt.costmanagement.models.ExportDefinition - :keyword run_history: If requested, has the most recent run history for the export. - :paramtype run_history: ~azure.mgmt.costmanagement.models.ExportExecutionListResult - :keyword partition_data: If set to true, exported data will be partitioned by size and placed - in a blob directory together with a manifest file. Note: this option is currently available - only for Microsoft Customer Agreement commerce scopes. - :paramtype partition_data: bool + :keyword description: Description of a cost allocation rule. + :paramtype description: str + :keyword details: Resource information for the cost allocation rule. Required. + :paramtype details: ~azure.mgmt.costmanagement.models.CostAllocationRuleDetails + :keyword status: Status of the rule. Required. Known values are: "NotActive", "Active", and + "Processing". + :paramtype status: str or ~azure.mgmt.costmanagement.models.RuleStatus """ super().__init__(**kwargs) - self.format = format - self.delivery_info = delivery_info - self.definition = definition - self.run_history = run_history - self.partition_data = partition_data - self.next_run_time_estimate = None + self.description = description + self.details = details + self.status = status + self.created_date = None + self.updated_date = None -class CostDetailsOperationResults(_serialization.Model): # pylint: disable=too-many-instance-attributes +class CostDetailsOperationResults(_serialization.Model): """The result of the long running operation for cost details Api. :ivar id: The id of the long running operation. @@ -1242,7 +2269,7 @@ class CostDetailsTimePeriod(_serialization.Model): """The start and end date for pulling data for the cost detailed report. API only allows data to be pulled for 1 month or less and no older than 13 months. - 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: The start date to pull data from. example format 2020-03-15. Required. :vartype start: str @@ -1425,7 +2452,37 @@ def __init__(self, **kwargs: Any) -> None: self.tags = None -class Dimension(CostManagementResource): # pylint: disable=too-many-instance-attributes +class CurrentSpend(_serialization.Model): + """The current amount of cost which is being tracked for a budget. + + Supported for CategoryType(s): Cost. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar amount: The total amount of cost which is being tracked by the budget. + :vartype amount: float + :ivar unit: The unit of measure for the budget amount. + :vartype unit: str + """ + + _validation = { + "amount": {"readonly": True}, + "unit": {"readonly": True}, + } + + _attribute_map = { + "amount": {"key": "amount", "type": "float"}, + "unit": {"key": "unit", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.amount = None + self.unit = None + + +class Dimension(CostManagementResource): """List of Dimension. Variables are only populated by the server, and will be ignored when sending a request. @@ -1541,7 +2598,7 @@ def __init__(self, **kwargs: Any) -> None: self.value = None -class DismissAlertPayload(_serialization.Model): # pylint: disable=too-many-instance-attributes +class DismissAlertPayload(_serialization.Model): """The request payload to update an alert. :ivar definition: defines the type of alert. @@ -1679,6 +2736,290 @@ def __init__( self.download_url = download_url +class EAPriceSheetProperties(_serialization.Model): + """The properties of the EA price sheet. Properties supported with version 2024-10-01-preview are + as below. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar enrollment_number: Unique identifier for the EA billing account. + :vartype enrollment_number: str + :ivar service_family: Type of Azure service. For example, Compute, Analytics, and Security. + :vartype service_family: float + :ivar product: Name of the product accruing the charges. + :vartype product: str + :ivar product_id: Unique identifier for the product whose meter is consumed. + :vartype product_id: str + :ivar sku_id: Unique identifier of the SKU. + :vartype sku_id: str + :ivar unit_of_measure: How usage is measured for the service. Note: The field “Unit” has been + removed with version 2023-11-01 as a duplicate of “UnitOfMeasure”, please use the field + “UnitOfMeasure”. + :vartype unit_of_measure: str + :ivar meter_id: Unique identifier of the meter. + :vartype meter_id: str + :ivar meter_name: Name of the meter. The meter represents the deployable resource of an Azure + service. + :vartype meter_name: str + :ivar meter_type: Name of the meter type. + :vartype meter_type: str + :ivar offer_id: Determines the Azure offer associated with this meter. [Learn more about Azure + offers] (https://azure.microsoft.com/en-us/support/legal/offer-details/). + :vartype offer_id: str + :ivar meter_category: Name of the classification category for the meter. For example, Cloud + services, Networking, etc. + :vartype meter_category: str + :ivar meter_sub_category: Name of the meter subclassification category. + :vartype meter_sub_category: str + :ivar meter_region: Name of the Azure region where the meter for the service is available. + :vartype meter_region: str + :ivar effective_start_date: Effective start date of the Price Sheet billing period. + :vartype effective_start_date: ~datetime.datetime + :ivar effective_end_date: Effective end date of the Price Sheet billing period. + :vartype effective_end_date: ~datetime.datetime + :ivar unit_price: The per-unit price at the time of billing for a given product or service, + inclusive of any negotiated discounts on top of the market price. + + For PriceType ReservedInstance, unit price reflects the total cost of the 1 or 3-year + commitment including discounts. + + Note: The unit price isn't the same as the effective price in usage details downloads when + services have differential prices across tiers. + + If services have multi-tiered pricing, the effective price is a blended rate across the tiers + and doesn't show a tier-specific unit price. The blended price or effective price is the net + price for the consumed quantity spanning across the multiple tiers (where each tier has a + specific unit price). + :vartype unit_price: str + :ivar base_price: The unit price at the time the customer signs on or the unit price at the + time of service meter GA launch if it is after sign-on. + + This is applicable for Enterprise Agreement users. + :vartype base_price: str + :ivar market_price: The current list price for a given product or service. This price is + without any negotiations and is based on your Microsoft Agreement type. + + For PriceType Consumption, market price is reflected as the pay-as-you-go price. + + For PriceType Savings Plan, market price reflects the Savings plan benefit on top of + pay-as-you-go price for the corresponding commitment term. + + For PriceType ReservedInstance, market price reflects the total price of the 1 or 3-year + commitment. + + Note: For EA customers with no negotiations, market price may appear rounded to a different + decimal precision than unit price. + :vartype market_price: str + :ivar included_quantity: Quantities of a specific service to which an EA customer is entitled + to consume without incremental charges. + :vartype included_quantity: str + :ivar currency_code: Currency in which the Enterprise Agreement was signed. + :vartype currency_code: str + :ivar term: Term length for Azure Savings Plan or Reservation term – one year or three years + (P1Y or P3Y). + :vartype term: str + :ivar price_type: Price type for a product. For example, an Azure resource with a pay-as-you-go + rate with priceType as Consumption. Other price types include ReservedInstance and Savings + Plan. + :vartype price_type: str + :ivar part_number: Part number associated with the meter. + :vartype part_number: str + """ + + _validation = { + "enrollment_number": {"readonly": True}, + "service_family": {"readonly": True}, + "product": {"readonly": True}, + "product_id": {"readonly": True}, + "sku_id": {"readonly": True}, + "unit_of_measure": {"readonly": True}, + "meter_id": {"readonly": True}, + "meter_name": {"readonly": True}, + "meter_type": {"readonly": True}, + "offer_id": {"readonly": True}, + "meter_category": {"readonly": True}, + "meter_sub_category": {"readonly": True}, + "meter_region": {"readonly": True}, + "effective_start_date": {"readonly": True}, + "effective_end_date": {"readonly": True}, + "unit_price": {"readonly": True}, + "base_price": {"readonly": True}, + "market_price": {"readonly": True}, + "included_quantity": {"readonly": True}, + "currency_code": {"readonly": True}, + "term": {"readonly": True}, + "price_type": {"readonly": True}, + "part_number": {"readonly": True}, + } + + _attribute_map = { + "enrollment_number": {"key": "enrollmentNumber", "type": "str"}, + "service_family": {"key": "serviceFamily", "type": "float"}, + "product": {"key": "product", "type": "str"}, + "product_id": {"key": "productId", "type": "str"}, + "sku_id": {"key": "skuId", "type": "str"}, + "unit_of_measure": {"key": "unitOfMeasure", "type": "str"}, + "meter_id": {"key": "meterId", "type": "str"}, + "meter_name": {"key": "meterName", "type": "str"}, + "meter_type": {"key": "meterType", "type": "str"}, + "offer_id": {"key": "offerId", "type": "str"}, + "meter_category": {"key": "meterCategory", "type": "str"}, + "meter_sub_category": {"key": "meterSubCategory", "type": "str"}, + "meter_region": {"key": "meterRegion", "type": "str"}, + "effective_start_date": {"key": "effectiveStartDate", "type": "iso-8601"}, + "effective_end_date": {"key": "effectiveEndDate", "type": "iso-8601"}, + "unit_price": {"key": "unitPrice", "type": "str"}, + "base_price": {"key": "basePrice", "type": "str"}, + "market_price": {"key": "marketPrice", "type": "str"}, + "included_quantity": {"key": "includedQuantity", "type": "str"}, + "currency_code": {"key": "currencyCode", "type": "str"}, + "term": {"key": "term", "type": "str"}, + "price_type": {"key": "priceType", "type": "str"}, + "part_number": {"key": "partNumber", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.enrollment_number = None + self.service_family = None + self.product = None + self.product_id = None + self.sku_id = None + self.unit_of_measure = None + self.meter_id = None + self.meter_name = None + self.meter_type = None + self.offer_id = None + self.meter_category = None + self.meter_sub_category = None + self.meter_region = None + self.effective_start_date = None + self.effective_end_date = None + self.unit_price = None + self.base_price = None + self.market_price = None + self.included_quantity = None + self.currency_code = None + self.term = None + self.price_type = None + self.part_number = 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 = None + self.info = 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.costmanagement.models.ErrorDetail] + :ivar additional_info: The error additional info. + :vartype additional_info: list[~azure.mgmt.costmanagement.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.code = None + self.message = None + self.target = None + self.details = None + self.additional_info = None + + +class ErrorDetailAutoGenerated(_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.costmanagement.models.ErrorDetailAutoGenerated] + :ivar additional_info: The error additional info. + :vartype additional_info: list[~azure.mgmt.costmanagement.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": "[ErrorDetailAutoGenerated]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.code = None + self.message = None + self.target = None + self.details = None + self.additional_info = None + + class ErrorDetails(_serialization.Model): """The details of the error. @@ -1770,6 +3111,48 @@ def __init__(self, *, error: Optional["_models.ErrorDetails"] = None, **kwargs: self.error = error +class ErrorResponseAutoGenerated(_serialization.Model): + """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.costmanagement.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.costmanagement.models.ErrorDetail + """ + super().__init__(**kwargs) + self.error = error + + +class ErrorResponseAutoGenerated2(_serialization.Model): + """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.costmanagement.models.ErrorDetailAutoGenerated + """ + + _attribute_map = { + "error": {"key": "error", "type": "ErrorDetailAutoGenerated"}, + } + + def __init__(self, *, error: Optional["_models.ErrorDetailAutoGenerated"] = None, **kwargs: Any) -> None: + """ + :keyword error: The error object. + :paramtype error: ~azure.mgmt.costmanagement.models.ErrorDetailAutoGenerated + """ + super().__init__(**kwargs) + self.error = error + + class ErrorResponseWithNestedDetails(_serialization.Model): """Error response indicates that the service is not able to process the incoming request. The reason is provided in the error message. @@ -1802,7 +3185,7 @@ def __init__(self, *, error: Optional["_models.ErrorDetailsWithNestedDetails"] = self.error = error -class Export(CostManagementProxyResource): # pylint: disable=too-many-instance-attributes +class Export(CostManagementProxyResource): """An export resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -1816,8 +3199,13 @@ class Export(CostManagementProxyResource): # pylint: disable=too-many-instance- :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 format: The format of the export being delivered. Currently only 'Csv' is supported. - "Csv" + :ivar identity: The managed identity associated with Export. + :vartype identity: ~azure.mgmt.costmanagement.models.SystemAssignedServiceIdentity + :ivar location: The location of the Export's managed identity. Only required when utilizing + managed identity. + :vartype location: str + :ivar format: The format of the export being delivered. Known values are: "Csv", "Parquet", and + "Delta". :vartype format: str or ~azure.mgmt.costmanagement.models.FormatType :ivar delivery_info: Has delivery information for the export. :vartype delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo @@ -1829,9 +3217,25 @@ class Export(CostManagementProxyResource): # pylint: disable=too-many-instance- blob directory together with a manifest file. Note: this option is currently available only for Microsoft Customer Agreement commerce scopes. :vartype partition_data: bool + :ivar data_overwrite_behavior: Allow customers to select overwrite + data(OverwritePreviousReport) for exports. This setting will enable overwrite data for the same + month in customer storage account. By default set to CreateNewReport. Known values are: + "OverwritePreviousReport" and "CreateNewReport". + :vartype data_overwrite_behavior: str or + ~azure.mgmt.costmanagement.models.DataOverwriteBehaviorType + :ivar compression_mode: Allow customers to select compress data(gzip) for exports. This setting + will enable destination file compression scheme at runtime. By default set to None. Known + values are: "gzip" and "None". + :vartype compression_mode: str or ~azure.mgmt.costmanagement.models.CompressionModeType + :ivar export_description: The export description set by customer at time of export + creation/update. + :vartype export_description: str :ivar next_run_time_estimate: If the export has an active schedule, provides an estimate of the next run time. :vartype next_run_time_estimate: ~datetime.datetime + :ivar system_suspension_context: The export suspension reason if export is in SystemSuspended + state. + :vartype system_suspension_context: ~azure.mgmt.costmanagement.models.ExportSuspensionContext :ivar schedule: Has schedule information for the export. :vartype schedule: ~azure.mgmt.costmanagement.models.ExportSchedule """ @@ -1841,6 +3245,7 @@ class Export(CostManagementProxyResource): # pylint: disable=too-many-instance- "name": {"readonly": True}, "type": {"readonly": True}, "next_run_time_estimate": {"readonly": True}, + "system_suspension_context": {"readonly": True}, } _attribute_map = { @@ -1848,12 +3253,18 @@ class Export(CostManagementProxyResource): # pylint: disable=too-many-instance- "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "e_tag": {"key": "eTag", "type": "str"}, + "identity": {"key": "identity", "type": "SystemAssignedServiceIdentity"}, + "location": {"key": "location", "type": "str"}, "format": {"key": "properties.format", "type": "str"}, "delivery_info": {"key": "properties.deliveryInfo", "type": "ExportDeliveryInfo"}, "definition": {"key": "properties.definition", "type": "ExportDefinition"}, "run_history": {"key": "properties.runHistory", "type": "ExportExecutionListResult"}, "partition_data": {"key": "properties.partitionData", "type": "bool"}, + "data_overwrite_behavior": {"key": "properties.dataOverwriteBehavior", "type": "str"}, + "compression_mode": {"key": "properties.compressionMode", "type": "str"}, + "export_description": {"key": "properties.exportDescription", "type": "str"}, "next_run_time_estimate": {"key": "properties.nextRunTimeEstimate", "type": "iso-8601"}, + "system_suspension_context": {"key": "properties.systemSuspensionContext", "type": "ExportSuspensionContext"}, "schedule": {"key": "properties.schedule", "type": "ExportSchedule"}, } @@ -1861,11 +3272,16 @@ def __init__( self, *, e_tag: Optional[str] = None, + identity: Optional["_models.SystemAssignedServiceIdentity"] = None, + location: Optional[str] = None, format: Optional[Union[str, "_models.FormatType"]] = None, delivery_info: Optional["_models.ExportDeliveryInfo"] = None, definition: Optional["_models.ExportDefinition"] = None, run_history: Optional["_models.ExportExecutionListResult"] = None, partition_data: Optional[bool] = None, + data_overwrite_behavior: Optional[Union[str, "_models.DataOverwriteBehaviorType"]] = None, + compression_mode: Optional[Union[str, "_models.CompressionModeType"]] = None, + export_description: Optional[str] = None, schedule: Optional["_models.ExportSchedule"] = None, **kwargs: Any ) -> None: @@ -1873,8 +3289,13 @@ def __init__( :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 - :keyword format: The format of the export being delivered. Currently only 'Csv' is supported. - "Csv" + :keyword identity: The managed identity associated with Export. + :paramtype identity: ~azure.mgmt.costmanagement.models.SystemAssignedServiceIdentity + :keyword location: The location of the Export's managed identity. Only required when utilizing + managed identity. + :paramtype location: str + :keyword format: The format of the export being delivered. Known values are: "Csv", "Parquet", + and "Delta". :paramtype format: str or ~azure.mgmt.costmanagement.models.FormatType :keyword delivery_info: Has delivery information for the export. :paramtype delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo @@ -1886,24 +3307,43 @@ def __init__( in a blob directory together with a manifest file. Note: this option is currently available only for Microsoft Customer Agreement commerce scopes. :paramtype partition_data: bool + :keyword data_overwrite_behavior: Allow customers to select overwrite + data(OverwritePreviousReport) for exports. This setting will enable overwrite data for the same + month in customer storage account. By default set to CreateNewReport. Known values are: + "OverwritePreviousReport" and "CreateNewReport". + :paramtype data_overwrite_behavior: str or + ~azure.mgmt.costmanagement.models.DataOverwriteBehaviorType + :keyword compression_mode: Allow customers to select compress data(gzip) for exports. This + setting will enable destination file compression scheme at runtime. By default set to None. + Known values are: "gzip" and "None". + :paramtype compression_mode: str or ~azure.mgmt.costmanagement.models.CompressionModeType + :keyword export_description: The export description set by customer at time of export + creation/update. + :paramtype export_description: str :keyword schedule: Has schedule information for the export. :paramtype schedule: ~azure.mgmt.costmanagement.models.ExportSchedule """ super().__init__(e_tag=e_tag, **kwargs) + self.identity = identity + self.location = location self.format = format self.delivery_info = delivery_info self.definition = definition self.run_history = run_history self.partition_data = partition_data + self.data_overwrite_behavior = data_overwrite_behavior + self.compression_mode = compression_mode + self.export_description = export_description self.next_run_time_estimate = None + self.system_suspension_context = None self.schedule = schedule class ExportDataset(_serialization.Model): """The definition for data in the export. - :ivar granularity: The granularity of rows in the export. Currently only 'Daily' is supported. - "Daily" + :ivar granularity: The granularity of rows in the export. Currently 'Daily' is supported for + most cases. Known values are: "Daily" and "Monthly". :vartype granularity: str or ~azure.mgmt.costmanagement.models.GranularityType :ivar configuration: The export dataset configuration. :vartype configuration: ~azure.mgmt.costmanagement.models.ExportDatasetConfiguration @@ -1922,8 +3362,8 @@ def __init__( **kwargs: Any ) -> None: """ - :keyword granularity: The granularity of rows in the export. Currently only 'Daily' is - supported. "Daily" + :keyword granularity: The granularity of rows in the export. Currently 'Daily' is supported for + most cases. Known values are: "Daily" and "Monthly". :paramtype granularity: str or ~azure.mgmt.costmanagement.models.GranularityType :keyword configuration: The export dataset configuration. :paramtype configuration: ~azure.mgmt.costmanagement.models.ExportDatasetConfiguration @@ -1934,42 +3374,60 @@ def __init__( class ExportDatasetConfiguration(_serialization.Model): - """The export dataset configuration. Allows columns to be selected for the export. If not provided - then the export will include all available columns. + """The export dataset configuration. - :ivar columns: Array of column names to be included in the export. If not provided then the - export will include all available columns. The available columns can vary by customer channel - (see examples). + :ivar columns: This is on path to deprecation and will not be supported going forward. :vartype columns: list[str] + :ivar data_version: The data version for the selected for the export. If not provided then the + export will default to latest data version. + :vartype data_version: str + :ivar filters: Filters associated with the data sets. + :vartype filters: list[~azure.mgmt.costmanagement.models.FilterItems] """ _attribute_map = { "columns": {"key": "columns", "type": "[str]"}, + "data_version": {"key": "dataVersion", "type": "str"}, + "filters": {"key": "filters", "type": "[FilterItems]"}, } - def __init__(self, *, columns: Optional[List[str]] = None, **kwargs: Any) -> None: + def __init__( + self, + *, + columns: Optional[List[str]] = None, + data_version: Optional[str] = None, + filters: Optional[List["_models.FilterItems"]] = None, + **kwargs: Any + ) -> None: """ - :keyword columns: Array of column names to be included in the export. If not provided then the - export will include all available columns. The available columns can vary by customer channel - (see examples). + :keyword columns: This is on path to deprecation and will not be supported going forward. :paramtype columns: list[str] + :keyword data_version: The data version for the selected for the export. If not provided then + the export will default to latest data version. + :paramtype data_version: str + :keyword filters: Filters associated with the data sets. + :paramtype filters: list[~azure.mgmt.costmanagement.models.FilterItems] """ super().__init__(**kwargs) self.columns = columns + self.data_version = data_version + self.filters = filters class ExportDefinition(_serialization.Model): """The definition of an export. - 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 type: The type of the export. Note that 'Usage' is equivalent to 'ActualCost' and is applicable to exports that do not yet provide data for charges or amortization for service - reservations. Required. Known values are: "Usage", "ActualCost", and "AmortizedCost". + reservations. Required. Known values are: "Usage", "ActualCost", "AmortizedCost", "FocusCost", + "PriceSheet", "ReservationTransactions", "ReservationRecommendations", and + "ReservationDetails". :vartype type: str or ~azure.mgmt.costmanagement.models.ExportType :ivar timeframe: The time frame for pulling data for the export. If custom, then a specific time period must be provided. Required. Known values are: "MonthToDate", "BillingMonthToDate", - "TheLastMonth", "TheLastBillingMonth", "WeekToDate", and "Custom". + "TheLastMonth", "TheLastBillingMonth", "WeekToDate", "Custom", and "TheCurrentMonth". :vartype timeframe: str or ~azure.mgmt.costmanagement.models.TimeframeType :ivar time_period: Has time period for pulling data for the export. :vartype time_period: ~azure.mgmt.costmanagement.models.ExportTimePeriod @@ -2001,11 +3459,13 @@ def __init__( """ :keyword type: The type of the export. Note that 'Usage' is equivalent to 'ActualCost' and is applicable to exports that do not yet provide data for charges or amortization for service - reservations. Required. Known values are: "Usage", "ActualCost", and "AmortizedCost". + reservations. Required. Known values are: "Usage", "ActualCost", "AmortizedCost", "FocusCost", + "PriceSheet", "ReservationTransactions", "ReservationRecommendations", and + "ReservationDetails". :paramtype type: str or ~azure.mgmt.costmanagement.models.ExportType :keyword timeframe: The time frame for pulling data for the export. If custom, then a specific time period must be provided. Required. Known values are: "MonthToDate", "BillingMonthToDate", - "TheLastMonth", "TheLastBillingMonth", "WeekToDate", and "Custom". + "TheLastMonth", "TheLastBillingMonth", "WeekToDate", "Custom", and "TheCurrentMonth". :paramtype timeframe: str or ~azure.mgmt.costmanagement.models.TimeframeType :keyword time_period: Has time period for pulling data for the export. :paramtype time_period: ~azure.mgmt.costmanagement.models.ExportTimePeriod @@ -2037,13 +3497,15 @@ class ExportDeliveryDestination(_serialization.Model): https://docs.microsoft.com/en-us/azure/cost-management-billing/costs/export-cost-data-storage-account-sas-key ). - All required parameters must be populated in order to send to Azure. - + :ivar type: The export delivery destination type. Currently only 'AzureBlob' and + 'MicrosoftFabric' is supported. If no value is provided it will default to 'AzureBlob'. Known + values are: "AzureBlob" and "MicrosoftFabric". + :vartype type: str or ~azure.mgmt.costmanagement.models.DestinationType :ivar resource_id: The resource id of the storage account where exports will be delivered. This is not required if a sasToken and storageAccount are specified. :vartype resource_id: str :ivar container: The name of the container where exports will be uploaded. If the container - does not exist it will be created. Required. + does not exist it will be created. :vartype container: str :ivar root_folder_path: The name of the directory where exports will be uploaded. :vartype root_folder_path: str @@ -2056,36 +3518,44 @@ class ExportDeliveryDestination(_serialization.Model): :ivar storage_account: The storage account where exports will be uploaded. For a restricted set of Azure customers this together with sasToken can be specified instead of resourceId. :vartype storage_account: str + :ivar microsoft_fabric_settings: The settings for the Microsoft Fabric destination. This is + only applicable when destination.type == 'MicrosoftFabric'. + :vartype microsoft_fabric_settings: + ~azure.mgmt.costmanagement.models.MicrosoftFabricDestinationSettings """ - _validation = { - "container": {"required": True}, - } - _attribute_map = { + "type": {"key": "type", "type": "str"}, "resource_id": {"key": "resourceId", "type": "str"}, "container": {"key": "container", "type": "str"}, "root_folder_path": {"key": "rootFolderPath", "type": "str"}, "sas_token": {"key": "sasToken", "type": "str"}, "storage_account": {"key": "storageAccount", "type": "str"}, + "microsoft_fabric_settings": {"key": "microsoftFabricSettings", "type": "MicrosoftFabricDestinationSettings"}, } def __init__( self, *, - container: str, + type: Optional[Union[str, "_models.DestinationType"]] = None, resource_id: Optional[str] = None, + container: Optional[str] = None, root_folder_path: Optional[str] = None, sas_token: Optional[str] = None, storage_account: Optional[str] = None, + microsoft_fabric_settings: Optional["_models.MicrosoftFabricDestinationSettings"] = None, **kwargs: Any ) -> None: """ + :keyword type: The export delivery destination type. Currently only 'AzureBlob' and + 'MicrosoftFabric' is supported. If no value is provided it will default to 'AzureBlob'. Known + values are: "AzureBlob" and "MicrosoftFabric". + :paramtype type: str or ~azure.mgmt.costmanagement.models.DestinationType :keyword resource_id: The resource id of the storage account where exports will be delivered. This is not required if a sasToken and storageAccount are specified. :paramtype resource_id: str :keyword container: The name of the container where exports will be uploaded. If the container - does not exist it will be created. Required. + does not exist it will be created. :paramtype container: str :keyword root_folder_path: The name of the directory where exports will be uploaded. :paramtype root_folder_path: str @@ -2098,19 +3568,25 @@ def __init__( :keyword storage_account: The storage account where exports will be uploaded. For a restricted set of Azure customers this together with sasToken can be specified instead of resourceId. :paramtype storage_account: str + :keyword microsoft_fabric_settings: The settings for the Microsoft Fabric destination. This is + only applicable when destination.type == 'MicrosoftFabric'. + :paramtype microsoft_fabric_settings: + ~azure.mgmt.costmanagement.models.MicrosoftFabricDestinationSettings """ super().__init__(**kwargs) + self.type = type self.resource_id = resource_id self.container = container self.root_folder_path = root_folder_path self.sas_token = sas_token self.storage_account = storage_account + self.microsoft_fabric_settings = microsoft_fabric_settings class ExportDeliveryInfo(_serialization.Model): """The delivery information associated with a export. - 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 destination: Has destination for the export being delivered. Required. :vartype destination: ~azure.mgmt.costmanagement.models.ExportDeliveryDestination @@ -2184,10 +3660,10 @@ class ExportProperties(CommonExportProperties): 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 format: The format of the export being delivered. Currently only 'Csv' is supported. - "Csv" + :ivar format: The format of the export being delivered. Known values are: "Csv", "Parquet", and + "Delta". :vartype format: str or ~azure.mgmt.costmanagement.models.FormatType :ivar delivery_info: Has delivery information for the export. Required. :vartype delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo @@ -2199,9 +3675,25 @@ class ExportProperties(CommonExportProperties): blob directory together with a manifest file. Note: this option is currently available only for Microsoft Customer Agreement commerce scopes. :vartype partition_data: bool + :ivar data_overwrite_behavior: Allow customers to select overwrite + data(OverwritePreviousReport) for exports. This setting will enable overwrite data for the same + month in customer storage account. By default set to CreateNewReport. Known values are: + "OverwritePreviousReport" and "CreateNewReport". + :vartype data_overwrite_behavior: str or + ~azure.mgmt.costmanagement.models.DataOverwriteBehaviorType + :ivar compression_mode: Allow customers to select compress data(gzip) for exports. This setting + will enable destination file compression scheme at runtime. By default set to None. Known + values are: "gzip" and "None". + :vartype compression_mode: str or ~azure.mgmt.costmanagement.models.CompressionModeType + :ivar export_description: The export description set by customer at time of export + creation/update. + :vartype export_description: str :ivar next_run_time_estimate: If the export has an active schedule, provides an estimate of the next run time. :vartype next_run_time_estimate: ~datetime.datetime + :ivar system_suspension_context: The export suspension reason if export is in SystemSuspended + state. + :vartype system_suspension_context: ~azure.mgmt.costmanagement.models.ExportSuspensionContext :ivar schedule: Has schedule information for the export. :vartype schedule: ~azure.mgmt.costmanagement.models.ExportSchedule """ @@ -2210,6 +3702,7 @@ class ExportProperties(CommonExportProperties): "delivery_info": {"required": True}, "definition": {"required": True}, "next_run_time_estimate": {"readonly": True}, + "system_suspension_context": {"readonly": True}, } _attribute_map = { @@ -2218,7 +3711,11 @@ class ExportProperties(CommonExportProperties): "definition": {"key": "definition", "type": "ExportDefinition"}, "run_history": {"key": "runHistory", "type": "ExportExecutionListResult"}, "partition_data": {"key": "partitionData", "type": "bool"}, + "data_overwrite_behavior": {"key": "dataOverwriteBehavior", "type": "str"}, + "compression_mode": {"key": "compressionMode", "type": "str"}, + "export_description": {"key": "exportDescription", "type": "str"}, "next_run_time_estimate": {"key": "nextRunTimeEstimate", "type": "iso-8601"}, + "system_suspension_context": {"key": "systemSuspensionContext", "type": "ExportSuspensionContext"}, "schedule": {"key": "schedule", "type": "ExportSchedule"}, } @@ -2230,12 +3727,15 @@ def __init__( format: Optional[Union[str, "_models.FormatType"]] = None, run_history: Optional["_models.ExportExecutionListResult"] = None, partition_data: Optional[bool] = None, + data_overwrite_behavior: Optional[Union[str, "_models.DataOverwriteBehaviorType"]] = None, + compression_mode: Optional[Union[str, "_models.CompressionModeType"]] = None, + export_description: Optional[str] = None, schedule: Optional["_models.ExportSchedule"] = None, **kwargs: Any ) -> None: """ - :keyword format: The format of the export being delivered. Currently only 'Csv' is supported. - "Csv" + :keyword format: The format of the export being delivered. Known values are: "Csv", "Parquet", + and "Delta". :paramtype format: str or ~azure.mgmt.costmanagement.models.FormatType :keyword delivery_info: Has delivery information for the export. Required. :paramtype delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo @@ -2247,6 +3747,19 @@ def __init__( in a blob directory together with a manifest file. Note: this option is currently available only for Microsoft Customer Agreement commerce scopes. :paramtype partition_data: bool + :keyword data_overwrite_behavior: Allow customers to select overwrite + data(OverwritePreviousReport) for exports. This setting will enable overwrite data for the same + month in customer storage account. By default set to CreateNewReport. Known values are: + "OverwritePreviousReport" and "CreateNewReport". + :paramtype data_overwrite_behavior: str or + ~azure.mgmt.costmanagement.models.DataOverwriteBehaviorType + :keyword compression_mode: Allow customers to select compress data(gzip) for exports. This + setting will enable destination file compression scheme at runtime. By default set to None. + Known values are: "gzip" and "None". + :paramtype compression_mode: str or ~azure.mgmt.costmanagement.models.CompressionModeType + :keyword export_description: The export description set by customer at time of export + creation/update. + :paramtype export_description: str :keyword schedule: Has schedule information for the export. :paramtype schedule: ~azure.mgmt.costmanagement.models.ExportSchedule """ @@ -2256,6 +3769,9 @@ def __init__( definition=definition, run_history=run_history, partition_data=partition_data, + data_overwrite_behavior=data_overwrite_behavior, + compression_mode=compression_mode, + export_description=export_description, **kwargs ) self.schedule = schedule @@ -2264,7 +3780,7 @@ def __init__( class ExportRecurrencePeriod(_serialization.Model): """The start and end date for recurrence schedule. - 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 from_property: The start date of recurrence. Required. :vartype from_property: ~datetime.datetime @@ -2295,7 +3811,7 @@ def __init__( self.to = to -class ExportRun(CostManagementProxyResource): # pylint: disable=too-many-instance-attributes +class ExportRun(CostManagementProxyResource): """An export run. Variables are only populated by the server, and will be ignored when sending a request. @@ -2321,10 +3837,16 @@ class ExportRun(CostManagementProxyResource): # pylint: disable=too-many-instan :vartype submitted_time: ~datetime.datetime :ivar processing_start_time: The time when export was picked up to be run. :vartype processing_start_time: ~datetime.datetime + :ivar start_date: The start datetime for the export. + :vartype start_date: ~datetime.datetime + :ivar end_date: The end datetime for the export. + :vartype end_date: ~datetime.datetime :ivar processing_end_time: The time when the export run finished. :vartype processing_end_time: ~datetime.datetime :ivar file_name: The name of the exported file. :vartype file_name: str + :ivar manifest_file: The manifest file location(URI location) for the exported files. + :vartype manifest_file: str :ivar run_settings: The export settings that were in effect for this run. :vartype run_settings: ~azure.mgmt.costmanagement.models.CommonExportProperties :ivar error: The details of any error. @@ -2347,8 +3869,11 @@ class ExportRun(CostManagementProxyResource): # pylint: disable=too-many-instan "submitted_by": {"key": "properties.submittedBy", "type": "str"}, "submitted_time": {"key": "properties.submittedTime", "type": "iso-8601"}, "processing_start_time": {"key": "properties.processingStartTime", "type": "iso-8601"}, + "start_date": {"key": "properties.startDate", "type": "iso-8601"}, + "end_date": {"key": "properties.endDate", "type": "iso-8601"}, "processing_end_time": {"key": "properties.processingEndTime", "type": "iso-8601"}, "file_name": {"key": "properties.fileName", "type": "str"}, + "manifest_file": {"key": "properties.manifestFile", "type": "str"}, "run_settings": {"key": "properties.runSettings", "type": "CommonExportProperties"}, "error": {"key": "properties.error", "type": "ErrorDetails"}, } @@ -2362,8 +3887,11 @@ def __init__( submitted_by: Optional[str] = None, submitted_time: Optional[datetime.datetime] = None, processing_start_time: Optional[datetime.datetime] = None, + start_date: Optional[datetime.datetime] = None, + end_date: Optional[datetime.datetime] = None, processing_end_time: Optional[datetime.datetime] = None, file_name: Optional[str] = None, + manifest_file: Optional[str] = None, run_settings: Optional["_models.CommonExportProperties"] = None, error: Optional["_models.ErrorDetails"] = None, **kwargs: Any @@ -2385,10 +3913,16 @@ def __init__( :paramtype submitted_time: ~datetime.datetime :keyword processing_start_time: The time when export was picked up to be run. :paramtype processing_start_time: ~datetime.datetime + :keyword start_date: The start datetime for the export. + :paramtype start_date: ~datetime.datetime + :keyword end_date: The end datetime for the export. + :paramtype end_date: ~datetime.datetime :keyword processing_end_time: The time when the export run finished. :paramtype processing_end_time: ~datetime.datetime :keyword file_name: The name of the exported file. :paramtype file_name: str + :keyword manifest_file: The manifest file location(URI location) for the exported files. + :paramtype manifest_file: str :keyword run_settings: The export settings that were in effect for this run. :paramtype run_settings: ~azure.mgmt.costmanagement.models.CommonExportProperties :keyword error: The details of any error. @@ -2400,17 +3934,41 @@ def __init__( self.submitted_by = submitted_by self.submitted_time = submitted_time self.processing_start_time = processing_start_time + self.start_date = start_date + self.end_date = end_date self.processing_end_time = processing_end_time self.file_name = file_name + self.manifest_file = manifest_file self.run_settings = run_settings self.error = error +class ExportRunRequest(_serialization.Model): + """The export run request. + + :ivar time_period: Has time period for pulling data for the export. + :vartype time_period: ~azure.mgmt.costmanagement.models.ExportTimePeriod + """ + + _attribute_map = { + "time_period": {"key": "timePeriod", "type": "ExportTimePeriod"}, + } + + def __init__(self, *, time_period: Optional["_models.ExportTimePeriod"] = None, **kwargs: Any) -> None: + """ + :keyword time_period: Has time period for pulling data for the export. + :paramtype time_period: ~azure.mgmt.costmanagement.models.ExportTimePeriod + """ + super().__init__(**kwargs) + self.time_period = time_period + + class ExportSchedule(_serialization.Model): """The schedule associated with the export. :ivar status: The status of the export's schedule. If 'Inactive', the export's schedule is - paused. Known values are: "Active" and "Inactive". + paused. 'SystemSuspended' can only be set by export service. Known values are: "Active", + "Inactive", and "SystemSuspended". :vartype status: str or ~azure.mgmt.costmanagement.models.StatusType :ivar recurrence: The schedule recurrence. Known values are: "Daily", "Weekly", "Monthly", and "Annually". @@ -2436,7 +3994,8 @@ def __init__( ) -> None: """ :keyword status: The status of the export's schedule. If 'Inactive', the export's schedule is - paused. Known values are: "Active" and "Inactive". + paused. 'SystemSuspended' can only be set by export service. Known values are: "Active", + "Inactive", and "SystemSuspended". :paramtype status: str or ~azure.mgmt.costmanagement.models.StatusType :keyword recurrence: The schedule recurrence. Known values are: "Daily", "Weekly", "Monthly", and "Annually". @@ -2451,11 +4010,50 @@ def __init__( self.recurrence_period = recurrence_period +class ExportSuspensionContext(_serialization.Model): + """The properties of the export run. + + :ivar suspension_code: The code for export suspension. + :vartype suspension_code: str + :ivar suspension_reason: The detailed reason for export suspension. + :vartype suspension_reason: str + :ivar suspension_time: The time when the export was suspended. + :vartype suspension_time: ~datetime.datetime + """ + + _attribute_map = { + "suspension_code": {"key": "suspensionCode", "type": "str"}, + "suspension_reason": {"key": "suspensionReason", "type": "str"}, + "suspension_time": {"key": "suspensionTime", "type": "iso-8601"}, + } + + def __init__( + self, + *, + suspension_code: Optional[str] = None, + suspension_reason: Optional[str] = None, + suspension_time: Optional[datetime.datetime] = None, + **kwargs: Any + ) -> None: + """ + :keyword suspension_code: The code for export suspension. + :paramtype suspension_code: str + :keyword suspension_reason: The detailed reason for export suspension. + :paramtype suspension_reason: str + :keyword suspension_time: The time when the export was suspended. + :paramtype suspension_time: ~datetime.datetime + """ + super().__init__(**kwargs) + self.suspension_code = suspension_code + self.suspension_reason = suspension_reason + self.suspension_time = suspension_time + + class ExportTimePeriod(_serialization.Model): """The date range for data in the export. This should only be specified with timeFrame set to - 'Custom'. The maximum date range is 3 months. + 'Custom'. The maximum date range is 1 month. - 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 from_property: The start date for export data. Required. :vartype from_property: ~datetime.datetime @@ -2485,6 +4083,74 @@ def __init__(self, *, from_property: datetime.datetime, to: datetime.datetime, * self.to = to +class FabricLakehouse(_serialization.Model): + """This represents the fabric lakehouse identifier. + + :ivar id: The identifier of the fabric lakehouse. + :vartype id: str + :ivar display_name: The display name of the fabric lakehouse. This is only returned in Get + operations. + :vartype display_name: str + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + display_name: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword id: The identifier of the fabric lakehouse. + :paramtype id: str + :keyword display_name: The display name of the fabric lakehouse. This is only returned in Get + operations. + :paramtype display_name: str + """ + super().__init__(**kwargs) + self.id = id + self.display_name = display_name + + +class FabricWorkspace(_serialization.Model): + """This represents the fabric workspace identifier. + + :ivar id: The identifier of the fabric workspace. + :vartype id: str + :ivar display_name: The display name of the fabric workspace. This is only returned in Get + operations. + :vartype display_name: str + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + display_name: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword id: The identifier of the fabric workspace. + :paramtype id: str + :keyword display_name: The display name of the fabric workspace. This is only returned in Get + operations. + :paramtype display_name: str + """ + super().__init__(**kwargs) + self.id = id + self.display_name = display_name + + class FileDestination(_serialization.Model): """Destination of the view data. This is optional. Currently only CSV format is supported. @@ -2505,10 +4171,57 @@ def __init__(self, *, file_formats: Optional[List[Union[str, "_models.FileFormat self.file_formats = file_formats +class FilterItems(_serialization.Model): + """Will contain the filter name and value to operate on. This is currently only supported for + Export Definition type of ReservationRecommendations. + + :ivar name: The name of the filter. This is currently only supported for Export Definition type + of ReservationRecommendations. Supported names are ['ReservationScope', 'LookBackPeriod', + 'ResourceType']. Known values are: "ReservationScope", "ResourceType", and "LookBackPeriod". + :vartype name: str or ~azure.mgmt.costmanagement.models.FilterItemNames + :ivar value: Value to filter by. Currently values supported per name are, for + 'ReservationScope' supported values are ['Single', 'Shared'], for 'LookBackPeriod' supported + values are ['Last7Days', 'Last30Days', 'Last60Days'] and for 'ResourceType' supported values + are ['VirtualMachines', 'SQLDatabases', 'PostgreSQL', 'ManagedDisk', 'MySQL', 'RedHat', + 'MariaDB', 'RedisCache', 'CosmosDB', 'SqlDataWarehouse', 'SUSELinux', 'AppService', + 'BlockBlob', 'AzureDataExplorer', 'VMwareCloudSimple']. + :vartype value: str + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "value": {"key": "value", "type": "str"}, + } + + def __init__( + self, + *, + name: Optional[Union[str, "_models.FilterItemNames"]] = None, + value: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The name of the filter. This is currently only supported for Export Definition + type of ReservationRecommendations. Supported names are ['ReservationScope', 'LookBackPeriod', + 'ResourceType']. Known values are: "ReservationScope", "ResourceType", and "LookBackPeriod". + :paramtype name: str or ~azure.mgmt.costmanagement.models.FilterItemNames + :keyword value: Value to filter by. Currently values supported per name are, for + 'ReservationScope' supported values are ['Single', 'Shared'], for 'LookBackPeriod' supported + values are ['Last7Days', 'Last30Days', 'Last60Days'] and for 'ResourceType' supported values + are ['VirtualMachines', 'SQLDatabases', 'PostgreSQL', 'ManagedDisk', 'MySQL', 'RedHat', + 'MariaDB', 'RedisCache', 'CosmosDB', 'SqlDataWarehouse', 'SUSELinux', 'AppService', + 'BlockBlob', 'AzureDataExplorer', 'VMwareCloudSimple']. + :paramtype value: str + """ + super().__init__(**kwargs) + self.name = name + self.value = value + + class ForecastAggregation(_serialization.Model): """The aggregation expression to be used in the forecast. - 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 aggregate. Required. Known values are: "PreTaxCostUSD", "Cost", "CostUSD", and "PreTaxCost". @@ -2571,7 +4284,7 @@ def __init__(self, *, name: Optional[str] = None, type: Optional[str] = None, ** class ForecastComparisonExpression(_serialization.Model): """The comparison expression to be used in the forecast. - 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 @@ -2614,9 +4327,10 @@ def __init__( class ForecastDataset(_serialization.Model): """The definition of data present in the forecast. - 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 granularity: The granularity of rows in the forecast. "Daily" + :ivar granularity: The granularity of rows in the forecast. Known values are: "Daily" and + "Monthly". :vartype granularity: str or ~azure.mgmt.costmanagement.models.GranularityType :ivar configuration: Has configuration information for the data in the export. The configuration will be ignored if aggregation and grouping are provided. @@ -2650,7 +4364,8 @@ def __init__( **kwargs: Any ) -> None: """ - :keyword granularity: The granularity of rows in the forecast. "Daily" + :keyword granularity: The granularity of rows in the forecast. Known values are: "Daily" and + "Monthly". :paramtype granularity: str or ~azure.mgmt.costmanagement.models.GranularityType :keyword configuration: Has configuration information for the data in the export. The configuration will be ignored if aggregation and grouping are provided. @@ -2694,7 +4409,7 @@ def __init__(self, *, columns: Optional[List[str]] = None, **kwargs: Any) -> Non class ForecastDefinition(_serialization.Model): """The definition of a forecast. - 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 type: The type of the forecast. Required. Known values are: "Usage", "ActualCost", and "AmortizedCost". @@ -2887,10 +4602,41 @@ def __init__( self.rows = rows +class ForecastSpend(_serialization.Model): + """The forecasted cost which is being tracked for a budget. + + Supported for CategoryType(s): Cost. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar amount: The forecasted cost for the total time period which is being tracked by the + budget. This value is only provided if the budget contains a forecast alert type. + :vartype amount: float + :ivar unit: The unit of measure for the budget amount. + :vartype unit: str + """ + + _validation = { + "amount": {"readonly": True}, + "unit": {"readonly": True}, + } + + _attribute_map = { + "amount": {"key": "amount", "type": "float"}, + "unit": {"key": "unit", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.amount = None + self.unit = None + + class ForecastTimePeriod(_serialization.Model): """Has time period for pulling data for the forecast. - 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 from_property: The start date to pull data from. Required. :vartype from_property: ~datetime.datetime @@ -2969,7 +4715,7 @@ def __init__(self, *, error: Optional["_models.ErrorDetails"] = None, **kwargs: self.error = error -class GenerateCostDetailsReportRequestDefinition(_serialization.Model): +class GenerateCostDetailsReportRequestDefinition(_serialization.Model): # pylint: disable=name-too-long """The definition of a cost detailed report. :ivar metric: The type of the detailed report. By default ActualCost is provided. Known values @@ -3148,7 +4894,7 @@ def __init__(self, *, error: Optional["_models.ErrorDetails"] = None, **kwargs: self.error = error -class GenerateDetailedCostReportOperationResult(_serialization.Model): +class GenerateDetailedCostReportOperationResult(_serialization.Model): # pylint: disable=name-too-long """The result of the long running operation for cost detailed report. Variables are only populated by the server, and will be ignored when sending a request. @@ -3214,7 +4960,7 @@ def __init__( self.download_url = download_url -class GenerateDetailedCostReportOperationStatuses(_serialization.Model): +class GenerateDetailedCostReportOperationStatuses(_serialization.Model): # pylint: disable=name-too-long """The status of the long running operation for cost detailed report. Variables are only populated by the server, and will be ignored when sending a request. @@ -3311,7 +5057,7 @@ def __init__( class GenerateDetailedCostReportTimePeriod(_serialization.Model): """The start and end date for pulling data for the cost detailed report. - 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: The start date to pull data from. example format 2020-03-15. Required. :vartype start: str @@ -3346,10 +5092,10 @@ class IncludedQuantityUtilizationSummary(BenefitUtilizationSummary): 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: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -3416,7 +5162,9 @@ def __init__(self, *, benefit_type: Optional[Union[str, "_models.BenefitKind"]] self.utilization_percentage = None -class IncludedQuantityUtilizationSummaryProperties(BenefitUtilizationSummaryProperties): +class IncludedQuantityUtilizationSummaryProperties( + BenefitUtilizationSummaryProperties +): # pylint: disable=name-too-long """Included Quantity utilization summary properties. Variables are only populated by the server, and will be ignored when sending a request. @@ -3503,10 +5251,424 @@ def __init__( self.enabled = enabled +class MCAPriceSheetProperties(_serialization.Model): + """The properties of the price sheet. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar billing_account_id: Unique identifier for the billing account. + :vartype billing_account_id: str + :ivar billing_account_name: Name of the billing profile that is set up to receive invoices. The + prices in the price sheet are associated with this billing profile. + :vartype billing_account_name: str + :ivar billing_profile_id: Unique identifier for the billing profile. + :vartype billing_profile_id: str + :ivar billing_profile_name: Name of the billing profile that is set up to receive invoices. The + prices in the price sheet are associated with this billing profile. + :vartype billing_profile_name: str + :ivar product_order_name: Name of the purchased product plan. Indicates if this pricing is + standard Azure Plan pricing, Dev/Test pricing etc. + + Currently unavailable for Azure 3rd party and ReservedInstance meters. + :vartype product_order_name: str + :ivar service_family: Type of Azure service. For example, Compute, Analytics, and Security. + :vartype service_family: float + :ivar product: Name of the product accruing the charges. + :vartype product: str + :ivar product_id: Unique identifier for the product whose meter is consumed. + :vartype product_id: str + :ivar sku_id: Unique identifier of the SKU. + :vartype sku_id: str + :ivar unit_of_measure: How usage is measured for the service. + :vartype unit_of_measure: str + :ivar meter_id: Unique identifier of the meter. + :vartype meter_id: str + :ivar meter_name: Name of the meter. The meter represents the deployable resource of an Azure + service. + :vartype meter_name: str + :ivar meter_type: Name of the meter type. + :vartype meter_type: str + :ivar meter_category: Name of the classification category for the meter. For example, Cloud + services, Networking, etc. + :vartype meter_category: str + :ivar meter_sub_category: Name of the meter subclassification category. + :vartype meter_sub_category: str + :ivar meter_region: Name of the Azure region where the meter for the service is available. + :vartype meter_region: str + :ivar tier_minimum_units: Defines the lower bound of the tier range for which prices are + defined. For example, if the range is 0 to 100, tierMinimumUnits would be 0. + :vartype tier_minimum_units: str + :ivar effective_start_date: Effective start date of the Price Sheet billing period. + :vartype effective_start_date: ~datetime.datetime + :ivar effective_end_date: Effective end date of the Price Sheet billing period. + :vartype effective_end_date: ~datetime.datetime + :ivar unit_price: The per-unit price at the time of billing for a given product or service, + inclusive of any negotiated discounts on top of the market price. + + For PriceType ReservedInstance, unit price reflects the total cost of the 1 or 3-year + commitment including discounts. + + Note: The unit price isn't the same as the effective price in usage details downloads when + services have differential prices across tiers. + + If services have multi-tiered pricing, the effective price is a blended rate across the tiers + and doesn't show a tier-specific unit price. The blended price or effective price is the net + price for the consumed quantity spanning across the multiple tiers (where each tier has a + specific unit price). + :vartype unit_price: str + :ivar base_price: The unit price at the time the customer signs on or the unit price at the + time of service meter GA launch if it is after sign-on. + + This is applicable for Enterprise Agreement users. + :vartype base_price: str + :ivar market_price: The current list price for a given product or service. This price is + without any negotiations and is based on your Microsoft Agreement type. + + For PriceType Consumption, market price is reflected as the pay-as-you-go price. + + For PriceType Savings Plan, market price reflects the Savings plan benefit on top of + pay-as-you-go price for the corresponding commitment term. + + For PriceType ReservedInstance, market price reflects the total price of the 1 or 3-year + commitment. + :vartype market_price: str + :ivar currency: Currency in which all the prices are reflected. + :vartype currency: str + :ivar billing_currency: Currency in which charges are posted. + :vartype billing_currency: str + :ivar term: Term length for Azure Savings Plan or Reservation term – one year or three years + (P1Y or P3Y). + :vartype term: str + :ivar price_type: Price type for a product. For example, an Azure resource with a pay-as-you-go + rate with priceType as Consumption. Other price types include ReservedInstance and Savings + Plan. + :vartype price_type: str + """ + + _validation = { + "billing_account_id": {"readonly": True}, + "billing_account_name": {"readonly": True}, + "billing_profile_id": {"readonly": True}, + "billing_profile_name": {"readonly": True}, + "product_order_name": {"readonly": True}, + "service_family": {"readonly": True}, + "product": {"readonly": True}, + "product_id": {"readonly": True}, + "sku_id": {"readonly": True}, + "unit_of_measure": {"readonly": True}, + "meter_id": {"readonly": True}, + "meter_name": {"readonly": True}, + "meter_type": {"readonly": True}, + "meter_category": {"readonly": True}, + "meter_sub_category": {"readonly": True}, + "meter_region": {"readonly": True}, + "tier_minimum_units": {"readonly": True}, + "effective_start_date": {"readonly": True}, + "effective_end_date": {"readonly": True}, + "unit_price": {"readonly": True}, + "base_price": {"readonly": True}, + "market_price": {"readonly": True}, + "currency": {"readonly": True}, + "billing_currency": {"readonly": True}, + "term": {"readonly": True}, + "price_type": {"readonly": True}, + } + + _attribute_map = { + "billing_account_id": {"key": "billingAccountID", "type": "str"}, + "billing_account_name": {"key": "billingAccountName", "type": "str"}, + "billing_profile_id": {"key": "billingProfileId", "type": "str"}, + "billing_profile_name": {"key": "billingProfileName", "type": "str"}, + "product_order_name": {"key": "productOrderName", "type": "str"}, + "service_family": {"key": "serviceFamily", "type": "float"}, + "product": {"key": "product", "type": "str"}, + "product_id": {"key": "productId", "type": "str"}, + "sku_id": {"key": "skuId", "type": "str"}, + "unit_of_measure": {"key": "unitOfMeasure", "type": "str"}, + "meter_id": {"key": "meterId", "type": "str"}, + "meter_name": {"key": "meterName", "type": "str"}, + "meter_type": {"key": "meterType", "type": "str"}, + "meter_category": {"key": "meterCategory", "type": "str"}, + "meter_sub_category": {"key": "meterSubCategory", "type": "str"}, + "meter_region": {"key": "meterRegion", "type": "str"}, + "tier_minimum_units": {"key": "tierMinimumUnits", "type": "str"}, + "effective_start_date": {"key": "effectiveStartDate", "type": "iso-8601"}, + "effective_end_date": {"key": "effectiveEndDate", "type": "iso-8601"}, + "unit_price": {"key": "unitPrice", "type": "str"}, + "base_price": {"key": "basePrice", "type": "str"}, + "market_price": {"key": "marketPrice", "type": "str"}, + "currency": {"key": "currency", "type": "str"}, + "billing_currency": {"key": "billingCurrency", "type": "str"}, + "term": {"key": "term", "type": "str"}, + "price_type": {"key": "priceType", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: # pylint: disable=too-many-locals + """ """ + super().__init__(**kwargs) + self.billing_account_id = None + self.billing_account_name = None + self.billing_profile_id = None + self.billing_profile_name = None + self.product_order_name = None + self.service_family = None + self.product = None + self.product_id = None + self.sku_id = None + self.unit_of_measure = None + self.meter_id = None + self.meter_name = None + self.meter_type = None + self.meter_category = None + self.meter_sub_category = None + self.meter_region = None + self.tier_minimum_units = None + self.effective_start_date = None + self.effective_end_date = None + self.unit_price = None + self.base_price = None + self.market_price = None + self.currency = None + self.billing_currency = None + self.term = None + self.price_type = None + + +class MicrosoftFabricDestinationSettings(_serialization.Model): + """This represents the fabric specific settings for export destination when delivery info type is + 'MicrosoftFabric'. + + :ivar workspace: The Microsoft Fabric Workspace Identifier. + :vartype workspace: ~azure.mgmt.costmanagement.models.FabricWorkspace + :ivar lakehouse: The Microsoft Fabric Lakehouse Identifier. + :vartype lakehouse: ~azure.mgmt.costmanagement.models.FabricLakehouse + :ivar table_name: The name of the Microsoft Fabric Lakehouse Delta table where export data will + be ingested to. + :vartype table_name: str + """ + + _attribute_map = { + "workspace": {"key": "workspace", "type": "FabricWorkspace"}, + "lakehouse": {"key": "lakehouse", "type": "FabricLakehouse"}, + "table_name": {"key": "tableName", "type": "str"}, + } + + def __init__( + self, + *, + workspace: Optional["_models.FabricWorkspace"] = None, + lakehouse: Optional["_models.FabricLakehouse"] = None, + table_name: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword workspace: The Microsoft Fabric Workspace Identifier. + :paramtype workspace: ~azure.mgmt.costmanagement.models.FabricWorkspace + :keyword lakehouse: The Microsoft Fabric Lakehouse Identifier. + :paramtype lakehouse: ~azure.mgmt.costmanagement.models.FabricLakehouse + :keyword table_name: The name of the Microsoft Fabric Lakehouse Delta table where export data + will be ingested to. + :paramtype table_name: str + """ + super().__init__(**kwargs) + self.workspace = workspace + self.lakehouse = lakehouse + self.table_name = table_name + + +class Notification(_serialization.Model): + """The notification associated with a budget. + + Supported for CategoryType(s): Cost, ReservationUtilization. + + All required parameters must be populated in order to send to server. + + :ivar enabled: The notification is enabled or not. + + Supported for CategoryType(s): Cost, ReservationUtilization. Required. + :vartype enabled: bool + :ivar operator: The comparison operator. + + Supported for CategoryType(s): Cost, ReservationUtilization. + + Supported operators for **CategoryType: Cost** + + + * GreaterThan + * + GreaterThanOrEqualTo + + Supported operators for **CategoryType: ReservationUtilization** + + * LessThan. Required. Known values are: "EqualTo", "GreaterThan", "GreaterThanOrEqualTo", and + "LessThan". + :vartype operator: str or ~azure.mgmt.costmanagement.models.BudgetNotificationOperatorType + :ivar threshold: Threshold value associated with a notification. It is always percent with a + maximum of 2 decimal places. + + Supported for CategoryType(s): Cost, ReservationUtilization. + + **CategoryType: Cost** - Must be between 0 and 1000. Notification is sent when the cost + exceeded the threshold. + + **CategoryType: ReservationUtilization** - Must be between 0 and 100. Notification is sent + when a reservation has a utilization percentage below the threshold. Required. + :vartype threshold: float + :ivar frequency: Frequency of a notification. Represents how long the notification will be + silent after triggering an alert for a threshold breach. If not specified, the frequency will + be set by default based on the timeGrain (Weekly when timeGrain: Last7Days, Monthly when + timeGrain: Last30Days). + + Supported for CategoryType(s): ReservationUtilization. Known values are: "Daily", "Weekly", + and "Monthly". + :vartype frequency: str or ~azure.mgmt.costmanagement.models.Frequency + :ivar contact_emails: Email addresses to send the notification to when the threshold is + breached. Must have at least one contact email or contact group specified at the Subscription + or Resource Group scopes. All other scopes must have at least one contact email specified. + + Supported for CategoryType(s): Cost, ReservationUtilization. Required. + :vartype contact_emails: list[str] + :ivar contact_roles: Subscription or Resource Group scopes only. Contact roles to send the + notification to when the threshold is breached. + + Supported for CategoryType(s): Cost. + :vartype contact_roles: list[str] + :ivar contact_groups: Subscription or Resource Group scopes only. Action groups to send the + notification to when the threshold is exceeded. Must be provided as a fully qualified Azure + resource id. + + Supported for CategoryType(s): Cost. + :vartype contact_groups: list[str] + :ivar threshold_type: The type of threshold. + + Supported for CategoryType(s): Cost. Known values are: "Actual" and "Forecasted". + :vartype threshold_type: str or ~azure.mgmt.costmanagement.models.ThresholdType + :ivar locale: Language in which the recipient will receive the notification, + + Supported for CategoryType(s): Cost, ReservationUtilization. Known values are: "en-us", + "ja-jp", "zh-cn", "de-de", "es-es", "fr-fr", "it-it", "ko-kr", "pt-br", "ru-ru", "zh-tw", + "cs-cz", "pl-pl", "tr-tr", "da-dk", "en-gb", "hu-hu", "nb-no", "nl-nl", "pt-pt", and "sv-se". + :vartype locale: str or ~azure.mgmt.costmanagement.models.CultureCode + """ + + _validation = { + "enabled": {"required": True}, + "operator": {"required": True}, + "threshold": {"required": True}, + "contact_emails": {"required": True, "max_items": 50, "min_items": 0}, + "contact_groups": {"max_items": 50, "min_items": 0}, + } + + _attribute_map = { + "enabled": {"key": "enabled", "type": "bool"}, + "operator": {"key": "operator", "type": "str"}, + "threshold": {"key": "threshold", "type": "float"}, + "frequency": {"key": "frequency", "type": "str"}, + "contact_emails": {"key": "contactEmails", "type": "[str]"}, + "contact_roles": {"key": "contactRoles", "type": "[str]"}, + "contact_groups": {"key": "contactGroups", "type": "[str]"}, + "threshold_type": {"key": "thresholdType", "type": "str"}, + "locale": {"key": "locale", "type": "str"}, + } + + def __init__( + self, + *, + enabled: bool, + operator: Union[str, "_models.BudgetNotificationOperatorType"], + threshold: float, + contact_emails: List[str], + frequency: Optional[Union[str, "_models.Frequency"]] = None, + contact_roles: Optional[List[str]] = None, + contact_groups: Optional[List[str]] = None, + threshold_type: Union[str, "_models.ThresholdType"] = "Actual", + locale: Optional[Union[str, "_models.CultureCode"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword enabled: The notification is enabled or not. + + Supported for CategoryType(s): Cost, ReservationUtilization. Required. + :paramtype enabled: bool + :keyword operator: The comparison operator. + + Supported for CategoryType(s): Cost, ReservationUtilization. + + Supported operators for **CategoryType: Cost** + + + * GreaterThan + * + GreaterThanOrEqualTo + + Supported operators for **CategoryType: ReservationUtilization** + + * LessThan. Required. Known values are: "EqualTo", "GreaterThan", "GreaterThanOrEqualTo", and + "LessThan". + :paramtype operator: str or ~azure.mgmt.costmanagement.models.BudgetNotificationOperatorType + :keyword threshold: Threshold value associated with a notification. It is always percent with a + maximum of 2 decimal places. + + Supported for CategoryType(s): Cost, ReservationUtilization. + + **CategoryType: Cost** - Must be between 0 and 1000. Notification is sent when the cost + exceeded the threshold. + + **CategoryType: ReservationUtilization** - Must be between 0 and 100. Notification is sent + when a reservation has a utilization percentage below the threshold. Required. + :paramtype threshold: float + :keyword frequency: Frequency of a notification. Represents how long the notification will be + silent after triggering an alert for a threshold breach. If not specified, the frequency will + be set by default based on the timeGrain (Weekly when timeGrain: Last7Days, Monthly when + timeGrain: Last30Days). + + Supported for CategoryType(s): ReservationUtilization. Known values are: "Daily", "Weekly", + and "Monthly". + :paramtype frequency: str or ~azure.mgmt.costmanagement.models.Frequency + :keyword contact_emails: Email addresses to send the notification to when the threshold is + breached. Must have at least one contact email or contact group specified at the Subscription + or Resource Group scopes. All other scopes must have at least one contact email specified. + + Supported for CategoryType(s): Cost, ReservationUtilization. Required. + :paramtype contact_emails: list[str] + :keyword contact_roles: Subscription or Resource Group scopes only. Contact roles to send the + notification to when the threshold is breached. + + Supported for CategoryType(s): Cost. + :paramtype contact_roles: list[str] + :keyword contact_groups: Subscription or Resource Group scopes only. Action groups to send the + notification to when the threshold is exceeded. Must be provided as a fully qualified Azure + resource id. + + Supported for CategoryType(s): Cost. + :paramtype contact_groups: list[str] + :keyword threshold_type: The type of threshold. + + Supported for CategoryType(s): Cost. Known values are: "Actual" and "Forecasted". + :paramtype threshold_type: str or ~azure.mgmt.costmanagement.models.ThresholdType + :keyword locale: Language in which the recipient will receive the notification, + + Supported for CategoryType(s): Cost, ReservationUtilization. Known values are: "en-us", + "ja-jp", "zh-cn", "de-de", "es-es", "fr-fr", "it-it", "ko-kr", "pt-br", "ru-ru", "zh-tw", + "cs-cz", "pl-pl", "tr-tr", "da-dk", "en-gb", "hu-hu", "nb-no", "nl-nl", "pt-pt", and "sv-se". + :paramtype locale: str or ~azure.mgmt.costmanagement.models.CultureCode + """ + super().__init__(**kwargs) + self.enabled = enabled + self.operator = operator + self.threshold = threshold + self.frequency = frequency + self.contact_emails = contact_emails + self.contact_roles = contact_roles + self.contact_groups = contact_groups + self.threshold_type = threshold_type + self.locale = locale + + class NotificationProperties(_serialization.Model): """The properties of the scheduled action notification. - 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 to: Array of email addresses. Required. :vartype to: list[str] @@ -3642,7 +5804,7 @@ class OperationStatus(_serialization.Model): """The status of the long running operation. :ivar status: The status of the long running operation. Known values are: "Running", - "Completed", and "Failed". + "Complete", "Failed", and "Completed". :vartype status: str or ~azure.mgmt.costmanagement.models.OperationStatusType :ivar report_url: The CSV file from the reportUrl blob link consists of reservation usage data with the following schema at daily granularity. Known values are: "InstanceFlexibilityGroup", @@ -3655,35 +5817,84 @@ class OperationStatus(_serialization.Model): _attribute_map = { "status": {"key": "status", "type": "str"}, - "report_url": {"key": "properties.reportUrl", "type": "str"}, - "valid_until": {"key": "properties.validUntil", "type": "iso-8601"}, + "report_url": {"key": "properties.reportUrl", "type": "str"}, + "valid_until": {"key": "properties.validUntil", "type": "iso-8601"}, + } + + def __init__( + self, + *, + status: Optional[Union[str, "_models.OperationStatusType"]] = None, + report_url: Optional[Union[str, "_models.ReservationReportSchema"]] = None, + valid_until: Optional[datetime.datetime] = None, + **kwargs: Any + ) -> None: + """ + :keyword status: The status of the long running operation. Known values are: "Running", + "Complete", "Failed", and "Completed". + :paramtype status: str or ~azure.mgmt.costmanagement.models.OperationStatusType + :keyword report_url: The CSV file from the reportUrl blob link consists of reservation usage + data with the following schema at daily granularity. Known values are: + "InstanceFlexibilityGroup", "InstanceFlexibilityRatio", "InstanceId", "Kind", "ReservationId", + "ReservationOrderId", "ReservedHours", "SkuName", "TotalReservedQuantity", "UsageDate", and + "UsedHours". + :paramtype report_url: str or ~azure.mgmt.costmanagement.models.ReservationReportSchema + :keyword valid_until: The time at which report URL becomes invalid. + :paramtype valid_until: ~datetime.datetime + """ + super().__init__(**kwargs) + self.status = status + self.report_url = report_url + self.valid_until = valid_until + + +class OperationStatusAutoGenerated(_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", + "Complete", "Failed", and "Completed". + :vartype status: str or ~azure.mgmt.costmanagement.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 + :ivar download_file_properties: The properties in downloaded file. + :vartype download_file_properties: ~azure.mgmt.costmanagement.models.EAPriceSheetProperties + """ + + _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"}, + "download_file_properties": {"key": "properties.downloadFileProperties", "type": "EAPriceSheetProperties"}, } def __init__( self, *, status: Optional[Union[str, "_models.OperationStatusType"]] = None, - report_url: Optional[Union[str, "_models.ReservationReportSchema"]] = None, - valid_until: Optional[datetime.datetime] = None, + download_file_properties: Optional["_models.EAPriceSheetProperties"] = None, **kwargs: Any ) -> None: """ :keyword status: The status of the long running operation. Known values are: "Running", - "Completed", and "Failed". + "Complete", "Failed", and "Completed". :paramtype status: str or ~azure.mgmt.costmanagement.models.OperationStatusType - :keyword report_url: The CSV file from the reportUrl blob link consists of reservation usage - data with the following schema at daily granularity. Known values are: - "InstanceFlexibilityGroup", "InstanceFlexibilityRatio", "InstanceId", "Kind", "ReservationId", - "ReservationOrderId", "ReservedHours", "SkuName", "TotalReservedQuantity", "UsageDate", and - "UsedHours". - :paramtype report_url: str or ~azure.mgmt.costmanagement.models.ReservationReportSchema - :keyword valid_until: The time at which report URL becomes invalid. - :paramtype valid_until: ~datetime.datetime + :keyword download_file_properties: The properties in downloaded file. + :paramtype download_file_properties: ~azure.mgmt.costmanagement.models.EAPriceSheetProperties """ super().__init__(**kwargs) self.status = status - self.report_url = report_url - self.valid_until = valid_until + self.download_url = None + self.valid_till = None + self.download_file_properties = download_file_properties class PivotProperties(_serialization.Model): @@ -3714,6 +5925,49 @@ def __init__( self.name = name +class PricesheetDownloadProperties(_serialization.Model): + """The URL to download the generated report. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar expiry_time: The time at which report URL becomes invalid/expires in UTC e.g. + 2020-12-08T05:55:59.4394737Z. + :vartype expiry_time: ~datetime.datetime + :ivar download_url: The URL to download the generated report. + :vartype download_url: str + :ivar download_file_properties: The properties in downloaded file. + :vartype download_file_properties: ~azure.mgmt.costmanagement.models.MCAPriceSheetProperties + """ + + _validation = { + "expiry_time": {"readonly": True}, + } + + _attribute_map = { + "expiry_time": {"key": "expiryTime", "type": "iso-8601"}, + "download_url": {"key": "downloadUrl", "type": "str"}, + "download_file_properties": {"key": "downloadFileProperties", "type": "MCAPriceSheetProperties"}, + } + + def __init__( + self, + *, + download_url: Optional[str] = None, + download_file_properties: Optional["_models.MCAPriceSheetProperties"] = None, + **kwargs: Any + ) -> None: + """ + :keyword download_url: The URL to download the generated report. + :paramtype download_url: str + :keyword download_file_properties: The properties in downloaded file. + :paramtype download_file_properties: ~azure.mgmt.costmanagement.models.MCAPriceSheetProperties + """ + super().__init__(**kwargs) + self.expiry_time = None + self.download_url = download_url + self.download_file_properties = download_file_properties + + class ProxyResource(Resource): """The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location. @@ -3721,7 +5975,7 @@ class ProxyResource(Resource): Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -3730,27 +5984,11 @@ class ProxyResource(Resource): :vartype type: str """ - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - class QueryAggregation(_serialization.Model): """The aggregation expression to be used in the query. - 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 aggregate. Required. :vartype name: str @@ -3809,7 +6047,7 @@ def __init__(self, *, name: Optional[str] = None, type: Optional[str] = None, ** class QueryComparisonExpression(_serialization.Model): """The comparison expression to be used in the query. - 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 @@ -3852,7 +6090,8 @@ def __init__( class QueryDataset(_serialization.Model): """The definition of data present in the query. - :ivar granularity: The granularity of rows in the query. "Daily" + :ivar granularity: The granularity of rows in the query. Known values are: "Daily" and + "Monthly". :vartype granularity: str or ~azure.mgmt.costmanagement.models.GranularityType :ivar configuration: Has configuration information for the data in the export. The configuration will be ignored if aggregation and grouping are provided. @@ -3892,7 +6131,8 @@ def __init__( **kwargs: Any ) -> None: """ - :keyword granularity: The granularity of rows in the query. "Daily" + :keyword granularity: The granularity of rows in the query. Known values are: "Daily" and + "Monthly". :paramtype granularity: str or ~azure.mgmt.costmanagement.models.GranularityType :keyword configuration: Has configuration information for the data in the export. The configuration will be ignored if aggregation and grouping are provided. @@ -3941,14 +6181,15 @@ def __init__(self, *, columns: Optional[List[str]] = None, **kwargs: Any) -> Non class QueryDefinition(_serialization.Model): """The definition of a query. - 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 type: The type of the query. Required. Known values are: "Usage", "ActualCost", and - "AmortizedCost". + :ivar type: The type of the query. Required. Known values are: "Usage", "ActualCost", + "AmortizedCost", "FocusCost", "PriceSheet", "ReservationTransactions", + "ReservationRecommendations", and "ReservationDetails". :vartype type: str or ~azure.mgmt.costmanagement.models.ExportType :ivar timeframe: The time frame for pulling data for the query. If custom, then a specific time period must be provided. Required. Known values are: "MonthToDate", "BillingMonthToDate", - "TheLastMonth", "TheLastBillingMonth", "WeekToDate", and "Custom". + "TheLastMonth", "TheLastBillingMonth", "WeekToDate", "Custom", and "TheCurrentMonth". :vartype timeframe: str or ~azure.mgmt.costmanagement.models.TimeframeType :ivar time_period: Has time period for pulling data for the query. :vartype time_period: ~azure.mgmt.costmanagement.models.QueryTimePeriod @@ -3979,12 +6220,13 @@ def __init__( **kwargs: Any ) -> None: """ - :keyword type: The type of the query. Required. Known values are: "Usage", "ActualCost", and - "AmortizedCost". + :keyword type: The type of the query. Required. Known values are: "Usage", "ActualCost", + "AmortizedCost", "FocusCost", "PriceSheet", "ReservationTransactions", + "ReservationRecommendations", and "ReservationDetails". :paramtype type: str or ~azure.mgmt.costmanagement.models.ExportType :keyword timeframe: The time frame for pulling data for the query. If custom, then a specific time period must be provided. Required. Known values are: "MonthToDate", "BillingMonthToDate", - "TheLastMonth", "TheLastBillingMonth", "WeekToDate", and "Custom". + "TheLastMonth", "TheLastBillingMonth", "WeekToDate", "Custom", and "TheCurrentMonth". :paramtype timeframe: str or ~azure.mgmt.costmanagement.models.TimeframeType :keyword time_period: Has time period for pulling data for the query. :paramtype time_period: ~azure.mgmt.costmanagement.models.QueryTimePeriod @@ -4052,7 +6294,7 @@ def __init__( class QueryGrouping(_serialization.Model): """The group by expression to be used in the query. - 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 type: Has type of the column to group. Required. Known values are: "TagKey" and "Dimension". @@ -4159,7 +6401,7 @@ def __init__( class QueryTimePeriod(_serialization.Model): """The start and end date for pulling data for the query. - 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 from_property: The start date to pull data from. Required. :vartype from_property: ~datetime.datetime @@ -4226,7 +6468,7 @@ def __init__(self, *, usage_grain: Optional[Union[str, "_models.Grain"]] = None, class ReportConfigAggregation(_serialization.Model): """The aggregation expression to be used in the report. - 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 aggregate. Required. :vartype name: str @@ -4259,7 +6501,7 @@ def __init__(self, *, name: str, function: Union[str, "_models.FunctionType"], * class ReportConfigComparisonExpression(_serialization.Model): """The comparison expression to be used in the report. - 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 @@ -4450,7 +6692,7 @@ def __init__( class ReportConfigGrouping(_serialization.Model): """The group by expression to be used in the report. - 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 type: Has type of the column to group. Required. Known values are: "TagKey" and "Dimension". @@ -4487,7 +6729,7 @@ def __init__(self, *, type: Union[str, "_models.QueryColumnType"], name: str, ** class ReportConfigSorting(_serialization.Model): """The order by expression to be used in the report. - 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 direction: Direction of sort. Known values are: "Ascending" and "Descending". :vartype direction: str or ~azure.mgmt.costmanagement.models.ReportConfigSortingType @@ -4521,7 +6763,7 @@ def __init__( class ReportConfigTimePeriod(_serialization.Model): """The start and end date for pulling data for the report. - 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 from_property: The start date to pull data from. Required. :vartype from_property: ~datetime.datetime @@ -4551,15 +6793,15 @@ def __init__(self, *, from_property: datetime.datetime, to: datetime.datetime, * self.to = to -class SavingsPlanUtilizationSummary(BenefitUtilizationSummary): # pylint: disable=too-many-instance-attributes +class SavingsPlanUtilizationSummary(BenefitUtilizationSummary): """Savings plan utilization summary 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: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -4583,26 +6825,28 @@ class SavingsPlanUtilizationSummary(BenefitUtilizationSummary): # pylint: disab :vartype usage_date: ~datetime.datetime :ivar avg_utilization_percentage: This is the average hourly utilization for each date range that corresponds to given grain (Daily, Monthly). Suppose the API call is for usageDate > - 2022-10-01 and usageDate < 2022-10-31 at a daily granularity. There will be one record per - benefit id for each day. For a single day, the avgUtilizationPercentage value will be equal to - the average of the set of values where the set contains 24 utilization percentage entries one - for each hour in a specific day. + 2024-10-01-preview and usageDate < 2022-10-31 at a daily granularity. There will be one record + per benefit id for each day. For a single day, the avgUtilizationPercentage value will be equal + to the average of the set of values where the set contains 24 utilization percentage entries + one for each hour in a specific day. :vartype avg_utilization_percentage: float :ivar min_utilization_percentage: This is the minimum hourly utilization for each date range that corresponds to given grain (Daily, Monthly). Suppose the API call is for usageDate > - 2022-10-01 and usageDate < 2022-10-31 at a daily granularity. There will be one record per - benefit id for each day. For a single day, the minUtilizationPercentage value will be equal to - the smallest in the set of values where the set contains 24 utilization percentage entries one - for each hour in a specific day. If on the day 2022-10-18, the lowest utilization percentage - was 10% at hour 4, then the value for the minUtilizationPercentage in the response will be 10%. + 2024-10-01-preview and usageDate < 2022-10-31 at a daily granularity. There will be one record + per benefit id for each day. For a single day, the minUtilizationPercentage value will be equal + to the smallest in the set of values where the set contains 24 utilization percentage entries + one for each hour in a specific day. If on the day 2022-10-18, the lowest utilization + percentage was 10% at hour 4, then the value for the minUtilizationPercentage in the response + will be 10%. :vartype min_utilization_percentage: float :ivar max_utilization_percentage: This is the maximum hourly utilization for each date range that corresponds to given grain (Daily, Monthly). Suppose the API call is for usageDate > - 2022-10-01 and usageDate < 2022-10-31 at a daily granularity. There will be one record per - benefit id for each day. For a single day, the maxUtilizationPercentage value will be equal to - the largest in the set of values where the set contains 24 utilization percentage entries one - for each hour in a specific day. If on the day 2022-10-18, the largest utilization percentage - was 90% at hour 5, then the value for the maxUtilizationPercentage in the response will be 90%. + 2024-10-01-preview and usageDate < 2022-10-31 at a daily granularity. There will be one record + per benefit id for each day. For a single day, the maxUtilizationPercentage value will be equal + to the largest in the set of values where the set contains 24 utilization percentage entries + one for each hour in a specific day. If on the day 2022-10-18, the largest utilization + percentage was 90% at hour 5, then the value for the maxUtilizationPercentage in the response + will be 90%. :vartype max_utilization_percentage: float """ @@ -4672,26 +6916,28 @@ class SavingsPlanUtilizationSummaryProperties(BenefitUtilizationSummaryPropertie :vartype usage_date: ~datetime.datetime :ivar avg_utilization_percentage: This is the average hourly utilization for each date range that corresponds to given grain (Daily, Monthly). Suppose the API call is for usageDate > - 2022-10-01 and usageDate < 2022-10-31 at a daily granularity. There will be one record per - benefit id for each day. For a single day, the avgUtilizationPercentage value will be equal to - the average of the set of values where the set contains 24 utilization percentage entries one - for each hour in a specific day. + 2024-10-01-preview and usageDate < 2022-10-31 at a daily granularity. There will be one record + per benefit id for each day. For a single day, the avgUtilizationPercentage value will be equal + to the average of the set of values where the set contains 24 utilization percentage entries + one for each hour in a specific day. :vartype avg_utilization_percentage: float :ivar min_utilization_percentage: This is the minimum hourly utilization for each date range that corresponds to given grain (Daily, Monthly). Suppose the API call is for usageDate > - 2022-10-01 and usageDate < 2022-10-31 at a daily granularity. There will be one record per - benefit id for each day. For a single day, the minUtilizationPercentage value will be equal to - the smallest in the set of values where the set contains 24 utilization percentage entries one - for each hour in a specific day. If on the day 2022-10-18, the lowest utilization percentage - was 10% at hour 4, then the value for the minUtilizationPercentage in the response will be 10%. + 2024-10-01-preview and usageDate < 2022-10-31 at a daily granularity. There will be one record + per benefit id for each day. For a single day, the minUtilizationPercentage value will be equal + to the smallest in the set of values where the set contains 24 utilization percentage entries + one for each hour in a specific day. If on the day 2022-10-18, the lowest utilization + percentage was 10% at hour 4, then the value for the minUtilizationPercentage in the response + will be 10%. :vartype min_utilization_percentage: float :ivar max_utilization_percentage: This is the maximum hourly utilization for each date range that corresponds to given grain (Daily, Monthly). Suppose the API call is for usageDate > - 2022-10-01 and usageDate < 2022-10-31 at a daily granularity. There will be one record per - benefit id for each day. For a single day, the maxUtilizationPercentage value will be equal to - the largest in the set of values where the set contains 24 utilization percentage entries one - for each hour in a specific day. If on the day 2022-10-18, the largest utilization percentage - was 90% at hour 5, then the value for the maxUtilizationPercentage in the response will be 90%. + 2024-10-01-preview and usageDate < 2022-10-31 at a daily granularity. There will be one record + per benefit id for each day. For a single day, the maxUtilizationPercentage value will be equal + to the largest in the set of values where the set contains 24 utilization percentage entries + one for each hour in a specific day. If on the day 2022-10-18, the largest utilization + percentage was 90% at hour 5, then the value for the maxUtilizationPercentage in the response + will be 90%. :vartype max_utilization_percentage: float """ @@ -4734,7 +6980,7 @@ class ScheduledActionProxyResource(ProxyResource): Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -4780,13 +7026,13 @@ def __init__(self, *, kind: Optional[Union[str, "_models.ScheduledActionKind"]] self.system_data = None -class ScheduledAction(ScheduledActionProxyResource): # pylint: disable=too-many-instance-attributes +class ScheduledAction(ScheduledActionProxyResource): """Scheduled action definition. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -4813,10 +7059,11 @@ class ScheduledAction(ScheduledActionProxyResource): # pylint: disable=too-many :vartype notification_email: str :ivar schedule: Schedule of the scheduled action. :vartype schedule: ~azure.mgmt.costmanagement.models.ScheduleProperties - :ivar scope: Cost Management scope like 'subscriptions/{subscriptionId}' for subscription - scope, 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup - scope, 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account - scope, + :ivar scope: For private scheduled action(Create or Update), scope will be empty.\\ :code:`
` For shared scheduled action(Create or Update By Scope), Cost Management scope can be + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for Department scope, 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' @@ -4891,10 +7138,11 @@ def __init__( :paramtype notification_email: str :keyword schedule: Schedule of the scheduled action. :paramtype schedule: ~azure.mgmt.costmanagement.models.ScheduleProperties - :keyword scope: Cost Management scope like 'subscriptions/{subscriptionId}' for subscription - scope, 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup - scope, 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account - scope, + :keyword scope: For private scheduled action(Create or Update), scope will be empty.\\ + :code:`
` For shared scheduled action(Create or Update By Scope), Cost Management scope + can be 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for Department scope, 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' @@ -4957,7 +7205,7 @@ def __init__(self, **kwargs: Any) -> None: class ScheduleProperties(_serialization.Model): """The properties of the schedule. - 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 frequency: Frequency of the schedule. Required. Known values are: "Daily", "Weekly", and "Monthly". @@ -5039,14 +7287,79 @@ def __init__( self.end_date = end_date -class SharedScopeBenefitRecommendationProperties( - BenefitRecommendationProperties -): # pylint: disable=too-many-instance-attributes +class Setting(ProxyResource): + """Setting definition. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + TagInheritanceSetting + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar kind: Specifies the kind of settings. Required. "taginheritance" + :vartype kind: str or ~azure.mgmt.costmanagement.models.SettingsKind + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "kind": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "kind": {"key": "kind", "type": "str"}, + } + + _subtype_map = {"kind": {"taginheritance": "TagInheritanceSetting"}} + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.kind: Optional[str] = None + + +class SettingsListResult(_serialization.Model): + """Setting list result. It contains a list of settings. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: The list of settings. + :vartype value: list[~azure.mgmt.costmanagement.models.Setting] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[Setting]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + + +class SharedScopeBenefitRecommendationProperties(BenefitRecommendationProperties): # pylint: disable=name-too-long """The properties of the benefit recommendation when scope is 'Shared'. 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 first_consumption_date: The first usage date used for looking back for computing the recommendations. @@ -5150,14 +7463,12 @@ def __init__( self.scope: str = "Shared" -class SingleScopeBenefitRecommendationProperties( - BenefitRecommendationProperties -): # pylint: disable=too-many-instance-attributes +class SingleScopeBenefitRecommendationProperties(BenefitRecommendationProperties): # pylint: disable=name-too-long """The properties of the benefit recommendations when scope is 'Single'. 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 first_consumption_date: The first usage date used for looking back for computing the recommendations. @@ -5273,6 +7584,57 @@ def __init__( self.resource_group = None +class SourceCostAllocationResource(CostAllocationResource): + """Source resources for cost allocation. + + All required parameters must be populated in order to send to server. + + :ivar resource_type: Type of resources contained in this cost allocation rule. Required. Known + values are: "Dimension" and "Tag". + :vartype resource_type: str or ~azure.mgmt.costmanagement.models.CostAllocationResourceType + :ivar name: If resource type is dimension, this must be either ResourceGroupName or + SubscriptionId. If resource type is tag, this must be a valid Azure tag. Required. + :vartype name: str + :ivar values: Source Resources for cost allocation. This list cannot contain more than 25 + values. Required. + :vartype values: list[str] + """ + + _validation = { + "resource_type": {"required": True}, + "name": {"required": True}, + "values": {"required": True}, + } + + _attribute_map = { + "resource_type": {"key": "resourceType", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "values": {"key": "values", "type": "[str]"}, + } + + def __init__( + self, + *, + resource_type: Union[str, "_models.CostAllocationResourceType"], + name: str, + values: List[str], + **kwargs: Any + ) -> None: + """ + :keyword resource_type: Type of resources contained in this cost allocation rule. Required. + Known values are: "Dimension" and "Tag". + :paramtype resource_type: str or ~azure.mgmt.costmanagement.models.CostAllocationResourceType + :keyword name: If resource type is dimension, this must be either ResourceGroupName or + SubscriptionId. If resource type is tag, this must be a valid Azure tag. Required. + :paramtype name: str + :keyword values: Source Resources for cost allocation. This list cannot contain more than 25 + values. Required. + :paramtype values: list[str] + """ + super().__init__(resource_type=resource_type, name=name, **kwargs) + self.values = values + + class Status(_serialization.Model): """The status of the long running operation. @@ -5297,6 +7659,48 @@ def __init__( self.status = status +class SystemAssignedServiceIdentity(_serialization.Model): + """Managed service identity (either system assigned, or none). + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar principal_id: The service principal ID of the system assigned identity. This property + will only be provided for a system assigned identity. + :vartype principal_id: str + :ivar tenant_id: The tenant ID of the system assigned identity. This property will only be + provided for a system assigned identity. + :vartype tenant_id: str + :ivar type: Type of managed service identity (either system assigned, or none). Required. Known + values are: "None" and "SystemAssigned". + :vartype type: str or ~azure.mgmt.costmanagement.models.SystemAssignedServiceIdentityType + """ + + _validation = { + "principal_id": {"readonly": True}, + "tenant_id": {"readonly": True}, + "type": {"required": True}, + } + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "tenant_id": {"key": "tenantId", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, *, type: Union[str, "_models.SystemAssignedServiceIdentityType"], **kwargs: Any) -> None: + """ + :keyword type: Type of managed service identity (either system assigned, or none). Required. + Known values are: "None" and "SystemAssigned". + :paramtype type: str or ~azure.mgmt.costmanagement.models.SystemAssignedServiceIdentityType + """ + super().__init__(**kwargs) + self.principal_id = None + self.tenant_id = None + self.type = type + + class SystemData(_serialization.Model): """Metadata pertaining to creation and last modification of the resource. @@ -5361,7 +7765,150 @@ def __init__( self.last_modified_at = last_modified_at -class View(CostManagementProxyResource): # pylint: disable=too-many-instance-attributes +class TagInheritanceProperties(_serialization.Model): + """The properties of the tag inheritance setting. + + All required parameters must be populated in order to send to server. + + :ivar prefer_container_tags: This property defines the behavior when an inherited tag being + applied matches a lower scope tag (Eg. Subscription tag matches the resource tag). If set to + true - when tags match, the highest scope tags will be applied. Billing profile is the highest + scope, followed by invoice sections, subscriptions and resource groups (allows overriding of + lower scope tag values). If set to false - when tags match, the lowest scope tags will be + applied. So, if a resource has the same tag as a subscription tag, the resource tag will be + applied (does not allow overriding of lower scope tag values). Required. + :vartype prefer_container_tags: bool + """ + + _validation = { + "prefer_container_tags": {"required": True}, + } + + _attribute_map = { + "prefer_container_tags": {"key": "preferContainerTags", "type": "bool"}, + } + + def __init__(self, *, prefer_container_tags: bool, **kwargs: Any) -> None: + """ + :keyword prefer_container_tags: This property defines the behavior when an inherited tag being + applied matches a lower scope tag (Eg. Subscription tag matches the resource tag). If set to + true - when tags match, the highest scope tags will be applied. Billing profile is the highest + scope, followed by invoice sections, subscriptions and resource groups (allows overriding of + lower scope tag values). If set to false - when tags match, the lowest scope tags will be + applied. So, if a resource has the same tag as a subscription tag, the resource tag will be + applied (does not allow overriding of lower scope tag values). Required. + :paramtype prefer_container_tags: bool + """ + super().__init__(**kwargs) + self.prefer_container_tags = prefer_container_tags + + +class TagInheritanceSetting(Setting): + """Tag Inheritance Setting definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar kind: Specifies the kind of settings. Required. "taginheritance" + :vartype kind: str or ~azure.mgmt.costmanagement.models.SettingsKind + :ivar properties: The properties of the tag inheritance setting. + :vartype properties: ~azure.mgmt.costmanagement.models.TagInheritanceProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "kind": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "kind": {"key": "kind", "type": "str"}, + "properties": {"key": "properties", "type": "TagInheritanceProperties"}, + } + + def __init__(self, *, properties: Optional["_models.TagInheritanceProperties"] = None, **kwargs: Any) -> None: + """ + :keyword properties: The properties of the tag inheritance setting. + :paramtype properties: ~azure.mgmt.costmanagement.models.TagInheritanceProperties + """ + super().__init__(**kwargs) + self.kind: str = "taginheritance" + self.properties = properties + + +class TargetCostAllocationResource(CostAllocationResource): + """Target resources for cost allocation. + + All required parameters must be populated in order to send to server. + + :ivar resource_type: Type of resources contained in this cost allocation rule. Required. Known + values are: "Dimension" and "Tag". + :vartype resource_type: str or ~azure.mgmt.costmanagement.models.CostAllocationResourceType + :ivar name: If resource type is dimension, this must be either ResourceGroupName or + SubscriptionId. If resource type is tag, this must be a valid Azure tag. Required. + :vartype name: str + :ivar values: Target resources for cost allocation. This list cannot contain more than 25 + values. Required. + :vartype values: list[~azure.mgmt.costmanagement.models.CostAllocationProportion] + :ivar policy_type: Method of cost allocation for the rule. Required. "FixedProportion" + :vartype policy_type: str or ~azure.mgmt.costmanagement.models.CostAllocationPolicyType + """ + + _validation = { + "resource_type": {"required": True}, + "name": {"required": True}, + "values": {"required": True}, + "policy_type": {"required": True}, + } + + _attribute_map = { + "resource_type": {"key": "resourceType", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "values": {"key": "values", "type": "[CostAllocationProportion]"}, + "policy_type": {"key": "policyType", "type": "str"}, + } + + def __init__( + self, + *, + resource_type: Union[str, "_models.CostAllocationResourceType"], + name: str, + values: List["_models.CostAllocationProportion"], + policy_type: Union[str, "_models.CostAllocationPolicyType"], + **kwargs: Any + ) -> None: + """ + :keyword resource_type: Type of resources contained in this cost allocation rule. Required. + Known values are: "Dimension" and "Tag". + :paramtype resource_type: str or ~azure.mgmt.costmanagement.models.CostAllocationResourceType + :keyword name: If resource type is dimension, this must be either ResourceGroupName or + SubscriptionId. If resource type is tag, this must be a valid Azure tag. Required. + :paramtype name: str + :keyword values: Target resources for cost allocation. This list cannot contain more than 25 + values. Required. + :paramtype values: list[~azure.mgmt.costmanagement.models.CostAllocationProportion] + :keyword policy_type: Method of cost allocation for the rule. Required. "FixedProportion" + :paramtype policy_type: str or ~azure.mgmt.costmanagement.models.CostAllocationPolicyType + """ + super().__init__(resource_type=resource_type, name=name, **kwargs) + self.values = values + self.policy_type = policy_type + + +class View(CostManagementProxyResource): """States and configurations of Cost Analysis. Variables are only populated by the server, and will be ignored when sending a request. @@ -5436,7 +7983,6 @@ class View(CostManagementProxyResource): # pylint: disable=too-many-instance-at "name": {"readonly": True}, "type": {"readonly": True}, "created_on": {"readonly": True}, - "modified_on": {"readonly": True}, "currency": {"readonly": True}, } @@ -5469,6 +8015,7 @@ def __init__( e_tag: Optional[str] = None, display_name: Optional[str] = None, scope: Optional[str] = None, + modified_on: Optional[datetime.datetime] = None, date_range: Optional[str] = None, chart: Optional[Union[str, "_models.ChartType"]] = None, accumulated: Optional[Union[str, "_models.AccumulatedType"]] = None, @@ -5506,6 +8053,8 @@ def __init__( '/providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for ExternalSubscription scope. :paramtype scope: str + :keyword modified_on: Date when the user last modified this view. + :paramtype modified_on: ~datetime.datetime :keyword date_range: Date range of the current view. :paramtype date_range: str :keyword chart: Chart type of the main view in Cost Analysis. Required. Known values are: @@ -5539,7 +8088,7 @@ def __init__( self.display_name = display_name self.scope = scope self.created_on = None - self.modified_on = None + self.modified_on = modified_on self.date_range = date_range self.currency = None self.chart = chart diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/__init__.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/__init__.py index ba3f6355c103..abdd1e06a664 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/__init__.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/__init__.py @@ -5,49 +5,59 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._operations import Operations -from ._views_operations import ViewsOperations -from ._alerts_operations import AlertsOperations -from ._forecast_operations import ForecastOperations -from ._dimensions_operations import DimensionsOperations -from ._query_operations import QueryOperations -from ._generate_reservation_details_report_operations import GenerateReservationDetailsReportOperations -from ._exports_operations import ExportsOperations -from ._generate_cost_details_report_operations import GenerateCostDetailsReportOperations -from ._generate_detailed_cost_report_operations import GenerateDetailedCostReportOperations -from ._generate_detailed_cost_report_operation_results_operations import ( - GenerateDetailedCostReportOperationResultsOperations, -) -from ._generate_detailed_cost_report_operation_status_operations import ( - GenerateDetailedCostReportOperationStatusOperations, -) -from ._price_sheet_operations import PriceSheetOperations -from ._scheduled_actions_operations import ScheduledActionsOperations -from ._benefit_recommendations_operations import BenefitRecommendationsOperations -from ._benefit_utilization_summaries_operations import BenefitUtilizationSummariesOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import Operations # type: ignore +from ._cost_allocation_rules_operations import CostAllocationRulesOperations # type: ignore +from ._benefit_recommendations_operations import BenefitRecommendationsOperations # type: ignore +from ._benefit_utilization_summaries_operations import BenefitUtilizationSummariesOperations # type: ignore +from ._generate_benefit_utilization_summaries_report_operations import GenerateBenefitUtilizationSummariesReportOperations # type: ignore +from ._budgets_operations import BudgetsOperations # type: ignore +from ._exports_operations import ExportsOperations # type: ignore +from ._generate_cost_details_report_operations import GenerateCostDetailsReportOperations # type: ignore +from ._generate_detailed_cost_report_operations import GenerateDetailedCostReportOperations # type: ignore +from ._generate_detailed_cost_report_operation_results_operations import GenerateDetailedCostReportOperationResultsOperations # type: ignore +from ._generate_detailed_cost_report_operation_status_operations import GenerateDetailedCostReportOperationStatusOperations # type: ignore +from ._views_operations import ViewsOperations # type: ignore +from ._alerts_operations import AlertsOperations # type: ignore +from ._forecast_operations import ForecastOperations # type: ignore +from ._dimensions_operations import DimensionsOperations # type: ignore +from ._query_operations import QueryOperations # type: ignore +from ._generate_reservation_details_report_operations import GenerateReservationDetailsReportOperations # type: ignore +from ._price_sheet_operations import PriceSheetOperations # type: ignore +from ._scheduled_actions_operations import ScheduledActionsOperations # type: ignore +from ._settings_operations import SettingsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "Operations", + "CostAllocationRulesOperations", + "BenefitRecommendationsOperations", + "BenefitUtilizationSummariesOperations", + "GenerateBenefitUtilizationSummariesReportOperations", + "BudgetsOperations", + "ExportsOperations", + "GenerateCostDetailsReportOperations", + "GenerateDetailedCostReportOperations", + "GenerateDetailedCostReportOperationResultsOperations", + "GenerateDetailedCostReportOperationStatusOperations", "ViewsOperations", "AlertsOperations", "ForecastOperations", "DimensionsOperations", "QueryOperations", "GenerateReservationDetailsReportOperations", - "ExportsOperations", - "GenerateCostDetailsReportOperations", - "GenerateDetailedCostReportOperations", - "GenerateDetailedCostReportOperationResultsOperations", - "GenerateDetailedCostReportOperationStatusOperations", "PriceSheetOperations", "ScheduledActionsOperations", - "BenefitRecommendationsOperations", - "BenefitUtilizationSummariesOperations", + "SettingsOperations", ] -__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/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_alerts_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_alerts_operations.py index 266574888da0..933a9d690a76 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_alerts_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_alerts_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( @@ -18,16 +18,18 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -39,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: str = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -48,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") @@ -63,7 +65,7 @@ def build_get_request(scope: str, alert_id: 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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -73,7 +75,7 @@ def build_get_request(scope: str, alert_id: str, **kwargs: Any) -> HttpRequest: "alertId": _SERIALIZER.url("alert_id", alert_id, "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") @@ -88,7 +90,7 @@ def build_dismiss_request(scope: str, alert_id: str, **kwargs: Any) -> HttpReque _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -99,7 +101,7 @@ def build_dismiss_request(scope: str, alert_id: str, **kwargs: Any) -> HttpReque "alertId": _SERIALIZER.url("alert_id", alert_id, "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") @@ -120,7 +122,7 @@ def build_list_external_request( _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -135,7 +137,7 @@ def build_list_external_request( "externalCloudProviderId": _SERIALIZER.url("external_cloud_provider_id", external_cloud_provider_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") @@ -167,6 +169,7 @@ def __init__(self, *args, **kwargs): @distributed_trace def list(self, scope: str, **kwargs: Any) -> _models.AlertsResult: + # pylint: disable=line-too-long """Lists the alerts for scope defined. .. seealso:: @@ -189,12 +192,11 @@ def list(self, scope: str, **kwargs: Any) -> _models.AlertsResult: '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' specific for partners. Required. :type scope: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AlertsResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.AlertsResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -208,19 +210,17 @@ def list(self, scope: str, **kwargs: Any) -> _models.AlertsResult: api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.AlertsResult] = kwargs.pop("cls", None) - 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -230,17 +230,16 @@ def list(self, scope: str, **kwargs: Any) -> _models.AlertsResult: error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AlertsResult", pipeline_response) + deserialized = self._deserialize("AlertsResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - list.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/alerts"} + return deserialized # type: ignore @distributed_trace def get(self, scope: str, alert_id: str, **kwargs: Any) -> _models.Alert: + # pylint: disable=line-too-long """Gets the alert for the scope by alert ID. .. seealso:: @@ -265,12 +264,11 @@ def get(self, scope: str, alert_id: str, **kwargs: Any) -> _models.Alert: :type scope: str :param alert_id: Alert ID. Required. :type alert_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Alert or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Alert :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -284,20 +282,18 @@ def get(self, scope: str, alert_id: str, **kwargs: Any) -> _models.Alert: api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Alert] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( scope=scope, alert_id=alert_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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -307,14 +303,12 @@ def get(self, scope: str, alert_id: str, **kwargs: Any) -> _models.Alert: error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Alert", pipeline_response) + deserialized = self._deserialize("Alert", 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.CostManagement/alerts/{alertId}"} + return deserialized # type: ignore @overload def dismiss( @@ -326,6 +320,7 @@ def dismiss( content_type: str = "application/json", **kwargs: Any ) -> _models.Alert: + # pylint: disable=line-too-long """Dismisses the specified alert. .. seealso:: @@ -355,7 +350,6 @@ def dismiss( :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: Alert or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Alert :raises ~azure.core.exceptions.HttpResponseError: @@ -363,8 +357,9 @@ def dismiss( @overload def dismiss( - self, scope: str, alert_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, scope: str, alert_id: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.Alert: + # pylint: disable=line-too-long """Dismisses the specified alert. .. seealso:: @@ -390,11 +385,10 @@ def dismiss( :param alert_id: Alert ID. Required. :type alert_id: str :param parameters: Parameters supplied to the Dismiss Alert 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: Alert or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Alert :raises ~azure.core.exceptions.HttpResponseError: @@ -402,8 +396,9 @@ def dismiss( @distributed_trace def dismiss( - self, scope: str, alert_id: str, parameters: Union[_models.DismissAlertPayload, IO], **kwargs: Any + self, scope: str, alert_id: str, parameters: Union[_models.DismissAlertPayload, IO[bytes]], **kwargs: Any ) -> _models.Alert: + # pylint: disable=line-too-long """Dismisses the specified alert. .. seealso:: @@ -429,17 +424,13 @@ def dismiss( :param alert_id: Alert ID. Required. :type alert_id: str :param parameters: Parameters supplied to the Dismiss Alert operation. Is either a - DismissAlertPayload type or a IO type. Required. - :type parameters: ~azure.mgmt.costmanagement.models.DismissAlertPayload 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 + DismissAlertPayload type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.DismissAlertPayload or IO[bytes] :return: Alert or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Alert :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -462,23 +453,21 @@ def dismiss( else: _json = self._serialize.body(parameters, "DismissAlertPayload") - request = build_dismiss_request( + _request = build_dismiss_request( scope=scope, alert_id=alert_id, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.dismiss.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -488,14 +477,12 @@ def dismiss( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Alert", pipeline_response) + deserialized = self._deserialize("Alert", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - dismiss.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/alerts/{alertId}"} + return deserialized # type: ignore @distributed_trace def list_external( @@ -519,12 +506,11 @@ def list_external( '{externalBillingAccountId}' for consolidated account used with dimension/query operations. Required. :type external_cloud_provider_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AlertsResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.AlertsResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -538,20 +524,18 @@ def list_external( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.AlertsResult] = kwargs.pop("cls", None) - request = build_list_external_request( + _request = build_list_external_request( external_cloud_provider_type=external_cloud_provider_type, external_cloud_provider_id=external_cloud_provider_id, api_version=api_version, - template_url=self.list_external.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -561,13 +545,9 @@ def list_external( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AlertsResult", pipeline_response) + deserialized = self._deserialize("AlertsResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - list_external.metadata = { - "url": "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/alerts" - } + return deserialized # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_benefit_recommendations_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_benefit_recommendations_operations.py index 3503a1d3721e..99bb0edea352 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_benefit_recommendations_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_benefit_recommendations_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar import urllib.parse @@ -19,16 +19,18 @@ ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -47,7 +49,7 @@ def build_list_request( _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -56,7 +58,7 @@ def build_list_request( "billingScope": _SERIALIZER.url("billing_scope", billing_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: @@ -127,7 +129,6 @@ def list( :param expand: May be used to expand the properties by: properties/usage, properties/allRecommendationDetails. Default value is None. :type expand: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BenefitRecommendationModel or the result of cls(response) :rtype: @@ -140,7 +141,7 @@ def list( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BenefitRecommendationsListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -151,18 +152,16 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( billing_scope=billing_scope, filter=filter, orderby=orderby, expand=expand, 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 @@ -174,13 +173,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("BenefitRecommendationsListResult", pipeline_response) @@ -190,11 +188,11 @@ 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -206,5 +204,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{billingScope}/providers/Microsoft.CostManagement/benefitRecommendations"} diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_benefit_utilization_summaries_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_benefit_utilization_summaries_operations.py index 3a8af9d96867..a70b47607789 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_benefit_utilization_summaries_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_benefit_utilization_summaries_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union import urllib.parse @@ -19,16 +19,18 @@ ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -46,7 +48,7 @@ def build_list_by_billing_account_id_request( _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -58,7 +60,7 @@ def build_list_by_billing_account_id_request( "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") @@ -84,7 +86,7 @@ def build_list_by_billing_profile_id_request( _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -97,7 +99,7 @@ def build_list_by_billing_profile_id_request( "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") @@ -122,7 +124,7 @@ def build_list_by_savings_plan_order_request( _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -134,7 +136,7 @@ def build_list_by_savings_plan_order_request( "savingsPlanOrderId": _SERIALIZER.url("savings_plan_order_id", savings_plan_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["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -160,7 +162,7 @@ def build_list_by_savings_plan_id_request( _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -173,7 +175,7 @@ def build_list_by_savings_plan_id_request( "savingsPlanId": _SERIALIZER.url("savings_plan_id", savings_plan_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") @@ -229,7 +231,6 @@ def list_by_billing_account_id( :param filter: Supports filtering by properties/benefitId, properties/benefitOrderId and properties/usageDate. 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 BenefitUtilizationSummary or the result of cls(response) :rtype: @@ -242,7 +243,7 @@ def list_by_billing_account_id( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BenefitUtilizationSummariesListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -253,17 +254,15 @@ def list_by_billing_account_id( def prepare_request(next_link=None): if not next_link: - request = build_list_by_billing_account_id_request( + _request = build_list_by_billing_account_id_request( billing_account_id=billing_account_id, grain_parameter=grain_parameter, filter=filter, api_version=api_version, - template_url=self.list_by_billing_account_id.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 @@ -275,13 +274,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("BenefitUtilizationSummariesListResult", pipeline_response) @@ -291,11 +289,11 @@ 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -308,10 +306,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_billing_account_id.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/benefitUtilizationSummaries" - } - @distributed_trace def list_by_billing_profile_id( self, @@ -337,7 +331,6 @@ def list_by_billing_profile_id( :param filter: Supports filtering by properties/benefitId, properties/benefitOrderId and properties/usageDate. 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 BenefitUtilizationSummary or the result of cls(response) :rtype: @@ -350,7 +343,7 @@ def list_by_billing_profile_id( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BenefitUtilizationSummariesListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -361,18 +354,16 @@ def list_by_billing_profile_id( def prepare_request(next_link=None): if not next_link: - request = build_list_by_billing_profile_id_request( + _request = build_list_by_billing_profile_id_request( billing_account_id=billing_account_id, billing_profile_id=billing_profile_id, grain_parameter=grain_parameter, filter=filter, api_version=api_version, - template_url=self.list_by_billing_profile_id.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 @@ -384,13 +375,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("BenefitUtilizationSummariesListResult", pipeline_response) @@ -400,11 +390,11 @@ 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -417,10 +407,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_billing_profile_id.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.CostManagement/benefitUtilizationSummaries" - } - @distributed_trace def list_by_savings_plan_order( self, @@ -441,7 +427,6 @@ def list_by_savings_plan_order( :param grain_parameter: Grain. Known values are: "Hourly", "Daily", and "Monthly". Default value is None. :type grain_parameter: str or ~azure.mgmt.costmanagement.models.GrainParameter - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BenefitUtilizationSummary or the result of cls(response) :rtype: @@ -454,7 +439,7 @@ def list_by_savings_plan_order( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BenefitUtilizationSummariesListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -465,17 +450,15 @@ def list_by_savings_plan_order( def prepare_request(next_link=None): if not next_link: - request = build_list_by_savings_plan_order_request( + _request = build_list_by_savings_plan_order_request( savings_plan_order_id=savings_plan_order_id, filter=filter, grain_parameter=grain_parameter, api_version=api_version, - template_url=self.list_by_savings_plan_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 @@ -487,13 +470,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("BenefitUtilizationSummariesListResult", pipeline_response) @@ -503,11 +485,11 @@ 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -520,10 +502,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_savings_plan_order.metadata = { - "url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/providers/Microsoft.CostManagement/benefitUtilizationSummaries" - } - @distributed_trace def list_by_savings_plan_id( self, @@ -547,7 +525,6 @@ def list_by_savings_plan_id( :param grain_parameter: Grain. Known values are: "Hourly", "Daily", and "Monthly". Default value is None. :type grain_parameter: str or ~azure.mgmt.costmanagement.models.GrainParameter - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either BenefitUtilizationSummary or the result of cls(response) :rtype: @@ -560,7 +537,7 @@ def list_by_savings_plan_id( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.BenefitUtilizationSummariesListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -571,18 +548,16 @@ def list_by_savings_plan_id( def prepare_request(next_link=None): if not next_link: - request = build_list_by_savings_plan_id_request( + _request = build_list_by_savings_plan_id_request( savings_plan_order_id=savings_plan_order_id, savings_plan_id=savings_plan_id, filter=filter, grain_parameter=grain_parameter, api_version=api_version, - template_url=self.list_by_savings_plan_id.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 @@ -594,13 +569,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("BenefitUtilizationSummariesListResult", pipeline_response) @@ -610,11 +584,11 @@ 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -626,7 +600,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list_by_savings_plan_id.metadata = { - "url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans/{savingsPlanId}/providers/Microsoft.CostManagement/benefitUtilizationSummaries" - } diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_budgets_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_budgets_operations.py new file mode 100644 index 000000000000..c2333f04811b --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_budgets_operations.py @@ -0,0 +1,809 @@ +# 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 io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +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 + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(scope: 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: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/budgets") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(scope: str, budget_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/budgets/{budgetName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "budgetName": _SERIALIZER.url( + "budget_name", budget_name, "str", max_length=63, min_length=1, pattern=r"^[a-zA-Z0-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="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request(scope: str, budget_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/budgets/{budgetName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "budgetName": _SERIALIZER.url( + "budget_name", budget_name, "str", max_length=63, min_length=1, pattern=r"^[a-zA-Z0-9_-]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request(scope: str, budget_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/budgets/{budgetName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "budgetName": _SERIALIZER.url( + "budget_name", budget_name, "str", max_length=63, min_length=1, pattern=r"^[a-zA-Z0-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="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class BudgetsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`budgets` attribute. + """ + + models = _models + + 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") + + @distributed_trace + def list(self, scope: str, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.Budget"]: + # pylint: disable=line-too-long + """Lists all budgets for the defined scope. + + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/CostManagement/ + + :param scope: The scope associated with budget operations. + + Supported scopes for **CategoryType: Cost** + + Azure RBAC Scopes: + + + * '/subscriptions/{subscriptionId}/' for subscription scope + * '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope + * + '/providers/Microsoft.Management/managementGroups/{managementGroupId}' for Management Group + scope + + EA (Enterprise Agreement) Scopes: + + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope + + MCA (Modern Customer Agreement) Scopes: + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' for + customer scope (CSP only) + + Supported scopes for **CategoryType: ReservationUtilization** + + EA (Enterprise Agreement) Scopes: + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account Scope + + MCA (Modern Customer Agreement) Scopes: + + + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope (non-CSP only) + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' for + customer scope (CSP only). Required. + :type scope: str + :param filter: OData filter option. May be used to filter budgets by properties/category. The + filter supports 'eq' only. Default value is None. + :type filter: str + :return: An iterator like instance of either Budget or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.Budget] + :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.BudgetsListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + scope=scope, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("BudgetsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get(self, scope: str, budget_name: str, **kwargs: Any) -> _models.Budget: + # pylint: disable=line-too-long + """Gets the budget for the scope by budget name. + + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/CostManagement/ + + :param scope: The scope associated with budget operations. + + Supported scopes for **CategoryType: Cost** + + Azure RBAC Scopes: + + + * '/subscriptions/{subscriptionId}/' for subscription scope + * '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope + * + '/providers/Microsoft.Management/managementGroups/{managementGroupId}' for Management Group + scope + + EA (Enterprise Agreement) Scopes: + + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope + + MCA (Modern Customer Agreement) Scopes: + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' for + customer scope (CSP only) + + Supported scopes for **CategoryType: ReservationUtilization** + + EA (Enterprise Agreement) Scopes: + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account Scope + + MCA (Modern Customer Agreement) Scopes: + + + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope (non-CSP only) + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' for + customer scope (CSP only). Required. + :type scope: str + :param budget_name: Budget Name. Required. + :type budget_name: str + :return: Budget or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Budget + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.Budget] = kwargs.pop("cls", None) + + _request = build_get_request( + scope=scope, + budget_name=budget_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Budget", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_or_update( + self, + scope: str, + budget_name: str, + parameters: _models.Budget, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Budget: + # pylint: disable=line-too-long + """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/CostManagement/ + + :param scope: The scope associated with budget operations. + + Supported scopes for **CategoryType: Cost** + + Azure RBAC Scopes: + + + * '/subscriptions/{subscriptionId}/' for subscription scope + * '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope + * + '/providers/Microsoft.Management/managementGroups/{managementGroupId}' for Management Group + scope + + EA (Enterprise Agreement) Scopes: + + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope + + MCA (Modern Customer Agreement) Scopes: + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' for + customer scope (CSP only) + + Supported scopes for **CategoryType: ReservationUtilization** + + EA (Enterprise Agreement) Scopes: + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account Scope + + MCA (Modern Customer Agreement) Scopes: + + + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope (non-CSP only) + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' for + customer scope (CSP only). 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: ~azure.mgmt.costmanagement.models.Budget + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Budget or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Budget + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + scope: str, + budget_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Budget: + # pylint: disable=line-too-long + """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/CostManagement/ + + :param scope: The scope associated with budget operations. + + Supported scopes for **CategoryType: Cost** + + Azure RBAC Scopes: + + + * '/subscriptions/{subscriptionId}/' for subscription scope + * '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope + * + '/providers/Microsoft.Management/managementGroups/{managementGroupId}' for Management Group + scope + + EA (Enterprise Agreement) Scopes: + + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope + + MCA (Modern Customer Agreement) Scopes: + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' for + customer scope (CSP only) + + Supported scopes for **CategoryType: ReservationUtilization** + + EA (Enterprise Agreement) Scopes: + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account Scope + + MCA (Modern Customer Agreement) Scopes: + + + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope (non-CSP only) + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' for + customer scope (CSP only). 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[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Budget or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Budget + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, scope: str, budget_name: str, parameters: Union[_models.Budget, IO[bytes]], **kwargs: Any + ) -> _models.Budget: + # pylint: disable=line-too-long + """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/CostManagement/ + + :param scope: The scope associated with budget operations. + + Supported scopes for **CategoryType: Cost** + + Azure RBAC Scopes: + + + * '/subscriptions/{subscriptionId}/' for subscription scope + * '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope + * + '/providers/Microsoft.Management/managementGroups/{managementGroupId}' for Management Group + scope + + EA (Enterprise Agreement) Scopes: + + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope + + MCA (Modern Customer Agreement) Scopes: + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' for + customer scope (CSP only) + + Supported scopes for **CategoryType: ReservationUtilization** + + EA (Enterprise Agreement) Scopes: + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account Scope + + MCA (Modern Customer Agreement) Scopes: + + + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope (non-CSP only) + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' for + customer scope (CSP only). 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 Budget type + or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.Budget or IO[bytes] + :return: Budget or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Budget + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = 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", 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, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Budget") + + _request = build_create_or_update_request( + scope=scope, + budget_name=budget_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Budget", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, scope: str, budget_name: str, **kwargs: Any + ) -> None: + # pylint: disable=line-too-long + """The operation to delete a budget. + + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/CostManagement/ + + :param scope: The scope associated with budget operations. + + Supported scopes for **CategoryType: Cost** + + Azure RBAC Scopes: + + + * '/subscriptions/{subscriptionId}/' for subscription scope + * '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope + * + '/providers/Microsoft.Management/managementGroups/{managementGroupId}' for Management Group + scope + + EA (Enterprise Agreement) Scopes: + + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope + + MCA (Modern Customer Agreement) Scopes: + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' for + customer scope (CSP only) + + Supported scopes for **CategoryType: ReservationUtilization** + + EA (Enterprise Agreement) Scopes: + + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account Scope + + MCA (Modern Customer Agreement) Scopes: + + + * + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope (non-CSP only) + * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' for + customer scope (CSP only). Required. + :type scope: str + :param budget_name: Budget Name. Required. + :type budget_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_delete_request( + scope=scope, + budget_name=budget_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_cost_allocation_rules_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_cost_allocation_rules_operations.py new file mode 100644 index 000000000000..eeffb97b623b --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_cost_allocation_rules_operations.py @@ -0,0 +1,652 @@ +# 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 io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +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 + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(billing_account_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/costAllocationRules", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + } + + _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="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_check_name_availability_request(billing_account_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/costAllocationRules/checkNameAvailability", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(billing_account_id: str, rule_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/costAllocationRules/{ruleName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + "ruleName": _SERIALIZER.url("rule_name", rule_name, "str", pattern=r"[A-Za-z0-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="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request(billing_account_id: str, rule_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/costAllocationRules/{ruleName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + "ruleName": _SERIALIZER.url("rule_name", rule_name, "str", pattern=r"[A-Za-z0-9\-_]+"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request(billing_account_id: str, rule_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/costAllocationRules/{ruleName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + "ruleName": _SERIALIZER.url("rule_name", rule_name, "str", pattern=r"[A-Za-z0-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="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class CostAllocationRulesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`cost_allocation_rules` attribute. + """ + + models = _models + + 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") + + @distributed_trace + def list(self, billing_account_id: str, **kwargs: Any) -> Iterable["_models.CostAllocationRuleDefinition"]: + """Get the list of all cost allocation rules for a billing account or enterprise enrollment. + + :param billing_account_id: BillingAccount ID. Required. + :type billing_account_id: str + :return: An iterator like instance of either CostAllocationRuleDefinition or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.CostAllocationRuleDefinition] + :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.CostAllocationRuleList] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + billing_account_id=billing_account_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("CostAllocationRuleList", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @overload + def check_name_availability( + self, + billing_account_id: str, + cost_allocation_rule_check_name_availability_request: _models.CostAllocationRuleCheckNameAvailabilityRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CostAllocationRuleCheckNameAvailabilityResponse: + """Checks availability and correctness of a name for a cost allocation rule. + + :param billing_account_id: BillingAccount ID. Required. + :type billing_account_id: str + :param cost_allocation_rule_check_name_availability_request: Cost allocation rule to be created + or updated. Required. + :type cost_allocation_rule_check_name_availability_request: + ~azure.mgmt.costmanagement.models.CostAllocationRuleCheckNameAvailabilityRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: CostAllocationRuleCheckNameAvailabilityResponse or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.CostAllocationRuleCheckNameAvailabilityResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def check_name_availability( + self, + billing_account_id: str, + cost_allocation_rule_check_name_availability_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CostAllocationRuleCheckNameAvailabilityResponse: + """Checks availability and correctness of a name for a cost allocation rule. + + :param billing_account_id: BillingAccount ID. Required. + :type billing_account_id: str + :param cost_allocation_rule_check_name_availability_request: Cost allocation rule to be created + or updated. Required. + :type cost_allocation_rule_check_name_availability_request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: CostAllocationRuleCheckNameAvailabilityResponse or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.CostAllocationRuleCheckNameAvailabilityResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def check_name_availability( + self, + billing_account_id: str, + cost_allocation_rule_check_name_availability_request: Union[ + _models.CostAllocationRuleCheckNameAvailabilityRequest, IO[bytes] + ], + **kwargs: Any + ) -> _models.CostAllocationRuleCheckNameAvailabilityResponse: + """Checks availability and correctness of a name for a cost allocation rule. + + :param billing_account_id: BillingAccount ID. Required. + :type billing_account_id: str + :param cost_allocation_rule_check_name_availability_request: Cost allocation rule to be created + or updated. Is either a CostAllocationRuleCheckNameAvailabilityRequest type or a IO[bytes] + type. Required. + :type cost_allocation_rule_check_name_availability_request: + ~azure.mgmt.costmanagement.models.CostAllocationRuleCheckNameAvailabilityRequest or IO[bytes] + :return: CostAllocationRuleCheckNameAvailabilityResponse or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.CostAllocationRuleCheckNameAvailabilityResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = 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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CostAllocationRuleCheckNameAvailabilityResponse] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(cost_allocation_rule_check_name_availability_request, (IOBase, bytes)): + _content = cost_allocation_rule_check_name_availability_request + else: + _json = self._serialize.body( + cost_allocation_rule_check_name_availability_request, "CostAllocationRuleCheckNameAvailabilityRequest" + ) + + _request = build_check_name_availability_request( + billing_account_id=billing_account_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize( + "CostAllocationRuleCheckNameAvailabilityResponse", pipeline_response.http_response + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get(self, billing_account_id: str, rule_name: str, **kwargs: Any) -> _models.CostAllocationRuleDefinition: + """Get a cost allocation rule by rule name and billing account or enterprise enrollment. + + :param billing_account_id: BillingAccount ID. Required. + :type billing_account_id: str + :param rule_name: Cost allocation rule name. The name cannot include spaces or any non + alphanumeric characters other than '_' and '-'. The max length is 260 characters. Required. + :type rule_name: str + :return: CostAllocationRuleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.CostAllocationRuleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.CostAllocationRuleDefinition] = kwargs.pop("cls", None) + + _request = build_get_request( + billing_account_id=billing_account_id, + rule_name=rule_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("CostAllocationRuleDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_or_update( + self, + billing_account_id: str, + rule_name: str, + cost_allocation_rule: _models.CostAllocationRuleDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CostAllocationRuleDefinition: + """Create/Update a rule to allocate cost between different resources within a billing account or + enterprise enrollment. + + :param billing_account_id: BillingAccount ID. Required. + :type billing_account_id: str + :param rule_name: Cost allocation rule name. The name cannot include spaces or any non + alphanumeric characters other than '_' and '-'. The max length is 260 characters. Required. + :type rule_name: str + :param cost_allocation_rule: Cost allocation rule to be created or updated. Required. + :type cost_allocation_rule: ~azure.mgmt.costmanagement.models.CostAllocationRuleDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: CostAllocationRuleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.CostAllocationRuleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + billing_account_id: str, + rule_name: str, + cost_allocation_rule: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CostAllocationRuleDefinition: + """Create/Update a rule to allocate cost between different resources within a billing account or + enterprise enrollment. + + :param billing_account_id: BillingAccount ID. Required. + :type billing_account_id: str + :param rule_name: Cost allocation rule name. The name cannot include spaces or any non + alphanumeric characters other than '_' and '-'. The max length is 260 characters. Required. + :type rule_name: str + :param cost_allocation_rule: Cost allocation rule to be created or updated. Required. + :type cost_allocation_rule: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: CostAllocationRuleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.CostAllocationRuleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + billing_account_id: str, + rule_name: str, + cost_allocation_rule: Union[_models.CostAllocationRuleDefinition, IO[bytes]], + **kwargs: Any + ) -> _models.CostAllocationRuleDefinition: + """Create/Update a rule to allocate cost between different resources within a billing account or + enterprise enrollment. + + :param billing_account_id: BillingAccount ID. Required. + :type billing_account_id: str + :param rule_name: Cost allocation rule name. The name cannot include spaces or any non + alphanumeric characters other than '_' and '-'. The max length is 260 characters. Required. + :type rule_name: str + :param cost_allocation_rule: Cost allocation rule to be created or updated. Is either a + CostAllocationRuleDefinition type or a IO[bytes] type. Required. + :type cost_allocation_rule: ~azure.mgmt.costmanagement.models.CostAllocationRuleDefinition or + IO[bytes] + :return: CostAllocationRuleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.CostAllocationRuleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = 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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CostAllocationRuleDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(cost_allocation_rule, (IOBase, bytes)): + _content = cost_allocation_rule + else: + _json = self._serialize.body(cost_allocation_rule, "CostAllocationRuleDefinition") + + _request = build_create_or_update_request( + billing_account_id=billing_account_id, + rule_name=rule_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("CostAllocationRuleDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, billing_account_id: str, rule_name: str, **kwargs: Any + ) -> None: + """Delete cost allocation rule for billing account or enterprise enrollment. + + :param billing_account_id: BillingAccount ID. Required. + :type billing_account_id: str + :param rule_name: Cost allocation rule name. The name cannot include spaces or any non + alphanumeric characters other than '_' and '-'. The max length is 260 characters. Required. + :type rule_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_delete_request( + billing_account_id=billing_account_id, + rule_name=rule_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_dimensions_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_dimensions_operations.py index 19dec07c7dc7..6e4a35d7dcad 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_dimensions_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_dimensions_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union import urllib.parse @@ -19,16 +19,18 @@ ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -48,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: str = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -57,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 _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -76,7 +78,7 @@ def build_list_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_by_external_cloud_provider_type_request( +def build_by_external_cloud_provider_type_request( # pylint: disable=name-too-long external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], external_cloud_provider_id: str, *, @@ -89,7 +91,7 @@ def build_by_external_cloud_provider_type_request( _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -104,7 +106,7 @@ def build_by_external_cloud_provider_type_request( "externalCloudProviderId": _SERIALIZER.url("external_cloud_provider_id", external_cloud_provider_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") @@ -152,6 +154,7 @@ def list( top: Optional[int] = None, **kwargs: Any ) -> Iterable["_models.Dimension"]: + # pylint: disable=line-too-long """Lists the dimensions by the defined scope. .. seealso:: @@ -189,7 +192,6 @@ def list( :param top: May be used to limit the number of results to the most recent N dimension data. Default value is None. :type top: int - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Dimension or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.Dimension] :raises ~azure.core.exceptions.HttpResponseError: @@ -200,7 +202,7 @@ def list( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.DimensionsListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -211,19 +213,17 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( scope=scope, filter=filter, expand=expand, skiptoken=skiptoken, top=top, 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 @@ -235,13 +235,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("DimensionsListResult", pipeline_response) @@ -251,11 +250,11 @@ def extract_data(pipeline_response): return 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -268,8 +267,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/dimensions"} - @distributed_trace def by_external_cloud_provider_type( self, @@ -311,7 +308,6 @@ def by_external_cloud_provider_type( :param top: May be used to limit the number of results to the most recent N dimension data. Default value is None. :type top: int - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Dimension or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.Dimension] :raises ~azure.core.exceptions.HttpResponseError: @@ -322,7 +318,7 @@ def by_external_cloud_provider_type( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.DimensionsListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -333,7 +329,7 @@ def by_external_cloud_provider_type( def prepare_request(next_link=None): if not next_link: - request = build_by_external_cloud_provider_type_request( + _request = build_by_external_cloud_provider_type_request( external_cloud_provider_type=external_cloud_provider_type, external_cloud_provider_id=external_cloud_provider_id, filter=filter, @@ -341,12 +337,10 @@ def prepare_request(next_link=None): skiptoken=skiptoken, top=top, api_version=api_version, - template_url=self.by_external_cloud_provider_type.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 @@ -358,13 +352,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("DimensionsListResult", pipeline_response) @@ -374,11 +367,11 @@ def extract_data(pipeline_response): return 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -390,7 +383,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - by_external_cloud_provider_type.metadata = { - "url": "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/dimensions" - } diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_exports_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_exports_operations.py index e747255baa54..499c90003883 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_exports_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_exports_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( @@ -18,16 +18,18 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -39,7 +41,7 @@ def build_list_request(scope: str, *, expand: Optional[str] = None, **kwargs: An _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -48,7 +50,7 @@ def build_list_request(scope: str, *, expand: Optional[str] = None, **kwargs: An "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") @@ -65,7 +67,7 @@ def build_get_request(scope: str, export_name: str, *, expand: Optional[str] = N _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -75,7 +77,7 @@ def build_get_request(scope: str, export_name: str, *, expand: Optional[str] = N "exportName": _SERIALIZER.url("export_name", export_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") @@ -92,7 +94,7 @@ def build_create_or_update_request(scope: str, export_name: str, **kwargs: Any) _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -103,7 +105,7 @@ def build_create_or_update_request(scope: str, export_name: str, **kwargs: Any) "exportName": _SERIALIZER.url("export_name", export_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") @@ -120,7 +122,7 @@ def build_delete_request(scope: str, export_name: str, **kwargs: Any) -> HttpReq _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -130,7 +132,7 @@ def build_delete_request(scope: str, export_name: str, **kwargs: Any) -> HttpReq "exportName": _SERIALIZER.url("export_name", export_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") @@ -145,7 +147,8 @@ def build_execute_request(scope: str, export_name: str, **kwargs: Any) -> HttpRe _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -155,12 +158,14 @@ def build_execute_request(scope: str, export_name: str, **kwargs: Any) -> HttpRe "exportName": _SERIALIZER.url("export_name", export_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") # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) @@ -170,7 +175,7 @@ def build_get_execution_history_request(scope: str, export_name: str, **kwargs: _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -180,7 +185,7 @@ def build_get_execution_history_request(scope: str, export_name: str, **kwargs: "exportName": _SERIALIZER.url("export_name", export_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") @@ -212,6 +217,7 @@ def __init__(self, *args, **kwargs): @distributed_trace def list(self, scope: str, expand: Optional[str] = None, **kwargs: Any) -> _models.ExportListResult: + # pylint: disable=line-too-long """The operation to list all exports at the given scope. .. seealso:: @@ -238,12 +244,11 @@ def list(self, scope: str, expand: Optional[str] = None, **kwargs: Any) -> _mode 'runHistory' is supported and will return information for the last run of each export. Default value is None. :type expand: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ExportListResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ExportListResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -257,20 +262,18 @@ def list(self, scope: str, expand: Optional[str] = None, **kwargs: Any) -> _mode api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ExportListResult] = kwargs.pop("cls", None) - request = build_list_request( + _request = build_list_request( scope=scope, expand=expand, 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -280,17 +283,16 @@ def list(self, scope: str, expand: Optional[str] = None, **kwargs: Any) -> _mode error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ExportListResult", pipeline_response) + deserialized = self._deserialize("ExportListResult", 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.CostManagement/exports"} + return deserialized # type: ignore @distributed_trace def get(self, scope: str, export_name: str, expand: Optional[str] = None, **kwargs: Any) -> _models.Export: + # pylint: disable=line-too-long """The operation to get the export for the defined scope by export name. .. seealso:: @@ -319,12 +321,11 @@ def get(self, scope: str, export_name: str, expand: Optional[str] = None, **kwar 'runHistory' is supported and will return information for the last 10 runs of the export. Default value is None. :type expand: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Export or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Export :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -338,21 +339,19 @@ def get(self, scope: str, export_name: str, expand: Optional[str] = None, **kwar api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Export] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( scope=scope, export_name=export_name, expand=expand, 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -362,14 +361,12 @@ def get(self, scope: str, export_name: str, expand: Optional[str] = None, **kwar error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Export", pipeline_response) + deserialized = self._deserialize("Export", 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.CostManagement/exports/{exportName}"} + return deserialized # type: ignore @overload def create_or_update( @@ -381,6 +378,7 @@ def create_or_update( content_type: str = "application/json", **kwargs: Any ) -> _models.Export: + # pylint: disable=line-too-long """The operation to create or update a export. Update operation requires latest eTag to be set in the request. You may obtain the latest eTag by performing a get operation. Create operation does not require eTag. @@ -412,7 +410,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: Export or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Export :raises ~azure.core.exceptions.HttpResponseError: @@ -420,8 +417,15 @@ def create_or_update( @overload def create_or_update( - self, scope: str, export_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, + scope: str, + export_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models.Export: + # pylint: disable=line-too-long """The operation to create or update a export. Update operation requires latest eTag to be set in the request. You may obtain the latest eTag by performing a get operation. Create operation does not require eTag. @@ -449,11 +453,10 @@ def create_or_update( :param export_name: Export Name. Required. :type export_name: str :param parameters: Parameters supplied to the CreateOrUpdate Export 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: Export or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Export :raises ~azure.core.exceptions.HttpResponseError: @@ -461,8 +464,9 @@ def create_or_update( @distributed_trace def create_or_update( - self, scope: str, export_name: str, parameters: Union[_models.Export, IO], **kwargs: Any + self, scope: str, export_name: str, parameters: Union[_models.Export, IO[bytes]], **kwargs: Any ) -> _models.Export: + # pylint: disable=line-too-long """The operation to create or update a export. Update operation requires latest eTag to be set in the request. You may obtain the latest eTag by performing a get operation. Create operation does not require eTag. @@ -490,17 +494,13 @@ def create_or_update( :param export_name: Export Name. Required. :type export_name: str :param parameters: Parameters supplied to the CreateOrUpdate Export operation. Is either a - Export type or a IO type. Required. - :type parameters: ~azure.mgmt.costmanagement.models.Export 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 + Export type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.Export or IO[bytes] :return: Export or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Export :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -523,23 +523,21 @@ def create_or_update( else: _json = self._serialize.body(parameters, "Export") - request = build_create_or_update_request( + _request = build_create_or_update_request( scope=scope, export_name=export_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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -549,23 +547,18 @@ def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("Export", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("Export", pipeline_response) + deserialized = self._deserialize("Export", 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.CostManagement/exports/{exportName}"} - @distributed_trace def delete( # pylint: disable=inconsistent-return-statements self, scope: str, export_name: str, **kwargs: Any ) -> None: + # pylint: disable=line-too-long """The operation to delete a export. .. seealso:: @@ -590,12 +583,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type scope: str :param export_name: Export Name. Required. :type export_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, @@ -609,20 +601,18 @@ def delete( # pylint: disable=inconsistent-return-statements 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, export_name=export_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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -633,14 +623,109 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def execute( + self, + scope: str, + export_name: str, + parameters: Optional[_models.ExportRunRequest] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + # pylint: disable=line-too-long + """The operation to run an export. + + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/costmanagement/ + + :param scope: The scope associated with export operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param export_name: Export Name. Required. + :type export_name: str + :param parameters: Parameters supplied to the CreateOrUpdate Export operation. Default value is + None. + :type parameters: ~azure.mgmt.costmanagement.models.ExportRunRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def execute( + self, + scope: str, + export_name: str, + parameters: Optional[IO[bytes]] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + # pylint: disable=line-too-long + """The operation to run an export. - delete.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}"} + .. seealso:: + - https://docs.microsoft.com/en-us/rest/api/costmanagement/ + + :param scope: The scope associated with export operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param export_name: Export Name. Required. + :type export_name: str + :param parameters: Parameters supplied to the CreateOrUpdate Export operation. Default value is + None. + :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 + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def execute( # pylint: disable=inconsistent-return-statements - self, scope: str, export_name: str, **kwargs: Any + self, + scope: str, + export_name: str, + parameters: Optional[Union[_models.ExportRunRequest, IO[bytes]]] = None, + **kwargs: Any ) -> None: + # pylint: disable=line-too-long """The operation to run an export. .. seealso:: @@ -665,12 +750,14 @@ def execute( # pylint: disable=inconsistent-return-statements :type scope: str :param export_name: Export Name. Required. :type export_name: str - :keyword callable cls: A custom type or function that will be passed the direct response + :param parameters: Parameters supplied to the CreateOrUpdate Export operation. Is either a + ExportRunRequest type or a IO[bytes] type. Default value is None. + :type parameters: ~azure.mgmt.costmanagement.models.ExportRunRequest or IO[bytes] :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, @@ -678,26 +765,39 @@ def execute( # pylint: disable=inconsistent-return-statements } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_execute_request( + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + if parameters is not None: + _json = self._serialize.body(parameters, "ExportRunRequest") + else: + _json = None + + _request = build_execute_request( scope=scope, export_name=export_name, api_version=api_version, - template_url=self.execute.metadata["url"], + content_type=content_type, + json=_json, + content=_content, 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -708,12 +808,11 @@ def execute( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - execute.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}/run"} + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def get_execution_history(self, scope: str, export_name: str, **kwargs: Any) -> _models.ExportExecutionListResult: + # pylint: disable=line-too-long """The operation to get the run history of an export for the defined scope and export name. .. seealso:: @@ -738,12 +837,11 @@ def get_execution_history(self, scope: str, export_name: str, **kwargs: Any) -> :type scope: str :param export_name: Export Name. Required. :type export_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ExportExecutionListResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ExportExecutionListResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -757,20 +855,18 @@ def get_execution_history(self, scope: str, export_name: str, **kwargs: Any) -> api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ExportExecutionListResult] = kwargs.pop("cls", None) - request = build_get_execution_history_request( + _request = build_get_execution_history_request( scope=scope, export_name=export_name, api_version=api_version, - template_url=self.get_execution_history.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -780,13 +876,9 @@ def get_execution_history(self, scope: str, export_name: str, **kwargs: Any) -> error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ExportExecutionListResult", pipeline_response) + deserialized = self._deserialize("ExportExecutionListResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_execution_history.metadata = { - "url": "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}/runHistory" - } + return deserialized # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_forecast_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_forecast_operations.py index e39d94f30f09..56952899a008 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_forecast_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_forecast_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( @@ -18,16 +18,18 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -39,7 +41,7 @@ def build_usage_request(scope: str, *, filter: Optional[str] = None, **kwargs: A _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -49,7 +51,7 @@ def build_usage_request(scope: str, *, filter: Optional[str] = None, **kwargs: A "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: @@ -64,7 +66,7 @@ def build_usage_request(scope: str, *, filter: Optional[str] = None, **kwargs: A return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_external_cloud_provider_usage_request( +def build_external_cloud_provider_usage_request( # pylint: disable=name-too-long external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], external_cloud_provider_id: str, *, @@ -74,7 +76,7 @@ def build_external_cloud_provider_usage_request( _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -90,7 +92,7 @@ def build_external_cloud_provider_usage_request( "externalCloudProviderId": _SERIALIZER.url("external_cloud_provider_id", external_cloud_provider_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: @@ -134,6 +136,7 @@ def usage( content_type: str = "application/json", **kwargs: Any ) -> Optional[_models.ForecastResult]: + # pylint: disable=line-too-long """Lists the forecast charges for scope defined. .. seealso:: @@ -166,7 +169,6 @@ def usage( :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: ForecastResult or None or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ForecastResult or None :raises ~azure.core.exceptions.HttpResponseError: @@ -176,12 +178,13 @@ def usage( def usage( self, scope: str, - parameters: IO, + parameters: IO[bytes], filter: Optional[str] = None, *, content_type: str = "application/json", **kwargs: Any ) -> Optional[_models.ForecastResult]: + # pylint: disable=line-too-long """Lists the forecast charges for scope defined. .. seealso:: @@ -206,7 +209,7 @@ def usage( :type scope: str :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. Required. - :type parameters: IO + :type parameters: IO[bytes] :param filter: May be used to filter forecasts by properties/usageDate (Utc time), properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. @@ -214,7 +217,6 @@ def usage( :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: ForecastResult or None or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ForecastResult or None :raises ~azure.core.exceptions.HttpResponseError: @@ -222,8 +224,13 @@ def usage( @distributed_trace def usage( - self, scope: str, parameters: Union[_models.ForecastDefinition, IO], filter: Optional[str] = None, **kwargs: Any + self, + scope: str, + parameters: Union[_models.ForecastDefinition, IO[bytes]], + filter: Optional[str] = None, + **kwargs: Any ) -> Optional[_models.ForecastResult]: + # pylint: disable=line-too-long """Lists the forecast charges for scope defined. .. seealso:: @@ -247,21 +254,17 @@ def usage( specific for partners. Required. :type scope: str :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. Is - either a ForecastDefinition type or a IO type. Required. - :type parameters: ~azure.mgmt.costmanagement.models.ForecastDefinition or IO + either a ForecastDefinition type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.ForecastDefinition or IO[bytes] :param filter: May be used to filter forecasts by properties/usageDate (Utc time), properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. :type filter: str - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ForecastResult or None or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ForecastResult or None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -284,23 +287,21 @@ def usage( else: _json = self._serialize.body(parameters, "ForecastDefinition") - request = build_usage_request( + _request = build_usage_request( scope=scope, filter=filter, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.usage.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -312,14 +313,12 @@ def usage( deserialized = None if response.status_code == 200: - deserialized = self._deserialize("ForecastResult", pipeline_response) + deserialized = self._deserialize("ForecastResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - usage.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/forecast"} + return deserialized # type: ignore @overload def external_cloud_provider_usage( @@ -357,7 +356,6 @@ def external_cloud_provider_usage( :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: ForecastResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ForecastResult :raises ~azure.core.exceptions.HttpResponseError: @@ -368,7 +366,7 @@ def external_cloud_provider_usage( self, external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], external_cloud_provider_id: str, - parameters: IO, + parameters: IO[bytes], filter: Optional[str] = None, *, content_type: str = "application/json", @@ -391,7 +389,7 @@ def external_cloud_provider_usage( :type external_cloud_provider_id: str :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. Required. - :type parameters: IO + :type parameters: IO[bytes] :param filter: May be used to filter forecasts by properties/usageDate (Utc time), properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. @@ -399,7 +397,6 @@ def external_cloud_provider_usage( :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: ForecastResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ForecastResult :raises ~azure.core.exceptions.HttpResponseError: @@ -410,7 +407,7 @@ def external_cloud_provider_usage( self, external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], external_cloud_provider_id: str, - parameters: Union[_models.ForecastDefinition, IO], + parameters: Union[_models.ForecastDefinition, IO[bytes]], filter: Optional[str] = None, **kwargs: Any ) -> _models.ForecastResult: @@ -430,21 +427,17 @@ def external_cloud_provider_usage( Required. :type external_cloud_provider_id: str :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. Is - either a ForecastDefinition type or a IO type. Required. - :type parameters: ~azure.mgmt.costmanagement.models.ForecastDefinition or IO + either a ForecastDefinition type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.ForecastDefinition or IO[bytes] :param filter: May be used to filter forecasts by properties/usageDate (Utc time), properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. :type filter: str - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ForecastResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ForecastResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -467,7 +460,7 @@ def external_cloud_provider_usage( else: _json = self._serialize.body(parameters, "ForecastDefinition") - request = build_external_cloud_provider_usage_request( + _request = build_external_cloud_provider_usage_request( external_cloud_provider_type=external_cloud_provider_type, external_cloud_provider_id=external_cloud_provider_id, filter=filter, @@ -475,16 +468,14 @@ def external_cloud_provider_usage( content_type=content_type, json=_json, content=_content, - template_url=self.external_cloud_provider_usage.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -494,13 +485,9 @@ def external_cloud_provider_usage( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ForecastResult", pipeline_response) + deserialized = self._deserialize("ForecastResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - external_cloud_provider_usage.metadata = { - "url": "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/forecast" - } + return deserialized # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_benefit_utilization_summaries_report_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_benefit_utilization_summaries_report_operations.py new file mode 100644 index 000000000000..59e1336e984f --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_benefit_utilization_summaries_report_operations.py @@ -0,0 +1,1517 @@ +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterator, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +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 + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_generate_by_billing_account_request( # pylint: disable=name-too-long + billing_account_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/generateBenefitUtilizationSummariesReport", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_generate_by_billing_profile_request( # pylint: disable=name-too-long + billing_account_id: str, billing_profile_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.CostManagement/generateBenefitUtilizationSummariesReport", + ) # 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 = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_generate_by_reservation_order_id_request( # pylint: disable=name-too-long + reservation_order_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/providers/Microsoft.CostManagement/generateBenefitUtilizationSummariesReport", + ) # pylint: disable=line-too-long + path_format_arguments = { + "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_generate_by_reservation_id_request( + reservation_order_id: str, reservation_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/reservations/{reservationId}/providers/Microsoft.CostManagement/generateBenefitUtilizationSummariesReport", + ) # 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 = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_generate_by_savings_plan_order_id_request( # pylint: disable=name-too-long + savings_plan_order_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/providers/Microsoft.CostManagement/generateBenefitUtilizationSummariesReport", + ) # pylint: disable=line-too-long + path_format_arguments = { + "savingsPlanOrderId": _SERIALIZER.url("savings_plan_order_id", savings_plan_order_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_generate_by_savings_plan_id_request( # pylint: disable=name-too-long + savings_plan_order_id: str, savings_plan_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans/{savingsPlanId}/providers/Microsoft.CostManagement/generateBenefitUtilizationSummariesReport", + ) # pylint: disable=line-too-long + path_format_arguments = { + "savingsPlanOrderId": _SERIALIZER.url("savings_plan_order_id", savings_plan_order_id, "str"), + "savingsPlanId": _SERIALIZER.url("savings_plan_id", savings_plan_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class GenerateBenefitUtilizationSummariesReportOperations: # pylint: disable=name-too-long + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`generate_benefit_utilization_summaries_report` attribute. + """ + + models = _models + + 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") + + def _generate_by_billing_account_initial( + self, + billing_account_id: str, + benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(benefit_utilization_summaries_request, (IOBase, bytes)): + _content = benefit_utilization_summaries_request + else: + _json = self._serialize.body(benefit_utilization_summaries_request, "BenefitUtilizationSummariesRequest") + + _request = build_generate_by_billing_account_request( + billing_account_id=billing_account_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + 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.ErrorResponseAutoGenerated, 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 + + @overload + def begin_generate_by_billing_account( + self, + billing_account_id: str, + benefit_utilization_summaries_request: _models.BenefitUtilizationSummariesRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + """Triggers generation of a benefit utilization summaries report for the provided billing account. + This API supports only enrollment accounts. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param billing_account_id: Billing account ID. Required. + :type billing_account_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Required. + :type benefit_utilization_summaries_request: + ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_generate_by_billing_account( + self, + billing_account_id: str, + benefit_utilization_summaries_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + """Triggers generation of a benefit utilization summaries report for the provided billing account. + This API supports only enrollment accounts. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param billing_account_id: Billing account ID. Required. + :type billing_account_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Required. + :type benefit_utilization_summaries_request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_generate_by_billing_account( + self, + billing_account_id: str, + benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + """Triggers generation of a benefit utilization summaries report for the provided billing account. + This API supports only enrollment accounts. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param billing_account_id: Billing account ID. Required. + :type billing_account_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Is either a BenefitUtilizationSummariesRequest type or a IO[bytes] type. Required. + :type benefit_utilization_summaries_request: + ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest or IO[bytes] + :return: An instance of LROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.BenefitUtilizationSummariesOperationStatus] = 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._generate_by_billing_account_initial( + billing_account_id=billing_account_id, + benefit_utilization_summaries_request=benefit_utilization_summaries_request, + api_version=api_version, + content_type=content_type, + 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( + "BenefitUtilizationSummariesOperationStatus", 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.BenefitUtilizationSummariesOperationStatus].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.BenefitUtilizationSummariesOperationStatus]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _generate_by_billing_profile_initial( + self, + billing_account_id: str, + billing_profile_id: str, + benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(benefit_utilization_summaries_request, (IOBase, bytes)): + _content = benefit_utilization_summaries_request + else: + _json = self._serialize.body(benefit_utilization_summaries_request, "BenefitUtilizationSummariesRequest") + + _request = build_generate_by_billing_profile_request( + billing_account_id=billing_account_id, + billing_profile_id=billing_profile_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + 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.ErrorResponseAutoGenerated, 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 + + @overload + def begin_generate_by_billing_profile( + self, + billing_account_id: str, + billing_profile_id: str, + benefit_utilization_summaries_request: _models.BenefitUtilizationSummariesRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + """Triggers generation of a benefit utilization summaries report for the provided billing account + and billing profile. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param billing_account_id: Billing account ID. Required. + :type billing_account_id: str + :param billing_profile_id: Billing profile ID. Required. + :type billing_profile_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Required. + :type benefit_utilization_summaries_request: + ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_generate_by_billing_profile( + self, + billing_account_id: str, + billing_profile_id: str, + benefit_utilization_summaries_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + """Triggers generation of a benefit utilization summaries report for the provided billing account + and billing profile. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param billing_account_id: Billing account ID. Required. + :type billing_account_id: str + :param billing_profile_id: Billing profile ID. Required. + :type billing_profile_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Required. + :type benefit_utilization_summaries_request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_generate_by_billing_profile( + self, + billing_account_id: str, + billing_profile_id: str, + benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + """Triggers generation of a benefit utilization summaries report for the provided billing account + and billing profile. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param billing_account_id: Billing account ID. Required. + :type billing_account_id: str + :param billing_profile_id: Billing profile ID. Required. + :type billing_profile_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Is either a BenefitUtilizationSummariesRequest type or a IO[bytes] type. Required. + :type benefit_utilization_summaries_request: + ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest or IO[bytes] + :return: An instance of LROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.BenefitUtilizationSummariesOperationStatus] = 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._generate_by_billing_profile_initial( + billing_account_id=billing_account_id, + billing_profile_id=billing_profile_id, + benefit_utilization_summaries_request=benefit_utilization_summaries_request, + api_version=api_version, + content_type=content_type, + 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( + "BenefitUtilizationSummariesOperationStatus", 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.BenefitUtilizationSummariesOperationStatus].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.BenefitUtilizationSummariesOperationStatus]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _generate_by_reservation_order_id_initial( # pylint: disable=name-too-long + self, + reservation_order_id: str, + benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(benefit_utilization_summaries_request, (IOBase, bytes)): + _content = benefit_utilization_summaries_request + else: + _json = self._serialize.body(benefit_utilization_summaries_request, "BenefitUtilizationSummariesRequest") + + _request = build_generate_by_reservation_order_id_request( + reservation_order_id=reservation_order_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + 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.ErrorResponseAutoGenerated, 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 + + @overload + def begin_generate_by_reservation_order_id( + self, + reservation_order_id: str, + benefit_utilization_summaries_request: _models.BenefitUtilizationSummariesRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + """Triggers generation of a benefit utilization summaries report for the provided reservation + order. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param reservation_order_id: Reservation Order ID. Required. + :type reservation_order_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Required. + :type benefit_utilization_summaries_request: + ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_generate_by_reservation_order_id( + self, + reservation_order_id: str, + benefit_utilization_summaries_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + """Triggers generation of a benefit utilization summaries report for the provided reservation + order. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param reservation_order_id: Reservation Order ID. Required. + :type reservation_order_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Required. + :type benefit_utilization_summaries_request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_generate_by_reservation_order_id( + self, + reservation_order_id: str, + benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + """Triggers generation of a benefit utilization summaries report for the provided reservation + order. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param reservation_order_id: Reservation Order ID. Required. + :type reservation_order_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Is either a BenefitUtilizationSummariesRequest type or a IO[bytes] type. Required. + :type benefit_utilization_summaries_request: + ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest or IO[bytes] + :return: An instance of LROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.BenefitUtilizationSummariesOperationStatus] = 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._generate_by_reservation_order_id_initial( + reservation_order_id=reservation_order_id, + benefit_utilization_summaries_request=benefit_utilization_summaries_request, + api_version=api_version, + content_type=content_type, + 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( + "BenefitUtilizationSummariesOperationStatus", 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.BenefitUtilizationSummariesOperationStatus].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.BenefitUtilizationSummariesOperationStatus]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _generate_by_reservation_id_initial( + self, + reservation_order_id: str, + reservation_id: str, + benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(benefit_utilization_summaries_request, (IOBase, bytes)): + _content = benefit_utilization_summaries_request + else: + _json = self._serialize.body(benefit_utilization_summaries_request, "BenefitUtilizationSummariesRequest") + + _request = build_generate_by_reservation_id_request( + reservation_order_id=reservation_order_id, + reservation_id=reservation_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + 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.ErrorResponseAutoGenerated, 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 + + @overload + def begin_generate_by_reservation_id( + self, + reservation_order_id: str, + reservation_id: str, + benefit_utilization_summaries_request: _models.BenefitUtilizationSummariesRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + """Triggers generation of a benefit utilization summaries report for the provided reservation. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param reservation_order_id: Reservation Order ID. Required. + :type reservation_order_id: str + :param reservation_id: Reservation ID. Required. + :type reservation_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Required. + :type benefit_utilization_summaries_request: + ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_generate_by_reservation_id( + self, + reservation_order_id: str, + reservation_id: str, + benefit_utilization_summaries_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + """Triggers generation of a benefit utilization summaries report for the provided reservation. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param reservation_order_id: Reservation Order ID. Required. + :type reservation_order_id: str + :param reservation_id: Reservation ID. Required. + :type reservation_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Required. + :type benefit_utilization_summaries_request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_generate_by_reservation_id( + self, + reservation_order_id: str, + reservation_id: str, + benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + """Triggers generation of a benefit utilization summaries report for the provided reservation. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param reservation_order_id: Reservation Order ID. Required. + :type reservation_order_id: str + :param reservation_id: Reservation ID. Required. + :type reservation_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Is either a BenefitUtilizationSummariesRequest type or a IO[bytes] type. Required. + :type benefit_utilization_summaries_request: + ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest or IO[bytes] + :return: An instance of LROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.BenefitUtilizationSummariesOperationStatus] = 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._generate_by_reservation_id_initial( + reservation_order_id=reservation_order_id, + reservation_id=reservation_id, + benefit_utilization_summaries_request=benefit_utilization_summaries_request, + api_version=api_version, + content_type=content_type, + 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( + "BenefitUtilizationSummariesOperationStatus", 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.BenefitUtilizationSummariesOperationStatus].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.BenefitUtilizationSummariesOperationStatus]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _generate_by_savings_plan_order_id_initial( # pylint: disable=name-too-long + self, + savings_plan_order_id: str, + benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(benefit_utilization_summaries_request, (IOBase, bytes)): + _content = benefit_utilization_summaries_request + else: + _json = self._serialize.body(benefit_utilization_summaries_request, "BenefitUtilizationSummariesRequest") + + _request = build_generate_by_savings_plan_order_id_request( + savings_plan_order_id=savings_plan_order_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + 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.ErrorResponseAutoGenerated, 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 + + @overload + def begin_generate_by_savings_plan_order_id( + self, + savings_plan_order_id: str, + benefit_utilization_summaries_request: _models.BenefitUtilizationSummariesRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + """Triggers generation of a benefit utilization summaries report for the provided savings plan + order. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param savings_plan_order_id: Savings plan order ID. Required. + :type savings_plan_order_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Required. + :type benefit_utilization_summaries_request: + ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_generate_by_savings_plan_order_id( + self, + savings_plan_order_id: str, + benefit_utilization_summaries_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + """Triggers generation of a benefit utilization summaries report for the provided savings plan + order. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param savings_plan_order_id: Savings plan order ID. Required. + :type savings_plan_order_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Required. + :type benefit_utilization_summaries_request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_generate_by_savings_plan_order_id( + self, + savings_plan_order_id: str, + benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + """Triggers generation of a benefit utilization summaries report for the provided savings plan + order. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param savings_plan_order_id: Savings plan order ID. Required. + :type savings_plan_order_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Is either a BenefitUtilizationSummariesRequest type or a IO[bytes] type. Required. + :type benefit_utilization_summaries_request: + ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest or IO[bytes] + :return: An instance of LROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.BenefitUtilizationSummariesOperationStatus] = 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._generate_by_savings_plan_order_id_initial( + savings_plan_order_id=savings_plan_order_id, + benefit_utilization_summaries_request=benefit_utilization_summaries_request, + api_version=api_version, + content_type=content_type, + 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( + "BenefitUtilizationSummariesOperationStatus", 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.BenefitUtilizationSummariesOperationStatus].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.BenefitUtilizationSummariesOperationStatus]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _generate_by_savings_plan_id_initial( + self, + savings_plan_order_id: str, + savings_plan_id: str, + benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(benefit_utilization_summaries_request, (IOBase, bytes)): + _content = benefit_utilization_summaries_request + else: + _json = self._serialize.body(benefit_utilization_summaries_request, "BenefitUtilizationSummariesRequest") + + _request = build_generate_by_savings_plan_id_request( + savings_plan_order_id=savings_plan_order_id, + savings_plan_id=savings_plan_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + 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.ErrorResponseAutoGenerated, 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 + + @overload + def begin_generate_by_savings_plan_id( + self, + savings_plan_order_id: str, + savings_plan_id: str, + benefit_utilization_summaries_request: _models.BenefitUtilizationSummariesRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + """Triggers generation of a benefit utilization summaries report for the provided savings plan. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param savings_plan_order_id: Savings plan order ID. Required. + :type savings_plan_order_id: str + :param savings_plan_id: Savings plan ID. Required. + :type savings_plan_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Required. + :type benefit_utilization_summaries_request: + ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_generate_by_savings_plan_id( + self, + savings_plan_order_id: str, + savings_plan_id: str, + benefit_utilization_summaries_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + """Triggers generation of a benefit utilization summaries report for the provided savings plan. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param savings_plan_order_id: Savings plan order ID. Required. + :type savings_plan_order_id: str + :param savings_plan_id: Savings plan ID. Required. + :type savings_plan_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Required. + :type benefit_utilization_summaries_request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_generate_by_savings_plan_id( + self, + savings_plan_order_id: str, + savings_plan_id: str, + benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.BenefitUtilizationSummariesOperationStatus]: + """Triggers generation of a benefit utilization summaries report for the provided savings plan. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param savings_plan_order_id: Savings plan order ID. Required. + :type savings_plan_order_id: str + :param savings_plan_id: Savings plan ID. Required. + :type savings_plan_id: str + :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be + created. Is either a BenefitUtilizationSummariesRequest type or a IO[bytes] type. Required. + :type benefit_utilization_summaries_request: + ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest or IO[bytes] + :return: An instance of LROPoller that returns either + BenefitUtilizationSummariesOperationStatus or the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.BenefitUtilizationSummariesOperationStatus] = 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._generate_by_savings_plan_id_initial( + savings_plan_order_id=savings_plan_order_id, + savings_plan_id=savings_plan_id, + benefit_utilization_summaries_request=benefit_utilization_summaries_request, + api_version=api_version, + content_type=content_type, + 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( + "BenefitUtilizationSummariesOperationStatus", 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.BenefitUtilizationSummariesOperationStatus].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.BenefitUtilizationSummariesOperationStatus]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_cost_details_report_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_cost_details_report_operations.py index 7f9f5529f879..6c3a6ed64af5 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_cost_details_report_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_cost_details_report_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,7 +6,8 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from io import IOBase -from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import sys +from typing import Any, Callable, Dict, IO, Iterator, Optional, TypeVar, Union, cast, overload from azure.core.exceptions import ( ClientAuthenticationError, @@ -15,12 +15,13 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat @@ -28,8 +29,11 @@ from .. import models as _models from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -41,7 +45,7 @@ def build_create_operation_request(scope: 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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -51,7 +55,7 @@ def build_create_operation_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") @@ -68,7 +72,7 @@ def build_get_operation_results_request(scope: str, operation_id: str, **kwargs: _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -80,7 +84,7 @@ def build_get_operation_results_request(scope: str, operation_id: str, **kwargs: "operationId": _SERIALIZER.url("operation_id", operation_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") @@ -111,9 +115,12 @@ def __init__(self, *args, **kwargs): self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") def _create_operation_initial( - self, scope: str, parameters: Union[_models.GenerateCostDetailsReportRequestDefinition, IO], **kwargs: Any - ) -> Optional[_models.CostDetailsOperationResults]: - error_map = { + self, + scope: str, + parameters: Union[_models.GenerateCostDetailsReportRequestDefinition, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -126,7 +133,7 @@ def _create_operation_initial( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.CostDetailsOperationResults]] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None @@ -136,50 +143,47 @@ def _create_operation_initial( else: _json = self._serialize.body(parameters, "GenerateCostDetailsReportRequestDefinition") - request = build_create_operation_request( + _request = build_create_operation_request( scope=scope, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self._create_operation_initial.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 + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize( _models.GenerateCostDetailsReportErrorResponse, pipeline_response ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("CostDetailsOperationResults", pipeline_response) - 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")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _create_operation_initial.metadata = { - "url": "/{scope}/providers/Microsoft.CostManagement/generateCostDetailsReport" - } + return deserialized # type: ignore @overload def begin_create_operation( @@ -201,27 +205,20 @@ def begin_create_operation( response along with details on the report blob(s) that are available for download. The details on the file(s) available for download will be available in the polling response body. To Understand cost details (formerly known as usage details) fields found in files ,see - https://learn.microsoft.com/azure/cost-management-billing/automate/understand-usage-details-fields. + https://learn.microsoft.com/en-us/azure/cost-management-billing/automate/understand-usage-details-fields. .. seealso:: - https://docs.microsoft.com/en-us/rest/api/costmanagement/ - :param scope: The ARM Resource ID for subscription, resource group, billing account, or other - billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. + :param scope: The ARM Resource ID for subscription, billing account, or other billing + scopes.Currently Resource Group and Management Group are not supported. For details, see + https://aka.ms/costmgmt/scopes. Required. :type scope: str :param parameters: Parameters supplied to the Create cost details operation. Required. :type parameters: ~azure.mgmt.costmanagement.models.GenerateCostDetailsReportRequestDefinition :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either CostDetailsOperationResults or the result of cls(response) :rtype: @@ -231,7 +228,7 @@ def begin_create_operation( @overload def begin_create_operation( - self, scope: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, scope: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.CostDetailsOperationResults]: """This API is the replacement for all previously release Usage Details APIs. Request to generate a cost details report for the provided date range, billing period (Only enterprise customers) @@ -244,27 +241,20 @@ def begin_create_operation( response along with details on the report blob(s) that are available for download. The details on the file(s) available for download will be available in the polling response body. To Understand cost details (formerly known as usage details) fields found in files ,see - https://learn.microsoft.com/azure/cost-management-billing/automate/understand-usage-details-fields. + https://learn.microsoft.com/en-us/azure/cost-management-billing/automate/understand-usage-details-fields. .. seealso:: - https://docs.microsoft.com/en-us/rest/api/costmanagement/ - :param scope: The ARM Resource ID for subscription, resource group, billing account, or other - billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. + :param scope: The ARM Resource ID for subscription, billing account, or other billing + scopes.Currently Resource Group and Management Group are not supported. For details, see + https://aka.ms/costmgmt/scopes. Required. :type scope: str :param parameters: Parameters supplied to the Create cost details 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 - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either CostDetailsOperationResults or the result of cls(response) :rtype: @@ -274,7 +264,10 @@ def begin_create_operation( @distributed_trace def begin_create_operation( - self, scope: str, parameters: Union[_models.GenerateCostDetailsReportRequestDefinition, IO], **kwargs: Any + self, + scope: str, + parameters: Union[_models.GenerateCostDetailsReportRequestDefinition, IO[bytes]], + **kwargs: Any ) -> LROPoller[_models.CostDetailsOperationResults]: """This API is the replacement for all previously release Usage Details APIs. Request to generate a cost details report for the provided date range, billing period (Only enterprise customers) @@ -287,29 +280,19 @@ def begin_create_operation( response along with details on the report blob(s) that are available for download. The details on the file(s) available for download will be available in the polling response body. To Understand cost details (formerly known as usage details) fields found in files ,see - https://learn.microsoft.com/azure/cost-management-billing/automate/understand-usage-details-fields. + https://learn.microsoft.com/en-us/azure/cost-management-billing/automate/understand-usage-details-fields. .. seealso:: - https://docs.microsoft.com/en-us/rest/api/costmanagement/ - :param scope: The ARM Resource ID for subscription, resource group, billing account, or other - billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. + :param scope: The ARM Resource ID for subscription, billing account, or other billing + scopes.Currently Resource Group and Management Group are not supported. For details, see + https://aka.ms/costmgmt/scopes. Required. :type scope: str :param parameters: Parameters supplied to the Create cost details operation. Is either a - GenerateCostDetailsReportRequestDefinition type or a IO type. Required. + GenerateCostDetailsReportRequestDefinition type or a IO[bytes] type. Required. :type parameters: ~azure.mgmt.costmanagement.models.GenerateCostDetailsReportRequestDefinition - 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 - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + or IO[bytes] :return: An instance of LROPoller that returns either CostDetailsOperationResults or the result of cls(response) :rtype: @@ -336,12 +319,13 @@ def begin_create_operation( 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("CostDetailsOperationResults", pipeline_response) + deserialized = self._deserialize("CostDetailsOperationResults", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -353,20 +337,18 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.CostDetailsOperationResults].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_operation.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/generateCostDetailsReport"} + return LROPoller[_models.CostDetailsOperationResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) - def _get_operation_results_initial( - self, scope: str, operation_id: str, **kwargs: Any - ) -> Optional[_models.CostDetailsOperationResults]: - error_map = { + def _get_operation_results_initial(self, scope: str, operation_id: str, **kwargs: Any) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -378,43 +360,40 @@ def _get_operation_results_initial( _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[Optional[_models.CostDetailsOperationResults]] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - request = build_get_operation_results_request( + _request = build_get_operation_results_request( scope=scope, operation_id=operation_id, api_version=api_version, - template_url=self._get_operation_results_initial.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 + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _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) - deserialized = None - if response.status_code == 200: - deserialized = self._deserialize("CostDetailsOperationResults", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - _get_operation_results_initial.metadata = { - "url": "/{scope}/providers/Microsoft.CostManagement/costDetailsOperationResults/{operationId}" - } + return deserialized # type: ignore @distributed_trace def begin_get_operation_results( @@ -423,19 +402,12 @@ def begin_get_operation_results( """Get the result of the specified operation. This link is provided in the CostDetails creation request response Location header. - :param scope: The ARM Resource ID for subscription, resource group, billing account, or other - billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. + :param scope: The ARM Resource ID for subscription, billing account, or other billing + scopes.Currently Resource Group and Management Group are not supported. For details, see + https://aka.ms/costmgmt/scopes. Required. :type scope: str :param operation_id: The target operation Id. Required. :type operation_id: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either CostDetailsOperationResults or the result of cls(response) :rtype: @@ -460,12 +432,13 @@ def begin_get_operation_results( 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("CostDetailsOperationResults", pipeline_response) + deserialized = self._deserialize("CostDetailsOperationResults", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -477,14 +450,12 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.CostDetailsOperationResults].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_get_operation_results.metadata = { - "url": "/{scope}/providers/Microsoft.CostManagement/costDetailsOperationResults/{operationId}" - } + return LROPoller[_models.CostDetailsOperationResults]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operation_results_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operation_results_operations.py index fe9816fc945f..c2ed45f59620 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operation_results_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operation_results_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Optional, TypeVar, Union, cast +import sys +from typing import Any, Callable, Dict, Iterator, Optional, TypeVar, Union, cast from azure.core.exceptions import ( ClientAuthenticationError, @@ -14,12 +14,13 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat @@ -27,8 +28,11 @@ from .. import models as _models from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -40,7 +44,7 @@ def build_get_request(operation_id: str, scope: str, **kwargs: Any) -> HttpReque _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -50,7 +54,7 @@ def build_get_request(operation_id: str, scope: str, **kwargs: Any) -> HttpReque "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") @@ -61,7 +65,7 @@ def build_get_request(operation_id: str, scope: str, **kwargs: Any) -> HttpReque return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -class GenerateDetailedCostReportOperationResultsOperations: +class GenerateDetailedCostReportOperationResultsOperations: # pylint: disable=name-too-long """ .. warning:: **DO NOT** instantiate this class directly. @@ -80,10 +84,8 @@ def __init__(self, *args, **kwargs): 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") - def _get_initial( - self, operation_id: str, scope: str, **kwargs: Any - ) -> Optional[_models.GenerateDetailedCostReportOperationResult]: - error_map = { + def _get_initial(self, operation_id: str, scope: str, **kwargs: Any) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -95,41 +97,40 @@ def _get_initial( _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[Optional[_models.GenerateDetailedCostReportOperationResult]] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( operation_id=operation_id, scope=scope, api_version=api_version, - template_url=self._get_initial.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 + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _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) - deserialized = None - if response.status_code == 200: - deserialized = self._deserialize("GenerateDetailedCostReportOperationResult", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - _get_initial.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/operationResults/{operationId}"} + return deserialized # type: ignore @distributed_trace def begin_get( @@ -143,14 +144,6 @@ def begin_get( :param scope: The ARM Resource ID for subscription, resource group, billing account, or other billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. :type scope: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either GenerateDetailedCostReportOperationResult or the result of cls(response) :rtype: @@ -175,12 +168,15 @@ def begin_get( 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("GenerateDetailedCostReportOperationResult", pipeline_response) + deserialized = self._deserialize( + "GenerateDetailedCostReportOperationResult", pipeline_response.http_response + ) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -190,12 +186,12 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.GenerateDetailedCostReportOperationResult].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_get.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/operationResults/{operationId}"} + return LROPoller[_models.GenerateDetailedCostReportOperationResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operation_status_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operation_status_operations.py index 35352c896734..533e5f3a85a1 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operation_status_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operation_status_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # 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 azure.core.exceptions import ( @@ -17,16 +17,18 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -38,7 +40,7 @@ def build_get_request(operation_id: str, scope: str, **kwargs: Any) -> HttpReque _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -48,7 +50,7 @@ def build_get_request(operation_id: str, scope: str, **kwargs: Any) -> HttpReque "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") @@ -59,7 +61,7 @@ def build_get_request(operation_id: str, scope: str, **kwargs: Any) -> HttpReque return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -class GenerateDetailedCostReportOperationStatusOperations: +class GenerateDetailedCostReportOperationStatusOperations: # pylint: disable=name-too-long """ .. warning:: **DO NOT** instantiate this class directly. @@ -88,12 +90,11 @@ def get(self, operation_id: str, scope: str, **kwargs: Any) -> _models.GenerateD :param scope: The ARM Resource ID for subscription, resource group, billing account, or other billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. :type scope: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: GenerateDetailedCostReportOperationStatuses or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportOperationStatuses :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -107,20 +108,18 @@ def get(self, operation_id: str, scope: str, **kwargs: Any) -> _models.GenerateD api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.GenerateDetailedCostReportOperationStatuses] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( operation_id=operation_id, 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -130,11 +129,9 @@ def get(self, operation_id: str, scope: str, **kwargs: Any) -> _models.GenerateD error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("GenerateDetailedCostReportOperationStatuses", pipeline_response) + deserialized = self._deserialize("GenerateDetailedCostReportOperationStatuses", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - get.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/operationStatus/{operationId}"} + return deserialized # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operations.py index d97dc71e376c..c040b85dff59 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,7 +6,8 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from io import IOBase -from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import sys +from typing import Any, Callable, Dict, IO, Iterator, Optional, TypeVar, Union, cast, overload from azure.core.exceptions import ( ClientAuthenticationError, @@ -15,12 +15,13 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat @@ -28,8 +29,11 @@ from .. import models as _models from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -41,7 +45,7 @@ def build_create_operation_request(scope: 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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -51,7 +55,7 @@ def build_create_operation_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") @@ -84,9 +88,9 @@ def __init__(self, *args, **kwargs): self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") def _create_operation_initial( - self, scope: str, parameters: Union[_models.GenerateDetailedCostReportDefinition, IO], **kwargs: Any - ) -> Optional[_models.GenerateDetailedCostReportOperationResult]: - error_map = { + self, scope: str, parameters: Union[_models.GenerateDetailedCostReportDefinition, IO[bytes]], **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -99,7 +103,7 @@ def _create_operation_initial( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.GenerateDetailedCostReportOperationResult]] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None @@ -109,38 +113,37 @@ def _create_operation_initial( else: _json = self._serialize.body(parameters, "GenerateDetailedCostReportDefinition") - request = build_create_operation_request( + _request = build_create_operation_request( scope=scope, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self._create_operation_initial.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 + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _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.GenerateDetailedCostReportErrorResponse, pipeline_response ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("GenerateDetailedCostReportOperationResult", pipeline_response) - if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Azure-Consumption-AsyncOperation"] = self._deserialize( @@ -151,14 +154,12 @@ def _create_operation_initial( ) response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _create_operation_initial.metadata = { - "url": "/{scope}/providers/Microsoft.CostManagement/generateDetailedCostReport" - } + return deserialized # type: ignore @overload def begin_create_operation( @@ -186,14 +187,6 @@ def begin_create_operation( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either GenerateDetailedCostReportOperationResult or the result of cls(response) :rtype: @@ -203,7 +196,7 @@ def begin_create_operation( @overload def begin_create_operation( - self, scope: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, scope: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.GenerateDetailedCostReportOperationResult]: """Generates the detailed cost report for provided date range, billing period(only enterprise customers) or Invoice ID asynchronously at a certain scope. Call returns a 202 with header @@ -218,18 +211,10 @@ def begin_create_operation( billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. :type scope: str :param parameters: Parameters supplied to the Create detailed cost report 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 - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either GenerateDetailedCostReportOperationResult or the result of cls(response) :rtype: @@ -239,7 +224,7 @@ def begin_create_operation( @distributed_trace def begin_create_operation( - self, scope: str, parameters: Union[_models.GenerateDetailedCostReportDefinition, IO], **kwargs: Any + self, scope: str, parameters: Union[_models.GenerateDetailedCostReportDefinition, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.GenerateDetailedCostReportOperationResult]: """Generates the detailed cost report for provided date range, billing period(only enterprise customers) or Invoice ID asynchronously at a certain scope. Call returns a 202 with header @@ -254,19 +239,9 @@ def begin_create_operation( billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. :type scope: str :param parameters: Parameters supplied to the Create detailed cost report operation. Is either - a GenerateDetailedCostReportDefinition type or a IO type. Required. - :type parameters: ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportDefinition 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 - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + a GenerateDetailedCostReportDefinition type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportDefinition or + IO[bytes] :return: An instance of LROPoller that returns either GenerateDetailedCostReportOperationResult or the result of cls(response) :rtype: @@ -293,12 +268,15 @@ def begin_create_operation( 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("GenerateDetailedCostReportOperationResult", pipeline_response) + deserialized = self._deserialize( + "GenerateDetailedCostReportOperationResult", pipeline_response.http_response + ) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -310,12 +288,12 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.GenerateDetailedCostReportOperationResult].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_operation.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/generateDetailedCostReport"} + return LROPoller[_models.GenerateDetailedCostReportOperationResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_reservation_details_report_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_reservation_details_report_operations.py index acfd66c3eca0..a094ab690fee 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_reservation_details_report_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_reservation_details_report_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Optional, TypeVar, Union, cast +import sys +from typing import Any, Callable, Dict, Iterator, Optional, TypeVar, Union, cast from azure.core.exceptions import ( ClientAuthenticationError, @@ -14,12 +14,13 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat @@ -27,8 +28,11 @@ from .. import models as _models from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -42,7 +46,7 @@ def build_by_billing_account_id_request( _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -54,7 +58,7 @@ def build_by_billing_account_id_request( "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["startDate"] = _SERIALIZER.query("start_date", start_date, "str") @@ -73,7 +77,7 @@ def build_by_billing_profile_id_request( _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -86,7 +90,7 @@ def build_by_billing_profile_id_request( "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["startDate"] = _SERIALIZER.query("start_date", start_date, "str") @@ -99,7 +103,7 @@ def build_by_billing_profile_id_request( return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -class GenerateReservationDetailsReportOperations: +class GenerateReservationDetailsReportOperations: # pylint: disable=name-too-long """ .. warning:: **DO NOT** instantiate this class directly. @@ -120,8 +124,8 @@ def __init__(self, *args, **kwargs): def _by_billing_account_id_initial( self, billing_account_id: str, start_date: str, end_date: str, **kwargs: Any - ) -> Optional[_models.OperationStatus]: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -133,49 +137,46 @@ def _by_billing_account_id_initial( _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[Optional[_models.OperationStatus]] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - request = build_by_billing_account_id_request( + _request = build_by_billing_account_id_request( billing_account_id=billing_account_id, start_date=start_date, end_date=end_date, api_version=api_version, - template_url=self._by_billing_account_id_initial.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 + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _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) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("OperationStatus", pipeline_response) - 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")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _by_billing_account_id_initial.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/generateReservationDetailsReport" - } + return deserialized # type: ignore @distributed_trace def begin_by_billing_account_id( @@ -184,7 +185,7 @@ def begin_by_billing_account_id( """Generates the reservations details report for provided date range asynchronously based on enrollment id. The Reservation usage details can be viewed only by certain enterprise roles. For more details on the roles see, - https://docs.microsoft.com/azure/cost-management-billing/manage/understand-ea-roles#usage-and-costs-access-by-role. + https://docs.microsoft.com/en-us/azure/cost-management-billing/manage/understand-ea-roles#usage-and-costs-access-by-role. .. seealso:: - https://docs.microsoft.com/en-us/rest/api/costmanagement/ @@ -195,14 +196,6 @@ def begin_by_billing_account_id( :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 - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either OperationStatus or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.OperationStatus] @@ -227,12 +220,13 @@ def begin_by_billing_account_id( 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) + deserialized = self._deserialize("OperationStatus", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -244,22 +238,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_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(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_by_billing_account_id.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/generateReservationDetailsReport" - } + return LROPoller[_models.OperationStatus]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) def _by_billing_profile_id_initial( self, billing_account_id: str, billing_profile_id: str, start_date: str, end_date: str, **kwargs: Any - ) -> Optional[_models.OperationStatus]: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -271,50 +263,47 @@ def _by_billing_profile_id_initial( _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[Optional[_models.OperationStatus]] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - request = build_by_billing_profile_id_request( + _request = build_by_billing_profile_id_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._by_billing_profile_id_initial.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 + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _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) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("OperationStatus", pipeline_response) - 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")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _by_billing_profile_id_initial.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.CostManagement/generateReservationDetailsReport" - } + return deserialized # type: ignore @distributed_trace def begin_by_billing_profile_id( @@ -323,7 +312,7 @@ def begin_by_billing_profile_id( """Generates the reservations details report for provided date range asynchronously by billing profile. The Reservation usage details can be viewed by only certain enterprise roles by default. For more details on the roles see, - https://docs.microsoft.com/azure/cost-management-billing/reservations/reservation-utilization#view-utilization-in-the-azure-portal-with-azure-rbac-access. + https://docs.microsoft.com/en-us/azure/cost-management-billing/reservations/reservation-utilization#view-utilization-in-the-azure-portal-with-azure-rbac-access. .. seealso:: - https://docs.microsoft.com/en-us/rest/api/costmanagement/ @@ -336,14 +325,6 @@ def begin_by_billing_profile_id( :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 - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either OperationStatus or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.OperationStatus] @@ -369,12 +350,13 @@ def begin_by_billing_profile_id( 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) + deserialized = self._deserialize("OperationStatus", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -386,14 +368,12 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_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(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_by_billing_profile_id.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.CostManagement/generateReservationDetailsReport" - } + return LROPoller[_models.OperationStatus]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_operations.py index d227fb63fadc..947bc80faa49 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar import urllib.parse @@ -19,16 +19,18 @@ ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer -from .._vendor import _convert_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -40,7 +42,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: str = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -78,7 +80,6 @@ def __init__(self, *args, **kwargs): def list(self, **kwargs: Any) -> Iterable["_models.CostManagementOperation"]: """Lists all of the available cost management REST API operations. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either CostManagementOperation or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.CostManagementOperation] @@ -90,7 +91,7 @@ def list(self, **kwargs: Any) -> Iterable["_models.CostManagementOperation"]: 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, @@ -101,14 +102,12 @@ def list(self, **kwargs: Any) -> Iterable["_models.CostManagementOperation"]: 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 @@ -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 def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) @@ -136,11 +134,11 @@ 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -152,5 +150,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/providers/Microsoft.CostManagement/operations"} diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_price_sheet_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_price_sheet_operations.py index 708b3b455e76..764aefba7032 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_price_sheet_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/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,7 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Optional, TypeVar, Union, cast +import sys +from typing import Any, Callable, Dict, Iterator, Optional, TypeVar, Union, cast from azure.core.exceptions import ( ClientAuthenticationError, @@ -14,12 +14,13 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat @@ -27,8 +28,11 @@ from .. import models as _models from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -36,13 +40,13 @@ _SERIALIZER.client_side_validation = False -def build_download_request( +def build_download_by_invoice_request( billing_account_name: str, billing_profile_name: str, invoice_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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -63,7 +67,7 @@ def build_download_request( "invoiceName": _SERIALIZER.url("invoice_name", invoice_name, "str", pattern=r"[A-Za-z0-9]+"), } - _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") @@ -74,13 +78,13 @@ def build_download_request( return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_download_by_billing_profile_request( +def build_download_by_billing_profile_request( # pylint: disable=name-too-long billing_account_name: str, billing_profile_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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -100,7 +104,37 @@ def build_download_by_billing_profile_request( ), } - _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") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_download_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: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingPeriods/{billingPeriodName}/providers/Microsoft.CostManagement/pricesheets/default/download", + ) # 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", 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") @@ -130,10 +164,10 @@ def __init__(self, *args, **kwargs): 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") - def _download_initial( + def _download_by_invoice_initial( self, billing_account_name: str, billing_profile_name: str, invoice_name: str, **kwargs: Any - ) -> Optional[_models.DownloadURL]: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -145,53 +179,50 @@ def _download_initial( _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[Optional[_models.DownloadURL]] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - request = build_download_request( + _request = build_download_by_invoice_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_name=invoice_name, api_version=api_version, - template_url=self._download_initial.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 + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _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) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("DownloadURL", pipeline_response) - if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) response_headers["OData-EntityId"] = self._deserialize("str", response.headers.get("OData-EntityId")) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + if cls: - return cls(pipeline_response, deserialized, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized - - _download_initial.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoices/{invoiceName}/providers/Microsoft.CostManagement/pricesheets/default/download" - } + return deserialized # type: ignore @distributed_trace - def begin_download( + def begin_download_by_invoice( self, billing_account_name: str, billing_profile_name: str, invoice_name: str, **kwargs: Any ) -> LROPoller[_models.DownloadURL]: """Gets a URL to download the pricesheet for an invoice. The operation is supported for billing @@ -203,14 +234,6 @@ def begin_download( :type billing_profile_name: str :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either DownloadURL or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.DownloadURL] @@ -225,7 +248,7 @@ def begin_download( 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_initial( + raw_result = self._download_by_invoice_initial( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_name=invoice_name, @@ -235,12 +258,13 @@ def begin_download( 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("DownloadURL", pipeline_response) + deserialized = self._deserialize("DownloadURL", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -252,22 +276,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.DownloadURL].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_download.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoices/{invoiceName}/providers/Microsoft.CostManagement/pricesheets/default/download" - } + return LROPoller[_models.DownloadURL]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) def _download_by_billing_profile_initial( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any - ) -> Optional[_models.DownloadURL]: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -279,82 +301,77 @@ def _download_by_billing_profile_initial( _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[Optional[_models.DownloadURL]] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - request = build_download_by_billing_profile_request( + _request = build_download_by_billing_profile_request( billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, api_version=api_version, - template_url=self._download_by_billing_profile_initial.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 + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _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) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("DownloadURL", pipeline_response) - if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) response_headers["OData-EntityId"] = self._deserialize("str", response.headers.get("OData-EntityId")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _download_by_billing_profile_initial.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/providers/Microsoft.CostManagement/pricesheets/default/download" - } + return deserialized # type: ignore @distributed_trace def begin_download_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, **kwargs: Any - ) -> LROPoller[_models.DownloadURL]: + ) -> LROPoller[_models.PricesheetDownloadProperties]: """Gets a URL to download the current month's pricesheet for a billing profile. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft - Customer Agreement.Due to Azure product growth, the Azure price sheet download experience in - this preview version will be updated from a single csv file to a Zip file containing multiple - csv files, each with max 200k records. + Customer Agreement. + + You can use the new 2023-09-01 API version for billing periods January 2023 onwards. Azure + Reserved Instance (RI) pricing is only available through the new version of the API. + + Due to Azure product growth, the Azure price sheet download experience in this preview version + will be updated from a single csv/json file to a Zip file containing multiple csv/json files, + each with max size of 75MB. :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either DownloadURL or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.DownloadURL] + :return: An instance of LROPoller that returns either PricesheetDownloadProperties or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.PricesheetDownloadProperties] :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.DownloadURL] = kwargs.pop("cls", None) + cls: ClsType[_models.PricesheetDownloadProperties] = 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) @@ -368,12 +385,13 @@ def begin_download_by_billing_profile( 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("DownloadURL", pipeline_response) + deserialized = self._deserialize("PricesheetDownloadProperties", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -385,14 +403,152 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.PricesheetDownloadProperties].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return LROPoller[_models.PricesheetDownloadProperties]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) - begin_download_by_billing_profile.metadata = { - "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/providers/Microsoft.CostManagement/pricesheets/default/download" - } + def _download_by_billing_account_initial( + 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_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.ErrorResponseAutoGenerated2, 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("str", 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( + self, billing_account_id: str, billing_period_name: str, **kwargs: Any + ) -> LROPoller[_models.OperationStatusAutoGenerated]: + """Generates the pricesheet for the provided billing period asynchronously based on the Enrollment + ID. This is for Enterprise Agreement customers. + + **Migrate to version 2024-10-01-preview** + + You can use the 2024-10-01-preview API version with the new URI: + + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingPeriods/{billingPeriodName}/providers/Microsoft.CostManagement/pricesheets/default/download' + + With a new schema detailed below, the new version of the price sheet provides additional + information and includes prices for Azure Reserved Instances (RI) for the current billing + period. We recommend downloading an Azure Price Sheet for when entering a new billing period if + you would maintain an ongoing record of past Azure Reserved Instance (RI) pricing. + + The EA Azure price sheet is available for billing periods in the past 13 months. To request a + price sheet for a billing period older than 13 months, please contact support. + + The Azure price sheet download experience has been updated from a single .csv file to a zip + file containing multiple .csv files, each with max size of 75MB. The 2023-11-01 version has + been upgraded to use http POST method; details can be found below. + + All versions of the Microsoft.Consumption Azure Price Sheet - Download by Billing Account + (including 2022-06-01, 2021-10-01, 2020-01-01-preview, 2019-10-01, 2019-05-01) are scheduled to + be retired on 01 June 2026 and will no longer be supported after this date. + + :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 OperationStatusAutoGenerated or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.OperationStatusAutoGenerated] + :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.OperationStatusAutoGenerated] = 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_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("OperationStatusAutoGenerated", 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.OperationStatusAutoGenerated].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.OperationStatusAutoGenerated]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_query_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_query_operations.py index 6438c2d581b9..ea619b51036d 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_query_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_query_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( @@ -18,16 +18,18 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -39,7 +41,7 @@ def build_usage_request(scope: 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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -49,7 +51,7 @@ def build_usage_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") @@ -62,7 +64,7 @@ def build_usage_request(scope: str, **kwargs: Any) -> HttpRequest: return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_usage_by_external_cloud_provider_type_request( +def build_usage_by_external_cloud_provider_type_request( # pylint: disable=name-too-long external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], external_cloud_provider_id: str, **kwargs: Any @@ -70,7 +72,7 @@ def build_usage_by_external_cloud_provider_type_request( _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -86,7 +88,7 @@ def build_usage_by_external_cloud_provider_type_request( "externalCloudProviderId": _SERIALIZER.url("external_cloud_provider_id", external_cloud_provider_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") @@ -122,6 +124,7 @@ def __init__(self, *args, **kwargs): def usage( self, scope: str, parameters: _models.QueryDefinition, *, content_type: str = "application/json", **kwargs: Any ) -> Optional[_models.QueryResult]: + # pylint: disable=line-too-long """Query the usage data for scope defined. .. seealso:: @@ -149,7 +152,6 @@ def usage( :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: QueryResult or None or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.QueryResult or None :raises ~azure.core.exceptions.HttpResponseError: @@ -157,8 +159,9 @@ def usage( @overload def usage( - self, scope: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, scope: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> Optional[_models.QueryResult]: + # pylint: disable=line-too-long """Query the usage data for scope defined. .. seealso:: @@ -182,11 +185,10 @@ def usage( specific for partners. Required. :type scope: str :param parameters: Parameters supplied to the CreateOrUpdate Query Config 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: QueryResult or None or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.QueryResult or None :raises ~azure.core.exceptions.HttpResponseError: @@ -194,8 +196,9 @@ def usage( @distributed_trace def usage( - self, scope: str, parameters: Union[_models.QueryDefinition, IO], **kwargs: Any + self, scope: str, parameters: Union[_models.QueryDefinition, IO[bytes]], **kwargs: Any ) -> Optional[_models.QueryResult]: + # pylint: disable=line-too-long """Query the usage data for scope defined. .. seealso:: @@ -219,17 +222,13 @@ def usage( specific for partners. Required. :type scope: str :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Is either - a QueryDefinition type or a IO type. Required. - :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition 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 + a QueryDefinition type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition or IO[bytes] :return: QueryResult or None or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.QueryResult or None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -252,22 +251,20 @@ def usage( else: _json = self._serialize.body(parameters, "QueryDefinition") - request = build_usage_request( + _request = build_usage_request( scope=scope, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.usage.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -279,14 +276,12 @@ def usage( deserialized = None if response.status_code == 200: - deserialized = self._deserialize("QueryResult", pipeline_response) + deserialized = self._deserialize("QueryResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - usage.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/query"} + return deserialized # type: ignore @overload def usage_by_external_cloud_provider_type( @@ -318,7 +313,6 @@ def usage_by_external_cloud_provider_type( :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: QueryResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.QueryResult :raises ~azure.core.exceptions.HttpResponseError: @@ -329,7 +323,7 @@ def usage_by_external_cloud_provider_type( self, external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], external_cloud_provider_id: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -350,11 +344,10 @@ def usage_by_external_cloud_provider_type( Required. :type external_cloud_provider_id: str :param parameters: Parameters supplied to the CreateOrUpdate Query Config 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: QueryResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.QueryResult :raises ~azure.core.exceptions.HttpResponseError: @@ -365,7 +358,7 @@ def usage_by_external_cloud_provider_type( self, external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], external_cloud_provider_id: str, - parameters: Union[_models.QueryDefinition, IO], + parameters: Union[_models.QueryDefinition, IO[bytes]], **kwargs: Any ) -> _models.QueryResult: """Query the usage data for external cloud provider type defined. @@ -384,17 +377,13 @@ def usage_by_external_cloud_provider_type( Required. :type external_cloud_provider_id: str :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Is either - a QueryDefinition type or a IO type. Required. - :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition 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 + a QueryDefinition type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition or IO[bytes] :return: QueryResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.QueryResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -417,23 +406,21 @@ def usage_by_external_cloud_provider_type( else: _json = self._serialize.body(parameters, "QueryDefinition") - request = build_usage_by_external_cloud_provider_type_request( + _request = build_usage_by_external_cloud_provider_type_request( external_cloud_provider_type=external_cloud_provider_type, external_cloud_provider_id=external_cloud_provider_id, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.usage_by_external_cloud_provider_type.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -443,13 +430,9 @@ def usage_by_external_cloud_provider_type( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("QueryResult", pipeline_response) + deserialized = self._deserialize("QueryResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - usage_by_external_cloud_provider_type.metadata = { - "url": "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/query" - } + return deserialized # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_scheduled_actions_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_scheduled_actions_operations.py index c50ba6872037..adf1e7edadec 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_scheduled_actions_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_scheduled_actions_operations.py @@ -7,6 +7,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -20,16 +21,18 @@ ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -41,7 +44,7 @@ def build_list_request(*, filter: Optional[str] = None, **kwargs: Any) -> HttpRe _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -62,7 +65,7 @@ def build_list_by_scope_request(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: str = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -71,7 +74,7 @@ def build_list_by_scope_request(scope: str, *, filter: Optional[str] = None, **k "scope": _SERIALIZER.url("scope", scope, "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") @@ -88,7 +91,7 @@ def build_create_or_update_request(name: str, *, if_match: Optional[str] = None, _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -98,7 +101,7 @@ def build_create_or_update_request(name: str, *, if_match: Optional[str] = None, "name": _SERIALIZER.url("name", 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") @@ -117,7 +120,7 @@ def build_get_request(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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -126,7 +129,7 @@ def build_get_request(name: str, **kwargs: Any) -> HttpRequest: "name": _SERIALIZER.url("name", 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") @@ -141,7 +144,7 @@ def build_delete_request(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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -150,7 +153,7 @@ def build_delete_request(name: str, **kwargs: Any) -> HttpRequest: "name": _SERIALIZER.url("name", 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") @@ -167,7 +170,7 @@ def build_create_or_update_by_scope_request( _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -178,7 +181,7 @@ def build_create_or_update_by_scope_request( "name": _SERIALIZER.url("name", 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") @@ -197,7 +200,7 @@ def build_get_by_scope_request(scope: str, name: str, **kwargs: Any) -> HttpRequ _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -207,7 +210,7 @@ def build_get_by_scope_request(scope: str, name: str, **kwargs: Any) -> HttpRequ "name": _SERIALIZER.url("name", 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") @@ -222,7 +225,7 @@ def build_delete_by_scope_request(scope: str, name: str, **kwargs: Any) -> HttpR _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -232,7 +235,7 @@ def build_delete_by_scope_request(scope: str, name: str, **kwargs: Any) -> HttpR "name": _SERIALIZER.url("name", 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") @@ -247,7 +250,7 @@ def build_run_request(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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -256,7 +259,7 @@ def build_run_request(name: str, **kwargs: Any) -> HttpRequest: "name": _SERIALIZER.url("name", 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") @@ -271,7 +274,7 @@ def build_run_by_scope_request(scope: str, name: str, **kwargs: Any) -> HttpRequ _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -281,7 +284,7 @@ def build_run_by_scope_request(scope: str, name: str, **kwargs: Any) -> HttpRequ "name": _SERIALIZER.url("name", 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") @@ -296,7 +299,7 @@ def build_check_name_availability_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -314,11 +317,13 @@ def build_check_name_availability_request(**kwargs: Any) -> HttpRequest: return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_check_name_availability_by_scope_request(scope: str, **kwargs: Any) -> HttpRequest: +def build_check_name_availability_by_scope_request( # pylint: disable=name-too-long + scope: 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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -328,7 +333,7 @@ def build_check_name_availability_by_scope_request(scope: str, **kwargs: Any) -> "scope": _SERIALIZER.url("scope", scope, "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") @@ -370,7 +375,6 @@ def list(self, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models :param filter: May be used to filter scheduled actions by properties/viewId. Supported operator is 'eq'. 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 ScheduledAction or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.ScheduledAction] :raises ~azure.core.exceptions.HttpResponseError: @@ -381,7 +385,7 @@ def list(self, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ScheduledActionListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -392,15 +396,13 @@ def list(self, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( 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 @@ -412,13 +414,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("ScheduledActionListResult", pipeline_response) @@ -428,11 +429,11 @@ 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -447,8 +448,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list.metadata = {"url": "/providers/Microsoft.CostManagement/scheduledActions"} - @distributed_trace def list_by_scope( self, scope: str, filter: Optional[str] = None, **kwargs: Any @@ -479,7 +478,6 @@ def list_by_scope( :param filter: May be used to filter scheduled actions by properties/viewId. Supported operator is 'eq'. 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 ScheduledAction or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.ScheduledAction] :raises ~azure.core.exceptions.HttpResponseError: @@ -490,7 +488,7 @@ def list_by_scope( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ScheduledActionListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -501,16 +499,14 @@ def list_by_scope( def prepare_request(next_link=None): if not next_link: - request = build_list_by_scope_request( + _request = build_list_by_scope_request( scope=scope, filter=filter, api_version=api_version, - template_url=self.list_by_scope.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 @@ -522,13 +518,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("ScheduledActionListResult", pipeline_response) @@ -538,11 +533,11 @@ 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -557,8 +552,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/scheduledActions"} - @overload def create_or_update( self, @@ -582,7 +575,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: ScheduledAction or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction :raises ~azure.core.exceptions.HttpResponseError: @@ -592,7 +584,7 @@ def create_or_update( def create_or_update( self, name: str, - scheduled_action: IO, + scheduled_action: IO[bytes], if_match: Optional[str] = None, *, content_type: str = "application/json", @@ -603,7 +595,7 @@ def create_or_update( :param name: Scheduled action name. Required. :type name: str :param scheduled_action: Scheduled action to be created or updated. Required. - :type scheduled_action: IO + :type scheduled_action: IO[bytes] :param if_match: ETag of the Entity. Not required when creating an entity. Optional when updating an entity and can be specified to achieve optimistic concurrency. Default value is None. @@ -611,7 +603,6 @@ def create_or_update( :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: ScheduledAction or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction :raises ~azure.core.exceptions.HttpResponseError: @@ -621,7 +612,7 @@ def create_or_update( def create_or_update( self, name: str, - scheduled_action: Union[_models.ScheduledAction, IO], + scheduled_action: Union[_models.ScheduledAction, IO[bytes]], if_match: Optional[str] = None, **kwargs: Any ) -> _models.ScheduledAction: @@ -630,21 +621,17 @@ def create_or_update( :param name: Scheduled action name. Required. :type name: str :param scheduled_action: Scheduled action to be created or updated. Is either a ScheduledAction - type or a IO type. Required. - :type scheduled_action: ~azure.mgmt.costmanagement.models.ScheduledAction or IO + type or a IO[bytes] type. Required. + :type scheduled_action: ~azure.mgmt.costmanagement.models.ScheduledAction or IO[bytes] :param if_match: ETag of the Entity. Not required when creating an entity. Optional when updating an entity and can be specified to achieve optimistic concurrency. Default value is None. :type if_match: str - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ScheduledAction or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -667,23 +654,21 @@ def create_or_update( else: _json = self._serialize.body(scheduled_action, "ScheduledAction") - request = build_create_or_update_request( + _request = build_create_or_update_request( name=name, if_match=if_match, 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -693,19 +678,13 @@ def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseWithNestedDetails, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("ScheduledAction", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ScheduledAction", pipeline_response) + deserialized = self._deserialize("ScheduledAction", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = {"url": "/providers/Microsoft.CostManagement/scheduledActions/{name}"} - @distributed_trace def get(self, name: str, **kwargs: Any) -> _models.ScheduledAction: """Get the private scheduled action by name. @@ -715,12 +694,11 @@ def get(self, name: str, **kwargs: Any) -> _models.ScheduledAction: :param name: Scheduled action name. Required. :type name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ScheduledAction or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -734,19 +712,17 @@ def get(self, name: str, **kwargs: Any) -> _models.ScheduledAction: api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ScheduledAction] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( name=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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -756,14 +732,12 @@ def get(self, name: str, **kwargs: Any) -> _models.ScheduledAction: error = self._deserialize.failsafe_deserialize(_models.ErrorResponseWithNestedDetails, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ScheduledAction", pipeline_response) + deserialized = self._deserialize("ScheduledAction", 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.CostManagement/scheduledActions/{name}"} + return deserialized # type: ignore @distributed_trace def delete(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements @@ -774,12 +748,11 @@ def delete(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsist :param name: Scheduled action name. Required. :type 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, @@ -793,19 +766,17 @@ def delete(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsist 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( name=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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -816,9 +787,7 @@ def delete(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsist raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = {"url": "/providers/Microsoft.CostManagement/scheduledActions/{name}"} + return cls(pipeline_response, None, {}) # type: ignore @overload def create_or_update_by_scope( @@ -862,7 +831,6 @@ def create_or_update_by_scope( :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: ScheduledAction or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction :raises ~azure.core.exceptions.HttpResponseError: @@ -873,7 +841,7 @@ def create_or_update_by_scope( self, scope: str, name: str, - scheduled_action: IO, + scheduled_action: IO[bytes], if_match: Optional[str] = None, *, content_type: str = "application/json", @@ -902,7 +870,7 @@ def create_or_update_by_scope( :param name: Scheduled action name. Required. :type name: str :param scheduled_action: Scheduled action to be created or updated. Required. - :type scheduled_action: IO + :type scheduled_action: IO[bytes] :param if_match: ETag of the Entity. Not required when creating an entity. Optional when updating an entity and can be specified to achieve optimistic concurrency. Default value is None. @@ -910,7 +878,6 @@ def create_or_update_by_scope( :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: ScheduledAction or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction :raises ~azure.core.exceptions.HttpResponseError: @@ -921,7 +888,7 @@ def create_or_update_by_scope( self, scope: str, name: str, - scheduled_action: Union[_models.ScheduledAction, IO], + scheduled_action: Union[_models.ScheduledAction, IO[bytes]], if_match: Optional[str] = None, **kwargs: Any ) -> _models.ScheduledAction: @@ -948,21 +915,17 @@ def create_or_update_by_scope( :param name: Scheduled action name. Required. :type name: str :param scheduled_action: Scheduled action to be created or updated. Is either a ScheduledAction - type or a IO type. Required. - :type scheduled_action: ~azure.mgmt.costmanagement.models.ScheduledAction or IO + type or a IO[bytes] type. Required. + :type scheduled_action: ~azure.mgmt.costmanagement.models.ScheduledAction or IO[bytes] :param if_match: ETag of the Entity. Not required when creating an entity. Optional when updating an entity and can be specified to achieve optimistic concurrency. Default value is None. :type if_match: str - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ScheduledAction or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -985,7 +948,7 @@ def create_or_update_by_scope( else: _json = self._serialize.body(scheduled_action, "ScheduledAction") - request = build_create_or_update_by_scope_request( + _request = build_create_or_update_by_scope_request( scope=scope, name=name, if_match=if_match, @@ -993,16 +956,14 @@ def create_or_update_by_scope( content_type=content_type, json=_json, content=_content, - template_url=self.create_or_update_by_scope.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1012,19 +973,13 @@ def create_or_update_by_scope( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseWithNestedDetails, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("ScheduledAction", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ScheduledAction", pipeline_response) + deserialized = self._deserialize("ScheduledAction", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/scheduledActions/{name}"} - @distributed_trace def get_by_scope(self, scope: str, name: str, **kwargs: Any) -> _models.ScheduledAction: """Get the shared scheduled action from the given scope by name. @@ -1052,12 +1007,11 @@ def get_by_scope(self, scope: str, name: str, **kwargs: Any) -> _models.Schedule :type scope: str :param name: Scheduled action name. Required. :type name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ScheduledAction or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1071,20 +1025,18 @@ def get_by_scope(self, scope: str, name: str, **kwargs: Any) -> _models.Schedule api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ScheduledAction] = kwargs.pop("cls", None) - request = build_get_by_scope_request( + _request = build_get_by_scope_request( scope=scope, name=name, api_version=api_version, - template_url=self.get_by_scope.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1094,14 +1046,12 @@ def get_by_scope(self, scope: str, name: str, **kwargs: Any) -> _models.Schedule error = self._deserialize.failsafe_deserialize(_models.ErrorResponseWithNestedDetails, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ScheduledAction", pipeline_response) + deserialized = self._deserialize("ScheduledAction", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/scheduledActions/{name}"} + return deserialized # type: ignore @distributed_trace def delete_by_scope( # pylint: disable=inconsistent-return-statements @@ -1132,12 +1082,11 @@ def delete_by_scope( # pylint: disable=inconsistent-return-statements :type scope: str :param name: Scheduled action name. Required. :type 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, @@ -1151,20 +1100,18 @@ def delete_by_scope( # pylint: disable=inconsistent-return-statements 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_by_scope_request( + _request = build_delete_by_scope_request( scope=scope, name=name, api_version=api_version, - template_url=self.delete_by_scope.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1175,9 +1122,7 @@ def delete_by_scope( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/scheduledActions/{name}"} + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def run(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements @@ -1185,12 +1130,11 @@ def run(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent :param name: Scheduled action name. Required. :type 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, @@ -1204,19 +1148,17 @@ def run(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_run_request( + _request = build_run_request( name=name, api_version=api_version, - template_url=self.run.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1227,9 +1169,7 @@ def run(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - run.metadata = {"url": "/providers/Microsoft.CostManagement/scheduledActions/{name}/execute"} + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def run_by_scope( # pylint: disable=inconsistent-return-statements @@ -1257,12 +1197,11 @@ def run_by_scope( # pylint: disable=inconsistent-return-statements :type scope: str :param name: Scheduled action name. Required. :type 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, @@ -1276,20 +1215,18 @@ def run_by_scope( # pylint: disable=inconsistent-return-statements api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_run_by_scope_request( + _request = build_run_by_scope_request( scope=scope, name=name, api_version=api_version, - template_url=self.run_by_scope.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1300,9 +1237,7 @@ def run_by_scope( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - run_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/scheduledActions/{name}/execute"} + return cls(pipeline_response, None, {}) # type: ignore @overload def check_name_availability( @@ -1320,7 +1255,6 @@ def check_name_availability( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: CheckNameAvailabilityResponse or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse :raises ~azure.core.exceptions.HttpResponseError: @@ -1328,16 +1262,15 @@ def check_name_availability( @overload def check_name_availability( - self, check_name_availability_request: IO, *, content_type: str = "application/json", **kwargs: Any + self, check_name_availability_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.CheckNameAvailabilityResponse: """Checks availability and correctness of the name for a scheduled action. :param check_name_availability_request: Scheduled action to be created or updated. Required. - :type check_name_availability_request: IO + :type check_name_availability_request: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: CheckNameAvailabilityResponse or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse :raises ~azure.core.exceptions.HttpResponseError: @@ -1345,23 +1278,19 @@ def check_name_availability( @distributed_trace def check_name_availability( - self, check_name_availability_request: Union[_models.CheckNameAvailabilityRequest, IO], **kwargs: Any + self, check_name_availability_request: Union[_models.CheckNameAvailabilityRequest, IO[bytes]], **kwargs: Any ) -> _models.CheckNameAvailabilityResponse: """Checks availability and correctness of the name for a scheduled action. :param check_name_availability_request: Scheduled action to be created or updated. Is either a - CheckNameAvailabilityRequest type or a IO type. Required. + CheckNameAvailabilityRequest type or a IO[bytes] type. Required. :type check_name_availability_request: - ~azure.mgmt.costmanagement.models.CheckNameAvailabilityRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + ~azure.mgmt.costmanagement.models.CheckNameAvailabilityRequest or IO[bytes] :return: CheckNameAvailabilityResponse or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1384,21 +1313,19 @@ def check_name_availability( else: _json = self._serialize.body(check_name_availability_request, "CheckNameAvailabilityRequest") - request = build_check_name_availability_request( + _request = build_check_name_availability_request( api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.check_name_availability.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1408,14 +1335,12 @@ def check_name_availability( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseWithNestedDetails, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("CheckNameAvailabilityResponse", pipeline_response) + deserialized = self._deserialize("CheckNameAvailabilityResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - check_name_availability.metadata = {"url": "/providers/Microsoft.CostManagement/checkNameAvailability"} + return deserialized # type: ignore @overload def check_name_availability_by_scope( @@ -1452,7 +1377,6 @@ def check_name_availability_by_scope( :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: CheckNameAvailabilityResponse or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse :raises ~azure.core.exceptions.HttpResponseError: @@ -1460,7 +1384,12 @@ def check_name_availability_by_scope( @overload def check_name_availability_by_scope( - self, scope: str, check_name_availability_request: IO, *, content_type: str = "application/json", **kwargs: Any + self, + scope: str, + check_name_availability_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models.CheckNameAvailabilityResponse: """Checks availability and correctness of the name for a scheduled action within the given scope. @@ -1483,11 +1412,10 @@ def check_name_availability_by_scope( Required. :type scope: str :param check_name_availability_request: Scheduled action to be created or updated. Required. - :type check_name_availability_request: IO + :type check_name_availability_request: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: CheckNameAvailabilityResponse or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse :raises ~azure.core.exceptions.HttpResponseError: @@ -1497,7 +1425,7 @@ def check_name_availability_by_scope( def check_name_availability_by_scope( self, scope: str, - check_name_availability_request: Union[_models.CheckNameAvailabilityRequest, IO], + check_name_availability_request: Union[_models.CheckNameAvailabilityRequest, IO[bytes]], **kwargs: Any ) -> _models.CheckNameAvailabilityResponse: """Checks availability and correctness of the name for a scheduled action within the given scope. @@ -1521,18 +1449,14 @@ def check_name_availability_by_scope( Required. :type scope: str :param check_name_availability_request: Scheduled action to be created or updated. Is either a - CheckNameAvailabilityRequest type or a IO type. Required. + CheckNameAvailabilityRequest type or a IO[bytes] type. Required. :type check_name_availability_request: - ~azure.mgmt.costmanagement.models.CheckNameAvailabilityRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + ~azure.mgmt.costmanagement.models.CheckNameAvailabilityRequest or IO[bytes] :return: CheckNameAvailabilityResponse or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1555,22 +1479,20 @@ def check_name_availability_by_scope( else: _json = self._serialize.body(check_name_availability_request, "CheckNameAvailabilityRequest") - request = build_check_name_availability_by_scope_request( + _request = build_check_name_availability_by_scope_request( scope=scope, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.check_name_availability_by_scope.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1580,13 +1502,9 @@ def check_name_availability_by_scope( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseWithNestedDetails, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("CheckNameAvailabilityResponse", pipeline_response) + deserialized = self._deserialize("CheckNameAvailabilityResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - check_name_availability_by_scope.metadata = { - "url": "/{scope}/providers/Microsoft.CostManagement/checkNameAvailability" - } + return deserialized # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_settings_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_settings_operations.py new file mode 100644 index 000000000000..12739056aaa2 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_settings_operations.py @@ -0,0 +1,478 @@ +# 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 io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +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 + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +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: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/settings") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + } + + _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="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_by_scope_request( + scope: str, type: Union[str, _models.SettingType], **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/settings/{type}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "type": _SERIALIZER.url("type", type, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_scope_request(scope: str, type: Union[str, _models.SettingType], **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/settings/{type}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "type": _SERIALIZER.url("type", type, "str"), + } + + _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="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_by_scope_request(scope: str, type: Union[str, _models.SettingType], **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/settings/{type}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "type": _SERIALIZER.url("type", type, "str"), + } + + _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="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class SettingsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`settings` attribute. + """ + + models = _models + + 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") + + @distributed_trace + def list(self, scope: str, **kwargs: Any) -> _models.SettingsListResult: + """List all cost management settings in the requested scope. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param scope: The scope associated with this setting. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billing profile scope. Required. + :type scope: str + :return: SettingsListResult or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.SettingsListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.SettingsListResult] = kwargs.pop("cls", None) + + _request = build_list_request( + scope=scope, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("SettingsListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_or_update_by_scope( + self, + scope: str, + type: Union[str, _models.SettingType], + setting: _models.Setting, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Setting: + """Create or update a setting within the given scope. + + :param scope: The scope associated with this setting. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billing profile scope. Required. + :type scope: str + :param type: Setting type. "taginheritance" Required. + :type type: str or ~azure.mgmt.costmanagement.models.SettingType + :param setting: Setting to be created or updated. Required. + :type setting: ~azure.mgmt.costmanagement.models.Setting + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Setting or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Setting + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_by_scope( + self, + scope: str, + type: Union[str, _models.SettingType], + setting: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Setting: + """Create or update a setting within the given scope. + + :param scope: The scope associated with this setting. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billing profile scope. Required. + :type scope: str + :param type: Setting type. "taginheritance" Required. + :type type: str or ~azure.mgmt.costmanagement.models.SettingType + :param setting: Setting to be created or updated. Required. + :type setting: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Setting or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Setting + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_by_scope( + self, + scope: str, + type: Union[str, _models.SettingType], + setting: Union[_models.Setting, IO[bytes]], + **kwargs: Any + ) -> _models.Setting: + """Create or update a setting within the given scope. + + :param scope: The scope associated with this setting. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billing profile scope. Required. + :type scope: str + :param type: Setting type. "taginheritance" Required. + :type type: str or ~azure.mgmt.costmanagement.models.SettingType + :param setting: Setting to be created or updated. Is either a Setting type or a IO[bytes] type. + Required. + :type setting: ~azure.mgmt.costmanagement.models.Setting or IO[bytes] + :return: Setting or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Setting + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = 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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Setting] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(setting, (IOBase, bytes)): + _content = setting + else: + _json = self._serialize.body(setting, "Setting") + + _request = build_create_or_update_by_scope_request( + scope=scope, + type=type, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Setting", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_by_scope(self, scope: str, type: Union[str, _models.SettingType], **kwargs: Any) -> _models.Setting: + """Get the setting from the given scope by name. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param scope: The scope associated with this setting. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billing profile scope. Required. + :type scope: str + :param type: Setting type. "taginheritance" Required. + :type type: str or ~azure.mgmt.costmanagement.models.SettingType + :return: Setting or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Setting + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.Setting] = kwargs.pop("cls", None) + + _request = build_get_by_scope_request( + scope=scope, + type=type, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Setting", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete_by_scope( # pylint: disable=inconsistent-return-statements + self, scope: str, type: Union[str, _models.SettingType], **kwargs: Any + ) -> None: + """Delete a setting within the given scope. + + .. seealso:: + - https://docs.microsoft.com/rest/api/cost-management/ + + :param scope: The scope associated with this setting. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billing profile scope. Required. + :type scope: str + :param type: Setting type. "taginheritance" Required. + :type type: str or ~azure.mgmt.costmanagement.models.SettingType + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_delete_by_scope_request( + scope=scope, + type=type, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_views_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_views_operations.py index 421a20005715..8ebcf8253d44 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_views_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_views_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -20,16 +20,18 @@ ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -41,7 +43,7 @@ def build_list_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -60,7 +62,7 @@ def build_list_by_scope_request(scope: 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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -69,7 +71,7 @@ def build_list_by_scope_request(scope: str, **kwargs: Any) -> HttpRequest: "scope": _SERIALIZER.url("scope", scope, "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") @@ -84,7 +86,7 @@ def build_get_request(view_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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -93,7 +95,7 @@ def build_get_request(view_name: str, **kwargs: Any) -> HttpRequest: "viewName": _SERIALIZER.url("view_name", view_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") @@ -108,7 +110,7 @@ def build_create_or_update_request(view_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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -118,7 +120,7 @@ def build_create_or_update_request(view_name: str, **kwargs: Any) -> HttpRequest "viewName": _SERIALIZER.url("view_name", view_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") @@ -135,7 +137,7 @@ def build_delete_request(view_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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -144,7 +146,7 @@ def build_delete_request(view_name: str, **kwargs: Any) -> HttpRequest: "viewName": _SERIALIZER.url("view_name", view_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") @@ -159,7 +161,7 @@ def build_get_by_scope_request(scope: str, view_name: str, **kwargs: Any) -> Htt _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -169,7 +171,7 @@ def build_get_by_scope_request(scope: str, view_name: str, **kwargs: Any) -> Htt "viewName": _SERIALIZER.url("view_name", view_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") @@ -184,7 +186,7 @@ def build_create_or_update_by_scope_request(scope: str, view_name: str, **kwargs _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -195,7 +197,7 @@ def build_create_or_update_by_scope_request(scope: str, view_name: str, **kwargs "viewName": _SERIALIZER.url("view_name", view_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") @@ -212,7 +214,7 @@ def build_delete_by_scope_request(scope: str, view_name: str, **kwargs: Any) -> _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -222,7 +224,7 @@ def build_delete_by_scope_request(scope: str, view_name: str, **kwargs: Any) -> "viewName": _SERIALIZER.url("view_name", view_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") @@ -259,7 +261,6 @@ def list(self, **kwargs: Any) -> Iterable["_models.View"]: .. seealso:: - https://docs.microsoft.com/en-us/rest/api/costmanagement/ - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either View or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.View] :raises ~azure.core.exceptions.HttpResponseError: @@ -270,7 +271,7 @@ def list(self, **kwargs: Any) -> Iterable["_models.View"]: api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ViewListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -281,14 +282,12 @@ def list(self, **kwargs: Any) -> Iterable["_models.View"]: 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 @@ -300,13 +299,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("ViewListResult", pipeline_response) @@ -316,11 +314,11 @@ 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -333,8 +331,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list.metadata = {"url": "/providers/Microsoft.CostManagement/views"} - @distributed_trace def list_by_scope(self, scope: str, **kwargs: Any) -> Iterable["_models.View"]: """Lists all views at the given scope. @@ -360,7 +356,6 @@ def list_by_scope(self, scope: str, **kwargs: Any) -> Iterable["_models.View"]: 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for External Subscription 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 View or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.View] :raises ~azure.core.exceptions.HttpResponseError: @@ -371,7 +366,7 @@ def list_by_scope(self, scope: str, **kwargs: Any) -> Iterable["_models.View"]: api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ViewListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -382,15 +377,13 @@ def list_by_scope(self, scope: str, **kwargs: Any) -> Iterable["_models.View"]: def prepare_request(next_link=None): if not next_link: - request = build_list_by_scope_request( + _request = build_list_by_scope_request( scope=scope, api_version=api_version, - template_url=self.list_by_scope.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 +395,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("ViewListResult", pipeline_response) @@ -418,11 +410,11 @@ 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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -435,8 +427,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/views"} - @distributed_trace def get(self, view_name: str, **kwargs: Any) -> _models.View: """Gets the view by view name. @@ -446,12 +436,11 @@ def get(self, view_name: str, **kwargs: Any) -> _models.View: :param view_name: View name. Required. :type view_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -465,19 +454,17 @@ def get(self, view_name: str, **kwargs: Any) -> _models.View: api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.View] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( view_name=view_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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -487,14 +474,12 @@ def get(self, view_name: str, **kwargs: Any) -> _models.View: error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("View", pipeline_response) + deserialized = self._deserialize("View", 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.CostManagement/views/{viewName}"} + return deserialized # type: ignore @overload def create_or_update( @@ -514,7 +499,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: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View :raises ~azure.core.exceptions.HttpResponseError: @@ -522,7 +506,7 @@ def create_or_update( @overload def create_or_update( - self, view_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, view_name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.View: """The operation to create or update a view. Update operation requires latest eTag to be set in the request. You may obtain the latest eTag by performing a get operation. Create operation @@ -534,18 +518,19 @@ def create_or_update( :param view_name: View name. Required. :type view_name: str :param parameters: Parameters supplied to the CreateOrUpdate View 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: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - def create_or_update(self, view_name: str, parameters: Union[_models.View, IO], **kwargs: Any) -> _models.View: + def create_or_update( + self, view_name: str, parameters: Union[_models.View, IO[bytes]], **kwargs: Any + ) -> _models.View: """The operation to create or update a view. Update operation requires latest eTag to be set in the request. You may obtain the latest eTag by performing a get operation. Create operation does not require eTag. @@ -556,17 +541,13 @@ def create_or_update(self, view_name: str, parameters: Union[_models.View, IO], :param view_name: View name. Required. :type view_name: str :param parameters: Parameters supplied to the CreateOrUpdate View operation. Is either a View - type or a IO type. Required. - :type parameters: ~azure.mgmt.costmanagement.models.View 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 + type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.View or IO[bytes] :return: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -589,22 +570,20 @@ def create_or_update(self, view_name: str, parameters: Union[_models.View, IO], else: _json = self._serialize.body(parameters, "View") - request = build_create_or_update_request( + _request = build_create_or_update_request( view_name=view_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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -614,19 +593,13 @@ def create_or_update(self, view_name: str, parameters: Union[_models.View, IO], error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("View", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("View", pipeline_response) + deserialized = self._deserialize("View", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = {"url": "/providers/Microsoft.CostManagement/views/{viewName}"} - @distributed_trace def delete(self, view_name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements """The operation to delete a view. @@ -636,12 +609,11 @@ def delete(self, view_name: str, **kwargs: Any) -> None: # pylint: disable=inco :param view_name: View name. Required. :type view_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, @@ -655,19 +627,17 @@ def delete(self, view_name: str, **kwargs: Any) -> None: # pylint: disable=inco 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( view_name=view_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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -678,9 +648,7 @@ def delete(self, view_name: str, **kwargs: Any) -> None: # pylint: disable=inco raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = {"url": "/providers/Microsoft.CostManagement/views/{viewName}"} + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def get_by_scope(self, scope: str, view_name: str, **kwargs: Any) -> _models.View: @@ -709,12 +677,11 @@ def get_by_scope(self, scope: str, view_name: str, **kwargs: Any) -> _models.Vie :type scope: str :param view_name: View name. Required. :type view_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -728,20 +695,18 @@ def get_by_scope(self, scope: str, view_name: str, **kwargs: Any) -> _models.Vie api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.View] = kwargs.pop("cls", None) - request = build_get_by_scope_request( + _request = build_get_by_scope_request( scope=scope, view_name=view_name, api_version=api_version, - template_url=self.get_by_scope.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -751,14 +716,12 @@ def get_by_scope(self, scope: str, view_name: str, **kwargs: Any) -> _models.Vie error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("View", pipeline_response) + deserialized = self._deserialize("View", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/views/{viewName}"} + return deserialized # type: ignore @overload def create_or_update_by_scope( @@ -802,7 +765,6 @@ def create_or_update_by_scope( :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: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View :raises ~azure.core.exceptions.HttpResponseError: @@ -810,7 +772,13 @@ def create_or_update_by_scope( @overload def create_or_update_by_scope( - self, scope: str, view_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, + scope: str, + view_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models.View: """The operation to create or update a view. Update operation requires latest eTag to be set in the request. You may obtain the latest eTag by performing a get operation. Create operation @@ -840,11 +808,10 @@ def create_or_update_by_scope( :param view_name: View name. Required. :type view_name: str :param parameters: Parameters supplied to the CreateOrUpdate View 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: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View :raises ~azure.core.exceptions.HttpResponseError: @@ -852,7 +819,7 @@ def create_or_update_by_scope( @distributed_trace def create_or_update_by_scope( - self, scope: str, view_name: str, parameters: Union[_models.View, IO], **kwargs: Any + self, scope: str, view_name: str, parameters: Union[_models.View, IO[bytes]], **kwargs: Any ) -> _models.View: """The operation to create or update a view. Update operation requires latest eTag to be set in the request. You may obtain the latest eTag by performing a get operation. Create operation @@ -882,17 +849,13 @@ def create_or_update_by_scope( :param view_name: View name. Required. :type view_name: str :param parameters: Parameters supplied to the CreateOrUpdate View operation. Is either a View - type or a IO type. Required. - :type parameters: ~azure.mgmt.costmanagement.models.View 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 + type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.View or IO[bytes] :return: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -915,23 +878,21 @@ def create_or_update_by_scope( else: _json = self._serialize.body(parameters, "View") - request = build_create_or_update_by_scope_request( + _request = build_create_or_update_by_scope_request( scope=scope, view_name=view_name, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.create_or_update_by_scope.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -941,19 +902,13 @@ def create_or_update_by_scope( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("View", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("View", pipeline_response) + deserialized = self._deserialize("View", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/views/{viewName}"} - @distributed_trace def delete_by_scope( # pylint: disable=inconsistent-return-statements self, scope: str, view_name: str, **kwargs: Any @@ -983,12 +938,11 @@ def delete_by_scope( # pylint: disable=inconsistent-return-statements :type scope: str :param view_name: View name. Required. :type view_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, @@ -1002,20 +956,18 @@ def delete_by_scope( # pylint: disable=inconsistent-return-statements 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_by_scope_request( + _request = build_delete_by_scope_request( scope=scope, view_name=view_name, api_version=api_version, - template_url=self.delete_by_scope.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=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1026,6 +978,4 @@ def delete_by_scope( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/views/{viewName}"} + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_recommendations_by_billing_account.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_recommendations_by_billing_account.py index 92332e0a8bf2..2b13a937bb31 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_recommendations_by_billing_account.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_recommendations_by_billing_account.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/BenefitRecommendationsByBillingAccount.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/BenefitRecommendationsByBillingAccount.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/async/generate_benefit_utilization_summaries_report_by_billing_account.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/async/generate_benefit_utilization_summaries_report_by_billing_account.py new file mode 100644 index 000000000000..59808db97f8b --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/async/generate_benefit_utilization_summaries_report_by_billing_account.py @@ -0,0 +1,46 @@ +# 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python generate_benefit_utilization_summaries_report_by_billing_account.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.generate_benefit_utilization_summaries_report.begin_generate_by_billing_account( + billing_account_id="8099099", + benefit_utilization_summaries_request={ + "endDate": "2022-08-31T00:00:00Z", + "grain": "Daily", + "kind": "Reservation", + "startDate": "2022-06-01T00:00:00Z", + }, + ).result() + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/BenefitUtilizationSummaries/Async/GenerateBenefitUtilizationSummariesReportByBillingAccount.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/async/generate_benefit_utilization_summaries_report_by_billing_profile.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/async/generate_benefit_utilization_summaries_report_by_billing_profile.py new file mode 100644 index 000000000000..7a47a20b1b63 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/async/generate_benefit_utilization_summaries_report_by_billing_profile.py @@ -0,0 +1,47 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python generate_benefit_utilization_summaries_report_by_billing_profile.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.generate_benefit_utilization_summaries_report.begin_generate_by_billing_profile( + billing_account_id="00000000-0000-0000-0000-000000000000", + billing_profile_id="CZSFR-SDFXC-DSDF", + benefit_utilization_summaries_request={ + "endDate": "2022-08-31T00:00:00Z", + "grain": "Daily", + "kind": "Reservation", + "startDate": "2022-06-01T00:00:00Z", + }, + ).result() + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/BenefitUtilizationSummaries/Async/GenerateBenefitUtilizationSummariesReportByBillingProfile.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/async/generate_benefit_utilization_summaries_report_by_reservation.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/async/generate_benefit_utilization_summaries_report_by_reservation.py new file mode 100644 index 000000000000..3b42e5cb5863 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/async/generate_benefit_utilization_summaries_report_by_reservation.py @@ -0,0 +1,46 @@ +# 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python generate_benefit_utilization_summaries_report_by_reservation.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.generate_benefit_utilization_summaries_report.begin_generate_by_reservation_id( + reservation_order_id="00000000-0000-0000-0000-000000000000", + reservation_id="00000000-0000-0000-0000-000000000000", + benefit_utilization_summaries_request={ + "endDate": "2022-08-31T00:00:00Z", + "grain": "Daily", + "startDate": "2022-06-01T00:00:00Z", + }, + ).result() + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/BenefitUtilizationSummaries/Async/GenerateBenefitUtilizationSummariesReportByReservation.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/async/generate_benefit_utilization_summaries_report_by_reservation_order.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/async/generate_benefit_utilization_summaries_report_by_reservation_order.py new file mode 100644 index 000000000000..c0ac5d1802cc --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/async/generate_benefit_utilization_summaries_report_by_reservation_order.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. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python generate_benefit_utilization_summaries_report_by_reservation_order.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.generate_benefit_utilization_summaries_report.begin_generate_by_reservation_order_id( + reservation_order_id="00000000-0000-0000-0000-000000000000", + benefit_utilization_summaries_request={ + "endDate": "2022-08-31T00:00:00Z", + "grain": "Daily", + "startDate": "2022-06-01T00:00:00Z", + }, + ).result() + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/BenefitUtilizationSummaries/Async/GenerateBenefitUtilizationSummariesReportByReservationOrder.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/async/generate_benefit_utilization_summaries_report_by_savings_plan.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/async/generate_benefit_utilization_summaries_report_by_savings_plan.py new file mode 100644 index 000000000000..450fc5e8eb3b --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/async/generate_benefit_utilization_summaries_report_by_savings_plan.py @@ -0,0 +1,46 @@ +# 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python generate_benefit_utilization_summaries_report_by_savings_plan.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.generate_benefit_utilization_summaries_report.begin_generate_by_savings_plan_id( + savings_plan_order_id="00000000-0000-0000-0000-000000000000", + savings_plan_id="00000000-0000-0000-0000-000000000000", + benefit_utilization_summaries_request={ + "endDate": "2022-08-31T00:00:00Z", + "grain": "Daily", + "startDate": "2022-06-01T00:00:00Z", + }, + ).result() + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/BenefitUtilizationSummaries/Async/GenerateBenefitUtilizationSummariesReportBySavingsPlan.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/async/generate_benefit_utilization_summaries_report_by_savings_plan_order.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/async/generate_benefit_utilization_summaries_report_by_savings_plan_order.py new file mode 100644 index 000000000000..bd7916ae1d00 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/async/generate_benefit_utilization_summaries_report_by_savings_plan_order.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. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python generate_benefit_utilization_summaries_report_by_savings_plan_order.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.generate_benefit_utilization_summaries_report.begin_generate_by_savings_plan_order_id( + savings_plan_order_id="00000000-0000-0000-0000-000000000000", + benefit_utilization_summaries_request={ + "endDate": "2022-08-31T00:00:00Z", + "grain": "Daily", + "startDate": "2022-06-01T00:00:00Z", + }, + ).result() + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/BenefitUtilizationSummaries/Async/GenerateBenefitUtilizationSummariesReportBySavingsPlanOrder.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/savings_plan_billing_account.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/savings_plan_billing_account.py index c09892637945..adf27dee0cf4 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/savings_plan_billing_account.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/savings_plan_billing_account.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/BenefitUtilizationSummaries/SavingsPlan-BillingAccount.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/BenefitUtilizationSummaries/SavingsPlan-BillingAccount.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/savings_plan_billing_profile.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/savings_plan_billing_profile.py index 83fd2506ae40..007b968149d2 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/savings_plan_billing_profile.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/savings_plan_billing_profile.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/BenefitUtilizationSummaries/SavingsPlan-BillingProfile.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/BenefitUtilizationSummaries/SavingsPlan-BillingProfile.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/savings_plan_savings_plan_id_monthly.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/savings_plan_savings_plan_id_monthly.py index a3451662d9a5..2aa1543ab97a 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/savings_plan_savings_plan_id_monthly.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/savings_plan_savings_plan_id_monthly.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/BenefitUtilizationSummaries/SavingsPlan-SavingsPlanId-Monthly.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/BenefitUtilizationSummaries/SavingsPlan-SavingsPlanId-Monthly.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/savings_plan_savings_plan_order_id_daily.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/savings_plan_savings_plan_order_id_daily.py index 6aa7f30f86ef..b40effe3c858 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/savings_plan_savings_plan_order_id_daily.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_utilization_summaries/savings_plan_savings_plan_order_id_daily.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/BenefitUtilizationSummaries/SavingsPlan-SavingsPlanOrderId-Daily.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/BenefitUtilizationSummaries/SavingsPlan-SavingsPlanOrderId-Daily.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_alerts.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_alerts.py index b5bb07a53325..0b29644dd943 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_alerts.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_alerts.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/BillingAccountAlerts.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/BillingAccountAlerts.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list.py index f0e45e39ad6c..5d48413a5a60 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/BillingAccountDimensionsList.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/BillingAccountDimensionsList.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list_expand_and_top.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list_expand_and_top.py index 874fc420c63d..1b24999f74b9 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list_expand_and_top.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list_expand_and_top.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/BillingAccountDimensionsListExpandAndTop.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/BillingAccountDimensionsListExpandAndTop.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list_with_filter.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list_with_filter.py index 02bd4d716cc0..f25fb7d74e4f 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list_with_filter.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list_with_filter.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/BillingAccountDimensionsListWithFilter.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/BillingAccountDimensionsListWithFilter.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_forecast.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_forecast.py index 1b4628647f41..0f00f5a591f8 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_forecast.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_forecast.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -62,6 +63,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/BillingAccountForecast.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/BillingAccountForecast.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_query.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_query.py index a7cae2acc067..ff21ea057f15 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_query.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_query.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -58,6 +59,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/BillingAccountQuery.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/BillingAccountQuery.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_query_grouping.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_query_grouping.py index 13b762d01fcf..8927982a36b5 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_query_grouping.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_query_grouping.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -43,6 +44,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/BillingAccountQueryGrouping.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/BillingAccountQueryGrouping.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_profile_alerts.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_profile_alerts.py index e3d0e291e3a4..16023c0db1c5 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_profile_alerts.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_profile_alerts.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/BillingProfileAlerts.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/BillingProfileAlerts.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_profile_forecast.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_profile_forecast.py index 887aafbcf15e..aab7a9796573 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_profile_forecast.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_profile_forecast.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -62,6 +63,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/BillingProfileForecast.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/BillingProfileForecast.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/cost/create_or_update_cost_subscription_budget.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/cost/create_or_update_cost_subscription_budget.py new file mode 100644 index 000000000000..a33f8f092c87 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/cost/create_or_update_cost_subscription_budget.py @@ -0,0 +1,80 @@ +# 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python create_or_update_cost_subscription_budget.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.budgets.create_or_update( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + budget_name="TestBudget", + parameters={ + "eTag": '"1d34d016a593709"', + "properties": { + "amount": 100.65, + "category": "Cost", + "filter": { + "and": [ + { + "dimensions": { + "name": "ResourceId", + "operator": "In", + "values": [ + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG/providers/Microsoft.Compute/virtualMachines/MSVM2", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG/providers/Microsoft.Compute/virtualMachines/platformcloudplatformGeneric1", + ], + } + }, + {"tags": {"name": "category", "operator": "In", "values": ["Dev", "Prod"]}}, + {"tags": {"name": "department", "operator": "In", "values": ["engineering", "sales"]}}, + ] + }, + "notifications": { + "Actual_GreaterThan_80_Percent": { + "contactEmails": ["johndoe@contoso.com", "janesmith@contoso.com"], + "contactGroups": [ + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG/providers/microsoft.insights/actionGroups/SampleActionGroup" + ], + "contactRoles": ["Contributor", "Reader"], + "enabled": True, + "locale": "en-us", + "operator": "GreaterThan", + "threshold": 80, + "thresholdType": "Actual", + } + }, + "timeGrain": "Monthly", + "timePeriod": {"endDate": "2024-10-31T00:00:00Z", "startDate": "2023-04-01T00:00:00Z"}, + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/Budgets/CreateOrUpdate/Cost/CreateOrUpdate-Cost-Subscription-Budget.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/reservation_utilization/ea/billing_account_ea_alert_rule.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/reservation_utilization/ea/billing_account_ea_alert_rule.py new file mode 100644 index 000000000000..3b78519796da --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/reservation_utilization/ea/billing_account_ea_alert_rule.py @@ -0,0 +1,60 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_account_ea_alert_rule.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.budgets.create_or_update( + scope="providers/Microsoft.Billing/billingAccounts/123456", + budget_name="TestAlertRule", + parameters={ + "eTag": '"1d34d016a593709"', + "properties": { + "category": "ReservationUtilization", + "filter": {}, + "notifications": { + "Actual_LessThan_99_Percent": { + "contactEmails": ["johndoe@contoso.com", "janesmith@contoso.com"], + "enabled": True, + "frequency": "Weekly", + "locale": "en-us", + "operator": "LessThan", + "threshold": 99, + } + }, + "timeGrain": "Last7Days", + "timePeriod": {"endDate": "2025-04-01T00:00:00Z", "startDate": "2023-04-01T00:00:00Z"}, + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/Budgets/CreateOrUpdate/ReservationUtilization/EA/BillingAccountEA-AlertRule.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/reservation_utilization/ea/billing_account_ea_alert_rule_reservation_id_filter.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/reservation_utilization/ea/billing_account_ea_alert_rule_reservation_id_filter.py new file mode 100644 index 000000000000..209368f0157c --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/reservation_utilization/ea/billing_account_ea_alert_rule_reservation_id_filter.py @@ -0,0 +1,70 @@ +# 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_account_ea_alert_rule_reservation_id_filter.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.budgets.create_or_update( + scope="providers/Microsoft.Billing/billingAccounts/123456", + budget_name="TestAlertRule", + parameters={ + "eTag": '"1d34d016a593709"', + "properties": { + "category": "ReservationUtilization", + "filter": { + "dimensions": { + "name": "ReservationId", + "operator": "In", + "values": [ + "00000000-0000-0000-0000-000000000000", + "00000000-0000-0000-0000-000000000001", + "00000000-0000-0000-0000-000000000002", + ], + } + }, + "notifications": { + "Actual_LessThan_99_Percent": { + "contactEmails": ["johndoe@contoso.com", "janesmith@contoso.com"], + "enabled": True, + "frequency": "Weekly", + "locale": "en-us", + "operator": "LessThan", + "threshold": 99, + } + }, + "timeGrain": "Last7Days", + "timePeriod": {"endDate": "2025-04-01T00:00:00Z", "startDate": "2023-04-01T00:00:00Z"}, + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/Budgets/CreateOrUpdate/ReservationUtilization/EA/BillingAccountEA-AlertRule-ReservationIdFilter.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/reservation_utilization/ea/billing_account_ea_alert_rule_reserved_resource_type_filter.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/reservation_utilization/ea/billing_account_ea_alert_rule_reserved_resource_type_filter.py new file mode 100644 index 000000000000..d505e7c490d7 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/reservation_utilization/ea/billing_account_ea_alert_rule_reserved_resource_type_filter.py @@ -0,0 +1,66 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_account_ea_alert_rule_reserved_resource_type_filter.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.budgets.create_or_update( + scope="providers/Microsoft.Billing/billingAccounts/123456", + budget_name="TestAlertRule", + parameters={ + "eTag": '"1d34d016a593709"', + "properties": { + "category": "ReservationUtilization", + "filter": { + "dimensions": { + "name": "ReservedResourceType", + "operator": "In", + "values": ["VirtualMachines", "SqlDatabases", "CosmosDb"], + } + }, + "notifications": { + "Actual_LessThan_99_Percent": { + "contactEmails": ["johndoe@contoso.com", "janesmith@contoso.com"], + "enabled": True, + "frequency": "Weekly", + "locale": "en-us", + "operator": "LessThan", + "threshold": 99, + } + }, + "timeGrain": "Last7Days", + "timePeriod": {"endDate": "2025-04-01T00:00:00Z", "startDate": "2023-04-01T00:00:00Z"}, + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/Budgets/CreateOrUpdate/ReservationUtilization/EA/BillingAccountEA-AlertRule-ReservedResourceTypeFilter.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/reservation_utilization/mca/billing_profile_alert_rule.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/reservation_utilization/mca/billing_profile_alert_rule.py new file mode 100644 index 000000000000..d4c1d5156602 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/reservation_utilization/mca/billing_profile_alert_rule.py @@ -0,0 +1,60 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_profile_alert_rule.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.budgets.create_or_update( + scope="providers/Microsoft.Billing/billingAccounts/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee:ffffffff-gggg-hhhh-iiii-jjjjjjjjjjjj_2023-04-01/billingProfiles/KKKK-LLLL-MMM-NNN", + budget_name="TestAlertRule", + parameters={ + "eTag": '"1d34d016a593709"', + "properties": { + "category": "ReservationUtilization", + "filter": {}, + "notifications": { + "Actual_LessThan_99_Percent": { + "contactEmails": ["johndoe@contoso.com", "janesmith@contoso.com"], + "enabled": True, + "frequency": "Daily", + "locale": "en-us", + "operator": "LessThan", + "threshold": 99, + } + }, + "timeGrain": "Last30Days", + "timePeriod": {"endDate": "2025-04-01T00:00:00Z", "startDate": "2023-04-01T00:00:00Z"}, + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/Budgets/CreateOrUpdate/ReservationUtilization/MCA/BillingProfile-AlertRule.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/reservation_utilization/mca/billing_profile_alert_rule_reservation_id_filter.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/reservation_utilization/mca/billing_profile_alert_rule_reservation_id_filter.py new file mode 100644 index 000000000000..e433627455f4 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/reservation_utilization/mca/billing_profile_alert_rule_reservation_id_filter.py @@ -0,0 +1,70 @@ +# 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_profile_alert_rule_reservation_id_filter.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.budgets.create_or_update( + scope="providers/Microsoft.Billing/billingAccounts/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee:ffffffff-gggg-hhhh-iiii-jjjjjjjjjjjj_2023-04-01/billingProfiles/KKKK-LLLL-MMM-NNN", + budget_name="TestAlertRule", + parameters={ + "eTag": '"1d34d016a593709"', + "properties": { + "category": "ReservationUtilization", + "filter": { + "dimensions": { + "name": "ReservationId", + "operator": "In", + "values": [ + "00000000-0000-0000-0000-000000000000", + "00000000-0000-0000-0000-000000000001", + "00000000-0000-0000-0000-000000000002", + ], + } + }, + "notifications": { + "Actual_LessThan_99_Percent": { + "contactEmails": ["johndoe@contoso.com", "janesmith@contoso.com"], + "enabled": True, + "frequency": "Daily", + "locale": "en-us", + "operator": "LessThan", + "threshold": 99, + } + }, + "timeGrain": "Last30Days", + "timePeriod": {"endDate": "2025-04-01T00:00:00Z", "startDate": "2023-04-01T00:00:00Z"}, + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/Budgets/CreateOrUpdate/ReservationUtilization/MCA/BillingProfile-AlertRule-ReservationIdFilter.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/reservation_utilization/mca/billing_profile_alert_rule_reserved_resource_type_filter.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/reservation_utilization/mca/billing_profile_alert_rule_reserved_resource_type_filter.py new file mode 100644 index 000000000000..57a922496049 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/reservation_utilization/mca/billing_profile_alert_rule_reserved_resource_type_filter.py @@ -0,0 +1,66 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_profile_alert_rule_reserved_resource_type_filter.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.budgets.create_or_update( + scope="providers/Microsoft.Billing/billingAccounts/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee:ffffffff-gggg-hhhh-iiii-jjjjjjjjjjjj_2023-04-01/billingProfiles/KKKK-LLLL-MMM-NNN", + budget_name="TestAlertRule", + parameters={ + "eTag": '"1d34d016a593709"', + "properties": { + "category": "ReservationUtilization", + "filter": { + "dimensions": { + "name": "ReservedResourceType", + "operator": "In", + "values": ["VirtualMachines", "SqlDatabases", "CosmosDb"], + } + }, + "notifications": { + "Actual_LessThan_99_Percent": { + "contactEmails": ["johndoe@contoso.com", "janesmith@contoso.com"], + "enabled": True, + "frequency": "Daily", + "locale": "en-us", + "operator": "LessThan", + "threshold": 99, + } + }, + "timeGrain": "Last30Days", + "timePeriod": {"endDate": "2025-04-01T00:00:00Z", "startDate": "2023-04-01T00:00:00Z"}, + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/Budgets/CreateOrUpdate/ReservationUtilization/MCA/BillingProfile-AlertRule-ReservedResourceTypeFilter.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/reservation_utilization/mca/customer_alert_rule.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/reservation_utilization/mca/customer_alert_rule.py new file mode 100644 index 000000000000..a90ed274be35 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/reservation_utilization/mca/customer_alert_rule.py @@ -0,0 +1,60 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python customer_alert_rule.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.budgets.create_or_update( + scope="providers/Microsoft.Billing/billingAccounts/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee:ffffffff-gggg-hhhh-iiii-jjjjjjjjjjjj_2023-04-01/customers/000000-1111-2222-3333-444444444444", + budget_name="TestAlertRule", + parameters={ + "eTag": '"1d34d016a593709"', + "properties": { + "category": "ReservationUtilization", + "filter": {}, + "notifications": { + "Actual_LessThan_99_Percent": { + "contactEmails": ["johndoe@contoso.com", "janesmith@contoso.com"], + "enabled": True, + "frequency": "Daily", + "locale": "en-us", + "operator": "LessThan", + "threshold": 99, + } + }, + "timeGrain": "Last30Days", + "timePeriod": {"endDate": "2025-04-01T00:00:00Z", "startDate": "2023-04-01T00:00:00Z"}, + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/Budgets/CreateOrUpdate/ReservationUtilization/MCA/Customer-AlertRule.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/reservation_utilization/mca/customer_alert_rule_reservation_id_filter.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/reservation_utilization/mca/customer_alert_rule_reservation_id_filter.py new file mode 100644 index 000000000000..487d30a528c9 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/reservation_utilization/mca/customer_alert_rule_reservation_id_filter.py @@ -0,0 +1,70 @@ +# 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python customer_alert_rule_reservation_id_filter.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.budgets.create_or_update( + scope="providers/Microsoft.Billing/billingAccounts/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee:ffffffff-gggg-hhhh-iiii-jjjjjjjjjjjj_2023-04-01/customers/000000-1111-2222-3333-444444444444", + budget_name="TestAlertRule", + parameters={ + "eTag": '"1d34d016a593709"', + "properties": { + "category": "ReservationUtilization", + "filter": { + "dimensions": { + "name": "ReservationId", + "operator": "In", + "values": [ + "00000000-0000-0000-0000-000000000000", + "00000000-0000-0000-0000-000000000001", + "00000000-0000-0000-0000-000000000002", + ], + } + }, + "notifications": { + "Actual_LessThan_99_Percent": { + "contactEmails": ["johndoe@contoso.com", "janesmith@contoso.com"], + "enabled": True, + "frequency": "Daily", + "locale": "en-us", + "operator": "LessThan", + "threshold": 99, + } + }, + "timeGrain": "Last30Days", + "timePeriod": {"endDate": "2025-04-01T00:00:00Z", "startDate": "2023-04-01T00:00:00Z"}, + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/Budgets/CreateOrUpdate/ReservationUtilization/MCA/Customer-AlertRule-ReservationIdFilter.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/reservation_utilization/mca/customer_alert_rule_reserved_resource_type_filter.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/reservation_utilization/mca/customer_alert_rule_reserved_resource_type_filter.py new file mode 100644 index 000000000000..4b954a23e2bc --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/create_or_update/reservation_utilization/mca/customer_alert_rule_reserved_resource_type_filter.py @@ -0,0 +1,66 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python customer_alert_rule_reserved_resource_type_filter.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.budgets.create_or_update( + scope="providers/Microsoft.Billing/billingAccounts/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee:ffffffff-gggg-hhhh-iiii-jjjjjjjjjjjj_2023-04-01/customers/000000-1111-2222-3333-444444444444", + budget_name="TestAlertRule", + parameters={ + "eTag": '"1d34d016a593709"', + "properties": { + "category": "ReservationUtilization", + "filter": { + "dimensions": { + "name": "ReservedResourceType", + "operator": "In", + "values": ["VirtualMachines", "SqlDatabases", "CosmosDb"], + } + }, + "notifications": { + "Actual_LessThan_99_Percent": { + "contactEmails": ["johndoe@contoso.com", "janesmith@contoso.com"], + "enabled": True, + "frequency": "Daily", + "locale": "en-us", + "operator": "LessThan", + "threshold": 99, + } + }, + "timeGrain": "Last30Days", + "timePeriod": {"endDate": "2025-04-01T00:00:00Z", "startDate": "2023-04-01T00:00:00Z"}, + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/Budgets/CreateOrUpdate/ReservationUtilization/MCA/Customer-AlertRule-ReservedResourceTypeFilter.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/delete/delete_budget.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/delete/delete_budget.py new file mode 100644 index 000000000000..d27264051e04 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/delete/delete_budget.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python delete_budget.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + client.budgets.delete( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + budget_name="TestBudget", + ) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/Budgets/Delete/DeleteBudget.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/get/cost/get_cost_budget.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/get/cost/get_cost_budget.py new file mode 100644 index 000000000000..9c4e549a8ca9 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/get/cost/get_cost_budget.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python get_cost_budget.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.budgets.get( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + budget_name="TestBudget", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/Budgets/Get/Cost/Get-Cost-Budget.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/get/reservation_utilization/get_reservation_utilization_alert_rule.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/get/reservation_utilization/get_reservation_utilization_alert_rule.py new file mode 100644 index 000000000000..c9e72dad8f76 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/get/reservation_utilization/get_reservation_utilization_alert_rule.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python get_reservation_utilization_alert_rule.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.budgets.get( + scope="providers/Microsoft.Billing/billingAccounts/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee:ffffffff-gggg-hhhh-iiii-jjjjjjjjjjjj_2023-04-01/billingProfiles/KKKK-LLLL-MMM-NNN", + budget_name="TestAlertRule", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/Budgets/Get/ReservationUtilization/Get-ReservationUtilization-AlertRule.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/ea/billing_account_budgets_list_ea.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/ea/billing_account_budgets_list_ea.py new file mode 100644 index 000000000000..402619110dde --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/ea/billing_account_budgets_list_ea.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_account_budgets_list_ea.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.budgets.list( + scope="providers/Microsoft.Billing/billingAccounts/123456", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/Budgets/List/EA/BillingAccountBudgetsList-EA.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/ea/billing_account_budgets_list_ea_category_type_filter.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/ea/billing_account_budgets_list_ea_category_type_filter.py new file mode 100644 index 000000000000..a5afa2df88b6 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/ea/billing_account_budgets_list_ea_category_type_filter.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_account_budgets_list_ea_category_type_filter.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.budgets.list( + scope="providers/Microsoft.Billing/billingAccounts/123456", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/Budgets/List/EA/BillingAccountBudgetsList-EA-CategoryTypeFilter.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/ea/department_budgets_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/ea/department_budgets_list.py new file mode 100644 index 000000000000..ab16794e2000 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/ea/department_budgets_list.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python department_budgets_list.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.budgets.list( + scope="providers/Microsoft.Billing/billingAccounts/123456/departments/789101", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/Budgets/List/EA/DepartmentBudgetsList.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/ea/enrollment_account_budgets_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/ea/enrollment_account_budgets_list.py new file mode 100644 index 000000000000..dac59431a455 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/ea/enrollment_account_budgets_list.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python enrollment_account_budgets_list.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.budgets.list( + scope="providers/Microsoft.Billing/billingAccounts/123456/enrollmentAccounts/473845", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/Budgets/List/EA/EnrollmentAccountBudgetsList.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/mca/billing_account_budgets_list_mca.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/mca/billing_account_budgets_list_mca.py new file mode 100644 index 000000000000..bcf350c18202 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/mca/billing_account_budgets_list_mca.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_account_budgets_list_mca.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.budgets.list( + scope="providers/Microsoft.Billing/billingAccounts/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee:ffffffff-gggg-hhhh-iiii-jjjjjjjjjjjj_2023-04-01", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/Budgets/List/MCA/BillingAccountBudgetsList-MCA.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/mca/billing_account_budgets_list_mca_category_type_filter.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/mca/billing_account_budgets_list_mca_category_type_filter.py new file mode 100644 index 000000000000..fdaca9713720 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/mca/billing_account_budgets_list_mca_category_type_filter.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_account_budgets_list_mca_category_type_filter.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.budgets.list( + scope="providers/Microsoft.Billing/billingAccounts/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee:ffffffff-gggg-hhhh-iiii-jjjjjjjjjjjj_2023-04-01", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/Budgets/List/MCA/BillingAccountBudgetsList-MCA-CategoryTypeFilter.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/mca/billing_profile_budgets_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/mca/billing_profile_budgets_list.py new file mode 100644 index 000000000000..ee33f3a52261 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/mca/billing_profile_budgets_list.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_profile_budgets_list.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.budgets.list( + scope="providers/Microsoft.Billing/billingAccounts/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee:ffffffff-gggg-hhhh-iiii-jjjjjjjjjjjj_2023-04-01/billingProfiles/MYDEVTESTBP", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/Budgets/List/MCA/BillingProfileBudgetsList.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/mca/billing_profile_budgets_list_category_type_filter.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/mca/billing_profile_budgets_list_category_type_filter.py new file mode 100644 index 000000000000..942b01bc9a6a --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/mca/billing_profile_budgets_list_category_type_filter.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_profile_budgets_list_category_type_filter.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.budgets.list( + scope="providers/Microsoft.Billing/billingAccounts/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee:ffffffff-gggg-hhhh-iiii-jjjjjjjjjjjj_2023-04-01/billingProfiles/MYDEVTESTBP", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/Budgets/List/MCA/BillingProfileBudgetsList-CategoryTypeFilter.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/mca/customer_budgets_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/mca/customer_budgets_list.py new file mode 100644 index 000000000000..1203be9cd29c --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/mca/customer_budgets_list.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python customer_budgets_list.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.budgets.list( + scope="providers/Microsoft.Billing/billingAccounts/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee:ffffffff-gggg-hhhh-iiii-jjjjjjjjjjjj_2023-04-01/customers/000000-1111-2222-3333-444444444444", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/Budgets/List/MCA/CustomerBudgetsList.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/mca/customer_budgets_list_category_type_filter.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/mca/customer_budgets_list_category_type_filter.py new file mode 100644 index 000000000000..7430db6c50ad --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/mca/customer_budgets_list_category_type_filter.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python customer_budgets_list_category_type_filter.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.budgets.list( + scope="providers/Microsoft.Billing/billingAccounts/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee:ffffffff-gggg-hhhh-iiii-jjjjjjjjjjjj_2023-04-01/customers/000000-1111-2222-3333-444444444444", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/Budgets/List/MCA/CustomerBudgetsList-CategoryTypeFilter.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/mca/invoice_section_budgets_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/mca/invoice_section_budgets_list.py new file mode 100644 index 000000000000..c3015db8f31f --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/mca/invoice_section_budgets_list.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python invoice_section_budgets_list.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.budgets.list( + scope="providers/Microsoft.Billing/billingAccounts/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee:ffffffff-gggg-hhhh-iiii-jjjjjjjjjjjj_2023-04-01/billingProfiles/MYDEVTESTBP/invoiceSections/AAAA-BBBB-CCC-DDD", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/Budgets/List/MCA/InvoiceSectionBudgetsList.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/rbac/management_group_budgets_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/rbac/management_group_budgets_list.py new file mode 100644 index 000000000000..e871ea65a15b --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/rbac/management_group_budgets_list.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python management_group_budgets_list.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.budgets.list( + scope="Microsoft.Management/managementGroups/MYDEVTESTMG", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/Budgets/List/RBAC/ManagementGroupBudgetsList.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/rbac/resource_group_budgets_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/rbac/resource_group_budgets_list.py new file mode 100644 index 000000000000..f2056e3ca46a --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/rbac/resource_group_budgets_list.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python resource_group_budgets_list.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.budgets.list( + scope="subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/Budgets/List/RBAC/ResourceGroupBudgetsList.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/rbac/subscription_budgets_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/rbac/subscription_budgets_list.py new file mode 100644 index 000000000000..8313769f727d --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/budgets/list/rbac/subscription_budgets_list.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python subscription_budgets_list.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.budgets.list( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/Budgets/List/RBAC/SubscriptionBudgetsList.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/cost_allocation_rule_check_name_availability.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/cost_allocation_rule_check_name_availability.py new file mode 100644 index 000000000000..e11878ac23af --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/cost_allocation_rule_check_name_availability.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. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python cost_allocation_rule_check_name_availability.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.cost_allocation_rules.check_name_availability( + billing_account_id="100", + cost_allocation_rule_check_name_availability_request={ + "name": "testRule", + "type": "Microsoft.CostManagement/costAllocationRules", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/CostAllocationRuleCheckNameAvailability.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/cost_allocation_rule_create.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/cost_allocation_rule_create.py new file mode 100644 index 000000000000..cdfad35d2f6f --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/cost_allocation_rule_create.py @@ -0,0 +1,63 @@ +# 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python cost_allocation_rule_create.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.cost_allocation_rules.create_or_update( + billing_account_id="100", + rule_name="testRule", + cost_allocation_rule={ + "properties": { + "description": "This is a testRule", + "details": { + "sourceResources": [ + {"name": "ResourceGroupName", "resourceType": "Dimension", "values": ["sampleRG", "secondRG"]} + ], + "targetResources": [ + { + "name": "ResourceGroupName", + "policyType": "FixedProportion", + "resourceType": "Dimension", + "values": [ + {"name": "destinationRG", "percentage": 45}, + {"name": "destinationRG2", "percentage": 54}, + ], + } + ], + }, + "status": "Active", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/CostAllocationRuleCreate.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/cost_allocation_rule_create_tag.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/cost_allocation_rule_create_tag.py new file mode 100644 index 000000000000..97a6bd053e4a --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/cost_allocation_rule_create_tag.py @@ -0,0 +1,62 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python cost_allocation_rule_create_tag.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.cost_allocation_rules.create_or_update( + billing_account_id="100", + rule_name="testRule", + cost_allocation_rule={ + "properties": { + "description": "This is a testRule", + "details": { + "sourceResources": [{"name": "category", "resourceType": "Tag", "values": ["devops"]}], + "targetResources": [ + { + "name": "ResourceGroupName", + "policyType": "FixedProportion", + "resourceType": "Dimension", + "values": [ + {"name": "destinationRG", "percentage": 33.33}, + {"name": "destinationRG2", "percentage": 33.33}, + {"name": "destinationRG3", "percentage": 33.34}, + ], + } + ], + }, + "status": "Active", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/CostAllocationRuleCreateTag.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/cost_allocation_rule_delete.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/cost_allocation_rule_delete.py new file mode 100644 index 000000000000..24940ea237de --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/cost_allocation_rule_delete.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python cost_allocation_rule_delete.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + client.cost_allocation_rules.delete( + billing_account_id="100", + rule_name="testRule", + ) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/CostAllocationRuleDelete.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/cost_allocation_rule_get.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/cost_allocation_rule_get.py new file mode 100644 index 000000000000..e051b2eeefae --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/cost_allocation_rule_get.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python cost_allocation_rule_get.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.cost_allocation_rules.get( + billing_account_id="100", + rule_name="testRule", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/CostAllocationRuleGet.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/cost_allocation_rules_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/cost_allocation_rules_list.py new file mode 100644 index 000000000000..54b5c1495190 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/cost_allocation_rules_list.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python cost_allocation_rules_list.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.cost_allocation_rules.list( + billing_account_id="100", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/CostAllocationRulesList.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/cost_details_operation_results_by_subscription_scope.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/cost_details_operation_results_by_subscription_scope.py index 5c2a8daab65e..ab8fdc9301fe 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/cost_details_operation_results_by_subscription_scope.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/cost_details_operation_results_by_subscription_scope.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/CostDetailsOperationResultsBySubscriptionScope.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/CostDetailsOperationResultsBySubscriptionScope.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_alerts.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_alerts.py index 88c238b30566..878fbb0eaaa1 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_alerts.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_alerts.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/DepartmentAlerts.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/DepartmentAlerts.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_dimensions_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_dimensions_list.py index a38421094702..ba72d19d4702 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_dimensions_list.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_dimensions_list.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/DepartmentDimensionsList.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/DepartmentDimensionsList.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_dimensions_list_expand_and_top.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_dimensions_list_expand_and_top.py index 48935633c8ac..0334cebc4e67 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_dimensions_list_expand_and_top.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_dimensions_list_expand_and_top.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/DepartmentDimensionsListExpandAndTop.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/DepartmentDimensionsListExpandAndTop.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_dimensions_list_with_filter.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_dimensions_list_with_filter.py index 23e65cb1cb0c..959433bd3e4c 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_dimensions_list_with_filter.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_dimensions_list_with_filter.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/DepartmentDimensionsListWithFilter.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/DepartmentDimensionsListWithFilter.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_forecast.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_forecast.py index 15b69c4b5200..f304294df35b 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_forecast.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_forecast.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -62,6 +63,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/DepartmentForecast.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/DepartmentForecast.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_query.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_query.py index f31157b94afd..71e3ec2a9ccf 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_query.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_query.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -58,6 +59,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/DepartmentQuery.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/DepartmentQuery.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_query_grouping.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_query_grouping.py index 36c7d45875f4..f624fd9d9844 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_query_grouping.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_query_grouping.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -43,6 +44,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/DepartmentQueryGrouping.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/DepartmentQueryGrouping.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/dismiss_resource_group_alerts.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/dismiss_resource_group_alerts.py index face8893712c..649e66b450b3 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/dismiss_resource_group_alerts.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/dismiss_resource_group_alerts.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -36,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/DismissResourceGroupAlerts.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/DismissResourceGroupAlerts.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/dismiss_subscription_alerts.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/dismiss_subscription_alerts.py index 2da152c2d778..22d0ee52605d 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/dismiss_subscription_alerts.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/dismiss_subscription_alerts.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -36,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/DismissSubscriptionAlerts.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/DismissSubscriptionAlerts.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/ea_price_sheet_for_billing_period.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/ea_price_sheet_for_billing_period.py new file mode 100644 index 000000000000..4e10e83ee52d --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/ea_price_sheet_for_billing_period.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# 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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.price_sheet.begin_download_by_billing_account( + billing_account_id="0000000", + billing_period_name="202311", + ).result() + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/EAPriceSheetForBillingPeriod.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_alerts.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_alerts.py index 1e246acd55bb..2e216f02f615 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_alerts.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_alerts.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/EnrollmentAccountAlerts.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/EnrollmentAccountAlerts.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_dimensions_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_dimensions_list.py index e58b8e1c6003..ecb774efb413 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_dimensions_list.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_dimensions_list.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/EnrollmentAccountDimensionsList.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/EnrollmentAccountDimensionsList.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_dimensions_list_expand_and_top.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_dimensions_list_expand_and_top.py index d730beedb0a2..f0be6888b44c 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_dimensions_list_expand_and_top.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_dimensions_list_expand_and_top.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/EnrollmentAccountDimensionsListExpandAndTop.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/EnrollmentAccountDimensionsListExpandAndTop.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_dimensions_list_with_filter.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_dimensions_list_with_filter.py index aa4098802237..1e663980a767 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_dimensions_list_with_filter.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_dimensions_list_with_filter.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/EnrollmentAccountDimensionsListWithFilter.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/EnrollmentAccountDimensionsListWithFilter.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_forecast.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_forecast.py index a418aca1b8b4..d0229b6fb674 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_forecast.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_forecast.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -62,6 +63,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/EnrollmentAccountForecast.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/EnrollmentAccountForecast.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_query.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_query.py index b62acd0963eb..0d717899743f 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_query.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_query.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -58,6 +59,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/EnrollmentAccountQuery.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/EnrollmentAccountQuery.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_query_grouping.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_query_grouping.py index 4a49084d6642..130f357513a7 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_query_grouping.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_query_grouping.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -43,6 +44,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/EnrollmentAccountQueryGrouping.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/EnrollmentAccountQueryGrouping.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_billing_account.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_billing_account.py index 24a9fdabca78..d4e42cd854f2 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_billing_account.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_billing_account.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -32,10 +33,17 @@ def main(): scope="providers/Microsoft.Billing/billingAccounts/123456", export_name="TestExport", parameters={ + "identity": {"type": "SystemAssigned"}, + "location": "centralus", "properties": { + "compressionMode": "gzip", + "dataOverwriteBehavior": "OverwritePreviousReport", "definition": { "dataSet": { - "configuration": {"columns": ["Date", "MeterId", "ResourceId", "ResourceLocation", "Quantity"]}, + "configuration": { + "columns": ["Date", "MeterId", "ResourceId", "ResourceLocation", "Quantity"], + "dataVersion": "2023-05-01", + }, "granularity": "Daily", }, "timeframe": "MonthToDate", @@ -46,20 +54,23 @@ def main(): "container": "exports", "resourceId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG/providers/Microsoft.Storage/storageAccounts/ccmeastusdiag182", "rootFolderPath": "ad-hoc", + "type": "AzureBlob", } }, + "exportDescription": "This is a test export.", "format": "Csv", + "partitionData": True, "schedule": { "recurrence": "Weekly", - "recurrencePeriod": {"from": "2020-06-01T00:00:00Z", "to": "2020-10-31T00:00:00Z"}, + "recurrencePeriod": {"from": "2020-06-01T00:00:00Z", "to": "2020-06-30T00:00:00Z"}, "status": "Active", }, - } + }, }, ) print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportCreateOrUpdateByBillingAccount.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportCreateOrUpdateByBillingAccount.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_department.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_department.py index ae5adf8565d1..effe74f3abb4 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_department.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_department.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -32,10 +33,17 @@ def main(): scope="providers/Microsoft.Billing/billingAccounts/12/departments/1234", export_name="TestExport", parameters={ + "identity": {"type": "SystemAssigned"}, + "location": "centralus", "properties": { + "compressionMode": "gzip", + "dataOverwriteBehavior": "OverwritePreviousReport", "definition": { "dataSet": { - "configuration": {"columns": ["Date", "MeterId", "ResourceId", "ResourceLocation", "Quantity"]}, + "configuration": { + "columns": ["Date", "MeterId", "ResourceId", "ResourceLocation", "Quantity"], + "dataVersion": "2023-05-01", + }, "granularity": "Daily", }, "timeframe": "MonthToDate", @@ -46,20 +54,23 @@ def main(): "container": "exports", "resourceId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG/providers/Microsoft.Storage/storageAccounts/ccmeastusdiag182", "rootFolderPath": "ad-hoc", + "type": "AzureBlob", } }, + "exportDescription": "This is a test export.", "format": "Csv", + "partitionData": True, "schedule": { "recurrence": "Weekly", - "recurrencePeriod": {"from": "2020-06-01T00:00:00Z", "to": "2020-10-31T00:00:00Z"}, + "recurrencePeriod": {"from": "2020-06-01T00:00:00Z", "to": "2020-06-30T00:00:00Z"}, "status": "Active", }, - } + }, }, ) print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportCreateOrUpdateByDepartment.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportCreateOrUpdateByDepartment.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_enrollment_account.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_enrollment_account.py index 259dd8f62917..c8ec60a4445e 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_enrollment_account.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_enrollment_account.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -32,10 +33,17 @@ def main(): scope="providers/Microsoft.Billing/billingAccounts/100/enrollmentAccounts/456", export_name="TestExport", parameters={ + "identity": {"type": "SystemAssigned"}, + "location": "centralus", "properties": { + "compressionMode": "gzip", + "dataOverwriteBehavior": "OverwritePreviousReport", "definition": { "dataSet": { - "configuration": {"columns": ["Date", "MeterId", "ResourceId", "ResourceLocation", "Quantity"]}, + "configuration": { + "columns": ["Date", "MeterId", "ResourceId", "ResourceLocation", "Quantity"], + "dataVersion": "2023-05-01", + }, "granularity": "Daily", }, "timeframe": "MonthToDate", @@ -46,20 +54,23 @@ def main(): "container": "exports", "resourceId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG/providers/Microsoft.Storage/storageAccounts/ccmeastusdiag182", "rootFolderPath": "ad-hoc", + "type": "AzureBlob", } }, + "exportDescription": "This is a test export.", "format": "Csv", + "partitionData": True, "schedule": { "recurrence": "Weekly", - "recurrencePeriod": {"from": "2020-06-01T00:00:00Z", "to": "2020-10-31T00:00:00Z"}, + "recurrencePeriod": {"from": "2020-06-01T00:00:00Z", "to": "2020-06-30T00:00:00Z"}, "status": "Active", }, - } + }, }, ) print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportCreateOrUpdateByEnrollmentAccount.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportCreateOrUpdateByEnrollmentAccount.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_management_group.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_management_group.py index a69690f9e8c2..d49a225ff46b 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_management_group.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_management_group.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -32,10 +33,17 @@ def main(): scope="providers/Microsoft.Management/managementGroups/TestMG", export_name="TestExport", parameters={ + "identity": {"type": "SystemAssigned"}, + "location": "centralus", "properties": { + "compressionMode": "gzip", + "dataOverwriteBehavior": "OverwritePreviousReport", "definition": { "dataSet": { - "configuration": {"columns": ["Date", "MeterId", "ResourceId", "ResourceLocation", "Quantity"]}, + "configuration": { + "columns": ["Date", "MeterId", "ResourceId", "ResourceLocation", "Quantity"], + "dataVersion": "2023-05-01", + }, "granularity": "Daily", }, "timeframe": "MonthToDate", @@ -46,20 +54,23 @@ def main(): "container": "exports", "resourceId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG/providers/Microsoft.Storage/storageAccounts/ccmeastusdiag182", "rootFolderPath": "ad-hoc", + "type": "AzureBlob", } }, + "exportDescription": "This is a test export.", "format": "Csv", + "partitionData": True, "schedule": { "recurrence": "Weekly", - "recurrencePeriod": {"from": "2020-06-01T00:00:00Z", "to": "2020-10-31T00:00:00Z"}, + "recurrencePeriod": {"from": "2020-06-01T00:00:00Z", "to": "2020-06-30T00:00:00Z"}, "status": "Active", }, - } + }, }, ) print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportCreateOrUpdateByManagementGroup.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportCreateOrUpdateByManagementGroup.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_resource_group.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_resource_group.py index c8fa59257795..a4813bc26995 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_resource_group.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_resource_group.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -32,10 +33,17 @@ def main(): scope="subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG", export_name="TestExport", parameters={ + "identity": {"type": "SystemAssigned"}, + "location": "centralus", "properties": { + "compressionMode": "gzip", + "dataOverwriteBehavior": "OverwritePreviousReport", "definition": { "dataSet": { - "configuration": {"columns": ["Date", "MeterId", "ResourceId", "ResourceLocation", "Quantity"]}, + "configuration": { + "columns": ["Date", "MeterId", "ResourceId", "ResourceLocation", "Quantity"], + "dataVersion": "2023-05-01", + }, "granularity": "Daily", }, "timeframe": "MonthToDate", @@ -46,20 +54,23 @@ def main(): "container": "exports", "resourceId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG/providers/Microsoft.Storage/storageAccounts/ccmeastusdiag182", "rootFolderPath": "ad-hoc", + "type": "AzureBlob", } }, + "exportDescription": "This is a test export.", "format": "Csv", + "partitionData": True, "schedule": { "recurrence": "Weekly", - "recurrencePeriod": {"from": "2020-06-01T00:00:00Z", "to": "2020-10-31T00:00:00Z"}, + "recurrencePeriod": {"from": "2020-06-01T00:00:00Z", "to": "2020-06-30T00:00:00Z"}, "status": "Active", }, - } + }, }, ) print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportCreateOrUpdateByResourceGroup.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportCreateOrUpdateByResourceGroup.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_subscription.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_subscription.py index 997f926419db..2248a05ba9e6 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_subscription.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_subscription.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -32,10 +33,17 @@ def main(): scope="subscriptions/00000000-0000-0000-0000-000000000000", export_name="TestExport", parameters={ + "identity": {"type": "SystemAssigned"}, + "location": "centralus", "properties": { + "compressionMode": "gzip", + "dataOverwriteBehavior": "OverwritePreviousReport", "definition": { "dataSet": { - "configuration": {"columns": ["Date", "MeterId", "ResourceId", "ResourceLocation", "Quantity"]}, + "configuration": { + "columns": ["Date", "MeterId", "ResourceId", "ResourceLocation", "Quantity"], + "dataVersion": "2023-05-01", + }, "granularity": "Daily", }, "timeframe": "MonthToDate", @@ -46,20 +54,23 @@ def main(): "container": "exports", "resourceId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG/providers/Microsoft.Storage/storageAccounts/ccmeastusdiag182", "rootFolderPath": "ad-hoc", + "type": "AzureBlob", } }, + "exportDescription": "This is a test export.", "format": "Csv", + "partitionData": True, "schedule": { "recurrence": "Weekly", - "recurrencePeriod": {"from": "2020-06-01T00:00:00Z", "to": "2020-10-31T00:00:00Z"}, + "recurrencePeriod": {"from": "2020-06-01T00:00:00Z", "to": "2020-06-30T00:00:00Z"}, "status": "Active", }, - } + }, }, ) print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportCreateOrUpdateBySubscription.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportCreateOrUpdateBySubscription.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_subscription_with_fabric_destination.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_subscription_with_fabric_destination.py new file mode 100644 index 000000000000..da17f24db9e6 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_subscription_with_fabric_destination.py @@ -0,0 +1,78 @@ +# 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_create_or_update_by_subscription_with_fabric_destination.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.create_or_update( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + export_name="TestExport", + parameters={ + "identity": {"type": "SystemAssigned"}, + "location": "centralus", + "properties": { + "compressionMode": None, + "dataOverwriteBehavior": "OverwritePreviousReport", + "definition": { + "dataSet": { + "configuration": { + "columns": ["Date", "MeterId", "ResourceId", "ResourceLocation", "Quantity"], + "dataVersion": "2023-05-01", + }, + "granularity": "Daily", + }, + "timeframe": "MonthToDate", + "type": "ActualCost", + }, + "deliveryInfo": { + "destination": { + "microsoftFabricSettings": { + "lakehouse": {"displayName": "MyLakehouse", "id": "00000000-0000-0000-0000-000000000000"}, + "tableName": "testexport", + "workspace": {"displayName": "MyWorkspace", "id": "00000000-0000-0000-0000-000000000000"}, + }, + "type": "MicrosoftFabric", + } + }, + "exportDescription": "This is a test export.", + "format": "Delta", + "partitionData": True, + "schedule": { + "recurrence": "Weekly", + "recurrencePeriod": {"from": "2020-06-01T00:00:00Z", "to": "2020-06-30T00:00:00Z"}, + "status": "Active", + }, + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportCreateOrUpdateBySubscriptionWithFabricDestination.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_billing_account.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_billing_account.py index 05c045b790fa..1c180d1b9f8d 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_billing_account.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_billing_account.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): ) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportDeleteByBillingAccount.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportDeleteByBillingAccount.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_department.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_department.py index ae811025f0a9..4ebef10c4576 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_department.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_department.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): ) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportDeleteByDepartment.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportDeleteByDepartment.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_enrollment_account.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_enrollment_account.py index c108b4b337d1..4f5c8d4ce0b4 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_enrollment_account.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_enrollment_account.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): ) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportDeleteByEnrollmentAccount.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportDeleteByEnrollmentAccount.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_management_group.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_management_group.py index 4bf2f36a8622..da8d6afb0527 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_management_group.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_management_group.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): ) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportDeleteByManagementGroup.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportDeleteByManagementGroup.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_resource_group.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_resource_group.py index 82229e9bba7c..3bd42600c711 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_resource_group.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_resource_group.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): ) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportDeleteByResourceGroup.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportDeleteByResourceGroup.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_subscription.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_subscription.py index 427f2a9f9138..33865708b527 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_subscription.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_subscription.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): ) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportDeleteBySubscription.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportDeleteBySubscription.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_billing_account.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_billing_account.py index 8266b9a594d2..10a747a1dc1e 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_billing_account.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_billing_account.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportGetByBillingAccount.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportGetByBillingAccount.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_department.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_department.py index e6aa15d5361c..4a796a9a316c 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_department.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_department.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportGetByDepartment.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportGetByDepartment.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_enrollment_account.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_enrollment_account.py index 4960c604686d..c8e8f66313c5 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_enrollment_account.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_enrollment_account.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportGetByEnrollmentAccount.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportGetByEnrollmentAccount.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_management_group.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_management_group.py index ac2e541426fc..1e5e1df29c5e 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_management_group.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_management_group.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportGetByManagementGroup.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportGetByManagementGroup.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_resource_group.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_resource_group.py index 307fb98bd806..757b9e2cb8d4 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_resource_group.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_resource_group.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportGetByResourceGroup.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportGetByResourceGroup.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_subscription.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_subscription.py index efbd1e8048b7..d14b2bd8351e 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_subscription.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_subscription.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportGetBySubscription.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportGetBySubscription.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_subscription_with_fabric_destination.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_subscription_with_fabric_destination.py new file mode 100644 index 000000000000..0bf9a8a46916 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_subscription_with_fabric_destination.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_get_by_subscription_with_fabric_destination.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.get( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + export_name="TestExport", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportGetBySubscriptionWithFabricDestination.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_billing_account.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_billing_account.py index 97740984b3de..8c0b162131a7 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_billing_account.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_billing_account.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): ) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportRunByBillingAccount.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportRunByBillingAccount.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_department.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_department.py index 64f869360de1..ab87d8c48817 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_department.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_department.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): ) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportRunByDepartment.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportRunByDepartment.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_enrollment_account.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_enrollment_account.py index 6e94d8ada049..aad4c6614556 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_enrollment_account.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_enrollment_account.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): ) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportRunByEnrollmentAccount.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportRunByEnrollmentAccount.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_management_group.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_management_group.py index 8b0d53edc4d5..9f96f47263c2 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_management_group.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_management_group.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): ) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportRunByManagementGroup.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportRunByManagementGroup.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_resource_group.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_resource_group.py index ab862471e963..e2f601d5495b 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_resource_group.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_resource_group.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): ) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportRunByResourceGroup.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportRunByResourceGroup.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_subscription.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_subscription.py index 4e61a79b18ac..b83bd4cf8bc5 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_subscription.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_subscription.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): ) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportRunBySubscription.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportRunBySubscription.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_billing_account.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_billing_account.py index 199740876c6b..14d13584c12f 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_billing_account.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_billing_account.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportRunHistoryGetByBillingAccount.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportRunHistoryGetByBillingAccount.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_department.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_department.py index 380019a2e8e1..e156d7bf415e 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_department.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_department.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportRunHistoryGetByDepartment.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportRunHistoryGetByDepartment.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_enrollment_account.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_enrollment_account.py index 79922afbc76d..83bb437d0161 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_enrollment_account.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_enrollment_account.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportRunHistoryGetByEnrollmentAccount.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportRunHistoryGetByEnrollmentAccount.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_management_group.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_management_group.py index 37d279c1cd97..e3cecab73246 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_management_group.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_management_group.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportRunHistoryGetByManagementGroup.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportRunHistoryGetByManagementGroup.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_resource_group.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_resource_group.py index 494201812bf2..b5d7ced83898 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_resource_group.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_resource_group.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportRunHistoryGetByResourceGroup.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportRunHistoryGetByResourceGroup.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_subscription.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_subscription.py index 4565b72e9911..78bd5756e88f 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_subscription.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_subscription.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportRunHistoryGetBySubscription.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportRunHistoryGetBySubscription.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_subscription_with_fabric_destination.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_subscription_with_fabric_destination.py new file mode 100644 index 000000000000..9bd211c57a2b --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_subscription_with_fabric_destination.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_run_history_get_by_subscription_with_fabric_destination.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.get_execution_history( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + export_name="TestExport", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportRunHistoryGetBySubscriptionWithFabricDestination.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_billing_account.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_billing_account.py index 6562d9dddf91..5b2333cc4bc8 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_billing_account.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_billing_account.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportsGetByBillingAccount.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportsGetByBillingAccount.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_department.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_department.py index e5f7c4444277..e8de6db5059c 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_department.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_department.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportsGetByDepartment.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportsGetByDepartment.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_enrollment_account.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_enrollment_account.py index de0b8d7490a8..34f32c4f9c6a 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_enrollment_account.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_enrollment_account.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportsGetByEnrollmentAccount.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportsGetByEnrollmentAccount.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_management_group.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_management_group.py index 8b78725d765d..1671e874ed80 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_management_group.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_management_group.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportsGetByManagementGroup.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportsGetByManagementGroup.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_resource_group.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_resource_group.py index b9662dd0ff45..c6dede1ac4cd 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_resource_group.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_resource_group.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportsGetByResourceGroup.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportsGetByResourceGroup.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_subscription.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_subscription.py index 37fcdbd45b49..374db96bfafb 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_subscription.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_subscription.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportsGetBySubscription.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExportsGetBySubscription.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_billing_account_alerts.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_billing_account_alerts.py index 779eb2320f80..fa1cad30cf65 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_billing_account_alerts.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_billing_account_alerts.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExternalBillingAccountAlerts.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExternalBillingAccountAlerts.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_billing_account_forecast.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_billing_account_forecast.py index dc1bb420b118..ae50f2f62383 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_billing_account_forecast.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_billing_account_forecast.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -61,6 +62,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExternalBillingAccountForecast.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExternalBillingAccountForecast.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_billing_accounts_dimensions.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_billing_accounts_dimensions.py index b764fdd3c0ed..ae4b54634b4a 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_billing_accounts_dimensions.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_billing_accounts_dimensions.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExternalBillingAccountsDimensions.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExternalBillingAccountsDimensions.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_billing_accounts_query.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_billing_accounts_query.py index 69b7503274a8..b32c236d27a6 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_billing_accounts_query.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_billing_accounts_query.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -59,6 +60,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExternalBillingAccountsQuery.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExternalBillingAccountsQuery.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_subscription_alerts.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_subscription_alerts.py index 24103f6c6562..2002d47e9ede 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_subscription_alerts.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_subscription_alerts.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExternalSubscriptionAlerts.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExternalSubscriptionAlerts.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_subscription_forecast.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_subscription_forecast.py index 39a6ed464e0f..3a31f2c501c1 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_subscription_forecast.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_subscription_forecast.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -61,6 +62,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExternalSubscriptionForecast.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExternalSubscriptionForecast.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_subscriptions_dimensions.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_subscriptions_dimensions.py index ff8ef5e75164..41e061f088e7 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_subscriptions_dimensions.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_subscriptions_dimensions.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExternalSubscriptionsDimensions.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExternalSubscriptionsDimensions.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_subscriptions_query.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_subscriptions_query.py index 5879a5230481..6ac4071871bf 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_subscriptions_query.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_subscriptions_query.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -59,6 +60,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExternalSubscriptionsQuery.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ExternalSubscriptionsQuery.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_billing_account_enterprise_agreement_customer_and_billing_period.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_billing_account_enterprise_agreement_customer_and_billing_period.py index 8fc7ecb2911b..a174be47798b 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_billing_account_enterprise_agreement_customer_and_billing_period.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_billing_account_enterprise_agreement_customer_and_billing_period.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateCostDetailsReportByBillingAccountEnterpriseAgreementCustomerAndBillingPeriod.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/GenerateCostDetailsReportByBillingAccountEnterpriseAgreementCustomerAndBillingPeriod.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_billing_profile_and_invoice_id.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_billing_profile_and_invoice_id.py index 3cc8d1ae18e2..762c32f142d4 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_billing_profile_and_invoice_id.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_billing_profile_and_invoice_id.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateCostDetailsReportByBillingProfileAndInvoiceId.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/GenerateCostDetailsReportByBillingProfileAndInvoiceId.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_billing_profile_and_invoice_id_and_customer_id.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_billing_profile_and_invoice_id_and_customer_id.py index 7e38e26e351f..2b09879841f5 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_billing_profile_and_invoice_id_and_customer_id.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_billing_profile_and_invoice_id_and_customer_id.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateCostDetailsReportByBillingProfileAndInvoiceIdAndCustomerId.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/GenerateCostDetailsReportByBillingProfileAndInvoiceIdAndCustomerId.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_customer_and_time_period.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_customer_and_time_period.py index 1d9fb4013da7..380541200e67 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_customer_and_time_period.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_customer_and_time_period.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateCostDetailsReportByCustomerAndTimePeriod.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/GenerateCostDetailsReportByCustomerAndTimePeriod.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_departments_and_time_period.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_departments_and_time_period.py index b7fd59c2d6f0..13a3b50363fa 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_departments_and_time_period.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_departments_and_time_period.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateCostDetailsReportByDepartmentsAndTimePeriod.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/GenerateCostDetailsReportByDepartmentsAndTimePeriod.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_enrollment_accounts_and_time_period.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_enrollment_accounts_and_time_period.py index 05857cda0b19..b9c61e7de4df 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_enrollment_accounts_and_time_period.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_enrollment_accounts_and_time_period.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateCostDetailsReportByEnrollmentAccountsAndTimePeriod.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/GenerateCostDetailsReportByEnrollmentAccountsAndTimePeriod.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_subscription_and_time_period.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_subscription_and_time_period.py index fa959fac4317..1fa489c52f33 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_subscription_and_time_period.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_subscription_and_time_period.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateCostDetailsReportBySubscriptionAndTimePeriod.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/GenerateCostDetailsReportBySubscriptionAndTimePeriod.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_billing_account_legacy_and_billing_period.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_billing_account_legacy_and_billing_period.py index 6c9aba183fb6..69e30bca130c 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_billing_account_legacy_and_billing_period.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_billing_account_legacy_and_billing_period.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateDetailedCostReportByBillingAccountLegacyAndBillingPeriod.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/GenerateDetailedCostReportByBillingAccountLegacyAndBillingPeriod.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_billing_profile_and_invoice_id.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_billing_profile_and_invoice_id.py index 171adc5bea17..8fec510370f2 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_billing_profile_and_invoice_id.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_billing_profile_and_invoice_id.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateDetailedCostReportByBillingProfileAndInvoiceId.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/GenerateDetailedCostReportByBillingProfileAndInvoiceId.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_billing_profile_and_invoice_id_and_customer_id.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_billing_profile_and_invoice_id_and_customer_id.py index 66e8751344e3..4a851b6414a4 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_billing_profile_and_invoice_id_and_customer_id.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_billing_profile_and_invoice_id_and_customer_id.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateDetailedCostReportByBillingProfileAndInvoiceIdAndCustomerId.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/GenerateDetailedCostReportByBillingProfileAndInvoiceIdAndCustomerId.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_customer_and_time_period.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_customer_and_time_period.py index 6b4c1c570c67..b70630c976c6 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_customer_and_time_period.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_customer_and_time_period.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateDetailedCostReportByCustomerAndTimePeriod.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/GenerateDetailedCostReportByCustomerAndTimePeriod.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_subscription_and_time_period.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_subscription_and_time_period.py index 002c901d4c44..1a286ab1b3fd 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_subscription_and_time_period.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_subscription_and_time_period.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateDetailedCostReportBySubscriptionAndTimePeriod.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/GenerateDetailedCostReportBySubscriptionAndTimePeriod.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_operation_results_by_subscription_scope.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_operation_results_by_subscription_scope.py index ad52d818c68e..8fbcccc72c0c 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_operation_results_by_subscription_scope.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_operation_results_by_subscription_scope.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateDetailedCostReportOperationResultsBySubscriptionScope.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/GenerateDetailedCostReportOperationResultsBySubscriptionScope.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_operation_status_by_subscription_scope.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_operation_status_by_subscription_scope.py index faf3c338f455..345ac612e6e9 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_operation_status_by_subscription_scope.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_operation_status_by_subscription_scope.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateDetailedCostReportOperationStatusBySubscriptionScope.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/GenerateDetailedCostReportOperationStatusBySubscriptionScope.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_reservation_details_report_by_billing_account.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_reservation_details_report_by_billing_account.py index 5cbf1f685c89..54b225ea2716 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_reservation_details_report_by_billing_account.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_reservation_details_report_by_billing_account.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -36,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateReservationDetailsReportByBillingAccount.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/GenerateReservationDetailsReportByBillingAccount.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_reservation_details_report_by_billing_profile.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_reservation_details_report_by_billing_profile.py index 29acfba80850..16ec54b4879f 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_reservation_details_report_by_billing_profile.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_reservation_details_report_by_billing_profile.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -37,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateReservationDetailsReportByBillingProfile.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/GenerateReservationDetailsReportByBillingProfile.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/invoice_section_alerts.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/invoice_section_alerts.py index 24be92520b5e..944a99720606 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/invoice_section_alerts.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/invoice_section_alerts.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/InvoiceSectionAlerts.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/InvoiceSectionAlerts.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/invoice_section_forecast.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/invoice_section_forecast.py index 5ca0635445f2..3eb145d0867c 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/invoice_section_forecast.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/invoice_section_forecast.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -62,6 +63,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/InvoiceSectionForecast.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/InvoiceSectionForecast.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_dimensions_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_dimensions_list.py index a57a6252f33b..b2f5358b68d3 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_dimensions_list.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_dimensions_list.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ManagementGroupDimensionsList.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ManagementGroupDimensionsList.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_dimensions_list_expand_and_top.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_dimensions_list_expand_and_top.py index fd618f059528..158f812a94ed 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_dimensions_list_expand_and_top.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_dimensions_list_expand_and_top.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ManagementGroupDimensionsListExpandAndTop.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ManagementGroupDimensionsListExpandAndTop.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_dimensions_list_with_filter.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_dimensions_list_with_filter.py index d6624fb9d858..24d881274053 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_dimensions_list_with_filter.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_dimensions_list_with_filter.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ManagementGroupDimensionsListWithFilter.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ManagementGroupDimensionsListWithFilter.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_query.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_query.py index 259ead41ae0e..765a875e9b66 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_query.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_query.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -58,6 +59,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ManagementGroupQuery.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ManagementGroupQuery.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_query_grouping.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_query_grouping.py index fda6bddcc595..e0ff03f3fb4f 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_query_grouping.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_query_grouping.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -43,6 +44,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ManagementGroupQueryGrouping.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ManagementGroupQueryGrouping.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_account_dimensions_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_account_dimensions_list.py index 9f7cba047e65..c2906bb31e16 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_account_dimensions_list.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_account_dimensions_list.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCABillingAccountDimensionsList.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/MCABillingAccountDimensionsList.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_account_dimensions_list_expand_and_top.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_account_dimensions_list_expand_and_top.py index 659323eb7296..3fa8d31c3ecf 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_account_dimensions_list_expand_and_top.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_account_dimensions_list_expand_and_top.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCABillingAccountDimensionsListExpandAndTop.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/MCABillingAccountDimensionsListExpandAndTop.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_account_dimensions_list_with_filter.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_account_dimensions_list_with_filter.py index 0f16db5f30bb..1a31d5ee360b 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_account_dimensions_list_with_filter.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_account_dimensions_list_with_filter.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCABillingAccountDimensionsListWithFilter.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/MCABillingAccountDimensionsListWithFilter.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_account_query.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_account_query.py index 7c8456bba766..4ba5d7df2da7 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_account_query.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_account_query.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -58,6 +59,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCABillingAccountQuery.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/MCABillingAccountQuery.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_account_query_grouping.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_account_query_grouping.py index 3e3dffe50f13..30180f46c9b2 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_account_query_grouping.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_account_query_grouping.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -43,6 +44,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCABillingAccountQueryGrouping.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/MCABillingAccountQueryGrouping.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_profile_dimensions_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_profile_dimensions_list.py index f4b4e44b51d1..0720e8c55dc6 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_profile_dimensions_list.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_profile_dimensions_list.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCABillingProfileDimensionsList.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/MCABillingProfileDimensionsList.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_profile_dimensions_list_expand_and_top.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_profile_dimensions_list_expand_and_top.py index 801c2ef43317..d636bd496e4c 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_profile_dimensions_list_expand_and_top.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_profile_dimensions_list_expand_and_top.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCABillingProfileDimensionsListExpandAndTop.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/MCABillingProfileDimensionsListExpandAndTop.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_profile_dimensions_list_with_filter.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_profile_dimensions_list_with_filter.py index ed2286ccfe72..83e36ad88479 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_profile_dimensions_list_with_filter.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_profile_dimensions_list_with_filter.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCABillingProfileDimensionsListWithFilter.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/MCABillingProfileDimensionsListWithFilter.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_profile_query.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_profile_query.py index bd56472dcdbb..3bb273cd2843 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_profile_query.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_profile_query.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -58,6 +59,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCABillingProfileQuery.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/MCABillingProfileQuery.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_profile_query_grouping.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_profile_query_grouping.py index cacb2c21e4d5..63e14ab98b61 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_profile_query_grouping.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_billing_profile_query_grouping.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -43,6 +44,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCABillingProfileQueryGrouping.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/MCABillingProfileQueryGrouping.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_customer_dimensions_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_customer_dimensions_list.py index 16ca7b1798a2..108daf986e16 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_customer_dimensions_list.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_customer_dimensions_list.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCACustomerDimensionsList.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/MCACustomerDimensionsList.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_customer_dimensions_list_expand_and_top.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_customer_dimensions_list_expand_and_top.py index b941fb680e48..003e53a9a643 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_customer_dimensions_list_expand_and_top.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_customer_dimensions_list_expand_and_top.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCACustomerDimensionsListExpandAndTop.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/MCACustomerDimensionsListExpandAndTop.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_customer_dimensions_list_with_filter.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_customer_dimensions_list_with_filter.py index 498fb66387df..05c5996e5a22 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_customer_dimensions_list_with_filter.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_customer_dimensions_list_with_filter.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCACustomerDimensionsListWithFilter.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/MCACustomerDimensionsListWithFilter.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_customer_query.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_customer_query.py index 4dcb6efde3d4..f2d513403ac9 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_customer_query.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_customer_query.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -58,6 +59,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCACustomerQuery.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/MCACustomerQuery.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_customer_query_grouping.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_customer_query_grouping.py index c4c0ff727c0a..def6c032a7f2 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_customer_query_grouping.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_customer_query_grouping.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -43,6 +44,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCACustomerQueryGrouping.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/MCACustomerQueryGrouping.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_invoice_section_dimensions_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_invoice_section_dimensions_list.py index 11b68a17f4d4..57569362f438 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_invoice_section_dimensions_list.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_invoice_section_dimensions_list.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCAInvoiceSectionDimensionsList.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/MCAInvoiceSectionDimensionsList.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_invoice_section_dimensions_list_expand_and_top.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_invoice_section_dimensions_list_expand_and_top.py index e449f04d320c..5aefa20ed42a 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_invoice_section_dimensions_list_expand_and_top.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_invoice_section_dimensions_list_expand_and_top.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCAInvoiceSectionDimensionsListExpandAndTop.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/MCAInvoiceSectionDimensionsListExpandAndTop.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_invoice_section_dimensions_list_with_filter.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_invoice_section_dimensions_list_with_filter.py index 14b352dfb098..9951a580eac6 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_invoice_section_dimensions_list_with_filter.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_invoice_section_dimensions_list_with_filter.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCAInvoiceSectionDimensionsListWithFilter.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/MCAInvoiceSectionDimensionsListWithFilter.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_invoice_section_query.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_invoice_section_query.py index 7a472df6af05..af71880c912d 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_invoice_section_query.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_invoice_section_query.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -58,6 +59,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCAInvoiceSectionQuery.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/MCAInvoiceSectionQuery.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_invoice_section_query_grouping.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_invoice_section_query_grouping.py index 2030ca2f13a1..0a969c970cf2 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_invoice_section_query_grouping.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/mca_invoice_section_query_grouping.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -43,6 +44,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCAInvoiceSectionQueryGrouping.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/MCAInvoiceSectionQueryGrouping.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/operation_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/operation_list.py index 6c325487a5b9..1606980b44cd 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/operation_list.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/operation_list.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -33,6 +34,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/OperationList.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/OperationList.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/pricesheet_download.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/pricesheet_download.py index 2450cd629150..e91bd63bca21 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/pricesheet_download.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/pricesheet_download.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -28,7 +29,7 @@ def main(): credential=DefaultAzureCredential(), ) - response = client.price_sheet.begin_download( + response = client.price_sheet.begin_download_by_invoice( billing_account_name="7c05a543-80ff-571e-9f98-1063b3b53cf2:99ad03ad-2d1b-4889-a452-090ad407d25f_2019-05-31", billing_profile_name="2USN-TPCD-BG7-TGB", invoice_name="T000940677", @@ -36,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/PricesheetDownload.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/PricesheetDownload.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/pricesheet_download_by_billing_profile.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/pricesheet_download_by_billing_profile.py index e6a64be2fa83..f1479b3a8b72 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/pricesheet_download_by_billing_profile.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/pricesheet_download_by_billing_profile.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/PricesheetDownloadByBillingProfile.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/PricesheetDownloadByBillingProfile.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_view.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_view.py index 506133cc0ef2..e4489abfe5af 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_view.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_view.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/PrivateView.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/PrivateView.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_view_create_or_update.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_view_create_or_update.py index 5b4bfb8a3143..de444f094aab 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_view_create_or_update.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_view_create_or_update.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -66,6 +67,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/PrivateViewCreateOrUpdate.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/PrivateViewCreateOrUpdate.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_view_delete.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_view_delete.py index cc5ae3b919e1..69de404a3f44 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_view_delete.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_view_delete.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -33,6 +34,6 @@ def main(): ) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/PrivateViewDelete.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/PrivateViewDelete.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_view_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_view_list.py index ff5ce767ac30..0d76e5b9fe52 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_view_list.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_view_list.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -33,6 +34,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/PrivateViewList.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/PrivateViewList.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_alerts.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_alerts.py index 4d2c8998f9a0..f06fef9bf978 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_alerts.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_alerts.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ResourceGroupAlerts.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ResourceGroupAlerts.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_dimensions_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_dimensions_list.py index d8c4c9543dc6..410a3a60b4bf 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_dimensions_list.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_dimensions_list.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ResourceGroupDimensionsList.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ResourceGroupDimensionsList.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_forecast.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_forecast.py index 4c7ea0276418..5a6498265134 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_forecast.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_forecast.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -62,6 +63,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ResourceGroupForecast.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ResourceGroupForecast.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_query.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_query.py index e4556d516b5f..b1b928f7fb87 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_query.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_query.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -58,6 +59,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ResourceGroupQuery.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ResourceGroupQuery.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_query_grouping.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_query_grouping.py index 1d63d0bafb57..798bd9d8b3d2 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_query_grouping.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_query_grouping.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -43,6 +44,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ResourceGroupQueryGrouping.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ResourceGroupQueryGrouping.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/check_name_availabilityprivatescheduled_action.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/check_name_availabilityprivatescheduled_action.py index 3fe817df9a29..371c70716765 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/check_name_availabilityprivatescheduled_action.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/check_name_availabilityprivatescheduled_action.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/checkNameAvailability-private-scheduledAction.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/scheduledActions/checkNameAvailability-private-scheduledAction.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/check_name_availabilitysharedscheduled_action.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/check_name_availabilitysharedscheduled_action.py index 3527687cfd09..b0ece9dfcead 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/check_name_availabilitysharedscheduled_action.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/check_name_availabilitysharedscheduled_action.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/checkNameAvailability-shared-scheduledAction.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/scheduledActions/checkNameAvailability-shared-scheduledAction.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actioncreate_or_updateprivate.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actioncreate_or_updateprivate.py index eccd776b189f..4d9becae6290 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actioncreate_or_updateprivate.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actioncreate_or_updateprivate.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -51,6 +52,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/scheduledAction-createOrUpdate-private.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/scheduledActions/scheduledAction-createOrUpdate-private.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actioncreate_or_updateshared.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actioncreate_or_updateshared.py index 957b8e9f1f5d..864f3703b4bb 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actioncreate_or_updateshared.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actioncreate_or_updateshared.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -53,6 +54,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/scheduledAction-createOrUpdate-shared.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/scheduledActions/scheduledAction-createOrUpdate-shared.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actiondeleteprivate.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actiondeleteprivate.py index 9f37bab8ab05..82727571eb62 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actiondeleteprivate.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actiondeleteprivate.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -33,6 +34,6 @@ def main(): ) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/scheduledAction-delete-private.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/scheduledActions/scheduledAction-delete-private.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actiondeleteshared.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actiondeleteshared.py index b13e2b926cb2..648a21f8e4e9 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actiondeleteshared.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actiondeleteshared.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): ) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/scheduledAction-delete-shared.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/scheduledActions/scheduledAction-delete-shared.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actiongetprivate.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actiongetprivate.py index baf04b00199f..1bb9b9833b12 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actiongetprivate.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actiongetprivate.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/scheduledAction-get-private.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/scheduledActions/scheduledAction-get-private.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actiongetshared.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actiongetshared.py index b21a8394b3cf..09147fd6fdfa 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actiongetshared.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actiongetshared.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/scheduledAction-get-shared.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/scheduledActions/scheduledAction-get-shared.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actioninsight_alertcreate_or_updateshared.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actioninsight_alertcreate_or_updateshared.py index fa047b3903d5..bf87a59240f0 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actioninsight_alertcreate_or_updateshared.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actioninsight_alertcreate_or_updateshared.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -52,6 +53,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/scheduledAction-insightAlert-createOrUpdate-shared.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/scheduledActions/scheduledAction-insightAlert-createOrUpdate-shared.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actionsend_nowprivate.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actionsend_nowprivate.py index 602e727e9ef5..ed736cdcec2a 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actionsend_nowprivate.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actionsend_nowprivate.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -33,6 +34,6 @@ def main(): ) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/scheduledAction-sendNow-private.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/scheduledActions/scheduledAction-sendNow-private.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actionsend_nowshared.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actionsend_nowshared.py index 72401f901922..107c5a320a73 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actionsend_nowshared.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actionsend_nowshared.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): ) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/scheduledAction-sendNow-shared.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/scheduledActions/scheduledAction-sendNow-shared.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actionslist_with_filterprivate.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actionslist_with_filterprivate.py index 229644b5997f..2486161c6307 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actionslist_with_filterprivate.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actionslist_with_filterprivate.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -33,6 +34,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/scheduledActions-listWithFilter-private.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/scheduledActions/scheduledActions-listWithFilter-private.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actionslist_with_filtershared.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actionslist_with_filtershared.py index 9815805b19a2..83f00dde331c 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actionslist_with_filtershared.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actionslist_with_filtershared.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/scheduledActions-listWithFilter-shared.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/scheduledActions/scheduledActions-listWithFilter-shared.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actionslistprivate.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actionslistprivate.py index 7e1bb07a89f8..08f121cde238 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actionslistprivate.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actionslistprivate.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -33,6 +34,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/scheduledActions-list-private.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/scheduledActions/scheduledActions-list-private.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actionslistshared.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actionslistshared.py index 1ce7057cf63c..b6b0100a8c35 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actionslistshared.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions/scheduled_actionslistshared.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/scheduledActions-list-shared.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/scheduledActions/scheduledActions-list-shared.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/settingdelete.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/settingdelete.py new file mode 100644 index 000000000000..4340c34166fb --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/settingdelete.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python settingdelete.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + client.settings.delete_by_scope( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + type="taginheritance", + ) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/setting-delete.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/settingget.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/settingget.py new file mode 100644 index 000000000000..7a7160e67e00 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/settingget.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python settingget.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.settings.get_by_scope( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + type="taginheritance", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/setting-get.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/settings_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/settings_list.py new file mode 100644 index 000000000000..b9fbe4d3efe7 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/settings_list.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) 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.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python settings_list.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 = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.settings.list( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/settingsList.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/settingscreate_or_update.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/settingscreate_or_update.py new file mode 100644 index 000000000000..7a5041c4273a --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/settingscreate_or_update.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. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python settingscreate_or_update.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.settings.create_or_update_by_scope( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + type="taginheritance", + setting={"kind": "taginheritance", "properties": {"preferContainerTags": False}}, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/settings-createOrUpdate.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/single_resource_group_alert.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/single_resource_group_alert.py index 9d9f5742c791..5ec0b72fac9d 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/single_resource_group_alert.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/single_resource_group_alert.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/SingleResourceGroupAlert.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/SingleResourceGroupAlert.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/single_subscription_alert.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/single_subscription_alert.py index 3a504fe6fdb2..2079ecd0425a 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/single_subscription_alert.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/single_subscription_alert.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/SingleSubscriptionAlert.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/SingleSubscriptionAlert.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_alerts.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_alerts.py index 3402e29b0f72..44678e453588 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_alerts.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_alerts.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/SubscriptionAlerts.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/SubscriptionAlerts.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_dimensions_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_dimensions_list.py index 7c82f57ea2ff..30e6c7e13e2f 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_dimensions_list.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_dimensions_list.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/SubscriptionDimensionsList.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/SubscriptionDimensionsList.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_forecast.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_forecast.py index 63c6ba54de7c..102a6aa0505c 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_forecast.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_forecast.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -62,6 +63,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/SubscriptionForecast.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/SubscriptionForecast.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_query.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_query.py index a80a9cb721c8..8fcc3ea8ff59 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_query.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_query.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -58,6 +59,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/SubscriptionQuery.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/SubscriptionQuery.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_query_grouping.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_query_grouping.py index 90f56b4f701e..f28b0c51147f 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_query_grouping.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_query_grouping.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -43,6 +44,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/SubscriptionQueryGrouping.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/SubscriptionQueryGrouping.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/view_by_resource_group.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/view_by_resource_group.py index 8ebf3ed7deec..5a75269cbd11 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/view_by_resource_group.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/view_by_resource_group.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ViewByResourceGroup.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ViewByResourceGroup.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/view_create_or_update_by_resource_group.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/view_create_or_update_by_resource_group.py index 0c0f6a148b5b..c4799e6ec8cf 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/view_create_or_update_by_resource_group.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/view_create_or_update_by_resource_group.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -67,6 +68,6 @@ def main(): print(response) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ViewCreateOrUpdateByResourceGroup.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ViewCreateOrUpdateByResourceGroup.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/view_delete_by_resource_group.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/view_delete_by_resource_group.py index 351d43f8c2f8..b8b80fd31895 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/view_delete_by_resource_group.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/view_delete_by_resource_group.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -34,6 +35,6 @@ def main(): ) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ViewDeleteByResourceGroup.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ViewDeleteByResourceGroup.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/view_list_by_resource_group.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/view_list_by_resource_group.py index 13608bc5eb00..70c4f0098a92 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/view_list_by_resource_group.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/view_list_by_resource_group.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.costmanagement import CostManagementClient """ @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ViewListByResourceGroup.json +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/preview/2024-10-01-preview/examples/ViewListByResourceGroup.json if __name__ == "__main__": main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/conftest.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/conftest.py new file mode 100644 index 000000000000..2c1c2a183ef0 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/conftest.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + costmanagement_subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + costmanagement_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + costmanagement_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + costmanagement_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=costmanagement_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=costmanagement_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=costmanagement_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=costmanagement_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/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_alerts_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_alerts_operations.py new file mode 100644 index 000000000000..448dad3814f1 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_alerts_operations.py @@ -0,0 +1,102 @@ +# 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.costmanagement import CostManagementClient + +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 TestCostManagementAlertsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_alerts_list(self, resource_group): + response = self.client.alerts.list( + scope="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_alerts_get(self, resource_group): + response = self.client.alerts.get( + scope="str", + alert_id="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_alerts_dismiss(self, resource_group): + response = self.client.alerts.dismiss( + scope="str", + alert_id="str", + parameters={ + "closeTime": "str", + "costEntityId": "str", + "creationTime": "str", + "definition": {"category": "str", "criteria": "str", "type": "str"}, + "description": "str", + "details": { + "amount": 0.0, + "companyName": "str", + "contactEmails": ["str"], + "contactGroups": ["str"], + "contactRoles": ["str"], + "currentSpend": 0.0, + "departmentName": "str", + "enrollmentEndDate": "str", + "enrollmentNumber": "str", + "enrollmentStartDate": "str", + "invoicingThreshold": 0.0, + "meterFilter": [{}], + "operator": "str", + "overridingAlert": "str", + "periodStartDate": "str", + "resourceFilter": [{}], + "resourceGroupFilter": [{}], + "tagFilter": {}, + "threshold": 0.0, + "timeGrainType": "str", + "triggeredBy": "str", + "unit": "str", + }, + "modificationTime": "str", + "source": "str", + "status": "str", + "statusModificationTime": "str", + "statusModificationUserName": "str", + }, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_alerts_list_external(self, resource_group): + response = self.client.alerts.list_external( + external_cloud_provider_type="str", + external_cloud_provider_id="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_alerts_operations_async.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_alerts_operations_async.py new file mode 100644 index 000000000000..ab76f178b6db --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_alerts_operations_async.py @@ -0,0 +1,103 @@ +# 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.costmanagement.aio import CostManagementClient + +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 TestCostManagementAlertsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_alerts_list(self, resource_group): + response = await self.client.alerts.list( + scope="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_alerts_get(self, resource_group): + response = await self.client.alerts.get( + scope="str", + alert_id="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_alerts_dismiss(self, resource_group): + response = await self.client.alerts.dismiss( + scope="str", + alert_id="str", + parameters={ + "closeTime": "str", + "costEntityId": "str", + "creationTime": "str", + "definition": {"category": "str", "criteria": "str", "type": "str"}, + "description": "str", + "details": { + "amount": 0.0, + "companyName": "str", + "contactEmails": ["str"], + "contactGroups": ["str"], + "contactRoles": ["str"], + "currentSpend": 0.0, + "departmentName": "str", + "enrollmentEndDate": "str", + "enrollmentNumber": "str", + "enrollmentStartDate": "str", + "invoicingThreshold": 0.0, + "meterFilter": [{}], + "operator": "str", + "overridingAlert": "str", + "periodStartDate": "str", + "resourceFilter": [{}], + "resourceGroupFilter": [{}], + "tagFilter": {}, + "threshold": 0.0, + "timeGrainType": "str", + "triggeredBy": "str", + "unit": "str", + }, + "modificationTime": "str", + "source": "str", + "status": "str", + "statusModificationTime": "str", + "statusModificationUserName": "str", + }, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_alerts_list_external(self, resource_group): + response = await self.client.alerts.list_external( + external_cloud_provider_type="str", + external_cloud_provider_id="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_benefit_recommendations_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_benefit_recommendations_operations.py new file mode 100644 index 000000000000..51caed530908 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_benefit_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.costmanagement import CostManagementClient + +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 TestCostManagementBenefitRecommendationsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_benefit_recommendations_list(self, resource_group): + response = self.client.benefit_recommendations.list( + billing_scope="str", + api_version="2024-10-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_benefit_recommendations_operations_async.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_benefit_recommendations_operations_async.py new file mode 100644 index 000000000000..39f449d0502b --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_benefit_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.costmanagement.aio import CostManagementClient + +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 TestCostManagementBenefitRecommendationsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_benefit_recommendations_list(self, resource_group): + response = self.client.benefit_recommendations.list( + billing_scope="str", + api_version="2024-10-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_benefit_utilization_summaries_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_benefit_utilization_summaries_operations.py new file mode 100644 index 000000000000..3e9cf4eaacfd --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_benefit_utilization_summaries_operations.py @@ -0,0 +1,65 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.costmanagement import CostManagementClient + +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 TestCostManagementBenefitUtilizationSummariesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_benefit_utilization_summaries_list_by_billing_account_id(self, resource_group): + response = self.client.benefit_utilization_summaries.list_by_billing_account_id( + billing_account_id="str", + api_version="2024-10-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_benefit_utilization_summaries_list_by_billing_profile_id(self, resource_group): + response = self.client.benefit_utilization_summaries.list_by_billing_profile_id( + billing_account_id="str", + billing_profile_id="str", + api_version="2024-10-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_benefit_utilization_summaries_list_by_savings_plan_order(self, resource_group): + response = self.client.benefit_utilization_summaries.list_by_savings_plan_order( + savings_plan_order_id="str", + api_version="2024-10-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_benefit_utilization_summaries_list_by_savings_plan_id(self, resource_group): + response = self.client.benefit_utilization_summaries.list_by_savings_plan_id( + savings_plan_order_id="str", + savings_plan_id="str", + api_version="2024-10-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_benefit_utilization_summaries_operations_async.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_benefit_utilization_summaries_operations_async.py new file mode 100644 index 000000000000..b4b825dc1703 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_benefit_utilization_summaries_operations_async.py @@ -0,0 +1,66 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.costmanagement.aio import CostManagementClient + +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 TestCostManagementBenefitUtilizationSummariesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_benefit_utilization_summaries_list_by_billing_account_id(self, resource_group): + response = self.client.benefit_utilization_summaries.list_by_billing_account_id( + billing_account_id="str", + api_version="2024-10-01-preview", + ) + 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_benefit_utilization_summaries_list_by_billing_profile_id(self, resource_group): + response = self.client.benefit_utilization_summaries.list_by_billing_profile_id( + billing_account_id="str", + billing_profile_id="str", + api_version="2024-10-01-preview", + ) + 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_benefit_utilization_summaries_list_by_savings_plan_order(self, resource_group): + response = self.client.benefit_utilization_summaries.list_by_savings_plan_order( + savings_plan_order_id="str", + api_version="2024-10-01-preview", + ) + 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_benefit_utilization_summaries_list_by_savings_plan_id(self, resource_group): + response = self.client.benefit_utilization_summaries.list_by_savings_plan_id( + savings_plan_order_id="str", + savings_plan_id="str", + api_version="2024-10-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_budgets_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_budgets_operations.py new file mode 100644 index 000000000000..ab917cb0b544 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_budgets_operations.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.costmanagement import CostManagementClient + +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 TestCostManagementBudgetsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_budgets_list(self, resource_group): + response = self.client.budgets.list( + scope="str", + api_version="2024-10-01-preview", + ) + 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="2024-10-01-preview", + ) + + # 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"], + "frequency": "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="2024-10-01-preview", + ) + + # 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="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_budgets_operations_async.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_budgets_operations_async.py new file mode 100644 index 000000000000..e7c1445edcb9 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_budgets_operations_async.py @@ -0,0 +1,102 @@ +# 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.costmanagement.aio import CostManagementClient + +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 TestCostManagementBudgetsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient, 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="2024-10-01-preview", + ) + 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="2024-10-01-preview", + ) + + # 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"], + "frequency": "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="2024-10-01-preview", + ) + + # 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="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_cost_allocation_rules_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_cost_allocation_rules_operations.py new file mode 100644 index 000000000000..036f920b44ec --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_cost_allocation_rules_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.costmanagement import CostManagementClient + +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 TestCostManagementCostAllocationRulesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_cost_allocation_rules_list(self, resource_group): + response = self.client.cost_allocation_rules.list( + billing_account_id="str", + api_version="2024-10-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_cost_allocation_rules_check_name_availability(self, resource_group): + response = self.client.cost_allocation_rules.check_name_availability( + billing_account_id="str", + cost_allocation_rule_check_name_availability_request={"name": "str", "type": "str"}, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_cost_allocation_rules_get(self, resource_group): + response = self.client.cost_allocation_rules.get( + billing_account_id="str", + rule_name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_cost_allocation_rules_create_or_update(self, resource_group): + response = self.client.cost_allocation_rules.create_or_update( + billing_account_id="str", + rule_name="str", + cost_allocation_rule={ + "id": "str", + "name": "str", + "properties": { + "details": { + "sourceResources": [{"name": "str", "resourceType": "str", "values": ["str"]}], + "targetResources": [ + { + "name": "str", + "policyType": "str", + "resourceType": "str", + "values": [{"name": "str", "percentage": 0.0}], + } + ], + }, + "status": "str", + "createdDate": "2020-02-20 00:00:00", + "description": "str", + "updatedDate": "2020-02-20 00:00:00", + }, + "type": "str", + }, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_cost_allocation_rules_delete(self, resource_group): + response = self.client.cost_allocation_rules.delete( + billing_account_id="str", + rule_name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_cost_allocation_rules_operations_async.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_cost_allocation_rules_operations_async.py new file mode 100644 index 000000000000..3d8846030be0 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_cost_allocation_rules_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.costmanagement.aio import CostManagementClient + +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 TestCostManagementCostAllocationRulesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_cost_allocation_rules_list(self, resource_group): + response = self.client.cost_allocation_rules.list( + billing_account_id="str", + api_version="2024-10-01-preview", + ) + 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_cost_allocation_rules_check_name_availability(self, resource_group): + response = await self.client.cost_allocation_rules.check_name_availability( + billing_account_id="str", + cost_allocation_rule_check_name_availability_request={"name": "str", "type": "str"}, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_cost_allocation_rules_get(self, resource_group): + response = await self.client.cost_allocation_rules.get( + billing_account_id="str", + rule_name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_cost_allocation_rules_create_or_update(self, resource_group): + response = await self.client.cost_allocation_rules.create_or_update( + billing_account_id="str", + rule_name="str", + cost_allocation_rule={ + "id": "str", + "name": "str", + "properties": { + "details": { + "sourceResources": [{"name": "str", "resourceType": "str", "values": ["str"]}], + "targetResources": [ + { + "name": "str", + "policyType": "str", + "resourceType": "str", + "values": [{"name": "str", "percentage": 0.0}], + } + ], + }, + "status": "str", + "createdDate": "2020-02-20 00:00:00", + "description": "str", + "updatedDate": "2020-02-20 00:00:00", + }, + "type": "str", + }, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_cost_allocation_rules_delete(self, resource_group): + response = await self.client.cost_allocation_rules.delete( + billing_account_id="str", + rule_name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_dimensions_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_dimensions_operations.py new file mode 100644 index 000000000000..cedb50ebb76f --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_dimensions_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.costmanagement import CostManagementClient + +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 TestCostManagementDimensionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_dimensions_list(self, resource_group): + response = self.client.dimensions.list( + scope="str", + api_version="2024-10-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_dimensions_by_external_cloud_provider_type(self, resource_group): + response = self.client.dimensions.by_external_cloud_provider_type( + external_cloud_provider_type="str", + external_cloud_provider_id="str", + api_version="2024-10-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_dimensions_operations_async.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_dimensions_operations_async.py new file mode 100644 index 000000000000..976c1520b554 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_dimensions_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.costmanagement.aio import CostManagementClient + +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 TestCostManagementDimensionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_dimensions_list(self, resource_group): + response = self.client.dimensions.list( + scope="str", + api_version="2024-10-01-preview", + ) + 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_dimensions_by_external_cloud_provider_type(self, resource_group): + response = self.client.dimensions.by_external_cloud_provider_type( + external_cloud_provider_type="str", + external_cloud_provider_id="str", + api_version="2024-10-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_exports_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_exports_operations.py new file mode 100644 index 000000000000..56034965ea10 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_exports_operations.py @@ -0,0 +1,205 @@ +# 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.costmanagement import CostManagementClient + +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 TestCostManagementExportsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_exports_list(self, resource_group): + response = self.client.exports.list( + scope="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_exports_get(self, resource_group): + response = self.client.exports.get( + scope="str", + export_name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_exports_create_or_update(self, resource_group): + response = self.client.exports.create_or_update( + scope="str", + export_name="str", + parameters={ + "compressionMode": "str", + "dataOverwriteBehavior": "str", + "definition": { + "timeframe": "str", + "type": "str", + "dataSet": { + "configuration": { + "columns": ["str"], + "dataVersion": "str", + "filters": [{"name": "str", "value": "str"}], + }, + "granularity": "str", + }, + "timePeriod": {"from": "2020-02-20 00:00:00", "to": "2020-02-20 00:00:00"}, + }, + "deliveryInfo": { + "destination": { + "container": "str", + "microsoftFabricSettings": { + "lakehouse": {"displayName": "str", "id": "str"}, + "tableName": "str", + "workspace": {"displayName": "str", "id": "str"}, + }, + "resourceId": "str", + "rootFolderPath": "str", + "sasToken": "str", + "storageAccount": "str", + "type": "str", + } + }, + "eTag": "str", + "exportDescription": "str", + "format": "str", + "id": "str", + "identity": {"type": "str", "principalId": "str", "tenantId": "str"}, + "location": "str", + "name": "str", + "nextRunTimeEstimate": "2020-02-20 00:00:00", + "partitionData": bool, + "runHistory": { + "value": [ + { + "eTag": "str", + "endDate": "2020-02-20 00:00:00", + "error": {"code": "str", "message": "str"}, + "executionType": "str", + "fileName": "str", + "id": "str", + "manifestFile": "str", + "name": "str", + "processingEndTime": "2020-02-20 00:00:00", + "processingStartTime": "2020-02-20 00:00:00", + "runSettings": { + "definition": { + "timeframe": "str", + "type": "str", + "dataSet": { + "configuration": { + "columns": ["str"], + "dataVersion": "str", + "filters": [{"name": "str", "value": "str"}], + }, + "granularity": "str", + }, + "timePeriod": {"from": "2020-02-20 00:00:00", "to": "2020-02-20 00:00:00"}, + }, + "deliveryInfo": { + "destination": { + "container": "str", + "microsoftFabricSettings": { + "lakehouse": {"displayName": "str", "id": "str"}, + "tableName": "str", + "workspace": {"displayName": "str", "id": "str"}, + }, + "resourceId": "str", + "rootFolderPath": "str", + "sasToken": "str", + "storageAccount": "str", + "type": "str", + } + }, + "compressionMode": "str", + "dataOverwriteBehavior": "str", + "exportDescription": "str", + "format": "str", + "nextRunTimeEstimate": "2020-02-20 00:00:00", + "partitionData": bool, + "runHistory": ..., + "systemSuspensionContext": { + "suspensionCode": "str", + "suspensionReason": "str", + "suspensionTime": "2020-02-20 00:00:00", + }, + }, + "startDate": "2020-02-20 00:00:00", + "status": "str", + "submittedBy": "str", + "submittedTime": "2020-02-20 00:00:00", + "type": "str", + } + ] + }, + "schedule": { + "recurrence": "str", + "recurrencePeriod": {"from": "2020-02-20 00:00:00", "to": "2020-02-20 00:00:00"}, + "status": "str", + }, + "systemSuspensionContext": { + "suspensionCode": "str", + "suspensionReason": "str", + "suspensionTime": "2020-02-20 00:00:00", + }, + "type": "str", + }, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_exports_delete(self, resource_group): + response = self.client.exports.delete( + scope="str", + export_name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_exports_execute(self, resource_group): + response = self.client.exports.execute( + scope="str", + export_name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_exports_get_execution_history(self, resource_group): + response = self.client.exports.get_execution_history( + scope="str", + export_name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_exports_operations_async.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_exports_operations_async.py new file mode 100644 index 000000000000..0ebcbcc514c2 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_exports_operations_async.py @@ -0,0 +1,206 @@ +# 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.costmanagement.aio import CostManagementClient + +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 TestCostManagementExportsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_exports_list(self, resource_group): + response = await self.client.exports.list( + scope="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_exports_get(self, resource_group): + response = await self.client.exports.get( + scope="str", + export_name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_exports_create_or_update(self, resource_group): + response = await self.client.exports.create_or_update( + scope="str", + export_name="str", + parameters={ + "compressionMode": "str", + "dataOverwriteBehavior": "str", + "definition": { + "timeframe": "str", + "type": "str", + "dataSet": { + "configuration": { + "columns": ["str"], + "dataVersion": "str", + "filters": [{"name": "str", "value": "str"}], + }, + "granularity": "str", + }, + "timePeriod": {"from": "2020-02-20 00:00:00", "to": "2020-02-20 00:00:00"}, + }, + "deliveryInfo": { + "destination": { + "container": "str", + "microsoftFabricSettings": { + "lakehouse": {"displayName": "str", "id": "str"}, + "tableName": "str", + "workspace": {"displayName": "str", "id": "str"}, + }, + "resourceId": "str", + "rootFolderPath": "str", + "sasToken": "str", + "storageAccount": "str", + "type": "str", + } + }, + "eTag": "str", + "exportDescription": "str", + "format": "str", + "id": "str", + "identity": {"type": "str", "principalId": "str", "tenantId": "str"}, + "location": "str", + "name": "str", + "nextRunTimeEstimate": "2020-02-20 00:00:00", + "partitionData": bool, + "runHistory": { + "value": [ + { + "eTag": "str", + "endDate": "2020-02-20 00:00:00", + "error": {"code": "str", "message": "str"}, + "executionType": "str", + "fileName": "str", + "id": "str", + "manifestFile": "str", + "name": "str", + "processingEndTime": "2020-02-20 00:00:00", + "processingStartTime": "2020-02-20 00:00:00", + "runSettings": { + "definition": { + "timeframe": "str", + "type": "str", + "dataSet": { + "configuration": { + "columns": ["str"], + "dataVersion": "str", + "filters": [{"name": "str", "value": "str"}], + }, + "granularity": "str", + }, + "timePeriod": {"from": "2020-02-20 00:00:00", "to": "2020-02-20 00:00:00"}, + }, + "deliveryInfo": { + "destination": { + "container": "str", + "microsoftFabricSettings": { + "lakehouse": {"displayName": "str", "id": "str"}, + "tableName": "str", + "workspace": {"displayName": "str", "id": "str"}, + }, + "resourceId": "str", + "rootFolderPath": "str", + "sasToken": "str", + "storageAccount": "str", + "type": "str", + } + }, + "compressionMode": "str", + "dataOverwriteBehavior": "str", + "exportDescription": "str", + "format": "str", + "nextRunTimeEstimate": "2020-02-20 00:00:00", + "partitionData": bool, + "runHistory": ..., + "systemSuspensionContext": { + "suspensionCode": "str", + "suspensionReason": "str", + "suspensionTime": "2020-02-20 00:00:00", + }, + }, + "startDate": "2020-02-20 00:00:00", + "status": "str", + "submittedBy": "str", + "submittedTime": "2020-02-20 00:00:00", + "type": "str", + } + ] + }, + "schedule": { + "recurrence": "str", + "recurrencePeriod": {"from": "2020-02-20 00:00:00", "to": "2020-02-20 00:00:00"}, + "status": "str", + }, + "systemSuspensionContext": { + "suspensionCode": "str", + "suspensionReason": "str", + "suspensionTime": "2020-02-20 00:00:00", + }, + "type": "str", + }, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_exports_delete(self, resource_group): + response = await self.client.exports.delete( + scope="str", + export_name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_exports_execute(self, resource_group): + response = await self.client.exports.execute( + scope="str", + export_name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_exports_get_execution_history(self, resource_group): + response = await self.client.exports.get_execution_history( + scope="str", + export_name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_forecast_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_forecast_operations.py new file mode 100644 index 000000000000..b9a489e37668 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_forecast_operations.py @@ -0,0 +1,78 @@ +# 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.costmanagement import CostManagementClient + +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 TestCostManagementForecastOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_forecast_usage(self, resource_group): + response = self.client.forecast.usage( + scope="str", + parameters={ + "dataset": { + "aggregation": {"str": {"function": "str", "name": "str"}}, + "configuration": {"columns": ["str"]}, + "filter": { + "and": [...], + "dimensions": {"name": "str", "operator": "str", "values": ["str"]}, + "or": [...], + "tags": {"name": "str", "operator": "str", "values": ["str"]}, + }, + "granularity": "str", + }, + "timeframe": "str", + "type": "str", + "includeActualCost": bool, + "includeFreshPartialCost": bool, + "timePeriod": {"from": "2020-02-20 00:00:00", "to": "2020-02-20 00:00:00"}, + }, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_forecast_external_cloud_provider_usage(self, resource_group): + response = self.client.forecast.external_cloud_provider_usage( + external_cloud_provider_type="str", + external_cloud_provider_id="str", + parameters={ + "dataset": { + "aggregation": {"str": {"function": "str", "name": "str"}}, + "configuration": {"columns": ["str"]}, + "filter": { + "and": [...], + "dimensions": {"name": "str", "operator": "str", "values": ["str"]}, + "or": [...], + "tags": {"name": "str", "operator": "str", "values": ["str"]}, + }, + "granularity": "str", + }, + "timeframe": "str", + "type": "str", + "includeActualCost": bool, + "includeFreshPartialCost": bool, + "timePeriod": {"from": "2020-02-20 00:00:00", "to": "2020-02-20 00:00:00"}, + }, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_forecast_operations_async.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_forecast_operations_async.py new file mode 100644 index 000000000000..3ecd415a52d6 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_forecast_operations_async.py @@ -0,0 +1,79 @@ +# 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.costmanagement.aio import CostManagementClient + +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 TestCostManagementForecastOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_forecast_usage(self, resource_group): + response = await self.client.forecast.usage( + scope="str", + parameters={ + "dataset": { + "aggregation": {"str": {"function": "str", "name": "str"}}, + "configuration": {"columns": ["str"]}, + "filter": { + "and": [...], + "dimensions": {"name": "str", "operator": "str", "values": ["str"]}, + "or": [...], + "tags": {"name": "str", "operator": "str", "values": ["str"]}, + }, + "granularity": "str", + }, + "timeframe": "str", + "type": "str", + "includeActualCost": bool, + "includeFreshPartialCost": bool, + "timePeriod": {"from": "2020-02-20 00:00:00", "to": "2020-02-20 00:00:00"}, + }, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_forecast_external_cloud_provider_usage(self, resource_group): + response = await self.client.forecast.external_cloud_provider_usage( + external_cloud_provider_type="str", + external_cloud_provider_id="str", + parameters={ + "dataset": { + "aggregation": {"str": {"function": "str", "name": "str"}}, + "configuration": {"columns": ["str"]}, + "filter": { + "and": [...], + "dimensions": {"name": "str", "operator": "str", "values": ["str"]}, + "or": [...], + "tags": {"name": "str", "operator": "str", "values": ["str"]}, + }, + "granularity": "str", + }, + "timeframe": "str", + "type": "str", + "includeActualCost": bool, + "includeFreshPartialCost": bool, + "timePeriod": {"from": "2020-02-20 00:00:00", "to": "2020-02-20 00:00:00"}, + }, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_benefit_utilization_summaries_report_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_benefit_utilization_summaries_report_operations.py new file mode 100644 index 000000000000..951a1ac20a9c --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_benefit_utilization_summaries_report_operations.py @@ -0,0 +1,150 @@ +# 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.costmanagement import CostManagementClient + +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 TestCostManagementGenerateBenefitUtilizationSummariesReportOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_generate_benefit_utilization_summaries_report_begin_generate_by_billing_account(self, resource_group): + response = self.client.generate_benefit_utilization_summaries_report.begin_generate_by_billing_account( + billing_account_id="str", + benefit_utilization_summaries_request={ + "endDate": "2020-02-20 00:00:00", + "grain": "str", + "startDate": "2020-02-20 00:00:00", + "benefitId": "str", + "benefitOrderId": "str", + "billingAccountId": "str", + "billingProfileId": "str", + "kind": "str", + }, + api_version="2024-10-01-preview", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_generate_benefit_utilization_summaries_report_begin_generate_by_billing_profile(self, resource_group): + response = self.client.generate_benefit_utilization_summaries_report.begin_generate_by_billing_profile( + billing_account_id="str", + billing_profile_id="str", + benefit_utilization_summaries_request={ + "endDate": "2020-02-20 00:00:00", + "grain": "str", + "startDate": "2020-02-20 00:00:00", + "benefitId": "str", + "benefitOrderId": "str", + "billingAccountId": "str", + "billingProfileId": "str", + "kind": "str", + }, + api_version="2024-10-01-preview", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_generate_benefit_utilization_summaries_report_begin_generate_by_reservation_order_id(self, resource_group): + response = self.client.generate_benefit_utilization_summaries_report.begin_generate_by_reservation_order_id( + reservation_order_id="str", + benefit_utilization_summaries_request={ + "endDate": "2020-02-20 00:00:00", + "grain": "str", + "startDate": "2020-02-20 00:00:00", + "benefitId": "str", + "benefitOrderId": "str", + "billingAccountId": "str", + "billingProfileId": "str", + "kind": "str", + }, + api_version="2024-10-01-preview", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_generate_benefit_utilization_summaries_report_begin_generate_by_reservation_id(self, resource_group): + response = self.client.generate_benefit_utilization_summaries_report.begin_generate_by_reservation_id( + reservation_order_id="str", + reservation_id="str", + benefit_utilization_summaries_request={ + "endDate": "2020-02-20 00:00:00", + "grain": "str", + "startDate": "2020-02-20 00:00:00", + "benefitId": "str", + "benefitOrderId": "str", + "billingAccountId": "str", + "billingProfileId": "str", + "kind": "str", + }, + api_version="2024-10-01-preview", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_generate_benefit_utilization_summaries_report_begin_generate_by_savings_plan_order_id( + self, resource_group + ): + response = self.client.generate_benefit_utilization_summaries_report.begin_generate_by_savings_plan_order_id( + savings_plan_order_id="str", + benefit_utilization_summaries_request={ + "endDate": "2020-02-20 00:00:00", + "grain": "str", + "startDate": "2020-02-20 00:00:00", + "benefitId": "str", + "benefitOrderId": "str", + "billingAccountId": "str", + "billingProfileId": "str", + "kind": "str", + }, + api_version="2024-10-01-preview", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_generate_benefit_utilization_summaries_report_begin_generate_by_savings_plan_id(self, resource_group): + response = self.client.generate_benefit_utilization_summaries_report.begin_generate_by_savings_plan_id( + savings_plan_order_id="str", + savings_plan_id="str", + benefit_utilization_summaries_request={ + "endDate": "2020-02-20 00:00:00", + "grain": "str", + "startDate": "2020-02-20 00:00:00", + "benefitId": "str", + "benefitOrderId": "str", + "billingAccountId": "str", + "billingProfileId": "str", + "kind": "str", + }, + api_version="2024-10-01-preview", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_benefit_utilization_summaries_report_operations_async.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_benefit_utilization_summaries_report_operations_async.py new file mode 100644 index 000000000000..0520902a66f1 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_benefit_utilization_summaries_report_operations_async.py @@ -0,0 +1,171 @@ +# 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.costmanagement.aio import CostManagementClient + +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 TestCostManagementGenerateBenefitUtilizationSummariesReportOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_generate_benefit_utilization_summaries_report_begin_generate_by_billing_account( + self, resource_group + ): + response = await ( + await self.client.generate_benefit_utilization_summaries_report.begin_generate_by_billing_account( + billing_account_id="str", + benefit_utilization_summaries_request={ + "endDate": "2020-02-20 00:00:00", + "grain": "str", + "startDate": "2020-02-20 00:00:00", + "benefitId": "str", + "benefitOrderId": "str", + "billingAccountId": "str", + "billingProfileId": "str", + "kind": "str", + }, + api_version="2024-10-01-preview", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_generate_benefit_utilization_summaries_report_begin_generate_by_billing_profile( + self, resource_group + ): + response = await ( + await self.client.generate_benefit_utilization_summaries_report.begin_generate_by_billing_profile( + billing_account_id="str", + billing_profile_id="str", + benefit_utilization_summaries_request={ + "endDate": "2020-02-20 00:00:00", + "grain": "str", + "startDate": "2020-02-20 00:00:00", + "benefitId": "str", + "benefitOrderId": "str", + "billingAccountId": "str", + "billingProfileId": "str", + "kind": "str", + }, + api_version="2024-10-01-preview", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_generate_benefit_utilization_summaries_report_begin_generate_by_reservation_order_id( + self, resource_group + ): + response = await ( + await self.client.generate_benefit_utilization_summaries_report.begin_generate_by_reservation_order_id( + reservation_order_id="str", + benefit_utilization_summaries_request={ + "endDate": "2020-02-20 00:00:00", + "grain": "str", + "startDate": "2020-02-20 00:00:00", + "benefitId": "str", + "benefitOrderId": "str", + "billingAccountId": "str", + "billingProfileId": "str", + "kind": "str", + }, + api_version="2024-10-01-preview", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_generate_benefit_utilization_summaries_report_begin_generate_by_reservation_id(self, resource_group): + response = await ( + await self.client.generate_benefit_utilization_summaries_report.begin_generate_by_reservation_id( + reservation_order_id="str", + reservation_id="str", + benefit_utilization_summaries_request={ + "endDate": "2020-02-20 00:00:00", + "grain": "str", + "startDate": "2020-02-20 00:00:00", + "benefitId": "str", + "benefitOrderId": "str", + "billingAccountId": "str", + "billingProfileId": "str", + "kind": "str", + }, + api_version="2024-10-01-preview", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_generate_benefit_utilization_summaries_report_begin_generate_by_savings_plan_order_id( + self, resource_group + ): + response = await ( + await self.client.generate_benefit_utilization_summaries_report.begin_generate_by_savings_plan_order_id( + savings_plan_order_id="str", + benefit_utilization_summaries_request={ + "endDate": "2020-02-20 00:00:00", + "grain": "str", + "startDate": "2020-02-20 00:00:00", + "benefitId": "str", + "benefitOrderId": "str", + "billingAccountId": "str", + "billingProfileId": "str", + "kind": "str", + }, + api_version="2024-10-01-preview", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_generate_benefit_utilization_summaries_report_begin_generate_by_savings_plan_id( + self, resource_group + ): + response = await ( + await self.client.generate_benefit_utilization_summaries_report.begin_generate_by_savings_plan_id( + savings_plan_order_id="str", + savings_plan_id="str", + benefit_utilization_summaries_request={ + "endDate": "2020-02-20 00:00:00", + "grain": "str", + "startDate": "2020-02-20 00:00:00", + "benefitId": "str", + "benefitOrderId": "str", + "billingAccountId": "str", + "billingProfileId": "str", + "kind": "str", + }, + api_version="2024-10-01-preview", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_cost_details_report_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_cost_details_report_operations.py new file mode 100644 index 000000000000..d65ad0bd836e --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_cost_details_report_operations.py @@ -0,0 +1,48 @@ +# 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.costmanagement import CostManagementClient + +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 TestCostManagementGenerateCostDetailsReportOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_generate_cost_details_report_begin_create_operation(self, resource_group): + response = self.client.generate_cost_details_report.begin_create_operation( + scope="str", + parameters={ + "billingPeriod": "str", + "invoiceId": "str", + "metric": "str", + "timePeriod": {"end": "str", "start": "str"}, + }, + api_version="2024-10-01-preview", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_generate_cost_details_report_begin_get_operation_results(self, resource_group): + response = self.client.generate_cost_details_report.begin_get_operation_results( + scope="str", + operation_id="str", + api_version="2024-10-01-preview", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_cost_details_report_operations_async.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_cost_details_report_operations_async.py new file mode 100644 index 000000000000..b6b0eafd5270 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_cost_details_report_operations_async.py @@ -0,0 +1,53 @@ +# 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.costmanagement.aio import CostManagementClient + +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 TestCostManagementGenerateCostDetailsReportOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_generate_cost_details_report_begin_create_operation(self, resource_group): + response = await ( + await self.client.generate_cost_details_report.begin_create_operation( + scope="str", + parameters={ + "billingPeriod": "str", + "invoiceId": "str", + "metric": "str", + "timePeriod": {"end": "str", "start": "str"}, + }, + api_version="2024-10-01-preview", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_generate_cost_details_report_begin_get_operation_results(self, resource_group): + response = await ( + await self.client.generate_cost_details_report.begin_get_operation_results( + scope="str", + operation_id="str", + api_version="2024-10-01-preview", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_detailed_cost_report_operation_results_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_detailed_cost_report_operation_results_operations.py new file mode 100644 index 000000000000..01c788ce53d1 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_detailed_cost_report_operation_results_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.costmanagement import CostManagementClient + +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 TestCostManagementGenerateDetailedCostReportOperationResultsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_generate_detailed_cost_report_operation_results_begin_get(self, resource_group): + response = self.client.generate_detailed_cost_report_operation_results.begin_get( + operation_id="str", + scope="str", + api_version="2024-10-01-preview", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_detailed_cost_report_operation_results_operations_async.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_detailed_cost_report_operation_results_operations_async.py new file mode 100644 index 000000000000..363a7eb1d274 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_detailed_cost_report_operation_results_operations_async.py @@ -0,0 +1,34 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.costmanagement.aio import CostManagementClient + +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 TestCostManagementGenerateDetailedCostReportOperationResultsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_generate_detailed_cost_report_operation_results_begin_get(self, resource_group): + response = await ( + await self.client.generate_detailed_cost_report_operation_results.begin_get( + operation_id="str", + scope="str", + api_version="2024-10-01-preview", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_detailed_cost_report_operation_status_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_detailed_cost_report_operation_status_operations.py new file mode 100644 index 000000000000..c6b5e392c1e1 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_detailed_cost_report_operation_status_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.costmanagement import CostManagementClient + +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 TestCostManagementGenerateDetailedCostReportOperationStatusOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_generate_detailed_cost_report_operation_status_get(self, resource_group): + response = self.client.generate_detailed_cost_report_operation_status.get( + operation_id="str", + scope="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_detailed_cost_report_operation_status_operations_async.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_detailed_cost_report_operation_status_operations_async.py new file mode 100644 index 000000000000..1c8a713a4651 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_detailed_cost_report_operation_status_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.costmanagement.aio import CostManagementClient + +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 TestCostManagementGenerateDetailedCostReportOperationStatusOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_generate_detailed_cost_report_operation_status_get(self, resource_group): + response = await self.client.generate_detailed_cost_report_operation_status.get( + operation_id="str", + scope="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_detailed_cost_report_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_detailed_cost_report_operations.py new file mode 100644 index 000000000000..b1389815c484 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_detailed_cost_report_operations.py @@ -0,0 +1,37 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.costmanagement import CostManagementClient + +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 TestCostManagementGenerateDetailedCostReportOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_generate_detailed_cost_report_begin_create_operation(self, resource_group): + response = self.client.generate_detailed_cost_report.begin_create_operation( + scope="str", + parameters={ + "billingPeriod": "str", + "customerId": "str", + "invoiceId": "str", + "metric": "str", + "timePeriod": {"end": "str", "start": "str"}, + }, + api_version="2024-10-01-preview", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_detailed_cost_report_operations_async.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_detailed_cost_report_operations_async.py new file mode 100644 index 000000000000..f603682e18d3 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_detailed_cost_report_operations_async.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.costmanagement.aio import CostManagementClient + +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 TestCostManagementGenerateDetailedCostReportOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_generate_detailed_cost_report_begin_create_operation(self, resource_group): + response = await ( + await self.client.generate_detailed_cost_report.begin_create_operation( + scope="str", + parameters={ + "billingPeriod": "str", + "customerId": "str", + "invoiceId": "str", + "metric": "str", + "timePeriod": {"end": "str", "start": "str"}, + }, + api_version="2024-10-01-preview", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_reservation_details_report_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_reservation_details_report_operations.py new file mode 100644 index 000000000000..f0853dc8c123 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_reservation_details_report_operations.py @@ -0,0 +1,46 @@ +# 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.costmanagement import CostManagementClient + +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 TestCostManagementGenerateReservationDetailsReportOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_generate_reservation_details_report_begin_by_billing_account_id(self, resource_group): + response = self.client.generate_reservation_details_report.begin_by_billing_account_id( + billing_account_id="str", + start_date="str", + end_date="str", + api_version="2024-10-01-preview", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_generate_reservation_details_report_begin_by_billing_profile_id(self, resource_group): + response = self.client.generate_reservation_details_report.begin_by_billing_profile_id( + billing_account_id="str", + billing_profile_id="str", + start_date="str", + end_date="str", + api_version="2024-10-01-preview", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_reservation_details_report_operations_async.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_reservation_details_report_operations_async.py new file mode 100644 index 000000000000..680712908445 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_generate_reservation_details_report_operations_async.py @@ -0,0 +1,51 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.costmanagement.aio import CostManagementClient + +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 TestCostManagementGenerateReservationDetailsReportOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_generate_reservation_details_report_begin_by_billing_account_id(self, resource_group): + response = await ( + await self.client.generate_reservation_details_report.begin_by_billing_account_id( + billing_account_id="str", + start_date="str", + end_date="str", + api_version="2024-10-01-preview", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_generate_reservation_details_report_begin_by_billing_profile_id(self, resource_group): + response = await ( + await self.client.generate_reservation_details_report.begin_by_billing_profile_id( + billing_account_id="str", + billing_profile_id="str", + start_date="str", + end_date="str", + api_version="2024-10-01-preview", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_operations.py new file mode 100644 index 000000000000..da639c0362e2 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_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.costmanagement import CostManagementClient + +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 TestCostManagementOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_operations_list(self, resource_group): + response = self.client.operations.list( + api_version="2024-10-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_operations_async.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_operations_async.py new file mode 100644 index 000000000000..3d0c33e88f30 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_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.costmanagement.aio import CostManagementClient + +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 TestCostManagementOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_operations_list(self, resource_group): + response = self.client.operations.list( + api_version="2024-10-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_price_sheet_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_price_sheet_operations.py new file mode 100644 index 000000000000..e364bc9c8fff --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_price_sheet_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.costmanagement import CostManagementClient + +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 TestCostManagementPriceSheetOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_price_sheet_begin_download_by_invoice(self, resource_group): + response = self.client.price_sheet.begin_download_by_invoice( + billing_account_name="str", + billing_profile_name="str", + invoice_name="str", + api_version="2024-10-01-preview", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_price_sheet_begin_download_by_billing_profile(self, resource_group): + response = self.client.price_sheet.begin_download_by_billing_profile( + billing_account_name="str", + billing_profile_name="str", + api_version="2024-10-01-preview", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_price_sheet_begin_download_by_billing_account(self, resource_group): + response = self.client.price_sheet.begin_download_by_billing_account( + billing_account_id="str", + billing_period_name="str", + api_version="2024-10-01-preview", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_price_sheet_operations_async.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_price_sheet_operations_async.py new file mode 100644 index 000000000000..55044f0e0b00 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_price_sheet_operations_async.py @@ -0,0 +1,63 @@ +# 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.costmanagement.aio import CostManagementClient + +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 TestCostManagementPriceSheetOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_price_sheet_begin_download_by_invoice(self, resource_group): + response = await ( + await self.client.price_sheet.begin_download_by_invoice( + billing_account_name="str", + billing_profile_name="str", + invoice_name="str", + api_version="2024-10-01-preview", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_price_sheet_begin_download_by_billing_profile(self, resource_group): + response = await ( + await self.client.price_sheet.begin_download_by_billing_profile( + billing_account_name="str", + billing_profile_name="str", + api_version="2024-10-01-preview", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_price_sheet_begin_download_by_billing_account(self, resource_group): + response = await ( + await self.client.price_sheet.begin_download_by_billing_account( + billing_account_id="str", + billing_period_name="str", + api_version="2024-10-01-preview", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_query_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_query_operations.py new file mode 100644 index 000000000000..f1925e81e33c --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_query_operations.py @@ -0,0 +1,76 @@ +# 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.costmanagement import CostManagementClient + +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 TestCostManagementQueryOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_query_usage(self, resource_group): + response = self.client.query.usage( + scope="str", + parameters={ + "dataset": { + "aggregation": {"str": {"function": "str", "name": "str"}}, + "configuration": {"columns": ["str"]}, + "filter": { + "and": [...], + "dimensions": {"name": "str", "operator": "str", "values": ["str"]}, + "or": [...], + "tags": {"name": "str", "operator": "str", "values": ["str"]}, + }, + "granularity": "str", + "grouping": [{"name": "str", "type": "str"}], + }, + "timeframe": "str", + "type": "str", + "timePeriod": {"from": "2020-02-20 00:00:00", "to": "2020-02-20 00:00:00"}, + }, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_query_usage_by_external_cloud_provider_type(self, resource_group): + response = self.client.query.usage_by_external_cloud_provider_type( + external_cloud_provider_type="str", + external_cloud_provider_id="str", + parameters={ + "dataset": { + "aggregation": {"str": {"function": "str", "name": "str"}}, + "configuration": {"columns": ["str"]}, + "filter": { + "and": [...], + "dimensions": {"name": "str", "operator": "str", "values": ["str"]}, + "or": [...], + "tags": {"name": "str", "operator": "str", "values": ["str"]}, + }, + "granularity": "str", + "grouping": [{"name": "str", "type": "str"}], + }, + "timeframe": "str", + "type": "str", + "timePeriod": {"from": "2020-02-20 00:00:00", "to": "2020-02-20 00:00:00"}, + }, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_query_operations_async.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_query_operations_async.py new file mode 100644 index 000000000000..52e277fcfb1c --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_query_operations_async.py @@ -0,0 +1,77 @@ +# 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.costmanagement.aio import CostManagementClient + +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 TestCostManagementQueryOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_query_usage(self, resource_group): + response = await self.client.query.usage( + scope="str", + parameters={ + "dataset": { + "aggregation": {"str": {"function": "str", "name": "str"}}, + "configuration": {"columns": ["str"]}, + "filter": { + "and": [...], + "dimensions": {"name": "str", "operator": "str", "values": ["str"]}, + "or": [...], + "tags": {"name": "str", "operator": "str", "values": ["str"]}, + }, + "granularity": "str", + "grouping": [{"name": "str", "type": "str"}], + }, + "timeframe": "str", + "type": "str", + "timePeriod": {"from": "2020-02-20 00:00:00", "to": "2020-02-20 00:00:00"}, + }, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_query_usage_by_external_cloud_provider_type(self, resource_group): + response = await self.client.query.usage_by_external_cloud_provider_type( + external_cloud_provider_type="str", + external_cloud_provider_id="str", + parameters={ + "dataset": { + "aggregation": {"str": {"function": "str", "name": "str"}}, + "configuration": {"columns": ["str"]}, + "filter": { + "and": [...], + "dimensions": {"name": "str", "operator": "str", "values": ["str"]}, + "or": [...], + "tags": {"name": "str", "operator": "str", "values": ["str"]}, + }, + "granularity": "str", + "grouping": [{"name": "str", "type": "str"}], + }, + "timeframe": "str", + "type": "str", + "timePeriod": {"from": "2020-02-20 00:00:00", "to": "2020-02-20 00:00:00"}, + }, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_scheduled_actions_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_scheduled_actions_operations.py new file mode 100644 index 000000000000..c88cfaef9cdf --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_scheduled_actions_operations.py @@ -0,0 +1,229 @@ +# 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.costmanagement import CostManagementClient + +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 TestCostManagementScheduledActionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_scheduled_actions_list(self, resource_group): + response = self.client.scheduled_actions.list( + api_version="2024-10-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_scheduled_actions_list_by_scope(self, resource_group): + response = self.client.scheduled_actions.list_by_scope( + scope="str", + api_version="2024-10-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_scheduled_actions_create_or_update(self, resource_group): + response = self.client.scheduled_actions.create_or_update( + name="str", + scheduled_action={ + "displayName": "str", + "eTag": "str", + "fileDestination": {"fileFormats": ["str"]}, + "id": "str", + "kind": "str", + "name": "str", + "notification": { + "subject": "str", + "to": ["str"], + "language": "str", + "message": "str", + "regionalFormat": "str", + }, + "notificationEmail": "str", + "schedule": { + "endDate": "2020-02-20 00:00:00", + "frequency": "str", + "startDate": "2020-02-20 00:00:00", + "dayOfMonth": 0, + "daysOfWeek": ["str"], + "hourOfDay": 0, + "weeksOfMonth": ["str"], + }, + "scope": "str", + "status": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "viewId": "str", + }, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_scheduled_actions_get(self, resource_group): + response = self.client.scheduled_actions.get( + name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_scheduled_actions_delete(self, resource_group): + response = self.client.scheduled_actions.delete( + name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_scheduled_actions_create_or_update_by_scope(self, resource_group): + response = self.client.scheduled_actions.create_or_update_by_scope( + scope="str", + name="str", + scheduled_action={ + "displayName": "str", + "eTag": "str", + "fileDestination": {"fileFormats": ["str"]}, + "id": "str", + "kind": "str", + "name": "str", + "notification": { + "subject": "str", + "to": ["str"], + "language": "str", + "message": "str", + "regionalFormat": "str", + }, + "notificationEmail": "str", + "schedule": { + "endDate": "2020-02-20 00:00:00", + "frequency": "str", + "startDate": "2020-02-20 00:00:00", + "dayOfMonth": 0, + "daysOfWeek": ["str"], + "hourOfDay": 0, + "weeksOfMonth": ["str"], + }, + "scope": "str", + "status": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "viewId": "str", + }, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_scheduled_actions_get_by_scope(self, resource_group): + response = self.client.scheduled_actions.get_by_scope( + scope="str", + name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_scheduled_actions_delete_by_scope(self, resource_group): + response = self.client.scheduled_actions.delete_by_scope( + scope="str", + name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_scheduled_actions_run(self, resource_group): + response = self.client.scheduled_actions.run( + name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_scheduled_actions_run_by_scope(self, resource_group): + response = self.client.scheduled_actions.run_by_scope( + scope="str", + name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_scheduled_actions_check_name_availability(self, resource_group): + response = self.client.scheduled_actions.check_name_availability( + check_name_availability_request={"name": "str", "type": "str"}, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_scheduled_actions_check_name_availability_by_scope(self, resource_group): + response = self.client.scheduled_actions.check_name_availability_by_scope( + scope="str", + check_name_availability_request={"name": "str", "type": "str"}, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_scheduled_actions_operations_async.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_scheduled_actions_operations_async.py new file mode 100644 index 000000000000..be3c8d8fc3dc --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_scheduled_actions_operations_async.py @@ -0,0 +1,230 @@ +# 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.costmanagement.aio import CostManagementClient + +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 TestCostManagementScheduledActionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_scheduled_actions_list(self, resource_group): + response = self.client.scheduled_actions.list( + api_version="2024-10-01-preview", + ) + 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_scheduled_actions_list_by_scope(self, resource_group): + response = self.client.scheduled_actions.list_by_scope( + scope="str", + api_version="2024-10-01-preview", + ) + 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_scheduled_actions_create_or_update(self, resource_group): + response = await self.client.scheduled_actions.create_or_update( + name="str", + scheduled_action={ + "displayName": "str", + "eTag": "str", + "fileDestination": {"fileFormats": ["str"]}, + "id": "str", + "kind": "str", + "name": "str", + "notification": { + "subject": "str", + "to": ["str"], + "language": "str", + "message": "str", + "regionalFormat": "str", + }, + "notificationEmail": "str", + "schedule": { + "endDate": "2020-02-20 00:00:00", + "frequency": "str", + "startDate": "2020-02-20 00:00:00", + "dayOfMonth": 0, + "daysOfWeek": ["str"], + "hourOfDay": 0, + "weeksOfMonth": ["str"], + }, + "scope": "str", + "status": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "viewId": "str", + }, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_scheduled_actions_get(self, resource_group): + response = await self.client.scheduled_actions.get( + name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_scheduled_actions_delete(self, resource_group): + response = await self.client.scheduled_actions.delete( + name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_scheduled_actions_create_or_update_by_scope(self, resource_group): + response = await self.client.scheduled_actions.create_or_update_by_scope( + scope="str", + name="str", + scheduled_action={ + "displayName": "str", + "eTag": "str", + "fileDestination": {"fileFormats": ["str"]}, + "id": "str", + "kind": "str", + "name": "str", + "notification": { + "subject": "str", + "to": ["str"], + "language": "str", + "message": "str", + "regionalFormat": "str", + }, + "notificationEmail": "str", + "schedule": { + "endDate": "2020-02-20 00:00:00", + "frequency": "str", + "startDate": "2020-02-20 00:00:00", + "dayOfMonth": 0, + "daysOfWeek": ["str"], + "hourOfDay": 0, + "weeksOfMonth": ["str"], + }, + "scope": "str", + "status": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "viewId": "str", + }, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_scheduled_actions_get_by_scope(self, resource_group): + response = await self.client.scheduled_actions.get_by_scope( + scope="str", + name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_scheduled_actions_delete_by_scope(self, resource_group): + response = await self.client.scheduled_actions.delete_by_scope( + scope="str", + name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_scheduled_actions_run(self, resource_group): + response = await self.client.scheduled_actions.run( + name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_scheduled_actions_run_by_scope(self, resource_group): + response = await self.client.scheduled_actions.run_by_scope( + scope="str", + name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_scheduled_actions_check_name_availability(self, resource_group): + response = await self.client.scheduled_actions.check_name_availability( + check_name_availability_request={"name": "str", "type": "str"}, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_scheduled_actions_check_name_availability_by_scope(self, resource_group): + response = await self.client.scheduled_actions.check_name_availability_by_scope( + scope="str", + check_name_availability_request={"name": "str", "type": "str"}, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_settings_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_settings_operations.py new file mode 100644 index 000000000000..b7cfdc3673b4 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_settings_operations.py @@ -0,0 +1,73 @@ +# 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.costmanagement import CostManagementClient + +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 TestCostManagementSettingsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_settings_list(self, resource_group): + response = self.client.settings.list( + scope="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_settings_create_or_update_by_scope(self, resource_group): + response = self.client.settings.create_or_update_by_scope( + scope="str", + type="str", + setting={ + "kind": "taginheritance", + "id": "str", + "name": "str", + "properties": {"preferContainerTags": bool}, + "type": "str", + }, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_settings_get_by_scope(self, resource_group): + response = self.client.settings.get_by_scope( + scope="str", + type="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_settings_delete_by_scope(self, resource_group): + response = self.client.settings.delete_by_scope( + scope="str", + type="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_settings_operations_async.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_settings_operations_async.py new file mode 100644 index 000000000000..47ab26066db5 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_settings_operations_async.py @@ -0,0 +1,74 @@ +# 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.costmanagement.aio import CostManagementClient + +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 TestCostManagementSettingsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_settings_list(self, resource_group): + response = await self.client.settings.list( + scope="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_settings_create_or_update_by_scope(self, resource_group): + response = await self.client.settings.create_or_update_by_scope( + scope="str", + type="str", + setting={ + "kind": "taginheritance", + "id": "str", + "name": "str", + "properties": {"preferContainerTags": bool}, + "type": "str", + }, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_settings_get_by_scope(self, resource_group): + response = await self.client.settings.get_by_scope( + scope="str", + type="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_settings_delete_by_scope(self, resource_group): + response = await self.client.settings.delete_by_scope( + scope="str", + type="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_views_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_views_operations.py new file mode 100644 index 000000000000..871a1bf16906 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_views_operations.py @@ -0,0 +1,175 @@ +# 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.costmanagement import CostManagementClient + +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 TestCostManagementViewsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_views_list(self, resource_group): + response = self.client.views.list( + api_version="2024-10-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_views_list_by_scope(self, resource_group): + response = self.client.views.list_by_scope( + scope="str", + api_version="2024-10-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_views_get(self, resource_group): + response = self.client.views.get( + view_name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_views_create_or_update(self, resource_group): + response = self.client.views.create_or_update( + view_name="str", + parameters={ + "accumulated": "str", + "chart": "str", + "createdOn": "2020-02-20 00:00:00", + "currency": "str", + "dataSet": { + "aggregation": {"str": {"function": "str", "name": "str"}}, + "configuration": {"columns": ["str"]}, + "filter": { + "and": [...], + "dimensions": {"name": "str", "operator": "str", "values": ["str"]}, + "or": [...], + "tags": {"name": "str", "operator": "str", "values": ["str"]}, + }, + "granularity": "str", + "grouping": [{"name": "str", "type": "str"}], + "sorting": [{"name": "str", "direction": "str"}], + }, + "dateRange": "str", + "displayName": "str", + "eTag": "str", + "id": "str", + "includeMonetaryCommitment": bool, + "kpis": [{"enabled": bool, "id": "str", "type": "str"}], + "metric": "str", + "modifiedOn": "2020-02-20 00:00:00", + "name": "str", + "pivots": [{"name": "str", "type": "str"}], + "scope": "str", + "timePeriod": {"from": "2020-02-20 00:00:00", "to": "2020-02-20 00:00:00"}, + "timeframe": "str", + "type": "str", + }, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_views_delete(self, resource_group): + response = self.client.views.delete( + view_name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_views_get_by_scope(self, resource_group): + response = self.client.views.get_by_scope( + scope="str", + view_name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_views_create_or_update_by_scope(self, resource_group): + response = self.client.views.create_or_update_by_scope( + scope="str", + view_name="str", + parameters={ + "accumulated": "str", + "chart": "str", + "createdOn": "2020-02-20 00:00:00", + "currency": "str", + "dataSet": { + "aggregation": {"str": {"function": "str", "name": "str"}}, + "configuration": {"columns": ["str"]}, + "filter": { + "and": [...], + "dimensions": {"name": "str", "operator": "str", "values": ["str"]}, + "or": [...], + "tags": {"name": "str", "operator": "str", "values": ["str"]}, + }, + "granularity": "str", + "grouping": [{"name": "str", "type": "str"}], + "sorting": [{"name": "str", "direction": "str"}], + }, + "dateRange": "str", + "displayName": "str", + "eTag": "str", + "id": "str", + "includeMonetaryCommitment": bool, + "kpis": [{"enabled": bool, "id": "str", "type": "str"}], + "metric": "str", + "modifiedOn": "2020-02-20 00:00:00", + "name": "str", + "pivots": [{"name": "str", "type": "str"}], + "scope": "str", + "timePeriod": {"from": "2020-02-20 00:00:00", "to": "2020-02-20 00:00:00"}, + "timeframe": "str", + "type": "str", + }, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_views_delete_by_scope(self, resource_group): + response = self.client.views.delete_by_scope( + scope="str", + view_name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_views_operations_async.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_views_operations_async.py new file mode 100644 index 000000000000..aae7f4828a4c --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_tests/test_cost_management_views_operations_async.py @@ -0,0 +1,176 @@ +# 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.costmanagement.aio import CostManagementClient + +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 TestCostManagementViewsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CostManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_views_list(self, resource_group): + response = self.client.views.list( + api_version="2024-10-01-preview", + ) + 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_views_list_by_scope(self, resource_group): + response = self.client.views.list_by_scope( + scope="str", + api_version="2024-10-01-preview", + ) + 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_views_get(self, resource_group): + response = await self.client.views.get( + view_name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_views_create_or_update(self, resource_group): + response = await self.client.views.create_or_update( + view_name="str", + parameters={ + "accumulated": "str", + "chart": "str", + "createdOn": "2020-02-20 00:00:00", + "currency": "str", + "dataSet": { + "aggregation": {"str": {"function": "str", "name": "str"}}, + "configuration": {"columns": ["str"]}, + "filter": { + "and": [...], + "dimensions": {"name": "str", "operator": "str", "values": ["str"]}, + "or": [...], + "tags": {"name": "str", "operator": "str", "values": ["str"]}, + }, + "granularity": "str", + "grouping": [{"name": "str", "type": "str"}], + "sorting": [{"name": "str", "direction": "str"}], + }, + "dateRange": "str", + "displayName": "str", + "eTag": "str", + "id": "str", + "includeMonetaryCommitment": bool, + "kpis": [{"enabled": bool, "id": "str", "type": "str"}], + "metric": "str", + "modifiedOn": "2020-02-20 00:00:00", + "name": "str", + "pivots": [{"name": "str", "type": "str"}], + "scope": "str", + "timePeriod": {"from": "2020-02-20 00:00:00", "to": "2020-02-20 00:00:00"}, + "timeframe": "str", + "type": "str", + }, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_views_delete(self, resource_group): + response = await self.client.views.delete( + view_name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_views_get_by_scope(self, resource_group): + response = await self.client.views.get_by_scope( + scope="str", + view_name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_views_create_or_update_by_scope(self, resource_group): + response = await self.client.views.create_or_update_by_scope( + scope="str", + view_name="str", + parameters={ + "accumulated": "str", + "chart": "str", + "createdOn": "2020-02-20 00:00:00", + "currency": "str", + "dataSet": { + "aggregation": {"str": {"function": "str", "name": "str"}}, + "configuration": {"columns": ["str"]}, + "filter": { + "and": [...], + "dimensions": {"name": "str", "operator": "str", "values": ["str"]}, + "or": [...], + "tags": {"name": "str", "operator": "str", "values": ["str"]}, + }, + "granularity": "str", + "grouping": [{"name": "str", "type": "str"}], + "sorting": [{"name": "str", "direction": "str"}], + }, + "dateRange": "str", + "displayName": "str", + "eTag": "str", + "id": "str", + "includeMonetaryCommitment": bool, + "kpis": [{"enabled": bool, "id": "str", "type": "str"}], + "metric": "str", + "modifiedOn": "2020-02-20 00:00:00", + "name": "str", + "pivots": [{"name": "str", "type": "str"}], + "scope": "str", + "timePeriod": {"from": "2020-02-20 00:00:00", "to": "2020-02-20 00:00:00"}, + "timeframe": "str", + "type": "str", + }, + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_views_delete_by_scope(self, resource_group): + response = await self.client.views.delete_by_scope( + scope="str", + view_name="str", + api_version="2024-10-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/sdk_packaging.toml b/sdk/costmanagement/azure-mgmt-costmanagement/sdk_packaging.toml index 0b4a31f4196f..f6c2c3e14e50 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/sdk_packaging.toml +++ b/sdk/costmanagement/azure-mgmt-costmanagement/sdk_packaging.toml @@ -3,7 +3,7 @@ package_name = "azure-mgmt-costmanagement" package_nspkg = "azure-mgmt-nspkg" package_pprint_name = "Cost Management" package_doc_id = "" -is_stable = true +is_stable = false is_arm = true title = "CostManagementClient" no_sub = true diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/setup.py b/sdk/costmanagement/azure-mgmt-costmanagement/setup.py index bdcf90a92b53..4432c907edd3 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/setup.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/setup.py @@ -49,15 +49,15 @@ 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 :: 5 - Production/Stable", + "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", + "Programming Language :: Python :: 3.12", "License :: OSI Approved :: MIT License", ], zip_safe=False, @@ -74,10 +74,10 @@ "pytyped": ["py.typed"], }, install_requires=[ - "isodate<1.0.0,>=0.6.1", - "azure-common~=1.1", - "azure-mgmt-core>=1.3.2,<2.0.0", - "typing-extensions>=4.3.0; python_version<'3.8.0'", + "isodate>=0.6.1", + "typing-extensions>=4.6.0", + "azure-common>=1.1", + "azure-mgmt-core>=1.3.2", ], - python_requires=">=3.7", + python_requires=">=3.8", )